From 2f2fb4e99b2d72e5f0159c0e1c32b5e1142c8b76 Mon Sep 17 00:00:00 2001 From: rUv Date: Fri, 26 Sep 2025 17:59:51 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=81=20Session=20end=20checkpoint:=20se?= =?UTF-8?q?ssion-20250926-175950?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 6988 +++++++++-------- .claude-flow/metrics/task-metrics.json | 6 +- .claude/checkpoints/1758909460.json | 1 + .claude/checkpoints/1758909461.json | 1 + .../summary-session-20250926-175950.md | 396 + dist-cjs/src/cli/simple-cli.js | 353 +- dist-cjs/src/cli/simple-cli.js.map | 2 +- dist-cjs/src/cli/simple-commands/hive-mind.js | 8 + .../src/cli/simple-commands/hive-mind.js.map | 2 +- dist-cjs/src/cli/simple-commands/swarm.js | 8 + dist-cjs/src/cli/simple-commands/swarm.js.map | 2 +- dist-cjs/src/ui/console/js/analysis-tools.js | 941 --- .../src/ui/console/js/analysis-tools.js.map | 1 - dist-cjs/src/ui/console/js/command-handler.js | 667 -- .../src/ui/console/js/command-handler.js.map | 1 - dist-cjs/src/ui/console/js/console.js | 410 - dist-cjs/src/ui/console/js/console.js.map | 1 - dist-cjs/src/ui/console/js/daa-tools.js | 891 --- dist-cjs/src/ui/console/js/daa-tools.js.map | 1 - .../src/ui/console/js/memory-interface.js | 792 -- .../src/ui/console/js/memory-interface.js.map | 1 - dist-cjs/src/ui/console/js/memory-test.js | 178 - dist-cjs/src/ui/console/js/memory-test.js.map | 1 - dist-cjs/src/ui/console/js/memory-tools.js | 1270 --- .../src/ui/console/js/memory-tools.js.map | 1 - .../src/ui/console/js/real-time-dashboard.js | 548 -- .../ui/console/js/real-time-dashboard.js.map | 1 - dist-cjs/src/ui/console/js/settings.js | 406 - dist-cjs/src/ui/console/js/settings.js.map | 1 - .../src/ui/console/js/swarm-integration.js | 359 - .../ui/console/js/swarm-integration.js.map | 1 - .../src/ui/console/js/swarm-visualizer.js | 661 -- .../src/ui/console/js/swarm-visualizer.js.map | 1 - .../src/ui/console/js/terminal-emulator.js | 444 -- .../ui/console/js/terminal-emulator.js.map | 1 - .../src/ui/console/js/websocket-client.js | 360 - .../src/ui/console/js/websocket-client.js.map | 1 - .../src/ui/console/js/workflow-designer.js | 1577 ---- .../ui/console/js/workflow-designer.js.map | 1 - .../src/ui/console/test-neural-networks.js | 220 - .../ui/console/test-neural-networks.js.map | 1 - dist-cjs/src/ui/hive-dashboard.js | 240 - dist-cjs/src/ui/hive-dashboard.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedProcessUI.js | 1775 ----- .../src/ui/web-ui/EnhancedProcessUI.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedWebUI.js | 420 - dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map | 1 - .../ui/web-ui/components/ComponentLibrary.js | 872 -- .../web-ui/components/ComponentLibrary.js.map | 1 - dist-cjs/src/ui/web-ui/core/EventBus.js | 359 - dist-cjs/src/ui/web-ui/core/EventBus.js.map | 1 - .../src/ui/web-ui/core/MCPIntegrationLayer.js | 948 --- .../ui/web-ui/core/MCPIntegrationLayer.js.map | 1 - dist-cjs/src/ui/web-ui/core/StateManager.js | 356 - .../src/ui/web-ui/core/StateManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/UIManager.js | 419 - dist-cjs/src/ui/web-ui/core/UIManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/ViewManager.js | 449 -- .../src/ui/web-ui/core/ViewManager.js.map | 1 - dist-cjs/src/ui/web-ui/index.js | 242 - dist-cjs/src/ui/web-ui/index.js.map | 1 - dist-cjs/src/ui/web-ui/neural-panel-test.js | 326 - .../src/ui/web-ui/neural-panel-test.js.map | 1 - dist-cjs/src/ui/web-ui/test-github-view.js | 64 - .../src/ui/web-ui/test-github-view.js.map | 1 - dist-cjs/src/ui/web-ui/views/DAAView.js | 1593 ---- dist-cjs/src/ui/web-ui/views/DAAView.js.map | 1 - .../ui/web-ui/views/GitHubIntegrationTest.js | 182 - .../web-ui/views/GitHubIntegrationTest.js.map | 1 - .../ui/web-ui/views/GitHubIntegrationView.js | 1356 ---- .../web-ui/views/GitHubIntegrationView.js.map | 1 - .../src/ui/web-ui/views/NeuralNetworkView.js | 795 -- .../ui/web-ui/views/NeuralNetworkView.js.map | 1 - .../ui/web-ui/views/WorkflowAutomationView.js | 1346 ---- .../views/WorkflowAutomationView.js.map | 1 - dist-cjs/src/utils/metrics-reader.js | 76 +- src/ui/console/README-analysis-tools.md | 389 - src/ui/console/README.md | 256 - src/ui/console/WORKFLOW_DESIGNER_README.md | 603 -- src/ui/console/analysis-tools.html | 316 - src/ui/console/analytics.html | 376 - src/ui/console/index.html | 258 - src/ui/console/js/analysis-tools.js | 1054 --- src/ui/console/js/command-handler.js | 853 -- src/ui/console/js/console.js | 669 -- src/ui/console/js/daa-tools.js | 1035 --- src/ui/console/js/memory-interface.js | 961 --- src/ui/console/js/memory-test.js | 247 - src/ui/console/js/memory-tools.js | 1512 ---- src/ui/console/js/real-time-dashboard.js | 715 -- src/ui/console/js/settings.js | 592 -- src/ui/console/js/swarm-integration.js | 485 -- src/ui/console/js/swarm-visualizer.js | 879 --- src/ui/console/js/terminal-emulator.js | 683 -- src/ui/console/js/websocket-client.js | 480 -- src/ui/console/js/workflow-designer.js | 1400 ---- src/ui/console/neural-networks-demo.md | 252 - src/ui/console/styles/analysis-tools.css | 938 --- src/ui/console/styles/console.css | 620 -- src/ui/console/styles/daa-tools.css | 601 -- src/ui/console/styles/responsive.css | 468 -- src/ui/console/styles/settings.css | 433 - src/ui/console/styles/swarm-visualizer.css | 487 -- src/ui/console/styles/workflow-designer.css | 1095 --- src/ui/console/test-neural-networks.js | 314 - src/ui/console/test-neural.html | 220 - src/ui/console/workflow-designer-demo.html | 530 -- src/ui/hive-dashboard.ts | 395 - src/ui/web-ui/EnhancedProcessUI.js | 1772 ----- src/ui/web-ui/EnhancedWebUI.js | 566 -- src/ui/web-ui/README.md | 308 - src/ui/web-ui/components/ComponentLibrary.js | 1054 --- src/ui/web-ui/core/EventBus.js | 514 -- src/ui/web-ui/core/MCPIntegrationLayer.js | 715 -- src/ui/web-ui/core/StateManager.js | 515 -- src/ui/web-ui/core/UIManager.js | 540 -- src/ui/web-ui/core/ViewManager.js | 617 -- src/ui/web-ui/index.js | 292 - src/ui/web-ui/neural-panel-test.js | 463 -- src/ui/web-ui/test-github-view.js | 83 - src/ui/web-ui/test-neural-panel.html | 228 - src/ui/web-ui/views/DAAView.js | 1809 ----- src/ui/web-ui/views/GitHubIntegrationTest.js | 197 - src/ui/web-ui/views/GitHubIntegrationView.js | 1532 ---- src/ui/web-ui/views/NeuralNetworkView.js | 919 --- src/ui/web-ui/views/WorkflowAutomationView.js | 1515 ---- 127 files changed, 4230 insertions(+), 58868 deletions(-) create mode 100644 .claude/checkpoints/1758909460.json create mode 100644 .claude/checkpoints/1758909461.json create mode 100644 .claude/checkpoints/summary-session-20250926-175950.md delete mode 100644 dist-cjs/src/ui/console/js/analysis-tools.js delete mode 100644 dist-cjs/src/ui/console/js/analysis-tools.js.map delete mode 100644 dist-cjs/src/ui/console/js/command-handler.js delete mode 100644 dist-cjs/src/ui/console/js/command-handler.js.map delete mode 100644 dist-cjs/src/ui/console/js/console.js delete mode 100644 dist-cjs/src/ui/console/js/console.js.map delete mode 100644 dist-cjs/src/ui/console/js/daa-tools.js delete mode 100644 dist-cjs/src/ui/console/js/daa-tools.js.map delete mode 100644 dist-cjs/src/ui/console/js/memory-interface.js delete mode 100644 dist-cjs/src/ui/console/js/memory-interface.js.map delete mode 100644 dist-cjs/src/ui/console/js/memory-test.js delete mode 100644 dist-cjs/src/ui/console/js/memory-test.js.map delete mode 100644 dist-cjs/src/ui/console/js/memory-tools.js delete mode 100644 dist-cjs/src/ui/console/js/memory-tools.js.map delete mode 100644 dist-cjs/src/ui/console/js/real-time-dashboard.js delete mode 100644 dist-cjs/src/ui/console/js/real-time-dashboard.js.map delete mode 100644 dist-cjs/src/ui/console/js/settings.js delete mode 100644 dist-cjs/src/ui/console/js/settings.js.map delete mode 100644 dist-cjs/src/ui/console/js/swarm-integration.js delete mode 100644 dist-cjs/src/ui/console/js/swarm-integration.js.map delete mode 100644 dist-cjs/src/ui/console/js/swarm-visualizer.js delete mode 100644 dist-cjs/src/ui/console/js/swarm-visualizer.js.map delete mode 100644 dist-cjs/src/ui/console/js/terminal-emulator.js delete mode 100644 dist-cjs/src/ui/console/js/terminal-emulator.js.map delete mode 100644 dist-cjs/src/ui/console/js/websocket-client.js delete mode 100644 dist-cjs/src/ui/console/js/websocket-client.js.map delete mode 100644 dist-cjs/src/ui/console/js/workflow-designer.js delete mode 100644 dist-cjs/src/ui/console/js/workflow-designer.js.map delete mode 100644 dist-cjs/src/ui/console/test-neural-networks.js delete mode 100644 dist-cjs/src/ui/console/test-neural-networks.js.map delete mode 100644 dist-cjs/src/ui/hive-dashboard.js delete mode 100644 dist-cjs/src/ui/hive-dashboard.js.map delete mode 100644 dist-cjs/src/ui/web-ui/EnhancedProcessUI.js delete mode 100644 dist-cjs/src/ui/web-ui/EnhancedProcessUI.js.map delete mode 100644 dist-cjs/src/ui/web-ui/EnhancedWebUI.js delete mode 100644 dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map delete mode 100644 dist-cjs/src/ui/web-ui/components/ComponentLibrary.js delete mode 100644 dist-cjs/src/ui/web-ui/components/ComponentLibrary.js.map delete mode 100644 dist-cjs/src/ui/web-ui/core/EventBus.js delete mode 100644 dist-cjs/src/ui/web-ui/core/EventBus.js.map delete mode 100644 dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js delete mode 100644 dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js.map delete mode 100644 dist-cjs/src/ui/web-ui/core/StateManager.js delete mode 100644 dist-cjs/src/ui/web-ui/core/StateManager.js.map delete mode 100644 dist-cjs/src/ui/web-ui/core/UIManager.js delete mode 100644 dist-cjs/src/ui/web-ui/core/UIManager.js.map delete mode 100644 dist-cjs/src/ui/web-ui/core/ViewManager.js delete mode 100644 dist-cjs/src/ui/web-ui/core/ViewManager.js.map delete mode 100644 dist-cjs/src/ui/web-ui/index.js delete mode 100644 dist-cjs/src/ui/web-ui/index.js.map delete mode 100644 dist-cjs/src/ui/web-ui/neural-panel-test.js delete mode 100644 dist-cjs/src/ui/web-ui/neural-panel-test.js.map delete mode 100644 dist-cjs/src/ui/web-ui/test-github-view.js delete mode 100644 dist-cjs/src/ui/web-ui/test-github-view.js.map delete mode 100644 dist-cjs/src/ui/web-ui/views/DAAView.js delete mode 100644 dist-cjs/src/ui/web-ui/views/DAAView.js.map delete mode 100644 dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js delete mode 100644 dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js.map delete mode 100644 dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js delete mode 100644 dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js.map delete mode 100644 dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js delete mode 100644 dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js.map delete mode 100644 dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js delete mode 100644 dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js.map delete mode 100644 src/ui/console/README-analysis-tools.md delete mode 100644 src/ui/console/README.md delete mode 100644 src/ui/console/WORKFLOW_DESIGNER_README.md delete mode 100644 src/ui/console/analysis-tools.html delete mode 100644 src/ui/console/analytics.html delete mode 100644 src/ui/console/index.html delete mode 100644 src/ui/console/js/analysis-tools.js delete mode 100644 src/ui/console/js/command-handler.js delete mode 100644 src/ui/console/js/console.js delete mode 100644 src/ui/console/js/daa-tools.js delete mode 100644 src/ui/console/js/memory-interface.js delete mode 100644 src/ui/console/js/memory-test.js delete mode 100644 src/ui/console/js/memory-tools.js delete mode 100644 src/ui/console/js/real-time-dashboard.js delete mode 100644 src/ui/console/js/settings.js delete mode 100644 src/ui/console/js/swarm-integration.js delete mode 100644 src/ui/console/js/swarm-visualizer.js delete mode 100644 src/ui/console/js/terminal-emulator.js delete mode 100644 src/ui/console/js/websocket-client.js delete mode 100644 src/ui/console/js/workflow-designer.js delete mode 100644 src/ui/console/neural-networks-demo.md delete mode 100644 src/ui/console/styles/analysis-tools.css delete mode 100644 src/ui/console/styles/console.css delete mode 100644 src/ui/console/styles/daa-tools.css delete mode 100644 src/ui/console/styles/responsive.css delete mode 100644 src/ui/console/styles/settings.css delete mode 100644 src/ui/console/styles/swarm-visualizer.css delete mode 100644 src/ui/console/styles/workflow-designer.css delete mode 100644 src/ui/console/test-neural-networks.js delete mode 100644 src/ui/console/test-neural.html delete mode 100644 src/ui/console/workflow-designer-demo.html delete mode 100644 src/ui/hive-dashboard.ts delete mode 100644 src/ui/web-ui/EnhancedProcessUI.js delete mode 100644 src/ui/web-ui/EnhancedWebUI.js delete mode 100644 src/ui/web-ui/README.md delete mode 100644 src/ui/web-ui/components/ComponentLibrary.js delete mode 100644 src/ui/web-ui/core/EventBus.js delete mode 100644 src/ui/web-ui/core/MCPIntegrationLayer.js delete mode 100644 src/ui/web-ui/core/StateManager.js delete mode 100644 src/ui/web-ui/core/UIManager.js delete mode 100644 src/ui/web-ui/core/ViewManager.js delete mode 100644 src/ui/web-ui/index.js delete mode 100644 src/ui/web-ui/neural-panel-test.js delete mode 100644 src/ui/web-ui/test-github-view.js delete mode 100644 src/ui/web-ui/test-neural-panel.html delete mode 100644 src/ui/web-ui/views/DAAView.js delete mode 100644 src/ui/web-ui/views/GitHubIntegrationTest.js delete mode 100644 src/ui/web-ui/views/GitHubIntegrationView.js delete mode 100644 src/ui/web-ui/views/NeuralNetworkView.js delete mode 100644 src/ui/web-ui/views/WorkflowAutomationView.js diff --git a/.claude-flow/metrics/performance.json b/.claude-flow/metrics/performance.json index 3490c15482..9a7f536782 100644 --- a/.claude-flow/metrics/performance.json +++ b/.claude-flow/metrics/performance.json @@ -1,5 +1,5 @@ { - "startTime": 1758909300011, + "startTime": 1758909566305, "totalTasks": 1, "successfulTasks": 1, "failedTasks": 0, diff --git a/.claude-flow/metrics/system-metrics.json b/.claude-flow/metrics/system-metrics.json index 2d06bfa0cf..0a934537f7 100644 --- a/.claude-flow/metrics/system-metrics.json +++ b/.claude-flow/metrics/system-metrics.json @@ -1,4010 +1,4190 @@ [ { - "timestamp": 1758899339932, + "timestamp": 1758899141868, "memoryTotal": 67427545088, - "memoryUsed": 6693584896, - "memoryFree": 60733960192, - "memoryUsagePercent": 9.92707785410869, - "memoryEfficiency": 90.07292214589131, + "memoryUsed": 6895316992, + "memoryFree": 60532228096, + "memoryUsagePercent": 10.226261363958736, + "memoryEfficiency": 89.77373863604126, "cpuCount": 16, - "cpuLoad": 0.016875, + "cpuLoad": 0.090625, "platform": "linux", - "uptime": 3068.06 + "uptime": 2870 }, { - "timestamp": 1758899369956, + "timestamp": 1758899171873, "memoryTotal": 67427545088, - "memoryUsed": 6716530688, - "memoryFree": 60711014400, - "memoryUsagePercent": 9.961108148360175, - "memoryEfficiency": 90.03889185163982, + "memoryUsed": 6584094720, + "memoryFree": 60843450368, + "memoryUsagePercent": 9.76469588416287, + "memoryEfficiency": 90.23530411583712, "cpuCount": 16, - "cpuLoad": 0.01375, + "cpuLoad": 0.059375, "platform": "linux", - "uptime": 3098.09 + "uptime": 2900 }, { - "timestamp": 1758899399980, + "timestamp": 1758899201902, "memoryTotal": 67427545088, - "memoryUsed": 8532135936, - "memoryFree": 58895409152, - "memoryUsagePercent": 12.65378403568552, - "memoryEfficiency": 87.34621596431448, + "memoryUsed": 6784204800, + "memoryFree": 60643340288, + "memoryUsagePercent": 10.061473825193996, + "memoryEfficiency": 89.938526174806, "cpuCount": 16, - "cpuLoad": 0.070625, + "cpuLoad": 0.039375, "platform": "linux", - "uptime": 3128.11 + "uptime": 2930.03 }, { - "timestamp": 1758899430009, + "timestamp": 1758899231933, "memoryTotal": 67427545088, - "memoryUsed": 6917201920, - "memoryFree": 60510343168, - "memoryUsagePercent": 10.258718319007947, - "memoryEfficiency": 89.74128168099205, + "memoryUsed": 6719586304, + "memoryFree": 60707958784, + "memoryUsagePercent": 9.965639851236222, + "memoryEfficiency": 90.03436014876378, "cpuCount": 16, - "cpuLoad": 0.081875, + "cpuLoad": 0.028125, "platform": "linux", - "uptime": 3158.14 + "uptime": 2960.06 }, { - "timestamp": 1758899460027, + "timestamp": 1758899261941, "memoryTotal": 67427545088, - "memoryUsed": 6968836096, - "memoryFree": 60458708992, - "memoryUsagePercent": 10.335295593076895, - "memoryEfficiency": 89.66470440692311, + "memoryUsed": 6355832832, + "memoryFree": 61071712256, + "memoryUsagePercent": 9.426166744918524, + "memoryEfficiency": 90.57383325508148, "cpuCount": 16, - "cpuLoad": 0.10375, + "cpuLoad": 0.025625, "platform": "linux", - "uptime": 3188.16 + "uptime": 2990.07 }, { - "timestamp": 1758899490036, + "timestamp": 1758899291972, "memoryTotal": 67427545088, - "memoryUsed": 7030255616, - "memoryFree": 60397289472, - "memoryUsagePercent": 10.42638525075291, - "memoryEfficiency": 89.57361474924708, + "memoryUsed": 6361497600, + "memoryFree": 61066047488, + "memoryUsagePercent": 9.43456801177854, + "memoryEfficiency": 90.56543198822146, "cpuCount": 16, - "cpuLoad": 0.1125, + "cpuLoad": 0.019375, "platform": "linux", - "uptime": 3218.17 + "uptime": 3020.1 }, { - "timestamp": 1758899520066, + "timestamp": 1758899322003, "memoryTotal": 67427545088, - "memoryUsed": 6888259584, - "memoryFree": 60539285504, - "memoryUsagePercent": 10.21579470972894, - "memoryEfficiency": 89.78420529027106, + "memoryUsed": 6952374272, + "memoryFree": 60475170816, + "memoryUsagePercent": 10.310881499432352, + "memoryEfficiency": 89.68911850056764, "cpuCount": 16, - "cpuLoad": 0.106875, + "cpuLoad": 0.02375, "platform": "linux", - "uptime": 3248.2 + "uptime": 3050.13 }, { - "timestamp": 1758899550096, + "timestamp": 1758899352033, "memoryTotal": 67427545088, - "memoryUsed": 6906724352, - "memoryFree": 60520820736, - "memoryUsagePercent": 10.243179316384724, - "memoryEfficiency": 89.75682068361527, + "memoryUsed": 6706225152, + "memoryFree": 60721319936, + "memoryUsagePercent": 9.945824281823807, + "memoryEfficiency": 90.0541757181762, "cpuCount": 16, - "cpuLoad": 0.093125, + "cpuLoad": 0.019375, "platform": "linux", - "uptime": 3278.23 + "uptime": 3080.16 }, { - "timestamp": 1758899580127, + "timestamp": 1758899382035, "memoryTotal": 67427545088, - "memoryUsed": 6844674048, - "memoryFree": 60582871040, - "memoryUsagePercent": 10.151154159723573, - "memoryEfficiency": 89.84884584027643, + "memoryUsed": 6974881792, + "memoryFree": 60452663296, + "memoryUsagePercent": 10.344261804129232, + "memoryEfficiency": 89.65573819587077, "cpuCount": 16, - "cpuLoad": 0.068125, + "cpuLoad": 0.03625, "platform": "linux", - "uptime": 3308.26 + "uptime": 3110.16 }, { - "timestamp": 1758899610129, + "timestamp": 1758899412064, "memoryTotal": 67427545088, - "memoryUsed": 6899515392, - "memoryFree": 60528029696, - "memoryUsagePercent": 10.232487899411748, - "memoryEfficiency": 89.76751210058825, - "cpuCount": 16, - "cpuLoad": 0.089375, - "platform": "linux", - "uptime": 3338.26 - }, - { - "timestamp": 1758899640144, - "memoryTotal": 67427545088, - "memoryUsed": 6945640448, - "memoryFree": 60481904640, - "memoryUsagePercent": 10.300894744032595, - "memoryEfficiency": 89.69910525596741, - "cpuCount": 16, - "cpuLoad": 0.0625, - "platform": "linux", - "uptime": 3368.27 - }, - { - "timestamp": 1758899670173, - "memoryTotal": 67427545088, - "memoryUsed": 7081402368, - "memoryFree": 60346142720, - "memoryUsagePercent": 10.502239639242433, - "memoryEfficiency": 89.49776036075757, - "cpuCount": 16, - "cpuLoad": 0.065, - "platform": "linux", - "uptime": 3398.3 - }, - { - "timestamp": 1758899700189, - "memoryTotal": 67427545088, - "memoryUsed": 7157092352, - "memoryFree": 60270452736, - "memoryUsagePercent": 10.614493442789955, - "memoryEfficiency": 89.38550655721005, - "cpuCount": 16, - "cpuLoad": 0.063125, - "platform": "linux", - "uptime": 3428.32 - }, - { - "timestamp": 1758899730219, - "memoryTotal": 67427545088, - "memoryUsed": 7631958016, - "memoryFree": 59795587072, - "memoryUsagePercent": 11.318754087872392, - "memoryEfficiency": 88.68124591212761, - "cpuCount": 16, - "cpuLoad": 0.05625, - "platform": "linux", - "uptime": 3458.35 - }, - { - "timestamp": 1758899760221, - "memoryTotal": 67427545088, - "memoryUsed": 7142342656, - "memoryFree": 60285202432, - "memoryUsagePercent": 10.592618560676495, - "memoryEfficiency": 89.4073814393235, - "cpuCount": 16, - "cpuLoad": 0.09375, - "platform": "linux", - "uptime": 3488.35 - }, - { - "timestamp": 1758899790250, - "memoryTotal": 67427545088, - "memoryUsed": 7126069248, - "memoryFree": 60301475840, - "memoryUsagePercent": 10.568483901793746, - "memoryEfficiency": 89.43151609820626, - "cpuCount": 16, - "cpuLoad": 0.094375, - "platform": "linux", - "uptime": 3518.38 - }, - { - "timestamp": 1758899820261, - "memoryTotal": 67427545088, - "memoryUsed": 7102099456, - "memoryFree": 60325445632, - "memoryUsagePercent": 10.532934940358599, - "memoryEfficiency": 89.4670650596414, - "cpuCount": 16, - "cpuLoad": 0.06625, - "platform": "linux", - "uptime": 3548.39 - }, - { - "timestamp": 1758899850290, - "memoryTotal": 67427545088, - "memoryUsed": 7626178560, - "memoryFree": 59801366528, - "memoryUsagePercent": 11.310182730287806, - "memoryEfficiency": 88.6898172697122, - "cpuCount": 16, - "cpuLoad": 0.083125, - "platform": "linux", - "uptime": 3578.42 - }, - { - "timestamp": 1758899880317, - "memoryTotal": 67427545088, - "memoryUsed": 7029112832, - "memoryFree": 60398432256, - "memoryUsagePercent": 10.424690418175944, - "memoryEfficiency": 89.57530958182406, + "memoryUsed": 6918488064, + "memoryFree": 60509057024, + "memoryUsagePercent": 10.260625764990628, + "memoryEfficiency": 89.73937423500936, "cpuCount": 16, "cpuLoad": 0.069375, "platform": "linux", - "uptime": 3608.45 + "uptime": 3140.19 }, { - "timestamp": 1758899910346, + "timestamp": 1758899442092, "memoryTotal": 67427545088, - "memoryUsed": 7151706112, - "memoryFree": 60275838976, - "memoryUsagePercent": 10.606505253403894, - "memoryEfficiency": 89.3934947465961, + "memoryUsed": 6908190720, + "memoryFree": 60519354368, + "memoryUsagePercent": 10.245354047791727, + "memoryEfficiency": 89.75464595220828, "cpuCount": 16, - "cpuLoad": 0.078125, + "cpuLoad": 0.06875, "platform": "linux", - "uptime": 3638.48 + "uptime": 3170.22 }, { - "timestamp": 1758899940377, + "timestamp": 1758899472122, "memoryTotal": 67427545088, - "memoryUsed": 7258664960, - "memoryFree": 60168880128, - "memoryUsagePercent": 10.765133078071704, - "memoryEfficiency": 89.2348669219283, - "cpuCount": 16, - "cpuLoad": 0.07, - "platform": "linux", - "uptime": 3668.51 - }, - { - "timestamp": 1758899970406, - "memoryTotal": 67427545088, - "memoryUsed": 7196332032, - "memoryFree": 60231213056, - "memoryUsagePercent": 10.672688769267861, - "memoryEfficiency": 89.32731123073214, - "cpuCount": 16, - "cpuLoad": 0.070625, - "platform": "linux", - "uptime": 3698.54 - }, - { - "timestamp": 1758900000436, - "memoryTotal": 67427545088, - "memoryUsed": 7416778752, - "memoryFree": 60010766336, - "memoryUsagePercent": 10.999627440566504, - "memoryEfficiency": 89.0003725594335, - "cpuCount": 16, - "cpuLoad": 0.09375, - "platform": "linux", - "uptime": 3728.57 - }, - { - "timestamp": 1758900030437, - "memoryTotal": 67427545088, - "memoryUsed": 7174213632, - "memoryFree": 60253331456, - "memoryUsagePercent": 10.639885558100774, - "memoryEfficiency": 89.36011444189923, - "cpuCount": 16, - "cpuLoad": 0.098125, - "platform": "linux", - "uptime": 3758.57 - }, - { - "timestamp": 1758900060468, - "memoryTotal": 67427545088, - "memoryUsed": 7312228352, - "memoryFree": 60115316736, - "memoryUsagePercent": 10.844571521114668, - "memoryEfficiency": 89.15542847888533, - "cpuCount": 16, - "cpuLoad": 0.084375, - "platform": "linux", - "uptime": 3788.6 - }, - { - "timestamp": 1758900090470, - "memoryTotal": 67427545088, - "memoryUsed": 7191527424, - "memoryFree": 60236017664, - "memoryUsagePercent": 10.665563182842122, - "memoryEfficiency": 89.33443681715788, - "cpuCount": 16, - "cpuLoad": 0.10125, - "platform": "linux", - "uptime": 3818.6 - }, - { - "timestamp": 1758900120500, - "memoryTotal": 67427545088, - "memoryUsed": 7450796032, - "memoryFree": 59976749056, - "memoryUsagePercent": 11.050077564407738, - "memoryEfficiency": 88.94992243559226, - "cpuCount": 16, - "cpuLoad": 0.09, - "platform": "linux", - "uptime": 3848.63 - }, - { - "timestamp": 1758900150530, - "memoryTotal": 67427545088, - "memoryUsed": 7204007936, - "memoryFree": 60223537152, - "memoryUsagePercent": 10.684072698476589, - "memoryEfficiency": 89.31592730152342, - "cpuCount": 16, - "cpuLoad": 0.084375, - "platform": "linux", - "uptime": 3878.66 - }, - { - "timestamp": 1758900180561, - "memoryTotal": 67427545088, - "memoryUsed": 7198232576, - "memoryFree": 60229312512, - "memoryUsagePercent": 10.675507415560737, - "memoryEfficiency": 89.32449258443927, - "cpuCount": 16, - "cpuLoad": 0.060625, - "platform": "linux", - "uptime": 3908.69 - }, - { - "timestamp": 1758900210591, - "memoryTotal": 67427545088, - "memoryUsed": 7432425472, - "memoryFree": 59995119616, - "memoryUsagePercent": 11.022832675132852, - "memoryEfficiency": 88.97716732486715, - "cpuCount": 16, - "cpuLoad": 0.1075, - "platform": "linux", - "uptime": 3938.72 - }, - { - "timestamp": 1758900240621, - "memoryTotal": 67427545088, - "memoryUsed": 7221108736, - "memoryFree": 60206436352, - "memoryUsagePercent": 10.709434440443735, - "memoryEfficiency": 89.29056555955627, - "cpuCount": 16, - "cpuLoad": 0.079375, - "platform": "linux", - "uptime": 3968.75 - }, - { - "timestamp": 1758900270651, - "memoryTotal": 67427545088, - "memoryUsed": 7222263808, - "memoryFree": 60205281280, - "memoryUsagePercent": 10.711147497026905, - "memoryEfficiency": 89.2888525029731, - "cpuCount": 16, - "cpuLoad": 0.0825, - "platform": "linux", - "uptime": 3998.78 - }, - { - "timestamp": 1758900300670, - "memoryTotal": 67427545088, - "memoryUsed": 7300214784, - "memoryFree": 60127330304, - "memoryUsagePercent": 10.826754517715951, - "memoryEfficiency": 89.17324548228405, + "memoryUsed": 7423680512, + "memoryFree": 60003864576, + "memoryUsagePercent": 11.009863257384382, + "memoryEfficiency": 88.99013674261562, "cpuCount": 16, "cpuLoad": 0.101875, "platform": "linux", - "uptime": 4028.8 + "uptime": 3200.25 }, { - "timestamp": 1758900330701, + "timestamp": 1758899502128, "memoryTotal": 67427545088, - "memoryUsed": 7315038208, - "memoryFree": 60112506880, - "memoryUsagePercent": 10.848738743866635, - "memoryEfficiency": 89.15126125613337, + "memoryUsed": 6904619008, + "memoryFree": 60522926080, + "memoryUsagePercent": 10.240056936655115, + "memoryEfficiency": 89.75994306334488, "cpuCount": 16, - "cpuLoad": 0.081875, + "cpuLoad": 0.11, "platform": "linux", - "uptime": 4058.83 + "uptime": 3230.26 }, { - "timestamp": 1758900360730, + "timestamp": 1758899532157, "memoryTotal": 67427545088, - "memoryUsed": 7301353472, - "memoryFree": 60126191616, - "memoryUsagePercent": 10.828443275624183, - "memoryEfficiency": 89.17155672437582, + "memoryUsed": 6909542400, + "memoryFree": 60518002688, + "memoryUsagePercent": 10.24735868847416, + "memoryEfficiency": 89.75264131152584, "cpuCount": 16, - "cpuLoad": 0.064375, + "cpuLoad": 0.090625, "platform": "linux", - "uptime": 4088.86 + "uptime": 3260.29 }, { - "timestamp": 1758900390743, + "timestamp": 1758899562174, "memoryTotal": 67427545088, - "memoryUsed": 7354961920, - "memoryFree": 60072583168, - "memoryUsagePercent": 10.907948540023229, - "memoryEfficiency": 89.09205145997677, + "memoryUsed": 6679261184, + "memoryFree": 60748283904, + "memoryUsagePercent": 9.905834737543634, + "memoryEfficiency": 90.09416526245637, "cpuCount": 16, - "cpuLoad": 0.085, + "cpuLoad": 0.083125, "platform": "linux", - "uptime": 4118.87 + "uptime": 3290.3 }, { - "timestamp": 1758900420744, + "timestamp": 1758899592205, "memoryTotal": 67427545088, - "memoryUsed": 7228264448, - "memoryFree": 60199280640, - "memoryUsagePercent": 10.72004688672316, - "memoryEfficiency": 89.27995311327683, + "memoryUsed": 6878601216, + "memoryFree": 60548943872, + "memoryUsagePercent": 10.201470640852646, + "memoryEfficiency": 89.79852935914735, "cpuCount": 16, - "cpuLoad": 0.086875, + "cpuLoad": 0.080625, "platform": "linux", - "uptime": 4148.87 + "uptime": 3320.33 }, { - "timestamp": 1758900450761, + "timestamp": 1758899622235, "memoryTotal": 67427545088, - "memoryUsed": 7174144000, - "memoryFree": 60253401088, - "memoryUsagePercent": 10.639782288732286, - "memoryEfficiency": 89.36021771126771, + "memoryUsed": 6963695616, + "memoryFree": 60463849472, + "memoryUsagePercent": 10.327671883814913, + "memoryEfficiency": 89.67232811618508, "cpuCount": 16, - "cpuLoad": 0.07, + "cpuLoad": 0.080625, "platform": "linux", - "uptime": 4178.89 + "uptime": 3350.36 }, { - "timestamp": 1758900480792, + "timestamp": 1758899652266, "memoryTotal": 67427545088, - "memoryUsed": 7280177152, - "memoryFree": 60147367936, - "memoryUsagePercent": 10.797037238266064, - "memoryEfficiency": 89.20296276173394, + "memoryUsed": 6967291904, + "memoryFree": 60460253184, + "memoryUsagePercent": 10.333005442963932, + "memoryEfficiency": 89.66699455703606, "cpuCount": 16, - "cpuLoad": 0.05, + "cpuLoad": 0.0525, "platform": "linux", - "uptime": 4208.92 + "uptime": 3380.4 }, { - "timestamp": 1758900510821, + "timestamp": 1758899682295, "memoryTotal": 67427545088, - "memoryUsed": 7383949312, - "memoryFree": 60043595776, - "memoryUsagePercent": 10.950938970658317, - "memoryEfficiency": 89.04906102934169, + "memoryUsed": 7144808448, + "memoryFree": 60282736640, + "memoryUsagePercent": 10.596275511254753, + "memoryEfficiency": 89.40372448874524, "cpuCount": 16, - "cpuLoad": 0.078125, + "cpuLoad": 0.069375, "platform": "linux", - "uptime": 4238.95 + "uptime": 3410.43 }, { - "timestamp": 1758900540822, + "timestamp": 1758899712325, "memoryTotal": 67427545088, - "memoryUsed": 7233978368, - "memoryFree": 60193566720, - "memoryUsagePercent": 10.728521049607991, - "memoryEfficiency": 89.27147895039201, + "memoryUsed": 6935228416, + "memoryFree": 60492316672, + "memoryUsagePercent": 10.285452936109126, + "memoryEfficiency": 89.71454706389088, + "cpuCount": 16, + "cpuLoad": 0.058125, + "platform": "linux", + "uptime": 3440.46 + }, + { + "timestamp": 1758899742355, + "memoryTotal": 67427545088, + "memoryUsed": 7159537664, + "memoryFree": 60268007424, + "memoryUsagePercent": 10.618120020024538, + "memoryEfficiency": 89.38187997997547, + "cpuCount": 16, + "cpuLoad": 0.0525, + "platform": "linux", + "uptime": 3470.48 + }, + { + "timestamp": 1758899772385, + "memoryTotal": 67427545088, + "memoryUsed": 7378903040, + "memoryFree": 60048642048, + "memoryUsagePercent": 10.943454978777234, + "memoryEfficiency": 89.05654502122276, + "cpuCount": 16, + "cpuLoad": 0.079375, + "platform": "linux", + "uptime": 3500.52 + }, + { + "timestamp": 1758899802402, + "memoryTotal": 67427545088, + "memoryUsed": 7117160448, + "memoryFree": 60310384640, + "memoryUsagePercent": 10.555271497295891, + "memoryEfficiency": 89.44472850270411, "cpuCount": 16, "cpuLoad": 0.08, "platform": "linux", - "uptime": 4268.95 + "uptime": 3530.53 }, { - "timestamp": 1758900570851, + "timestamp": 1758899832416, "memoryTotal": 67427545088, - "memoryUsed": 7341731840, - "memoryFree": 60085813248, - "memoryUsagePercent": 10.888327360010322, - "memoryEfficiency": 89.11167263998968, + "memoryUsed": 7062417408, + "memoryFree": 60365127680, + "memoryUsagePercent": 10.47408354965735, + "memoryEfficiency": 89.52591645034265, "cpuCount": 16, - "cpuLoad": 0.0775, + "cpuLoad": 0.08, "platform": "linux", - "uptime": 4298.98 + "uptime": 3560.55 }, { - "timestamp": 1758900600861, + "timestamp": 1758899862445, "memoryTotal": 67427545088, - "memoryUsed": 7351984128, - "memoryFree": 60075560960, - "memoryUsagePercent": 10.90353225585314, - "memoryEfficiency": 89.09646774414686, + "memoryUsed": 7130001408, + "memoryFree": 60297543680, + "memoryUsagePercent": 10.574315583779006, + "memoryEfficiency": 89.42568441622099, "cpuCount": 16, - "cpuLoad": 0.061875, + "cpuLoad": 0.085625, "platform": "linux", - "uptime": 4328.99 + "uptime": 3590.58 }, { - "timestamp": 1758900630891, + "timestamp": 1758899892475, "memoryTotal": 67427545088, - "memoryUsed": 7273558016, - "memoryFree": 60153987072, - "memoryUsagePercent": 10.787220573590876, - "memoryEfficiency": 89.21277942640913, - "cpuCount": 16, - "cpuLoad": 0.075, - "platform": "linux", - "uptime": 4359.02 - }, - { - "timestamp": 1758900660895, - "memoryTotal": 67427545088, - "memoryUsed": 7400284160, - "memoryFree": 60027260928, - "memoryUsagePercent": 10.975164749572084, - "memoryEfficiency": 89.02483525042791, + "memoryUsed": 7121948672, + "memoryFree": 60305596416, + "memoryUsagePercent": 10.562372785046692, + "memoryEfficiency": 89.43762721495331, "cpuCount": 16, "cpuLoad": 0.078125, "platform": "linux", - "uptime": 4389.02 + "uptime": 3620.6 }, { - "timestamp": 1758900690924, + "timestamp": 1758899922505, "memoryTotal": 67427545088, - "memoryUsed": 7313690624, - "memoryFree": 60113854464, - "memoryUsagePercent": 10.846740177852936, - "memoryEfficiency": 89.15325982214706, + "memoryUsed": 7138357248, + "memoryFree": 60289187840, + "memoryUsagePercent": 10.586707907997685, + "memoryEfficiency": 89.41329209200231, "cpuCount": 16, - "cpuLoad": 0.073125, + "cpuLoad": 0.06625, "platform": "linux", - "uptime": 4419.05 + "uptime": 3650.63 }, { - "timestamp": 1758900720947, + "timestamp": 1758899952525, "memoryTotal": 67427545088, - "memoryUsed": 7363432448, - "memoryFree": 60064112640, - "memoryUsagePercent": 10.920510954966476, - "memoryEfficiency": 89.07948904503353, + "memoryUsed": 7228649472, + "memoryFree": 60198895616, + "memoryUsagePercent": 10.720617905584218, + "memoryEfficiency": 89.27938209441578, "cpuCount": 16, - "cpuLoad": 0.11375, + "cpuLoad": 0.06875, "platform": "linux", - "uptime": 4449.08 + "uptime": 3680.66 }, { - "timestamp": 1758900750976, + "timestamp": 1758899982556, "memoryTotal": 67427545088, - "memoryUsed": 7727050752, - "memoryFree": 59700494336, - "memoryUsagePercent": 11.45978359721593, - "memoryEfficiency": 88.54021640278407, + "memoryUsed": 7288492032, + "memoryFree": 60139053056, + "memoryUsagePercent": 10.809368815797395, + "memoryEfficiency": 89.1906311842026, "cpuCount": 16, - "cpuLoad": 0.115625, + "cpuLoad": 0.064375, "platform": "linux", - "uptime": 4479.11 + "uptime": 3710.69 }, { - "timestamp": 1758900781005, + "timestamp": 1758900012587, "memoryTotal": 67427545088, - "memoryUsed": 7706279936, - "memoryFree": 59721265152, - "memoryUsagePercent": 11.428978952062542, - "memoryEfficiency": 88.57102104793746, + "memoryUsed": 7207915520, + "memoryFree": 60219629568, + "memoryUsagePercent": 10.68986793244944, + "memoryEfficiency": 89.31013206755055, "cpuCount": 16, - "cpuLoad": 0.12125, + "cpuLoad": 0.089375, "platform": "linux", - "uptime": 4509.14 + "uptime": 3740.72 }, { - "timestamp": 1758900811036, + "timestamp": 1758900042618, "memoryTotal": 67427545088, - "memoryUsed": 7819726848, - "memoryFree": 59607818240, - "memoryUsagePercent": 11.597229052006028, - "memoryEfficiency": 88.40277094799397, + "memoryUsed": 7351656448, + "memoryFree": 60075888640, + "memoryUsagePercent": 10.903046282354369, + "memoryEfficiency": 89.09695371764563, "cpuCount": 16, - "cpuLoad": 0.123125, + "cpuLoad": 0.088125, "platform": "linux", - "uptime": 4539.17 + "uptime": 3770.75 }, { - "timestamp": 1758900841064, + "timestamp": 1758900072645, "memoryTotal": 67427545088, - "memoryUsed": 7278972928, - "memoryFree": 60148572160, - "memoryUsagePercent": 10.795251285658077, - "memoryEfficiency": 89.20474871434192, + "memoryUsed": 7298699264, + "memoryFree": 60128845824, + "memoryUsagePercent": 10.824506890284132, + "memoryEfficiency": 89.17549310971587, "cpuCount": 16, - "cpuLoad": 0.085, + "cpuLoad": 0.09625, "platform": "linux", - "uptime": 4569.19 + "uptime": 3800.78 }, { - "timestamp": 1758900871067, + "timestamp": 1758900102675, "memoryTotal": 67427545088, - "memoryUsed": 7207084032, - "memoryFree": 60220461056, - "memoryUsagePercent": 10.688634774696308, - "memoryEfficiency": 89.31136522530369, + "memoryUsed": 7265611776, + "memoryFree": 60161933312, + "memoryUsagePercent": 10.775435716245664, + "memoryEfficiency": 89.22456428375433, "cpuCount": 16, - "cpuLoad": 0.07, + "cpuLoad": 0.085625, "platform": "linux", - "uptime": 4599.2 + "uptime": 3830.8 }, { - "timestamp": 1758900901098, + "timestamp": 1758900132705, "memoryTotal": 67427545088, - "memoryUsed": 7315447808, - "memoryFree": 60112097280, - "memoryUsagePercent": 10.8493462107401, - "memoryEfficiency": 89.1506537892599, + "memoryUsed": 7643938816, + "memoryFree": 59783606272, + "memoryUsagePercent": 11.33652249392123, + "memoryEfficiency": 88.66347750607878, "cpuCount": 16, - "cpuLoad": 0.0825, + "cpuLoad": 0.08125, "platform": "linux", - "uptime": 4629.23 + "uptime": 3860.84 }, { - "timestamp": 1758900931129, + "timestamp": 1758900162730, "memoryTotal": 67427545088, - "memoryUsed": 7335469056, - "memoryFree": 60092076032, - "memoryUsagePercent": 10.879039191515048, - "memoryEfficiency": 89.12096080848495, - "cpuCount": 16, - "cpuLoad": 0.09125, - "platform": "linux", - "uptime": 4659.26 - }, - { - "timestamp": 1758900961159, - "memoryTotal": 67427545088, - "memoryUsed": 7219589120, - "memoryFree": 60207955968, - "memoryUsagePercent": 10.707180738343181, - "memoryEfficiency": 89.29281926165682, + "memoryUsed": 7197814784, + "memoryFree": 60229730304, + "memoryUsagePercent": 10.674887799349804, + "memoryEfficiency": 89.3251122006502, "cpuCount": 16, "cpuLoad": 0.07125, "platform": "linux", - "uptime": 4689.29 + "uptime": 3890.86 }, { - "timestamp": 1758900991189, + "timestamp": 1758900192760, "memoryTotal": 67427545088, - "memoryUsed": 7177990144, - "memoryFree": 60249554944, - "memoryUsagePercent": 10.645486402674118, - "memoryEfficiency": 89.35451359732588, + "memoryUsed": 7903059968, + "memoryFree": 59524485120, + "memoryUsagePercent": 11.7208181874124, + "memoryEfficiency": 88.2791818125876, "cpuCount": 16, - "cpuLoad": 0.0475, + "cpuLoad": 0.06625, "platform": "linux", - "uptime": 4719.32 + "uptime": 3920.89 }, { - "timestamp": 1758901021219, + "timestamp": 1758900222790, "memoryTotal": 67427545088, - "memoryUsed": 7192850432, - "memoryFree": 60234694656, - "memoryUsagePercent": 10.667525300843412, - "memoryEfficiency": 89.33247469915659, + "memoryUsed": 7410724864, + "memoryFree": 60016820224, + "memoryUsagePercent": 10.990649080176699, + "memoryEfficiency": 89.0093509198233, "cpuCount": 16, - "cpuLoad": 0.02875, + "cpuLoad": 0.090625, "platform": "linux", - "uptime": 4749.35 + "uptime": 3950.92 }, { - "timestamp": 1758901051220, + "timestamp": 1758900252822, "memoryTotal": 67427545088, - "memoryUsed": 7392653312, - "memoryFree": 60034891776, - "memoryUsagePercent": 10.96384764171944, - "memoryEfficiency": 89.03615235828056, + "memoryUsed": 7143788544, + "memoryFree": 60283756544, + "memoryUsagePercent": 10.594762918739825, + "memoryEfficiency": 89.40523708126017, "cpuCount": 16, - "cpuLoad": 0.04375, + "cpuLoad": 0.090625, "platform": "linux", - "uptime": 4779.35 + "uptime": 3980.95 }, { - "timestamp": 1758901081251, + "timestamp": 1758900282851, "memoryTotal": 67427545088, - "memoryUsed": 7361277952, - "memoryFree": 60066267136, - "memoryUsagePercent": 10.917315679212052, - "memoryEfficiency": 89.08268432078795, + "memoryUsed": 7298514944, + "memoryFree": 60129030144, + "memoryUsagePercent": 10.824233530191073, + "memoryEfficiency": 89.17576646980893, + "cpuCount": 16, + "cpuLoad": 0.074375, + "platform": "linux", + "uptime": 4010.98 + }, + { + "timestamp": 1758900312881, + "memoryTotal": 67427545088, + "memoryUsed": 7321755648, + "memoryFree": 60105789440, + "memoryUsagePercent": 10.858701200591454, + "memoryEfficiency": 89.14129879940855, + "cpuCount": 16, + "cpuLoad": 0.09625, + "platform": "linux", + "uptime": 4041.01 + }, + { + "timestamp": 1758900342912, + "memoryTotal": 67427545088, + "memoryUsed": 7247220736, + "memoryFree": 60180324352, + "memoryUsagePercent": 10.748160453627102, + "memoryEfficiency": 89.25183954637289, + "cpuCount": 16, + "cpuLoad": 0.069375, + "platform": "linux", + "uptime": 4071.04 + }, + { + "timestamp": 1758900372930, + "memoryTotal": 67427545088, + "memoryUsed": 7428329472, + "memoryFree": 59999215616, + "memoryUsagePercent": 11.016758006398206, + "memoryEfficiency": 88.9832419936018, "cpuCount": 16, "cpuLoad": 0.06375, "platform": "linux", - "uptime": 4809.38 + "uptime": 4101.06 }, { - "timestamp": 1758901111282, + "timestamp": 1758900402959, "memoryTotal": 67427545088, - "memoryUsed": 7302512640, - "memoryFree": 60125032448, - "memoryUsagePercent": 10.830162406876088, - "memoryEfficiency": 89.16983759312392, - "cpuCount": 16, - "cpuLoad": 0.054375, - "platform": "linux", - "uptime": 4839.41 - }, - { - "timestamp": 1758901141312, - "memoryTotal": 67427545088, - "memoryUsed": 7238496256, - "memoryFree": 60189048832, - "memoryUsagePercent": 10.735221409222307, - "memoryEfficiency": 89.2647785907777, - "cpuCount": 16, - "cpuLoad": 0.033125, - "platform": "linux", - "uptime": 4869.44 - }, - { - "timestamp": 1758901171341, - "memoryTotal": 67427545088, - "memoryUsed": 7302516736, - "memoryFree": 60125028352, - "memoryUsagePercent": 10.830168481544822, - "memoryEfficiency": 89.16983151845518, - "cpuCount": 16, - "cpuLoad": 0.023125, - "platform": "linux", - "uptime": 4899.47 - }, - { - "timestamp": 1758901201372, - "memoryTotal": 67427545088, - "memoryUsed": 7439716352, - "memoryFree": 59987828736, - "memoryUsagePercent": 11.03364558548052, - "memoryEfficiency": 88.96635441451949, - "cpuCount": 16, - "cpuLoad": 0.030625, - "platform": "linux", - "uptime": 4929.5 - }, - { - "timestamp": 1758901231403, - "memoryTotal": 67427545088, - "memoryUsed": 7611138048, - "memoryFree": 59816407040, - "memoryUsagePercent": 11.287876546694186, - "memoryEfficiency": 88.71212345330582, - "cpuCount": 16, - "cpuLoad": 0.055625, - "platform": "linux", - "uptime": 4959.53 - }, - { - "timestamp": 1758901261434, - "memoryTotal": 67427545088, - "memoryUsed": 7644041216, - "memoryFree": 59783503872, - "memoryUsagePercent": 11.336674360639597, - "memoryEfficiency": 88.66332563936041, + "memoryUsed": 7455883264, + "memoryFree": 59971661824, + "memoryUsagePercent": 11.057622302976169, + "memoryEfficiency": 88.94237769702383, "cpuCount": 16, "cpuLoad": 0.08625, "platform": "linux", - "uptime": 4989.56 + "uptime": 4131.09 }, { - "timestamp": 1758901291463, + "timestamp": 1758900432972, "memoryTotal": 67427545088, - "memoryUsed": 7753461760, - "memoryFree": 59674083328, - "memoryUsagePercent": 11.498953061216929, - "memoryEfficiency": 88.50104693878308, + "memoryUsed": 7151644672, + "memoryFree": 60275900416, + "memoryUsagePercent": 10.606414133372875, + "memoryEfficiency": 89.39358586662712, "cpuCount": 16, - "cpuLoad": 0.10375, + "cpuLoad": 0.073125, "platform": "linux", - "uptime": 5019.59 + "uptime": 4161.1 }, { - "timestamp": 1758901321466, + "timestamp": 1758900462993, "memoryTotal": 67427545088, - "memoryUsed": 7363833856, - "memoryFree": 60063711232, - "memoryUsagePercent": 10.921106272502472, - "memoryEfficiency": 89.07889372749753, + "memoryUsed": 7174754304, + "memoryFree": 60252790784, + "memoryUsagePercent": 10.640687414373748, + "memoryEfficiency": 89.35931258562626, "cpuCount": 16, - "cpuLoad": 0.0775, + "cpuLoad": 0.064375, "platform": "linux", - "uptime": 5049.6 + "uptime": 4191.12 }, { - "timestamp": 1758901351472, + "timestamp": 1758900493000, "memoryTotal": 67427545088, - "memoryUsed": 7327551488, - "memoryFree": 60099993600, - "memoryUsagePercent": 10.867296856850977, - "memoryEfficiency": 89.13270314314903, + "memoryUsed": 7399305216, + "memoryFree": 60028239872, + "memoryUsagePercent": 10.973712903744506, + "memoryEfficiency": 89.02628709625549, "cpuCount": 16, - "cpuLoad": 0.05, + "cpuLoad": 0.046875, "platform": "linux", - "uptime": 5079.6 + "uptime": 4221.13 }, { - "timestamp": 1758901381503, + "timestamp": 1758900523004, "memoryTotal": 67427545088, - "memoryUsed": 7673958400, - "memoryFree": 59753586688, - "memoryUsagePercent": 11.381043741077452, - "memoryEfficiency": 88.61895625892255, + "memoryUsed": 7432724480, + "memoryFree": 59994820608, + "memoryUsagePercent": 11.023276125950481, + "memoryEfficiency": 88.97672387404953, "cpuCount": 16, - "cpuLoad": 0.03875, + "cpuLoad": 0.08, "platform": "linux", - "uptime": 5109.63 + "uptime": 4251.13 }, { - "timestamp": 1758901411532, + "timestamp": 1758900553034, "memoryTotal": 67427545088, - "memoryUsed": 7963303936, - "memoryFree": 59464241152, - "memoryUsagePercent": 11.810164415161571, - "memoryEfficiency": 88.18983558483843, + "memoryUsed": 7336321024, + "memoryFree": 60091224064, + "memoryUsagePercent": 10.880302722611855, + "memoryEfficiency": 89.11969727738814, "cpuCount": 16, - "cpuLoad": 0.1125, + "cpuLoad": 0.076875, "platform": "linux", - "uptime": 5139.66 + "uptime": 4281.16 }, { - "timestamp": 1758901441562, + "timestamp": 1758900583055, "memoryTotal": 67427545088, - "memoryUsed": 7544504320, - "memoryFree": 59883040768, - "memoryUsagePercent": 11.189053835718967, - "memoryEfficiency": 88.81094616428103, + "memoryUsed": 8016306176, + "memoryFree": 59411238912, + "memoryUsagePercent": 11.888770628587888, + "memoryEfficiency": 88.11122937141211, + "cpuCount": 16, + "cpuLoad": 0.079375, + "platform": "linux", + "uptime": 4311.18 + }, + { + "timestamp": 1758900613083, + "memoryTotal": 67427545088, + "memoryUsed": 7816654848, + "memoryFree": 59610890240, + "memoryUsagePercent": 11.592673050455044, + "memoryEfficiency": 88.40732694954495, + "cpuCount": 16, + "cpuLoad": 0.066875, + "platform": "linux", + "uptime": 4341.21 + }, + { + "timestamp": 1758900643107, + "memoryTotal": 67427545088, + "memoryUsed": 7432908800, + "memoryFree": 59994636288, + "memoryUsagePercent": 11.023549486043539, + "memoryEfficiency": 88.97645051395646, + "cpuCount": 16, + "cpuLoad": 0.096875, + "platform": "linux", + "uptime": 4371.24 + }, + { + "timestamp": 1758900673138, + "memoryTotal": 67427545088, + "memoryUsed": 7441235968, + "memoryFree": 59986309120, + "memoryUsagePercent": 11.035899287581074, + "memoryEfficiency": 88.96410071241893, + "cpuCount": 16, + "cpuLoad": 0.070625, + "platform": "linux", + "uptime": 4401.27 + }, + { + "timestamp": 1758900703168, + "memoryTotal": 67427545088, + "memoryUsed": 7303548928, + "memoryFree": 60123996160, + "memoryUsagePercent": 10.831699298065953, + "memoryEfficiency": 89.16830070193404, + "cpuCount": 16, + "cpuLoad": 0.105, + "platform": "linux", + "uptime": 4431.3 + }, + { + "timestamp": 1758900733171, + "memoryTotal": 67427545088, + "memoryUsed": 7860293632, + "memoryFree": 59567251456, + "memoryUsagePercent": 11.657392571153961, + "memoryEfficiency": 88.34260742884604, "cpuCount": 16, "cpuLoad": 0.105625, "platform": "linux", - "uptime": 5169.69 + "uptime": 4461.3 }, { - "timestamp": 1758901471593, + "timestamp": 1758900763201, "memoryTotal": 67427545088, - "memoryUsed": 7404642304, - "memoryFree": 60022902784, - "memoryUsagePercent": 10.98162819710575, - "memoryEfficiency": 89.01837180289425, + "memoryUsed": 7567638528, + "memoryFree": 59859906560, + "memoryUsagePercent": 11.223363564732248, + "memoryEfficiency": 88.77663643526775, "cpuCount": 16, - "cpuLoad": 0.109375, + "cpuLoad": 0.116875, "platform": "linux", - "uptime": 5199.72 + "uptime": 4491.33 }, { - "timestamp": 1758901501622, + "timestamp": 1758900793231, "memoryTotal": 67427545088, - "memoryUsed": 8030912512, - "memoryFree": 59396632576, - "memoryUsagePercent": 11.910432897295637, - "memoryEfficiency": 88.08956710270436, + "memoryUsed": 7668699136, + "memoryFree": 59758845952, + "memoryUsagePercent": 11.373243866422165, + "memoryEfficiency": 88.62675613357783, "cpuCount": 16, - "cpuLoad": 0.11125, + "cpuLoad": 0.116875, "platform": "linux", - "uptime": 5229.75 + "uptime": 4521.36 }, { - "timestamp": 1758901531653, + "timestamp": 1758900823244, "memoryTotal": 67427545088, - "memoryUsed": 7495917568, - "memoryFree": 59931627520, - "memoryUsagePercent": 11.116996115188597, - "memoryEfficiency": 88.8830038848114, + "memoryUsed": 7341051904, + "memoryFree": 60086493184, + "memoryUsagePercent": 10.887318965000372, + "memoryEfficiency": 89.11268103499962, "cpuCount": 16, - "cpuLoad": 0.1125, + "cpuLoad": 0.11875, "platform": "linux", - "uptime": 5259.78 + "uptime": 4551.37 }, { - "timestamp": 1758901561684, + "timestamp": 1758900853248, "memoryTotal": 67427545088, - "memoryUsed": 7476764672, - "memoryFree": 59950780416, - "memoryUsagePercent": 11.088590964185393, - "memoryEfficiency": 88.91140903581461, + "memoryUsed": 7214714880, + "memoryFree": 60212830208, + "memoryUsagePercent": 10.699951882548952, + "memoryEfficiency": 89.30004811745104, "cpuCount": 16, - "cpuLoad": 0.08625, + "cpuLoad": 0.071875, "platform": "linux", - "uptime": 5289.81 + "uptime": 4581.38 }, { - "timestamp": 1758901591706, + "timestamp": 1758900883279, "memoryTotal": 67427545088, - "memoryUsed": 7333957632, - "memoryFree": 60093587456, - "memoryUsagePercent": 10.876797638751965, - "memoryEfficiency": 89.12320236124803, + "memoryUsed": 7196872704, + "memoryFree": 60230672384, + "memoryUsagePercent": 10.673490625540834, + "memoryEfficiency": 89.32650937445916, "cpuCount": 16, - "cpuLoad": 0.0575, + "cpuLoad": 0.059375, "platform": "linux", - "uptime": 5319.84 + "uptime": 4611.41 }, { - "timestamp": 1758901621729, + "timestamp": 1758900913305, "memoryTotal": 67427545088, - "memoryUsed": 7351242752, - "memoryFree": 60076302336, - "memoryUsagePercent": 10.90243274081217, - "memoryEfficiency": 89.09756725918783, + "memoryUsed": 7265370112, + "memoryFree": 60162174976, + "memoryUsagePercent": 10.775077310790317, + "memoryEfficiency": 89.22492268920968, "cpuCount": 16, - "cpuLoad": 0.034375, + "cpuLoad": 0.08375, "platform": "linux", - "uptime": 5349.86 + "uptime": 4641.43 }, { - "timestamp": 1758901651760, + "timestamp": 1758900943335, + "memoryTotal": 67427545088, + "memoryUsed": 7232851968, + "memoryFree": 60194693120, + "memoryUsagePercent": 10.726850515705964, + "memoryEfficiency": 89.27314948429404, + "cpuCount": 16, + "cpuLoad": 0.075625, + "platform": "linux", + "uptime": 4671.47 + }, + { + "timestamp": 1758900973345, + "memoryTotal": 67427545088, + "memoryUsed": 7160004608, + "memoryFree": 60267540480, + "memoryUsagePercent": 10.618812532260288, + "memoryEfficiency": 89.38118746773971, + "cpuCount": 16, + "cpuLoad": 0.055625, + "platform": "linux", + "uptime": 4701.47 + }, + { + "timestamp": 1758901003376, + "memoryTotal": 67427545088, + "memoryUsed": 7182065664, + "memoryFree": 60245479424, + "memoryUsagePercent": 10.65153069806509, + "memoryEfficiency": 89.34846930193491, + "cpuCount": 16, + "cpuLoad": 0.036875, + "platform": "linux", + "uptime": 4731.51 + }, + { + "timestamp": 1758901033387, + "memoryTotal": 67427545088, + "memoryUsed": 7270645760, + "memoryFree": 60156899328, + "memoryUsagePercent": 10.782901484120542, + "memoryEfficiency": 89.21709851587946, + "cpuCount": 16, + "cpuLoad": 0.0275, + "platform": "linux", + "uptime": 4761.52 + }, + { + "timestamp": 1758901063417, + "memoryTotal": 67427545088, + "memoryUsed": 7421120512, + "memoryFree": 60006424576, + "memoryUsagePercent": 11.00606658942523, + "memoryEfficiency": 88.99393341057477, + "cpuCount": 16, + "cpuLoad": 0.0525, + "platform": "linux", + "uptime": 4791.55 + }, + { + "timestamp": 1758901093447, + "memoryTotal": 67427545088, + "memoryUsed": 7302041600, + "memoryFree": 60125503488, + "memoryUsagePercent": 10.829463819971604, + "memoryEfficiency": 89.17053618002839, + "cpuCount": 16, + "cpuLoad": 0.058125, + "platform": "linux", + "uptime": 4821.58 + }, + { + "timestamp": 1758901123476, + "memoryTotal": 67427545088, + "memoryUsed": 7251525632, + "memoryFree": 60176019456, + "memoryUsagePercent": 10.754544930467215, + "memoryEfficiency": 89.24545506953278, + "cpuCount": 16, + "cpuLoad": 0.0425, + "platform": "linux", + "uptime": 4851.61 + }, + { + "timestamp": 1758901153507, + "memoryTotal": 67427545088, + "memoryUsed": 7218941952, + "memoryFree": 60208603136, + "memoryUsagePercent": 10.706220940683107, + "memoryEfficiency": 89.29377905931689, + "cpuCount": 16, + "cpuLoad": 0.03, + "platform": "linux", + "uptime": 4881.64 + }, + { + "timestamp": 1758901183532, + "memoryTotal": 67427545088, + "memoryUsed": 7361789952, + "memoryFree": 60065755136, + "memoryUsagePercent": 10.918075012803884, + "memoryEfficiency": 89.08192498719612, + "cpuCount": 16, + "cpuLoad": 0.0275, + "platform": "linux", + "uptime": 4911.66 + }, + { + "timestamp": 1758901213563, + "memoryTotal": 67427545088, + "memoryUsed": 7434313728, + "memoryFree": 59993231360, + "memoryUsagePercent": 11.025633097419524, + "memoryEfficiency": 88.97436690258047, + "cpuCount": 16, + "cpuLoad": 0.02875, + "platform": "linux", + "uptime": 4941.69 + }, + { + "timestamp": 1758901243577, + "memoryTotal": 67427545088, + "memoryUsed": 7560744960, + "memoryFree": 59866800128, + "memoryUsagePercent": 11.213139897251837, + "memoryEfficiency": 88.78686010274816, + "cpuCount": 16, + "cpuLoad": 0.093125, + "platform": "linux", + "uptime": 4971.71 + }, + { + "timestamp": 1758901273608, + "memoryTotal": 67427545088, + "memoryUsed": 7694598144, + "memoryFree": 59732946944, + "memoryUsagePercent": 11.411653996831332, + "memoryEfficiency": 88.58834600316867, + "cpuCount": 16, + "cpuLoad": 0.10875, + "platform": "linux", + "uptime": 5001.74 + }, + { + "timestamp": 1758901303637, + "memoryTotal": 67427545088, + "memoryUsed": 7480143872, + "memoryFree": 59947401216, + "memoryUsagePercent": 11.093602565891477, + "memoryEfficiency": 88.90639743410853, + "cpuCount": 16, + "cpuLoad": 0.093125, + "platform": "linux", + "uptime": 5031.77 + }, + { + "timestamp": 1758901333638, + "memoryTotal": 67427545088, + "memoryUsed": 7371907072, + "memoryFree": 60055638016, + "memoryUsagePercent": 10.933079444578459, + "memoryEfficiency": 89.06692055542155, + "cpuCount": 16, + "cpuLoad": 0.064375, + "platform": "linux", + "uptime": 5061.77 + }, + { + "timestamp": 1758901363668, + "memoryTotal": 67427545088, + "memoryUsed": 7357501440, + "memoryFree": 60070043648, + "memoryUsagePercent": 10.911714834638708, + "memoryEfficiency": 89.0882851653613, + "cpuCount": 16, + "cpuLoad": 0.04375, + "platform": "linux", + "uptime": 5091.8 + }, + { + "timestamp": 1758901393698, + "memoryTotal": 67427545088, + "memoryUsed": 7777783808, + "memoryFree": 59649761280, + "memoryUsagePercent": 11.535024444163255, + "memoryEfficiency": 88.46497555583674, + "cpuCount": 16, + "cpuLoad": 0.085625, + "platform": "linux", + "uptime": 5121.83 + }, + { + "timestamp": 1758901423728, + "memoryTotal": 67427545088, + "memoryUsed": 8065908736, + "memoryFree": 59361636352, + "memoryUsagePercent": 11.96233486696445, + "memoryEfficiency": 88.03766513303555, + "cpuCount": 16, + "cpuLoad": 0.10625, + "platform": "linux", + "uptime": 5151.86 + }, + { + "timestamp": 1758901453759, + "memoryTotal": 67427545088, + "memoryUsed": 7591800832, + "memoryFree": 59835744256, + "memoryUsagePercent": 11.259198035597922, + "memoryEfficiency": 88.74080196440208, + "cpuCount": 16, + "cpuLoad": 0.113125, + "platform": "linux", + "uptime": 5181.89 + }, + { + "timestamp": 1758901483789, + "memoryTotal": 67427545088, + "memoryUsed": 7532363776, + "memoryFree": 59895181312, + "memoryUsagePercent": 11.171048517589476, + "memoryEfficiency": 88.82895148241053, + "cpuCount": 16, + "cpuLoad": 0.1075, + "platform": "linux", + "uptime": 5211.92 + }, + { + "timestamp": 1758901513818, + "memoryTotal": 67427545088, + "memoryUsed": 7684218880, + "memoryFree": 59743326208, + "memoryUsagePercent": 11.39626078625774, + "memoryEfficiency": 88.60373921374226, + "cpuCount": 16, + "cpuLoad": 0.114375, + "platform": "linux", + "uptime": 5241.95 + }, + { + "timestamp": 1758901543841, + "memoryTotal": 67427545088, + "memoryUsed": 7425302528, + "memoryFree": 60002242560, + "memoryUsagePercent": 11.012268826203302, + "memoryEfficiency": 88.9877311737967, + "cpuCount": 16, + "cpuLoad": 0.105625, + "platform": "linux", + "uptime": 5271.97 + }, + { + "timestamp": 1758901573870, + "memoryTotal": 67427545088, + "memoryUsed": 7435042816, + "memoryFree": 59992502272, + "memoryUsagePercent": 11.02671438845429, + "memoryEfficiency": 88.9732856115457, + "cpuCount": 16, + "cpuLoad": 0.0675, + "platform": "linux", + "uptime": 5302 + }, + { + "timestamp": 1758901603900, "memoryTotal": 67427545088, "memoryUsed": 7307915264, "memoryFree": 60119629824, "memoryUsagePercent": 10.838174894937087, "memoryEfficiency": 89.16182510506292, "cpuCount": 16, - "cpuLoad": 0.02125, - "platform": "linux", - "uptime": 5379.89 - }, - { - "timestamp": 1758901681791, - "memoryTotal": 67427545088, - "memoryUsed": 7350210560, - "memoryFree": 60077334528, - "memoryUsagePercent": 10.900901924291038, - "memoryEfficiency": 89.09909807570897, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 5409.92 - }, - { - "timestamp": 1758901711822, - "memoryTotal": 67427545088, - "memoryUsed": 7271858176, - "memoryFree": 60155686912, - "memoryUsagePercent": 10.784699586065997, - "memoryEfficiency": 89.215300413934, - "cpuCount": 16, - "cpuLoad": 0.03, - "platform": "linux", - "uptime": 5439.95 - }, - { - "timestamp": 1758901741852, - "memoryTotal": 67427545088, - "memoryUsed": 7546388480, - "memoryFree": 59881156608, - "memoryUsagePercent": 11.191848183336903, - "memoryEfficiency": 88.8081518166631, - "cpuCount": 16, - "cpuLoad": 0.043125, - "platform": "linux", - "uptime": 5469.98 - }, - { - "timestamp": 1758901771854, - "memoryTotal": 67427545088, - "memoryUsed": 7618883584, - "memoryFree": 59808661504, - "memoryUsagePercent": 11.299363745271402, - "memoryEfficiency": 88.7006362547286, - "cpuCount": 16, - "cpuLoad": 0.04, - "platform": "linux", - "uptime": 5499.98 - }, - { - "timestamp": 1758901801885, - "memoryTotal": 67427545088, - "memoryUsed": 7598682112, - "memoryFree": 59828862976, - "memoryUsagePercent": 11.269403479072128, - "memoryEfficiency": 88.73059652092788, - "cpuCount": 16, - "cpuLoad": 0.049375, - "platform": "linux", - "uptime": 5530.01 - }, - { - "timestamp": 1758901831914, - "memoryTotal": 67427545088, - "memoryUsed": 7472807936, - "memoryFree": 59954737152, - "memoryUsagePercent": 11.082722834187726, - "memoryEfficiency": 88.91727716581228, - "cpuCount": 16, - "cpuLoad": 0.07875, - "platform": "linux", - "uptime": 5560.04 - }, - { - "timestamp": 1758901861944, - "memoryTotal": 67427545088, - "memoryUsed": 7597441024, - "memoryFree": 59830104064, - "memoryUsagePercent": 11.26756285444553, - "memoryEfficiency": 88.73243714555447, - "cpuCount": 16, - "cpuLoad": 0.0875, - "platform": "linux", - "uptime": 5590.07 - }, - { - "timestamp": 1758901891975, - "memoryTotal": 67427545088, - "memoryUsed": 7636934656, - "memoryFree": 59790610432, - "memoryUsagePercent": 11.326134810384985, - "memoryEfficiency": 88.67386518961501, - "cpuCount": 16, - "cpuLoad": 0.0925, - "platform": "linux", - "uptime": 5620.1 - }, - { - "timestamp": 1758901922005, - "memoryTotal": 67427545088, - "memoryUsed": 7439163392, - "memoryFree": 59988381696, - "memoryUsagePercent": 11.032825505201343, - "memoryEfficiency": 88.96717449479866, - "cpuCount": 16, - "cpuLoad": 0.0975, - "platform": "linux", - "uptime": 5650.13 - }, - { - "timestamp": 1758901952007, - "memoryTotal": 67427545088, - "memoryUsed": 7331434496, - "memoryFree": 60096110592, - "memoryUsagePercent": 10.873055642811421, - "memoryEfficiency": 89.12694435718858, - "cpuCount": 16, - "cpuLoad": 0.066875, - "platform": "linux", - "uptime": 5680.14 - }, - { - "timestamp": 1758901982037, - "memoryTotal": 67427545088, - "memoryUsed": 7354630144, - "memoryFree": 60072914944, - "memoryUsagePercent": 10.907456491855722, - "memoryEfficiency": 89.09254350814427, - "cpuCount": 16, "cpuLoad": 0.044375, "platform": "linux", - "uptime": 5710.17 + "uptime": 5332.03 }, { - "timestamp": 1758902012067, + "timestamp": 1758901633930, "memoryTotal": 67427545088, - "memoryUsed": 7315603456, - "memoryFree": 60111941632, - "memoryUsagePercent": 10.849577048152016, - "memoryEfficiency": 89.15042295184799, - "cpuCount": 16, - "cpuLoad": 0.03625, - "platform": "linux", - "uptime": 5740.2 - }, - { - "timestamp": 1758902042097, - "memoryTotal": 67427545088, - "memoryUsed": 7341801472, - "memoryFree": 60085743616, - "memoryUsagePercent": 10.88843062937881, - "memoryEfficiency": 89.1115693706212, - "cpuCount": 16, - "cpuLoad": 0.029375, - "platform": "linux", - "uptime": 5770.23 - }, - { - "timestamp": 1758902072128, - "memoryTotal": 67427545088, - "memoryUsed": 7344545792, - "memoryFree": 60082999296, - "memoryUsagePercent": 10.892500657431023, - "memoryEfficiency": 89.10749934256897, - "cpuCount": 16, - "cpuLoad": 0.0175, - "platform": "linux", - "uptime": 5800.26 - }, - { - "timestamp": 1758902102159, - "memoryTotal": 67427545088, - "memoryUsed": 7343538176, - "memoryFree": 60084006912, - "memoryUsagePercent": 10.8910062889223, - "memoryEfficiency": 89.1089937110777, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 5830.29 - }, - { - "timestamp": 1758902132190, - "memoryTotal": 67427545088, - "memoryUsed": 7356129280, - "memoryFree": 60071415808, - "memoryUsagePercent": 10.909679820612602, - "memoryEfficiency": 89.09032017938739, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 5860.32 - }, - { - "timestamp": 1758902162219, - "memoryTotal": 67427545088, - "memoryUsed": 7342522368, - "memoryFree": 60085022720, - "memoryUsagePercent": 10.889499771076109, - "memoryEfficiency": 89.1105002289239, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 5890.35 - }, - { - "timestamp": 1758902192249, - "memoryTotal": 67427545088, - "memoryUsed": 7340449792, - "memoryFree": 60087095296, - "memoryUsagePercent": 10.886425988696379, - "memoryEfficiency": 89.11357401130363, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 5920.38 - }, - { - "timestamp": 1758902222279, - "memoryTotal": 67427545088, - "memoryUsed": 7335620608, - "memoryFree": 60091924480, - "memoryUsagePercent": 10.879263954258231, - "memoryEfficiency": 89.12073604574176, - "cpuCount": 16, - "cpuLoad": 0.02375, - "platform": "linux", - "uptime": 5950.41 - }, - { - "timestamp": 1758902252309, - "memoryTotal": 67427545088, - "memoryUsed": 7362572288, - "memoryFree": 60064972800, - "memoryUsagePercent": 10.9192352745322, - "memoryEfficiency": 89.0807647254678, - "cpuCount": 16, - "cpuLoad": 0.014375, - "platform": "linux", - "uptime": 5980.44 - }, - { - "timestamp": 1758902282337, - "memoryTotal": 67427545088, - "memoryUsed": 7371350016, - "memoryFree": 60056195072, - "memoryUsagePercent": 10.932253289630546, - "memoryEfficiency": 89.06774671036945, - "cpuCount": 16, - "cpuLoad": 0.019375, - "platform": "linux", - "uptime": 6010.47 - }, - { - "timestamp": 1758902312367, - "memoryTotal": 67427545088, - "memoryUsed": 7376564224, - "memoryFree": 60050980864, - "memoryUsagePercent": 10.939986342929751, - "memoryEfficiency": 89.06001365707024, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 6040.5 - }, - { - "timestamp": 1758902342398, - "memoryTotal": 67427545088, - "memoryUsed": 7339458560, - "memoryFree": 60088086528, - "memoryUsagePercent": 10.884955918862593, - "memoryEfficiency": 89.11504408113741, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 6070.53 - }, - { - "timestamp": 1758902372402, - "memoryTotal": 67427545088, - "memoryUsed": 7371874304, - "memoryFree": 60055670784, - "memoryUsagePercent": 10.933030847228581, - "memoryEfficiency": 89.06696915277142, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 6100.53 - }, - { - "timestamp": 1758902402414, - "memoryTotal": 67427545088, - "memoryUsed": 7356137472, - "memoryFree": 60071407616, - "memoryUsagePercent": 10.909691969950073, - "memoryEfficiency": 89.09030803004993, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 6130.54 - }, - { - "timestamp": 1758902432444, - "memoryTotal": 67427545088, - "memoryUsed": 7379140608, - "memoryFree": 60048404480, - "memoryUsagePercent": 10.943807309563843, - "memoryEfficiency": 89.05619269043616, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 6160.57 - }, - { - "timestamp": 1758902462445, - "memoryTotal": 67427545088, - "memoryUsed": 7386263552, - "memoryFree": 60041281536, - "memoryUsagePercent": 10.954371158493393, - "memoryEfficiency": 89.04562884150661, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 6190.57 - }, - { - "timestamp": 1758902492476, - "memoryTotal": 67427545088, - "memoryUsed": 7374639104, - "memoryFree": 60052905984, - "memoryUsagePercent": 10.937131248624468, - "memoryEfficiency": 89.06286875137553, - "cpuCount": 16, - "cpuLoad": 0.00375, - "platform": "linux", - "uptime": 6220.61 - }, - { - "timestamp": 1758902522506, - "memoryTotal": 67427545088, - "memoryUsed": 7352557568, - "memoryFree": 60074987520, - "memoryUsagePercent": 10.904382709475993, - "memoryEfficiency": 89.095617290524, - "cpuCount": 16, - "cpuLoad": 0.0025, - "platform": "linux", - "uptime": 6250.64 - }, - { - "timestamp": 1758902552529, - "memoryTotal": 67427545088, - "memoryUsed": 7397658624, - "memoryFree": 60029886464, - "memoryUsagePercent": 10.971270886913178, - "memoryEfficiency": 89.02872911308683, - "cpuCount": 16, - "cpuLoad": 0.00125, - "platform": "linux", - "uptime": 6280.66 - }, - { - "timestamp": 1758902582542, - "memoryTotal": 67427545088, - "memoryUsed": 7358566400, - "memoryFree": 60068978688, - "memoryUsagePercent": 10.913294248509716, - "memoryEfficiency": 89.08670575149029, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 6310.67 - }, - { - "timestamp": 1758902612573, - "memoryTotal": 67427545088, - "memoryUsed": 7343398912, - "memoryFree": 60084146176, - "memoryUsagePercent": 10.890799750185323, - "memoryEfficiency": 89.10920024981468, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 6340.7 - }, - { - "timestamp": 1758902642604, - "memoryTotal": 67427545088, - "memoryUsed": 7343484928, - "memoryFree": 60084060160, - "memoryUsagePercent": 10.890927318228751, - "memoryEfficiency": 89.10907268177125, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 6370.73 - }, - { - "timestamp": 1758902672635, - "memoryTotal": 67427545088, - "memoryUsed": 7353622528, - "memoryFree": 60073922560, - "memoryUsagePercent": 10.905962123346999, - "memoryEfficiency": 89.094037876653, - "cpuCount": 16, - "cpuLoad": 0.014375, - "platform": "linux", - "uptime": 6400.77 - }, - { - "timestamp": 1758902702666, - "memoryTotal": 67427545088, - "memoryUsed": 7286169600, - "memoryFree": 60141375488, - "memoryUsagePercent": 10.805924478624851, - "memoryEfficiency": 89.19407552137515, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 6430.8 - }, - { - "timestamp": 1758902732676, - "memoryTotal": 67427545088, - "memoryUsed": 7306002432, - "memoryFree": 60121542656, - "memoryUsagePercent": 10.835338024638006, - "memoryEfficiency": 89.164661975362, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 6460.81 - }, - { - "timestamp": 1758902762707, - "memoryTotal": 67427545088, - "memoryUsed": 7318822912, - "memoryFree": 60108722176, - "memoryUsagePercent": 10.854351737777447, - "memoryEfficiency": 89.14564826222255, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 6490.84 - }, - { - "timestamp": 1758902792708, - "memoryTotal": 67427545088, - "memoryUsed": 7334252544, - "memoryFree": 60093292544, - "memoryUsagePercent": 10.877235014900858, - "memoryEfficiency": 89.12276498509914, - "cpuCount": 16, - "cpuLoad": 0.01625, - "platform": "linux", - "uptime": 6520.84 - }, - { - "timestamp": 1758902822737, - "memoryTotal": 67427545088, - "memoryUsed": 7301939200, - "memoryFree": 60125605888, - "memoryUsagePercent": 10.829311953253237, - "memoryEfficiency": 89.17068804674676, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 6550.87 - }, - { - "timestamp": 1758902852768, - "memoryTotal": 67427545088, - "memoryUsed": 7303741440, - "memoryFree": 60123803648, - "memoryUsagePercent": 10.83198480749648, - "memoryEfficiency": 89.16801519250352, - "cpuCount": 16, - "cpuLoad": 0.016875, - "platform": "linux", - "uptime": 6580.9 - }, - { - "timestamp": 1758902882798, - "memoryTotal": 67427545088, - "memoryUsed": 7293480960, - "memoryFree": 60134064128, - "memoryUsagePercent": 10.816767762316193, - "memoryEfficiency": 89.18323223768381, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 6610.93 - }, - { - "timestamp": 1758902912828, - "memoryTotal": 67427545088, - "memoryUsed": 7294042112, - "memoryFree": 60133502976, - "memoryUsagePercent": 10.81759999193284, - "memoryEfficiency": 89.18240000806716, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 6640.96 - }, - { - "timestamp": 1758902942859, - "memoryTotal": 67427545088, - "memoryUsed": 7301140480, - "memoryFree": 60126404608, - "memoryUsagePercent": 10.828127392849982, - "memoryEfficiency": 89.17187260715002, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 6670.99 - }, - { - "timestamp": 1758902972864, - "memoryTotal": 67427545088, - "memoryUsed": 7324946432, - "memoryFree": 60102598656, - "memoryUsagePercent": 10.863433367535743, - "memoryEfficiency": 89.13656663246425, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 6700.99 - }, - { - "timestamp": 1758903002877, - "memoryTotal": 67427545088, - "memoryUsed": 7369551872, - "memoryFree": 60057993216, - "memoryUsagePercent": 10.929586510056037, - "memoryEfficiency": 89.07041348994396, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 6731.01 - }, - { - "timestamp": 1758903032908, - "memoryTotal": 67427545088, - "memoryUsed": 7340187648, - "memoryFree": 60087357440, - "memoryUsagePercent": 10.88603720989736, - "memoryEfficiency": 89.11396279010265, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 6761.04 - }, - { - "timestamp": 1758903062938, - "memoryTotal": 67427545088, - "memoryUsed": 7359967232, - "memoryFree": 60067577856, - "memoryUsagePercent": 10.915371785216966, - "memoryEfficiency": 89.08462821478304, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 6791.07 - }, - { - "timestamp": 1758903092968, - "memoryTotal": 67427545088, - "memoryUsed": 7355781120, - "memoryFree": 60071763968, - "memoryUsagePercent": 10.909163473770157, - "memoryEfficiency": 89.09083652622985, - "cpuCount": 16, - "cpuLoad": 0.003125, - "platform": "linux", - "uptime": 6821.1 - }, - { - "timestamp": 1758903122998, - "memoryTotal": 67427545088, - "memoryUsed": 7352446976, - "memoryFree": 60075098112, - "memoryUsagePercent": 10.904218693420157, - "memoryEfficiency": 89.09578130657984, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 6851.13 - }, - { - "timestamp": 1758903153026, - "memoryTotal": 67427545088, - "memoryUsed": 7351312384, - "memoryFree": 60076232704, - "memoryUsagePercent": 10.90253601018066, - "memoryEfficiency": 89.09746398981935, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 6881.16 - }, - { - "timestamp": 1758903183055, - "memoryTotal": 67427545088, - "memoryUsed": 7338295296, - "memoryFree": 60089249792, - "memoryUsagePercent": 10.883230712941955, - "memoryEfficiency": 89.11676928705805, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 6911.19 - }, - { - "timestamp": 1758903213085, - "memoryTotal": 67427545088, - "memoryUsed": 7367983104, - "memoryFree": 60059561984, - "memoryUsagePercent": 10.927259911930667, - "memoryEfficiency": 89.07274008806934, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 6941.21 - }, - { - "timestamp": 1758903243105, - "memoryTotal": 67427545088, - "memoryUsed": 7325351936, - "memoryFree": 60102193152, - "memoryUsagePercent": 10.864034759740473, - "memoryEfficiency": 89.13596524025952, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 6971.24 - }, - { - "timestamp": 1758903273121, - "memoryTotal": 67427545088, - "memoryUsed": 7365074944, - "memoryFree": 60062470144, - "memoryUsagePercent": 10.92294689712907, - "memoryEfficiency": 89.07705310287093, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 7001.25 - }, - { - "timestamp": 1758903303151, - "memoryTotal": 67427545088, - "memoryUsed": 7347658752, - "memoryFree": 60079886336, - "memoryUsagePercent": 10.897117405669354, - "memoryEfficiency": 89.10288259433065, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 7031.28 - }, - { - "timestamp": 1758903333182, - "memoryTotal": 67427545088, - "memoryUsed": 7319195648, - "memoryFree": 60108349440, - "memoryUsagePercent": 10.8549045326323, - "memoryEfficiency": 89.1450954673677, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 7061.31 - }, - { - "timestamp": 1758903363211, - "memoryTotal": 67427545088, - "memoryUsed": 7306993664, - "memoryFree": 60120551424, - "memoryUsagePercent": 10.83680809447179, - "memoryEfficiency": 89.16319190552821, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 7091.34 - }, - { - "timestamp": 1758903393242, - "memoryTotal": 67427545088, - "memoryUsed": 7313473536, - "memoryFree": 60114071552, - "memoryUsagePercent": 10.846418220410001, - "memoryEfficiency": 89.15358177959, - "cpuCount": 16, - "cpuLoad": 0.02875, - "platform": "linux", - "uptime": 7121.37 - }, - { - "timestamp": 1758903423273, - "memoryTotal": 67427545088, - "memoryUsed": 7320539136, - "memoryFree": 60107005952, - "memoryUsagePercent": 10.856897023977265, - "memoryEfficiency": 89.14310297602273, - "cpuCount": 16, - "cpuLoad": 0.0175, - "platform": "linux", - "uptime": 7151.4 - }, - { - "timestamp": 1758903453290, - "memoryTotal": 67427545088, - "memoryUsed": 7316504576, - "memoryFree": 60111040512, - "memoryUsagePercent": 10.850913475273638, - "memoryEfficiency": 89.14908652472636, - "cpuCount": 16, - "cpuLoad": 0.02375, - "platform": "linux", - "uptime": 7181.42 - }, - { - "timestamp": 1758903483297, - "memoryTotal": 67427545088, - "memoryUsed": 7311769600, - "memoryFree": 60115775488, - "memoryUsagePercent": 10.843891158216387, - "memoryEfficiency": 89.1561088417836, - "cpuCount": 16, - "cpuLoad": 0.014375, - "platform": "linux", - "uptime": 7211.43 - }, - { - "timestamp": 1758903513322, - "memoryTotal": 67427545088, - "memoryUsed": 7327178752, - "memoryFree": 60100366336, - "memoryUsagePercent": 10.866744061996126, - "memoryEfficiency": 89.13325593800387, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 7241.45 - }, - { - "timestamp": 1758903543352, - "memoryTotal": 67427545088, - "memoryUsed": 7325888512, - "memoryFree": 60101656576, - "memoryUsagePercent": 10.864830541344713, - "memoryEfficiency": 89.13516945865528, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 7271.48 - }, - { - "timestamp": 1758903573376, - "memoryTotal": 67427545088, - "memoryUsed": 7324844032, - "memoryFree": 60102701056, - "memoryUsagePercent": 10.863281500817378, - "memoryEfficiency": 89.13671849918262, - "cpuCount": 16, - "cpuLoad": 0.02125, - "platform": "linux", - "uptime": 7301.51 - }, - { - "timestamp": 1758903603407, - "memoryTotal": 67427545088, - "memoryUsed": 7349518336, - "memoryFree": 60078026752, - "memoryUsagePercent": 10.899875305274884, - "memoryEfficiency": 89.10012469472511, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 7331.54 - }, - { - "timestamp": 1758903633424, - "memoryTotal": 67427545088, - "memoryUsed": 7331995648, - "memoryFree": 60095549440, - "memoryUsagePercent": 10.87388787242807, - "memoryEfficiency": 89.12611212757193, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 7361.55 - }, - { - "timestamp": 1758903663454, - "memoryTotal": 67427545088, - "memoryUsed": 7335686144, - "memoryFree": 60091858944, - "memoryUsagePercent": 10.879361148957985, - "memoryEfficiency": 89.12063885104202, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 7391.58 - }, - { - "timestamp": 1758903693484, - "memoryTotal": 67427545088, - "memoryUsed": 7341654016, - "memoryFree": 60085891072, - "memoryUsagePercent": 10.888211941304364, - "memoryEfficiency": 89.11178805869564, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 7421.61 - }, - { - "timestamp": 1758903723514, - "memoryTotal": 67427545088, - "memoryUsed": 7322017792, - "memoryFree": 60105527296, - "memoryUsagePercent": 10.859089979390472, - "memoryEfficiency": 89.14091002060952, - "cpuCount": 16, - "cpuLoad": 0.00375, - "platform": "linux", - "uptime": 7451.64 - }, - { - "timestamp": 1758903753544, - "memoryTotal": 67427545088, - "memoryUsed": 7346524160, - "memoryFree": 60081020928, - "memoryUsagePercent": 10.895434722429858, - "memoryEfficiency": 89.10456527757015, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 7481.67 - }, - { - "timestamp": 1758903783575, - "memoryTotal": 67427545088, - "memoryUsed": 7340683264, - "memoryFree": 60086861824, - "memoryUsagePercent": 10.886772244814253, - "memoryEfficiency": 89.11322775518575, - "cpuCount": 16, - "cpuLoad": 0.02375, - "platform": "linux", - "uptime": 7511.7 - }, - { - "timestamp": 1758903813606, - "memoryTotal": 67427545088, - "memoryUsed": 7322517504, - "memoryFree": 60105027584, - "memoryUsagePercent": 10.859831088976097, - "memoryEfficiency": 89.1401689110239, - "cpuCount": 16, - "cpuLoad": 0.014375, - "platform": "linux", - "uptime": 7541.74 - }, - { - "timestamp": 1758903843637, - "memoryTotal": 67427545088, - "memoryUsed": 7318855680, - "memoryFree": 60108689408, - "memoryUsagePercent": 10.854400335127325, - "memoryEfficiency": 89.14559966487268, - "cpuCount": 16, - "cpuLoad": 0.00875, - "platform": "linux", - "uptime": 7571.77 - }, - { - "timestamp": 1758903873667, - "memoryTotal": 67427545088, - "memoryUsed": 7327916032, - "memoryFree": 60099629056, - "memoryUsagePercent": 10.867837502368362, - "memoryEfficiency": 89.13216249763164, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 7601.8 - }, - { - "timestamp": 1758903903698, - "memoryTotal": 67427545088, - "memoryUsed": 7325126656, - "memoryFree": 60102418432, - "memoryUsagePercent": 10.863700652960068, - "memoryEfficiency": 89.13629934703994, - "cpuCount": 16, - "cpuLoad": 0.003125, - "platform": "linux", - "uptime": 7631.83 - }, - { - "timestamp": 1758903933728, - "memoryTotal": 67427545088, - "memoryUsed": 7328632832, - "memoryFree": 60098912256, - "memoryUsagePercent": 10.868900569396924, - "memoryEfficiency": 89.13109943060307, - "cpuCount": 16, - "cpuLoad": 0.005625, - "platform": "linux", - "uptime": 7661.86 - }, - { - "timestamp": 1758903963759, - "memoryTotal": 67427545088, - "memoryUsed": 7327436800, - "memoryFree": 60100108288, - "memoryUsagePercent": 10.867126766126407, - "memoryEfficiency": 89.1328732338736, - "cpuCount": 16, - "cpuLoad": 0.003125, - "platform": "linux", - "uptime": 7691.89 - }, - { - "timestamp": 1758903993790, - "memoryTotal": 67427545088, - "memoryUsed": 7327625216, - "memoryFree": 60099919872, - "memoryUsagePercent": 10.867406200888203, - "memoryEfficiency": 89.1325937991118, - "cpuCount": 16, - "cpuLoad": 0.001875, - "platform": "linux", - "uptime": 7721.92 - }, - { - "timestamp": 1758904023808, - "memoryTotal": 67427545088, - "memoryUsed": 7317655552, - "memoryFree": 60109889536, - "memoryUsagePercent": 10.852620457188074, - "memoryEfficiency": 89.14737954281193, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 7751.94 - }, - { - "timestamp": 1758904053839, - "memoryTotal": 67427545088, - "memoryUsed": 7299153920, - "memoryFree": 60128391168, - "memoryUsagePercent": 10.825181178513677, - "memoryEfficiency": 89.17481882148633, + "memoryUsed": 7338643456, + "memoryFree": 60088901632, + "memoryUsagePercent": 10.8837470597844, + "memoryEfficiency": 89.1162529402156, "cpuCount": 16, "cpuLoad": 0.026875, "platform": "linux", - "uptime": 7781.97 + "uptime": 5362.06 }, { - "timestamp": 1758904083870, + "timestamp": 1758901663936, "memoryTotal": 67427545088, - "memoryUsed": 7324647424, - "memoryFree": 60102897664, - "memoryUsagePercent": 10.862989916718115, - "memoryEfficiency": 89.13701008328188, + "memoryUsed": 7315595264, + "memoryFree": 60111949824, + "memoryUsagePercent": 10.849564898814547, + "memoryEfficiency": 89.15043510118545, "cpuCount": 16, - "cpuLoad": 0.028125, + "cpuLoad": 0.01625, "platform": "linux", - "uptime": 7812 + "uptime": 5392.07 }, { - "timestamp": 1758904113900, + "timestamp": 1758901693966, "memoryTotal": 67427545088, - "memoryUsed": 7332851712, - "memoryFree": 60094693376, - "memoryUsagePercent": 10.87515747819361, - "memoryEfficiency": 89.12484252180639, + "memoryUsed": 7247118336, + "memoryFree": 60180426752, + "memoryUsagePercent": 10.748008586908735, + "memoryEfficiency": 89.25199141309126, "cpuCount": 16, - "cpuLoad": 0.030625, + "cpuLoad": 0.026875, "platform": "linux", - "uptime": 7842.03 + "uptime": 5422.1 }, { - "timestamp": 1758904143927, + "timestamp": 1758901723997, "memoryTotal": 67427545088, - "memoryUsed": 7308312576, - "memoryFree": 60119232512, - "memoryUsagePercent": 10.838764137804347, - "memoryEfficiency": 89.16123586219565, + "memoryUsed": 7376048128, + "memoryFree": 60051496960, + "memoryUsagePercent": 10.939220934669185, + "memoryEfficiency": 89.06077906533082, "cpuCount": 16, - "cpuLoad": 0.025, + "cpuLoad": 0.038125, "platform": "linux", - "uptime": 7872.06 + "uptime": 5452.13 }, { - "timestamp": 1758904173958, + "timestamp": 1758901754028, "memoryTotal": 67427545088, - "memoryUsed": 7320793088, - "memoryFree": 60106752000, - "memoryUsagePercent": 10.857273653438812, - "memoryEfficiency": 89.14272634656119, - "cpuCount": 16, - "cpuLoad": 0.015, - "platform": "linux", - "uptime": 7902.09 - }, - { - "timestamp": 1758904203986, - "memoryTotal": 67427545088, - "memoryUsed": 7311708160, - "memoryFree": 60115836928, - "memoryUsagePercent": 10.843800038185368, - "memoryEfficiency": 89.15619996181464, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 7932.12 - }, - { - "timestamp": 1758904233991, - "memoryTotal": 67427545088, - "memoryUsed": 7313403904, - "memoryFree": 60114141184, - "memoryUsagePercent": 10.84631495104151, - "memoryEfficiency": 89.1536850489585, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 7962.12 - }, - { - "timestamp": 1758904263996, - "memoryTotal": 67427545088, - "memoryUsed": 7322066944, - "memoryFree": 60105478144, - "memoryUsagePercent": 10.859162875415288, - "memoryEfficiency": 89.1408371245847, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 7992.13 - }, - { - "timestamp": 1758904294027, - "memoryTotal": 67427545088, - "memoryUsed": 7314563072, - "memoryFree": 60112982016, - "memoryUsagePercent": 10.848034082293417, - "memoryEfficiency": 89.15196591770658, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 8022.16 - }, - { - "timestamp": 1758904324047, - "memoryTotal": 67427545088, - "memoryUsed": 7322025984, - "memoryFree": 60105519104, - "memoryUsagePercent": 10.85910212872794, - "memoryEfficiency": 89.14089787127206, - "cpuCount": 16, - "cpuLoad": 0.009375, - "platform": "linux", - "uptime": 8052.18 - }, - { - "timestamp": 1758904354075, - "memoryTotal": 67427545088, - "memoryUsed": 7321526272, - "memoryFree": 60106018816, - "memoryUsagePercent": 10.858361019142313, - "memoryEfficiency": 89.14163898085769, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 8082.21 - }, - { - "timestamp": 1758904384100, - "memoryTotal": 67427545088, - "memoryUsed": 7322161152, - "memoryFree": 60105383936, - "memoryUsagePercent": 10.859302592796185, - "memoryEfficiency": 89.14069740720382, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 8112.23 - }, - { - "timestamp": 1758904414114, - "memoryTotal": 67427545088, - "memoryUsed": 7287037952, - "memoryFree": 60140507136, - "memoryUsagePercent": 10.807212308396595, - "memoryEfficiency": 89.1927876916034, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 8142.24 - }, - { - "timestamp": 1758904444144, - "memoryTotal": 67427545088, - "memoryUsed": 7288602624, - "memoryFree": 60138942464, - "memoryUsagePercent": 10.80953283185323, - "memoryEfficiency": 89.19046716814677, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 8172.27 - }, - { - "timestamp": 1758904474175, - "memoryTotal": 67427545088, - "memoryUsed": 7297871872, - "memoryFree": 60129673216, - "memoryUsagePercent": 10.823279807199734, - "memoryEfficiency": 89.17672019280026, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 8202.31 - }, - { - "timestamp": 1758904504184, - "memoryTotal": 67427545088, - "memoryUsed": 7295164416, - "memoryFree": 60132380672, - "memoryUsagePercent": 10.819264451166132, - "memoryEfficiency": 89.18073554883387, - "cpuCount": 16, - "cpuLoad": 0.021875, - "platform": "linux", - "uptime": 8232.31 - }, - { - "timestamp": 1758904534214, - "memoryTotal": 67427545088, - "memoryUsed": 7305867264, - "memoryFree": 60121677824, - "memoryUsagePercent": 10.835137560569763, - "memoryEfficiency": 89.16486243943024, - "cpuCount": 16, - "cpuLoad": 0.036875, - "platform": "linux", - "uptime": 8262.34 - }, - { - "timestamp": 1758904564244, - "memoryTotal": 67427545088, - "memoryUsed": 7283568640, - "memoryFree": 60143976448, - "memoryUsagePercent": 10.80206706397835, - "memoryEfficiency": 89.19793293602164, - "cpuCount": 16, - "cpuLoad": 0.0275, - "platform": "linux", - "uptime": 8292.37 - }, - { - "timestamp": 1758904594275, - "memoryTotal": 67427545088, - "memoryUsed": 7310872576, - "memoryFree": 60116672512, - "memoryUsagePercent": 10.8425608057635, - "memoryEfficiency": 89.1574391942365, - "cpuCount": 16, - "cpuLoad": 0.020625, - "platform": "linux", - "uptime": 8322.41 - }, - { - "timestamp": 1758904624305, - "memoryTotal": 67427545088, - "memoryUsed": 7295885312, - "memoryFree": 60131659776, - "memoryUsagePercent": 10.820333592863431, - "memoryEfficiency": 89.17966640713657, - "cpuCount": 16, - "cpuLoad": 0.020625, - "platform": "linux", - "uptime": 8352.44 - }, - { - "timestamp": 1758904654335, - "memoryTotal": 67427545088, - "memoryUsed": 7332564992, - "memoryFree": 60094980096, - "memoryUsagePercent": 10.874732251382184, - "memoryEfficiency": 89.12526774861782, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 8382.47 - }, - { - "timestamp": 1758904684344, - "memoryTotal": 67427545088, - "memoryUsed": 7299543040, - "memoryFree": 60128002048, - "memoryUsagePercent": 10.825758272043469, - "memoryEfficiency": 89.17424172795653, - "cpuCount": 16, - "cpuLoad": 0.02125, - "platform": "linux", - "uptime": 8412.47 - }, - { - "timestamp": 1758904714374, - "memoryTotal": 67427545088, - "memoryUsed": 7304359936, - "memoryFree": 60123185152, - "memoryUsagePercent": 10.832902082475412, - "memoryEfficiency": 89.16709791752459, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 8442.5 - }, - { - "timestamp": 1758904744405, - "memoryTotal": 67427545088, - "memoryUsed": 7288274944, - "memoryFree": 60139270144, - "memoryUsagePercent": 10.809046858354458, - "memoryEfficiency": 89.19095314164554, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 8472.54 - }, - { - "timestamp": 1758904774436, - "memoryTotal": 67427545088, - "memoryUsed": 7297347584, - "memoryFree": 60130197504, - "memoryUsagePercent": 10.8225022496017, - "memoryEfficiency": 89.1774977503983, - "cpuCount": 16, - "cpuLoad": 0.015, - "platform": "linux", - "uptime": 8502.57 - }, - { - "timestamp": 1758904804449, - "memoryTotal": 67427545088, - "memoryUsed": 7327404032, - "memoryFree": 60100141056, - "memoryUsagePercent": 10.867078168776532, - "memoryEfficiency": 89.13292183122347, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 8532.58 - }, - { - "timestamp": 1758904834479, - "memoryTotal": 67427545088, - "memoryUsed": 7305170944, - "memoryFree": 60122374144, - "memoryUsagePercent": 10.834104866884871, - "memoryEfficiency": 89.16589513311513, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 8562.61 - }, - { - "timestamp": 1758904864509, - "memoryTotal": 67427545088, - "memoryUsed": 7334907904, - "memoryFree": 60092637184, - "memoryUsagePercent": 10.878206961898403, - "memoryEfficiency": 89.1217930381016, - "cpuCount": 16, - "cpuLoad": 0.004375, - "platform": "linux", - "uptime": 8592.64 - }, - { - "timestamp": 1758904894540, - "memoryTotal": 67427545088, - "memoryUsed": 7301533696, - "memoryFree": 60126011392, - "memoryUsagePercent": 10.828710561048508, - "memoryEfficiency": 89.17128943895149, - "cpuCount": 16, - "cpuLoad": 0.0025, - "platform": "linux", - "uptime": 8622.67 - }, - { - "timestamp": 1758904924570, - "memoryTotal": 67427545088, - "memoryUsed": 7312916480, - "memoryFree": 60114628608, - "memoryUsagePercent": 10.845592065462089, - "memoryEfficiency": 89.15440793453791, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 8652.7 - }, - { - "timestamp": 1758904954593, - "memoryTotal": 67427545088, - "memoryUsed": 7306428416, - "memoryFree": 60121116672, - "memoryUsagePercent": 10.83596979018641, - "memoryEfficiency": 89.16403020981359, - "cpuCount": 16, - "cpuLoad": 0.015625, - "platform": "linux", - "uptime": 8682.72 - }, - { - "timestamp": 1758904984609, - "memoryTotal": 67427545088, - "memoryUsed": 7313801216, - "memoryFree": 60113743872, - "memoryUsagePercent": 10.846904193908772, - "memoryEfficiency": 89.15309580609123, - "cpuCount": 16, - "cpuLoad": 0.009375, - "platform": "linux", - "uptime": 8712.74 - }, - { - "timestamp": 1758905014625, - "memoryTotal": 67427545088, - "memoryUsed": 7303499776, - "memoryFree": 60124045312, - "memoryUsagePercent": 10.831626402041138, - "memoryEfficiency": 89.16837359795886, - "cpuCount": 16, - "cpuLoad": 0.009375, - "platform": "linux", - "uptime": 8742.76 - }, - { - "timestamp": 1758905044641, - "memoryTotal": 67427545088, - "memoryUsed": 7326777344, - "memoryFree": 60100767744, - "memoryUsagePercent": 10.86614874446013, - "memoryEfficiency": 89.13385125553987, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 8772.77 - }, - { - "timestamp": 1758905074657, - "memoryTotal": 67427545088, - "memoryUsed": 7339851776, - "memoryFree": 60087693312, - "memoryUsagePercent": 10.885539087061119, - "memoryEfficiency": 89.11446091293888, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 8802.79 - }, - { - "timestamp": 1758905104673, - "memoryTotal": 67427545088, - "memoryUsed": 7347150848, - "memoryFree": 60080394240, - "memoryUsagePercent": 10.896364146746258, - "memoryEfficiency": 89.10363585325373, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 8832.8 - }, - { - "timestamp": 1758905134703, - "memoryTotal": 67427545088, - "memoryUsed": 7343198208, - "memoryFree": 60084346880, - "memoryUsagePercent": 10.890502091417325, - "memoryEfficiency": 89.10949790858268, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 8862.83 - }, - { - "timestamp": 1758905164706, - "memoryTotal": 67427545088, - "memoryUsed": 7321587712, - "memoryFree": 60105957376, - "memoryUsagePercent": 10.858452139173332, - "memoryEfficiency": 89.14154786082666, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 8892.84 - }, - { - "timestamp": 1758905194706, - "memoryTotal": 67427545088, - "memoryUsed": 7336960000, - "memoryFree": 60090585088, - "memoryUsagePercent": 10.88125037093446, - "memoryEfficiency": 89.11874962906555, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 8922.84 - }, - { - "timestamp": 1758905224726, - "memoryTotal": 67427545088, - "memoryUsed": 7306600448, - "memoryFree": 60120944640, - "memoryUsagePercent": 10.836224926273266, - "memoryEfficiency": 89.16377507372674, - "cpuCount": 16, - "cpuLoad": 0.015625, - "platform": "linux", - "uptime": 8952.86 - }, - { - "timestamp": 1758905254757, - "memoryTotal": 67427545088, - "memoryUsed": 7335989248, - "memoryFree": 60091555840, - "memoryUsagePercent": 10.879810674444348, - "memoryEfficiency": 89.12018932555566, - "cpuCount": 16, - "cpuLoad": 0.009375, - "platform": "linux", - "uptime": 8982.89 - }, - { - "timestamp": 1758905284787, - "memoryTotal": 67427545088, - "memoryUsed": 7333965824, - "memoryFree": 60093579264, - "memoryUsagePercent": 10.876809788089433, - "memoryEfficiency": 89.12319021191057, - "cpuCount": 16, - "cpuLoad": 0.005625, - "platform": "linux", - "uptime": 9012.92 - }, - { - "timestamp": 1758905314817, - "memoryTotal": 67427545088, - "memoryUsed": 7463329792, - "memoryFree": 59964215296, - "memoryUsagePercent": 11.068666050735755, - "memoryEfficiency": 88.93133394926424, - "cpuCount": 16, - "cpuLoad": 0.020625, - "platform": "linux", - "uptime": 9042.95 - }, - { - "timestamp": 1758905344847, - "memoryTotal": 67427545088, - "memoryUsed": 7467286528, - "memoryFree": 59960258560, - "memoryUsagePercent": 11.074534180733423, - "memoryEfficiency": 88.92546581926658, - "cpuCount": 16, - "cpuLoad": 0.05875, - "platform": "linux", - "uptime": 9072.98 - }, - { - "timestamp": 1758905374852, - "memoryTotal": 67427545088, - "memoryUsed": 7375790080, - "memoryFree": 60051755008, - "memoryUsagePercent": 10.938838230538902, - "memoryEfficiency": 89.0611617694611, - "cpuCount": 16, - "cpuLoad": 0.05, - "platform": "linux", - "uptime": 9102.98 - }, - { - "timestamp": 1758905404882, - "memoryTotal": 67427545088, - "memoryUsed": 7393120256, - "memoryFree": 60034424832, - "memoryUsagePercent": 10.96454015395519, - "memoryEfficiency": 89.03545984604482, - "cpuCount": 16, - "cpuLoad": 0.03, - "platform": "linux", - "uptime": 9133.01 - }, - { - "timestamp": 1758905434913, - "memoryTotal": 67427545088, - "memoryUsed": 7372312576, - "memoryFree": 60055232512, - "memoryUsagePercent": 10.93368083678319, - "memoryEfficiency": 89.0663191632168, - "cpuCount": 16, - "cpuLoad": 0.0225, - "platform": "linux", - "uptime": 9163.04 - }, - { - "timestamp": 1758905464943, - "memoryTotal": 67427545088, - "memoryUsed": 7348367360, - "memoryFree": 60079177728, - "memoryUsagePercent": 10.898168323360448, - "memoryEfficiency": 89.10183167663955, - "cpuCount": 16, - "cpuLoad": 0.0275, - "platform": "linux", - "uptime": 9193.07 - }, - { - "timestamp": 1758905494974, - "memoryTotal": 67427545088, - "memoryUsed": 7378558976, - "memoryFree": 60048986112, - "memoryUsagePercent": 10.942944706603523, - "memoryEfficiency": 89.05705529339647, - "cpuCount": 16, - "cpuLoad": 0.016875, - "platform": "linux", - "uptime": 9223.1 - }, - { - "timestamp": 1758905525004, - "memoryTotal": 67427545088, - "memoryUsed": 7385448448, - "memoryFree": 60042096640, - "memoryUsagePercent": 10.953162299415197, - "memoryEfficiency": 89.0468377005848, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 9253.13 - }, - { - "timestamp": 1758905555034, - "memoryTotal": 67427545088, - "memoryUsed": 7387512832, - "memoryFree": 60040032256, - "memoryUsagePercent": 10.95622393245746, - "memoryEfficiency": 89.04377606754254, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 9283.16 - }, - { - "timestamp": 1758905585057, - "memoryTotal": 67427545088, - "memoryUsed": 7368880128, - "memoryFree": 60058664960, - "memoryUsagePercent": 10.928590264383555, - "memoryEfficiency": 89.07140973561644, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 9313.19 - }, - { - "timestamp": 1758905615087, - "memoryTotal": 67427545088, - "memoryUsed": 7373352960, - "memoryFree": 60054192128, - "memoryUsagePercent": 10.935223802641788, - "memoryEfficiency": 89.06477619735821, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 9343.22 - }, - { - "timestamp": 1758905645118, - "memoryTotal": 67427545088, - "memoryUsed": 7415611392, - "memoryFree": 60011933696, - "memoryUsagePercent": 10.997896159977131, - "memoryEfficiency": 89.00210384002287, - "cpuCount": 16, - "cpuLoad": 0.003125, - "platform": "linux", - "uptime": 9373.25 - }, - { - "timestamp": 1758905675148, - "memoryTotal": 67427545088, - "memoryUsed": 7399157760, - "memoryFree": 60028387328, - "memoryUsagePercent": 10.973494215670057, - "memoryEfficiency": 89.02650578432994, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 9403.28 - }, - { - "timestamp": 1758905705178, - "memoryTotal": 67427545088, - "memoryUsed": 7407570944, - "memoryFree": 60019974144, - "memoryUsagePercent": 10.98597158525102, - "memoryEfficiency": 89.01402841474898, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 9433.31 - }, - { - "timestamp": 1758905735208, - "memoryTotal": 67427545088, - "memoryUsed": 7391526912, - "memoryFree": 60036018176, - "memoryUsagePercent": 10.962177107817412, - "memoryEfficiency": 89.03782289218259, - "cpuCount": 16, - "cpuLoad": 0.021875, - "platform": "linux", - "uptime": 9463.34 - }, - { - "timestamp": 1758905765239, - "memoryTotal": 67427545088, - "memoryUsed": 7379783680, - "memoryFree": 60047761408, - "memoryUsagePercent": 10.944761032555181, - "memoryEfficiency": 89.05523896744482, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 9493.37 - }, - { - "timestamp": 1758905795268, - "memoryTotal": 67427545088, - "memoryUsed": 7400284160, - "memoryFree": 60027260928, - "memoryUsagePercent": 10.975164749572084, - "memoryEfficiency": 89.02483525042791, - "cpuCount": 16, - "cpuLoad": 0.0175, - "platform": "linux", - "uptime": 9523.4 - }, - { - "timestamp": 1758905825298, - "memoryTotal": 67427545088, - "memoryUsed": 7378423808, - "memoryFree": 60049121280, - "memoryUsagePercent": 10.94274424253528, - "memoryEfficiency": 89.05725575746472, - "cpuCount": 16, - "cpuLoad": 0.020625, - "platform": "linux", - "uptime": 9553.43 - }, - { - "timestamp": 1758905855307, - "memoryTotal": 67427545088, - "memoryUsed": 7412940800, - "memoryFree": 60014604288, - "memoryUsagePercent": 10.993935475962141, - "memoryEfficiency": 89.00606452403785, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 9583.44 - }, - { - "timestamp": 1758905885332, - "memoryTotal": 67427545088, - "memoryUsed": 7383584768, - "memoryFree": 60043960320, - "memoryUsagePercent": 10.950398325140934, - "memoryEfficiency": 89.04960167485906, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 9613.46 - }, - { - "timestamp": 1758905915363, - "memoryTotal": 67427545088, - "memoryUsed": 7387652096, - "memoryFree": 60039892992, - "memoryUsagePercent": 10.956430471194437, - "memoryEfficiency": 89.04356952880556, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 9643.49 - }, - { - "timestamp": 1758905945393, - "memoryTotal": 67427545088, - "memoryUsed": 7392976896, - "memoryFree": 60034568192, - "memoryUsagePercent": 10.964327540549478, - "memoryEfficiency": 89.03567245945052, - "cpuCount": 16, - "cpuLoad": 0.00375, - "platform": "linux", - "uptime": 9673.52 - }, - { - "timestamp": 1758905975424, - "memoryTotal": 67427545088, - "memoryUsed": 7405514752, - "memoryFree": 60022030336, - "memoryUsagePercent": 10.982922101546228, - "memoryEfficiency": 89.01707789845378, - "cpuCount": 16, - "cpuLoad": 0.0025, - "platform": "linux", - "uptime": 9703.55 - }, - { - "timestamp": 1758906005455, - "memoryTotal": 67427545088, - "memoryUsed": 7380357120, - "memoryFree": 60047187968, - "memoryUsagePercent": 10.945611486178034, - "memoryEfficiency": 89.05438851382196, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 9733.58 - }, - { - "timestamp": 1758906035484, - "memoryTotal": 67427545088, - "memoryUsed": 7406256128, - "memoryFree": 60021288960, - "memoryUsagePercent": 10.9840216165872, - "memoryEfficiency": 89.0159783834128, - "cpuCount": 16, - "cpuLoad": 0.009375, - "platform": "linux", - "uptime": 9763.61 - }, - { - "timestamp": 1758906065514, - "memoryTotal": 67427545088, - "memoryUsed": 7397883904, - "memoryFree": 60029661184, - "memoryUsagePercent": 10.971604993693584, - "memoryEfficiency": 89.02839500630641, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 9793.64 - }, - { - "timestamp": 1758906095531, - "memoryTotal": 67427545088, - "memoryUsed": 7388160000, - "memoryFree": 60039385088, - "memoryUsagePercent": 10.957183730117533, - "memoryEfficiency": 89.04281626988247, - "cpuCount": 16, - "cpuLoad": 0.008125, - "platform": "linux", - "uptime": 9823.66 - }, - { - "timestamp": 1758906125562, - "memoryTotal": 67427545088, - "memoryUsed": 7403048960, - "memoryFree": 60024496128, - "memoryUsagePercent": 10.97926515096797, - "memoryEfficiency": 89.02073484903202, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 9853.69 - }, - { - "timestamp": 1758906155592, - "memoryTotal": 67427545088, - "memoryUsed": 7379451904, - "memoryFree": 60048093184, - "memoryUsagePercent": 10.944268984387676, - "memoryEfficiency": 89.05573101561232, - "cpuCount": 16, - "cpuLoad": 0.010625, - "platform": "linux", - "uptime": 9883.72 - }, - { - "timestamp": 1758906185623, - "memoryTotal": 67427545088, - "memoryUsed": 7353663488, - "memoryFree": 60073881600, - "memoryUsagePercent": 10.906022870034345, - "memoryEfficiency": 89.09397712996565, - "cpuCount": 16, - "cpuLoad": 0.00625, - "platform": "linux", - "uptime": 9913.75 - }, - { - "timestamp": 1758906215653, - "memoryTotal": 67427545088, - "memoryUsed": 7349702656, - "memoryFree": 60077842432, - "memoryUsagePercent": 10.900148665367942, - "memoryEfficiency": 89.09985133463206, - "cpuCount": 16, - "cpuLoad": 0.00375, - "platform": "linux", - "uptime": 9943.78 - }, - { - "timestamp": 1758906245682, - "memoryTotal": 67427545088, - "memoryUsed": 7356911616, - "memoryFree": 60070633472, - "memoryUsagePercent": 10.91084008234092, - "memoryEfficiency": 89.08915991765907, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 9973.81 - }, - { - "timestamp": 1758906275713, - "memoryTotal": 67427545088, - "memoryUsed": 7358664704, - "memoryFree": 60068880384, - "memoryUsagePercent": 10.913440040559347, - "memoryEfficiency": 89.08655995944065, - "cpuCount": 16, - "cpuLoad": 0.0125, - "platform": "linux", - "uptime": 10003.84 - }, - { - "timestamp": 1758906305743, - "memoryTotal": 67427545088, - "memoryUsed": 7382736896, - "memoryFree": 60044808192, - "memoryUsagePercent": 10.949140868712862, - "memoryEfficiency": 89.05085913128714, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 10033.87 - }, - { - "timestamp": 1758906335774, - "memoryTotal": 67427545088, - "memoryUsed": 7377068032, - "memoryFree": 60050477056, - "memoryUsagePercent": 10.940733527184113, - "memoryEfficiency": 89.05926647281589, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 10063.9 - }, - { - "timestamp": 1758906365804, - "memoryTotal": 67427545088, - "memoryUsed": 7412596736, - "memoryFree": 60014948352, - "memoryUsagePercent": 10.99342520378843, - "memoryEfficiency": 89.00657479621157, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 10093.93 - }, - { - "timestamp": 1758906395813, - "memoryTotal": 67427545088, - "memoryUsed": 7482089472, - "memoryFree": 59945455616, - "memoryUsagePercent": 11.096488033540433, - "memoryEfficiency": 88.90351196645956, - "cpuCount": 16, - "cpuLoad": 0.0175, - "platform": "linux", - "uptime": 10123.94 - }, - { - "timestamp": 1758906425841, - "memoryTotal": 67427545088, - "memoryUsed": 7578402816, - "memoryFree": 59849142272, - "memoryUsagePercent": 11.239327794166897, - "memoryEfficiency": 88.7606722058331, - "cpuCount": 16, - "cpuLoad": 0.015, - "platform": "linux", - "uptime": 10153.97 - }, - { - "timestamp": 1758906455872, - "memoryTotal": 67427545088, - "memoryUsed": 7420014592, - "memoryFree": 60007530496, - "memoryUsagePercent": 11.004426428866875, - "memoryEfficiency": 88.99557357113312, - "cpuCount": 16, - "cpuLoad": 0.041875, - "platform": "linux", - "uptime": 10184 - }, - { - "timestamp": 1758906485902, - "memoryTotal": 67427545088, - "memoryUsed": 7506022400, - "memoryFree": 59921522688, - "memoryUsagePercent": 11.13198232295697, - "memoryEfficiency": 88.86801767704303, - "cpuCount": 16, - "cpuLoad": 0.045625, - "platform": "linux", - "uptime": 10214.03 - }, - { - "timestamp": 1758906515933, - "memoryTotal": 67427545088, - "memoryUsed": 7561560064, - "memoryFree": 59865985024, - "memoryUsagePercent": 11.214348756330033, - "memoryEfficiency": 88.78565124366997, - "cpuCount": 16, - "cpuLoad": 0.03625, - "platform": "linux", - "uptime": 10244.06 - }, - { - "timestamp": 1758906545963, - "memoryTotal": 67427545088, - "memoryUsed": 7522308096, - "memoryFree": 59905236992, - "memoryUsagePercent": 11.15613520584592, - "memoryEfficiency": 88.84386479415409, - "cpuCount": 16, - "cpuLoad": 0.035, - "platform": "linux", - "uptime": 10274.09 - }, - { - "timestamp": 1758906575965, - "memoryTotal": 67427545088, - "memoryUsed": 7498969088, - "memoryFree": 59928576000, - "memoryUsagePercent": 11.121521743395908, - "memoryEfficiency": 88.8784782566041, - "cpuCount": 16, - "cpuLoad": 0.040625, - "platform": "linux", - "uptime": 10304.1 - }, - { - "timestamp": 1758906605995, - "memoryTotal": 67427545088, - "memoryUsed": 7519477760, - "memoryFree": 59908067328, - "memoryUsagePercent": 11.15193760975028, - "memoryEfficiency": 88.84806239024972, - "cpuCount": 16, - "cpuLoad": 0.044375, - "platform": "linux", - "uptime": 10334.13 - }, - { - "timestamp": 1758906636015, - "memoryTotal": 67427545088, - "memoryUsed": 7452688384, - "memoryFree": 59974856704, - "memoryUsagePercent": 11.052884061363144, - "memoryEfficiency": 88.94711593863686, - "cpuCount": 16, - "cpuLoad": 0.03125, - "platform": "linux", - "uptime": 10364.15 - }, - { - "timestamp": 1758906666017, - "memoryTotal": 67427545088, - "memoryUsed": 7506706432, - "memoryFree": 59920838656, - "memoryUsagePercent": 11.132996792635655, - "memoryEfficiency": 88.86700320736435, + "memoryUsed": 7645425664, + "memoryFree": 59782119424, + "memoryUsagePercent": 11.338727598671907, + "memoryEfficiency": 88.66127240132809, "cpuCount": 16, "cpuLoad": 0.05125, "platform": "linux", - "uptime": 10394.15 + "uptime": 5482.16 }, { - "timestamp": 1758906696047, + "timestamp": 1758901784049, "memoryTotal": 67427545088, - "memoryUsed": 7569944576, - "memoryFree": 59857600512, - "memoryUsagePercent": 11.226783603229853, - "memoryEfficiency": 88.77321639677015, + "memoryUsed": 7938396160, + "memoryFree": 59489148928, + "memoryUsagePercent": 11.77322435458619, + "memoryEfficiency": 88.22677564541381, "cpuCount": 16, - "cpuLoad": 0.05, + "cpuLoad": 0.04, "platform": "linux", - "uptime": 10424.18 + "uptime": 5512.18 }, { - "timestamp": 1758906726056, + "timestamp": 1758901814080, "memoryTotal": 67427545088, - "memoryUsed": 7618088960, - "memoryFree": 59809456128, - "memoryUsagePercent": 11.298185259536881, - "memoryEfficiency": 88.70181474046312, + "memoryUsed": 7646855168, + "memoryFree": 59780689920, + "memoryUsagePercent": 11.3408476580603, + "memoryEfficiency": 88.6591523419397, "cpuCount": 16, - "cpuLoad": 0.055625, + "cpuLoad": 0.09, "platform": "linux", - "uptime": 10454.19 + "uptime": 5542.21 }, { - "timestamp": 1758906756085, + "timestamp": 1758901844110, "memoryTotal": 67427545088, - "memoryUsed": 7491678208, - "memoryFree": 59935866880, - "memoryUsagePercent": 11.110708833048239, - "memoryEfficiency": 88.88929116695176, + "memoryUsed": 7523151872, + "memoryFree": 59904393216, + "memoryUsagePercent": 11.15738658760526, + "memoryEfficiency": 88.84261341239474, "cpuCount": 16, - "cpuLoad": 0.036875, + "cpuLoad": 0.07625, "platform": "linux", - "uptime": 10484.22 + "uptime": 5572.24 }, { - "timestamp": 1758906786116, + "timestamp": 1758901874117, "memoryTotal": 67427545088, - "memoryUsed": 7443337216, - "memoryFree": 59984207872, - "memoryUsagePercent": 11.039015592641949, - "memoryEfficiency": 88.96098440735805, + "memoryUsed": 7536656384, + "memoryFree": 59890888704, + "memoryUsagePercent": 11.177414770423386, + "memoryEfficiency": 88.82258522957662, + "cpuCount": 16, + "cpuLoad": 0.095, + "platform": "linux", + "uptime": 5602.25 + }, + { + "timestamp": 1758901904146, + "memoryTotal": 67427545088, + "memoryUsed": 7510568960, + "memoryFree": 59916976128, + "memoryUsagePercent": 11.138725205252426, + "memoryEfficiency": 88.86127479474757, + "cpuCount": 16, + "cpuLoad": 0.1, + "platform": "linux", + "uptime": 5632.28 + }, + { + "timestamp": 1758901934176, + "memoryTotal": 67427545088, + "memoryUsed": 7402721280, + "memoryFree": 60024823808, + "memoryUsagePercent": 10.9787791774692, + "memoryEfficiency": 89.02122082253081, + "cpuCount": 16, + "cpuLoad": 0.085625, + "platform": "linux", + "uptime": 5662.31 + }, + { + "timestamp": 1758901964206, + "memoryTotal": 67427545088, + "memoryUsed": 7326724096, + "memoryFree": 60100820992, + "memoryUsagePercent": 10.86606977376658, + "memoryEfficiency": 89.13393022623342, + "cpuCount": 16, + "cpuLoad": 0.051875, + "platform": "linux", + "uptime": 5692.34 + }, + { + "timestamp": 1758901994236, + "memoryTotal": 67427545088, + "memoryUsed": 7321341952, + "memoryFree": 60106203136, + "memoryUsagePercent": 10.858087659049255, + "memoryEfficiency": 89.14191234095074, "cpuCount": 16, "cpuLoad": 0.035, "platform": "linux", - "uptime": 10514.25 + "uptime": 5722.37 }, { - "timestamp": 1758906816147, + "timestamp": 1758902024267, "memoryTotal": 67427545088, - "memoryUsed": 7390892032, - "memoryFree": 60036653056, - "memoryUsagePercent": 10.961235534163542, - "memoryEfficiency": 89.03876446583646, + "memoryUsed": 7350059008, + "memoryFree": 60077486080, + "memoryUsagePercent": 10.900677161547858, + "memoryEfficiency": 89.09932283845214, "cpuCount": 16, - "cpuLoad": 0.031875, + "cpuLoad": 0.0375, "platform": "linux", - "uptime": 10544.28 + "uptime": 5752.4 }, { - "timestamp": 1758906846154, + "timestamp": 1758902054273, "memoryTotal": 67427545088, - "memoryUsed": 7461081088, - "memoryFree": 59966464000, - "memoryUsagePercent": 11.065331057600435, - "memoryEfficiency": 88.93466894239957, + "memoryUsed": 7337758720, + "memoryFree": 60089786368, + "memoryUsagePercent": 10.882434931337716, + "memoryEfficiency": 89.11756506866229, "cpuCount": 16, - "cpuLoad": 0.033125, + "cpuLoad": 0.0225, "platform": "linux", - "uptime": 10574.28 + "uptime": 5782.4 }, { - "timestamp": 1758906876184, + "timestamp": 1758902084304, "memoryTotal": 67427545088, - "memoryUsed": 7397408768, - "memoryFree": 60030136320, - "memoryUsagePercent": 10.970900332120364, - "memoryEfficiency": 89.02909966787963, + "memoryUsed": 7356108800, + "memoryFree": 60071436288, + "memoryUsagePercent": 10.90964944726893, + "memoryEfficiency": 89.09035055273107, "cpuCount": 16, - "cpuLoad": 0.024375, + "cpuLoad": 0.018125, "platform": "linux", - "uptime": 10604.31 + "uptime": 5812.43 }, { - "timestamp": 1758906906193, + "timestamp": 1758902114334, "memoryTotal": 67427545088, - "memoryUsed": 7456239616, - "memoryFree": 59971305472, - "memoryUsagePercent": 11.058150799156083, - "memoryEfficiency": 88.94184920084392, + "memoryUsed": 7357157376, + "memoryFree": 60070387712, + "memoryUsagePercent": 10.911204562464999, + "memoryEfficiency": 89.088795437535, "cpuCount": 16, - "cpuLoad": 0.02625, + "cpuLoad": 0.010625, "platform": "linux", - "uptime": 10634.32 + "uptime": 5842.46 }, { - "timestamp": 1758906936199, + "timestamp": 1758902144337, "memoryTotal": 67427545088, - "memoryUsed": 7408041984, - "memoryFree": 60019503104, - "memoryUsagePercent": 10.986670172155504, - "memoryEfficiency": 89.0133298278445, + "memoryUsed": 7338897408, + "memoryFree": 60088647680, + "memoryUsagePercent": 10.884123689245948, + "memoryEfficiency": 89.11587631075405, "cpuCount": 16, - "cpuLoad": 0.01625, + "cpuLoad": 0.00625, "platform": "linux", - "uptime": 10664.33 + "uptime": 5872.47 }, { - "timestamp": 1758906966230, + "timestamp": 1758902174367, "memoryTotal": 67427545088, - "memoryUsed": 7433576448, - "memoryFree": 59993968640, - "memoryUsagePercent": 11.024539657047287, - "memoryEfficiency": 88.97546034295272, - "cpuCount": 16, - "cpuLoad": 0.014375, - "platform": "linux", - "uptime": 10694.36 - }, - { - "timestamp": 1758906996260, - "memoryTotal": 67427545088, - "memoryUsed": 7401136128, - "memoryFree": 60026408960, - "memoryUsagePercent": 10.976428280668891, - "memoryEfficiency": 89.0235717193311, + "memoryUsed": 7347564544, + "memoryFree": 60079980544, + "memoryUsagePercent": 10.896977688288457, + "memoryEfficiency": 89.10302231171154, "cpuCount": 16, "cpuLoad": 0.00875, "platform": "linux", - "uptime": 10724.39 + "uptime": 5902.5 }, { - "timestamp": 1758907026290, + "timestamp": 1758902204382, "memoryTotal": 67427545088, - "memoryUsed": 7410057216, - "memoryFree": 60017487872, - "memoryUsagePercent": 10.98965890917295, - "memoryEfficiency": 89.01034109082705, - "cpuCount": 16, - "cpuLoad": 0.005, - "platform": "linux", - "uptime": 10754.42 - }, - { - "timestamp": 1758907056320, - "memoryTotal": 67427545088, - "memoryUsed": 7394607104, - "memoryFree": 60032937984, - "memoryUsagePercent": 10.966745258705867, - "memoryEfficiency": 89.03325474129413, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 10784.45 - }, - { - "timestamp": 1758907086350, - "memoryTotal": 67427545088, - "memoryUsed": 7442571264, - "memoryFree": 59984973824, - "memoryUsagePercent": 11.03787962958857, - "memoryEfficiency": 88.96212037041143, - "cpuCount": 16, - "cpuLoad": 0.0075, - "platform": "linux", - "uptime": 10814.48 - }, - { - "timestamp": 1758907116368, - "memoryTotal": 67427545088, - "memoryUsed": 7419752448, - "memoryFree": 60007792640, - "memoryUsagePercent": 11.004037650067858, - "memoryEfficiency": 88.99596234993214, + "memoryUsed": 7353937920, + "memoryFree": 60073607168, + "memoryUsagePercent": 10.906429872839567, + "memoryEfficiency": 89.09357012716043, "cpuCount": 16, "cpuLoad": 0.01875, "platform": "linux", - "uptime": 10844.5 + "uptime": 5932.51 }, { - "timestamp": 1758907146381, + "timestamp": 1758902234385, "memoryTotal": 67427545088, - "memoryUsed": 7443861504, - "memoryFree": 59983683584, - "memoryUsagePercent": 11.039793150239984, - "memoryEfficiency": 88.96020684976001, + "memoryUsed": 7358689280, + "memoryFree": 60068855808, + "memoryUsagePercent": 10.913476488571757, + "memoryEfficiency": 89.08652351142824, "cpuCount": 16, - "cpuLoad": 0.046875, + "cpuLoad": 0.01875, "platform": "linux", - "uptime": 10874.51 + "uptime": 5962.52 }, { - "timestamp": 1758907176391, + "timestamp": 1758902264385, "memoryTotal": 67427545088, - "memoryUsed": 7391739904, - "memoryFree": 60035805184, - "memoryUsagePercent": 10.962492990591615, - "memoryEfficiency": 89.03750700940839, - "cpuCount": 16, - "cpuLoad": 0.0325, - "platform": "linux", - "uptime": 10904.52 - }, - { - "timestamp": 1758907206406, - "memoryTotal": 67427545088, - "memoryUsed": 7413481472, - "memoryFree": 60014063616, - "memoryUsagePercent": 10.994737332235115, - "memoryEfficiency": 89.00526266776488, - "cpuCount": 16, - "cpuLoad": 0.019375, - "platform": "linux", - "uptime": 10934.54 - }, - { - "timestamp": 1758907236436, - "memoryTotal": 67427545088, - "memoryUsed": 7437254656, - "memoryFree": 59990290432, - "memoryUsagePercent": 11.029994709571, - "memoryEfficiency": 88.970005290429, - "cpuCount": 16, - "cpuLoad": 0.02, - "platform": "linux", - "uptime": 10964.57 - }, - { - "timestamp": 1758907266466, - "memoryTotal": 67427545088, - "memoryUsed": 7420850176, - "memoryFree": 60006694912, - "memoryUsagePercent": 11.005665661288742, - "memoryEfficiency": 88.99433433871125, - "cpuCount": 16, - "cpuLoad": 0.021875, - "platform": "linux", - "uptime": 10994.6 - }, - { - "timestamp": 1758907296497, - "memoryTotal": 67427545088, - "memoryUsed": 7406862336, - "memoryFree": 60020682752, - "memoryUsagePercent": 10.984920667559926, - "memoryEfficiency": 89.01507933244008, - "cpuCount": 16, - "cpuLoad": 0.03375, - "platform": "linux", - "uptime": 11024.63 - }, - { - "timestamp": 1758907326500, - "memoryTotal": 67427545088, - "memoryUsed": 7420874752, - "memoryFree": 60006670336, - "memoryUsagePercent": 11.00570210930115, - "memoryEfficiency": 88.99429789069885, - "cpuCount": 16, - "cpuLoad": 0.02, - "platform": "linux", - "uptime": 11054.63 - }, - { - "timestamp": 1758907356521, - "memoryTotal": 67427545088, - "memoryUsed": 7446896640, - "memoryFree": 59980648448, - "memoryUsagePercent": 11.044294479772356, - "memoryEfficiency": 88.95570552022764, - "cpuCount": 16, - "cpuLoad": 0.029375, - "platform": "linux", - "uptime": 11084.65 - }, - { - "timestamp": 1758907386551, - "memoryTotal": 67427545088, - "memoryUsed": 7446347776, - "memoryFree": 59981197312, - "memoryUsagePercent": 11.043480474161912, - "memoryEfficiency": 88.95651952583809, - "cpuCount": 16, - "cpuLoad": 0.0175, - "platform": "linux", - "uptime": 11114.68 - }, - { - "timestamp": 1758907416580, - "memoryTotal": 67427545088, - "memoryUsed": 7416602624, - "memoryFree": 60010942464, - "memoryUsagePercent": 10.999366229810914, - "memoryEfficiency": 89.00063377018908, - "cpuCount": 16, - "cpuLoad": 0.01375, - "platform": "linux", - "uptime": 11144.71 - }, - { - "timestamp": 1758907446611, - "memoryTotal": 67427545088, - "memoryUsed": 7437312000, - "memoryFree": 59990233088, - "memoryUsagePercent": 11.030079754933283, - "memoryEfficiency": 88.96992024506672, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 11174.74 - }, - { - "timestamp": 1758907476642, - "memoryTotal": 67427545088, - "memoryUsed": 7435894784, - "memoryFree": 59991650304, - "memoryUsagePercent": 11.027977919551097, - "memoryEfficiency": 88.97202208044891, - "cpuCount": 16, - "cpuLoad": 0.01625, - "platform": "linux", - "uptime": 11204.77 - }, - { - "timestamp": 1758907506672, - "memoryTotal": 67427545088, - "memoryUsed": 7453286400, - "memoryFree": 59974258688, - "memoryUsagePercent": 11.053770962998403, - "memoryEfficiency": 88.9462290370016, - "cpuCount": 16, - "cpuLoad": 0.026875, - "platform": "linux", - "uptime": 11234.8 - }, - { - "timestamp": 1758907536703, - "memoryTotal": 67427545088, - "memoryUsed": 7428804608, - "memoryFree": 59998740480, - "memoryUsagePercent": 11.017462667971424, - "memoryEfficiency": 88.98253733202857, - "cpuCount": 16, - "cpuLoad": 0.01625, - "platform": "linux", - "uptime": 11264.83 - }, - { - "timestamp": 1758907566725, - "memoryTotal": 67427545088, - "memoryUsed": 7454187520, - "memoryFree": 59973357568, - "memoryUsagePercent": 11.055107390120025, - "memoryEfficiency": 88.94489260987997, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 11294.85 - }, - { - "timestamp": 1758907596755, - "memoryTotal": 67427545088, - "memoryUsed": 7462105088, - "memoryFree": 59965440000, - "memoryUsagePercent": 11.066849724784095, - "memoryEfficiency": 88.93315027521591, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 11324.89 - }, - { - "timestamp": 1758907626785, - "memoryTotal": 67427545088, - "memoryUsed": 7461830656, - "memoryFree": 59965714432, - "memoryUsagePercent": 11.066442721978873, - "memoryEfficiency": 88.93355727802113, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 11354.92 - }, - { - "timestamp": 1758907656816, - "memoryTotal": 67427545088, - "memoryUsed": 7430959104, - "memoryFree": 59996585984, - "memoryUsagePercent": 11.020657943725848, - "memoryEfficiency": 88.97934205627415, - "cpuCount": 16, - "cpuLoad": 0.004375, - "platform": "linux", - "uptime": 11384.95 - }, - { - "timestamp": 1758907686846, - "memoryTotal": 67427545088, - "memoryUsed": 7449636864, - "memoryFree": 59977908224, - "memoryUsagePercent": 11.048358433155833, - "memoryEfficiency": 88.95164156684416, - "cpuCount": 16, - "cpuLoad": 0.006875, - "platform": "linux", - "uptime": 11414.98 - }, - { - "timestamp": 1758907716877, - "memoryTotal": 67427545088, - "memoryUsed": 7447998464, - "memoryFree": 59979546624, - "memoryUsagePercent": 11.045928565661974, - "memoryEfficiency": 88.95407143433803, - "cpuCount": 16, - "cpuLoad": 0.00375, - "platform": "linux", - "uptime": 11445.01 - }, - { - "timestamp": 1758907746907, - "memoryTotal": 67427545088, - "memoryUsed": 7420674048, - "memoryFree": 60006871040, - "memoryUsagePercent": 11.005404450533153, - "memoryEfficiency": 88.99459554946685, - "cpuCount": 16, - "cpuLoad": 0.0025, - "platform": "linux", - "uptime": 11475.04 - }, - { - "timestamp": 1758907776938, - "memoryTotal": 67427545088, - "memoryUsed": 7442604032, - "memoryFree": 59984941056, - "memoryUsagePercent": 11.037928226938448, - "memoryEfficiency": 88.96207177306155, - "cpuCount": 16, - "cpuLoad": 0.01, - "platform": "linux", - "uptime": 11505.07 - }, - { - "timestamp": 1758907806941, - "memoryTotal": 67427545088, - "memoryUsed": 7490965504, - "memoryFree": 59936579584, - "memoryUsagePercent": 11.10965184068841, - "memoryEfficiency": 88.89034815931159, - "cpuCount": 16, - "cpuLoad": 0.01125, - "platform": "linux", - "uptime": 11535.07 - }, - { - "timestamp": 1758907836971, - "memoryTotal": 67427545088, - "memoryUsed": 7485009920, - "memoryFree": 59942535168, - "memoryUsagePercent": 11.100819272348234, - "memoryEfficiency": 88.89918072765177, - "cpuCount": 16, - "cpuLoad": 0.013125, - "platform": "linux", - "uptime": 11565.1 - }, - { - "timestamp": 1758907867002, - "memoryTotal": 67427545088, - "memoryUsed": 7503552512, - "memoryFree": 59923992576, - "memoryUsagePercent": 11.128319297709979, - "memoryEfficiency": 88.87168070229002, - "cpuCount": 16, - "cpuLoad": 0.011875, - "platform": "linux", - "uptime": 11595.13 - }, - { - "timestamp": 1758907897011, - "memoryTotal": 67427545088, - "memoryUsed": 7502368768, - "memoryFree": 59925176320, - "memoryUsagePercent": 11.126563718445665, - "memoryEfficiency": 88.87343628155433, + "memoryUsed": 7355609088, + "memoryFree": 60071936000, + "memoryUsagePercent": 10.908908337683302, + "memoryEfficiency": 89.0910916623167, "cpuCount": 16, "cpuLoad": 0.024375, "platform": "linux", - "uptime": 11625.14 + "uptime": 5992.52 }, { - "timestamp": 1758907927040, + "timestamp": 1758902294401, "memoryTotal": 67427545088, - "memoryUsed": 7557017600, - "memoryFree": 59870527488, - "memoryUsagePercent": 11.207611948703311, - "memoryEfficiency": 88.79238805129668, + "memoryUsed": 7353880576, + "memoryFree": 60073664512, + "memoryUsagePercent": 10.906344827477282, + "memoryEfficiency": 89.09365517252272, "cpuCount": 16, - "cpuLoad": 0.055625, + "cpuLoad": 0.015, "platform": "linux", - "uptime": 11655.17 + "uptime": 6022.53 }, { - "timestamp": 1758907957071, + "timestamp": 1758902324431, "memoryTotal": 67427545088, - "memoryUsed": 7770521600, - "memoryFree": 59657023488, - "memoryUsagePercent": 11.524254056496726, - "memoryEfficiency": 88.47574594350327, + "memoryUsed": 7341318144, + "memoryFree": 60086226944, + "memoryUsagePercent": 10.887713818468123, + "memoryEfficiency": 89.11228618153187, "cpuCount": 16, - "cpuLoad": 0.119375, + "cpuLoad": 0.00875, "platform": "linux", - "uptime": 11685.2 + "uptime": 6052.56 }, { - "timestamp": 1758907987101, + "timestamp": 1758902354462, "memoryTotal": 67427545088, - "memoryUsed": 7592484864, - "memoryFree": 59835060224, - "memoryUsagePercent": 11.260212505276609, - "memoryEfficiency": 88.73978749472339, + "memoryUsed": 7360921600, + "memoryFree": 60066623488, + "memoryUsagePercent": 10.916787183032138, + "memoryEfficiency": 89.08321281696786, "cpuCount": 16, - "cpuLoad": 0.099375, + "cpuLoad": 0.01, "platform": "linux", - "uptime": 11715.23 + "uptime": 6082.59 }, { - "timestamp": 1758908017131, + "timestamp": 1758902384492, "memoryTotal": 67427545088, - "memoryUsed": 7625740288, - "memoryFree": 59801804800, - "memoryUsagePercent": 11.3095327407332, - "memoryEfficiency": 88.6904672592668, + "memoryUsed": 7382290432, + "memoryFree": 60045254656, + "memoryUsagePercent": 10.948478729820787, + "memoryEfficiency": 89.05152127017921, "cpuCount": 16, - "cpuLoad": 0.09875, + "cpuLoad": 0.01375, "platform": "linux", - "uptime": 11745.26 + "uptime": 6112.62 }, { - "timestamp": 1758908047162, + "timestamp": 1758902414521, "memoryTotal": 67427545088, - "memoryUsed": 7550935040, - "memoryFree": 59876610048, - "memoryUsagePercent": 11.198591065632362, - "memoryEfficiency": 88.80140893436764, + "memoryUsed": 7363645440, + "memoryFree": 60063899648, + "memoryUsagePercent": 10.920826837740677, + "memoryEfficiency": 89.07917316225932, "cpuCount": 16, - "cpuLoad": 0.076875, + "cpuLoad": 0.008125, "platform": "linux", - "uptime": 11775.29 + "uptime": 6142.65 }, { - "timestamp": 1758908077191, + "timestamp": 1758902444551, "memoryTotal": 67427545088, - "memoryUsed": 7546167296, - "memoryFree": 59881377792, - "memoryUsagePercent": 11.191520151225234, - "memoryEfficiency": 88.80847984877477, + "memoryUsed": 7377502208, + "memoryFree": 60050042880, + "memoryUsagePercent": 10.941377442069983, + "memoryEfficiency": 89.05862255793002, "cpuCount": 16, - "cpuLoad": 0.060625, + "cpuLoad": 0.008125, "platform": "linux", - "uptime": 11805.32 + "uptime": 6172.68 }, { - "timestamp": 1758908107221, + "timestamp": 1758902474581, "memoryTotal": 67427545088, - "memoryUsed": 7556968448, - "memoryFree": 59870576640, - "memoryUsagePercent": 11.207539052678495, - "memoryEfficiency": 88.7924609473215, + "memoryUsed": 7365820416, + "memoryFree": 60061724672, + "memoryUsagePercent": 10.924052486838773, + "memoryEfficiency": 89.07594751316122, "cpuCount": 16, - "cpuLoad": 0.036875, + "cpuLoad": 0.005, "platform": "linux", - "uptime": 11835.35 + "uptime": 6202.71 }, { - "timestamp": 1758908137235, + "timestamp": 1758902504609, "memoryTotal": 67427545088, - "memoryUsed": 7622758400, - "memoryFree": 59804786688, - "memoryUsagePercent": 11.305110381894377, - "memoryEfficiency": 88.69488961810562, + "memoryUsed": 7373119488, + "memoryFree": 60054425600, + "memoryUsagePercent": 10.934877546523914, + "memoryEfficiency": 89.06512245347608, "cpuCount": 16, - "cpuLoad": 0.048125, + "cpuLoad": 0.003125, "platform": "linux", - "uptime": 11865.37 + "uptime": 6232.74 }, { - "timestamp": 1758908167253, + "timestamp": 1758902534625, "memoryTotal": 67427545088, - "memoryUsed": 7661240320, - "memoryFree": 59766304768, - "memoryUsagePercent": 11.362181894656375, - "memoryEfficiency": 88.63781810534363, + "memoryUsed": 7354834944, + "memoryFree": 60072710144, + "memoryUsagePercent": 10.907760225292455, + "memoryEfficiency": 89.09223977470755, "cpuCount": 16, - "cpuLoad": 0.03375, + "cpuLoad": 0.001875, "platform": "linux", - "uptime": 11895.38 + "uptime": 6262.76 }, { - "timestamp": 1758908197283, + "timestamp": 1758902564641, "memoryTotal": 67427545088, - "memoryUsed": 7551016960, - "memoryFree": 59876528128, - "memoryUsagePercent": 11.198712559007054, - "memoryEfficiency": 88.80128744099295, + "memoryUsed": 7361454080, + "memoryFree": 60066091008, + "memoryUsagePercent": 10.917576889967643, + "memoryEfficiency": 89.08242311003235, "cpuCount": 16, - "cpuLoad": 0.03875, + "cpuLoad": 0.005625, "platform": "linux", - "uptime": 11925.41 + "uptime": 6292.77 }, { - "timestamp": 1758908227311, + "timestamp": 1758902594657, "memoryTotal": 67427545088, - "memoryUsed": 7517286400, - "memoryFree": 59910258688, - "memoryUsagePercent": 11.148687661977245, - "memoryEfficiency": 88.85131233802275, + "memoryUsed": 7379058688, + "memoryFree": 60048486400, + "memoryUsagePercent": 10.94368581618915, + "memoryEfficiency": 89.05631418381085, "cpuCount": 16, - "cpuLoad": 0.0325, + "cpuLoad": 0.006875, "platform": "linux", - "uptime": 11955.44 + "uptime": 6322.79 }, { - "timestamp": 1758908257323, + "timestamp": 1758902624687, "memoryTotal": 67427545088, - "memoryUsed": 7562358784, - "memoryFree": 59865186304, - "memoryUsagePercent": 11.215533316733287, - "memoryEfficiency": 88.78446668326671, + "memoryUsed": 7333834752, + "memoryFree": 60093710336, + "memoryUsagePercent": 10.876615398689925, + "memoryEfficiency": 89.12338460131008, "cpuCount": 16, - "cpuLoad": 0.046875, + "cpuLoad": 0.008125, "platform": "linux", - "uptime": 11985.45 + "uptime": 6352.82 }, { - "timestamp": 1758908287353, + "timestamp": 1758902654706, "memoryTotal": 67427545088, - "memoryUsed": 7557431296, - "memoryFree": 59870113792, - "memoryUsagePercent": 11.208225490245509, - "memoryEfficiency": 88.79177450975449, + "memoryUsed": 7309410304, + "memoryFree": 60118134784, + "memoryUsagePercent": 10.84039214902523, + "memoryEfficiency": 89.15960785097477, "cpuCount": 16, - "cpuLoad": 0.065625, + "cpuLoad": 0.018125, "platform": "linux", - "uptime": 12015.48 + "uptime": 6382.84 }, { - "timestamp": 1758908317383, + "timestamp": 1758902684720, "memoryTotal": 67427545088, - "memoryUsed": 7561048064, - "memoryFree": 59866497024, - "memoryUsagePercent": 11.213589422738202, - "memoryEfficiency": 88.78641057726179, + "memoryUsed": 7300079616, + "memoryFree": 60127465472, + "memoryUsagePercent": 10.826554053647708, + "memoryEfficiency": 89.17344594635229, "cpuCount": 16, - "cpuLoad": 0.046875, + "cpuLoad": 0.010625, "platform": "linux", - "uptime": 12045.51 + "uptime": 6412.85 }, { - "timestamp": 1758908347414, + "timestamp": 1758902714750, "memoryTotal": 67427545088, - "memoryUsed": 7761285120, - "memoryFree": 59666259968, - "memoryUsagePercent": 11.5105556785001, - "memoryEfficiency": 88.4894443214999, + "memoryUsed": 7310970880, + "memoryFree": 60116574208, + "memoryUsagePercent": 10.842706597813132, + "memoryEfficiency": 89.15729340218687, "cpuCount": 16, - "cpuLoad": 0.046875, + "cpuLoad": 0.00625, "platform": "linux", - "uptime": 12075.54 + "uptime": 6442.88 }, { - "timestamp": 1758908377434, + "timestamp": 1758902744781, "memoryTotal": 67427545088, - "memoryUsed": 7608406016, - "memoryFree": 59819139072, - "memoryUsagePercent": 11.283824742648179, - "memoryEfficiency": 88.71617525735182, + "memoryUsed": 7313428480, + "memoryFree": 60114116608, + "memoryUsagePercent": 10.846351399053919, + "memoryEfficiency": 89.15364860094608, "cpuCount": 16, - "cpuLoad": 0.059375, + "cpuLoad": 0.00375, "platform": "linux", - "uptime": 12105.56 + "uptime": 6472.91 }, { - "timestamp": 1758908407464, + "timestamp": 1758902774786, "memoryTotal": 67427545088, - "memoryUsed": 8441389056, - "memoryFree": 58986156032, - "memoryUsagePercent": 12.51919974986944, - "memoryEfficiency": 87.48080025013056, + "memoryUsed": 7308439552, + "memoryFree": 60119105536, + "memoryUsagePercent": 10.838952452535121, + "memoryEfficiency": 89.16104754746488, "cpuCount": 16, - "cpuLoad": 0.07375, + "cpuLoad": 0.020625, "platform": "linux", - "uptime": 12135.59 + "uptime": 6502.92 }, { - "timestamp": 1758908437469, + "timestamp": 1758902804817, "memoryTotal": 67427545088, - "memoryUsed": 8091299840, - "memoryFree": 59336245248, - "memoryUsagePercent": 11.99999173845052, - "memoryEfficiency": 88.00000826154948, + "memoryUsed": 7293730816, + "memoryFree": 60133814272, + "memoryUsagePercent": 10.817138317109007, + "memoryEfficiency": 89.18286168289099, "cpuCount": 16, - "cpuLoad": 0.048125, + "cpuLoad": 0.0125, "platform": "linux", - "uptime": 12165.6 + "uptime": 6532.95 }, { - "timestamp": 1758908467492, + "timestamp": 1758902834848, "memoryTotal": 67427545088, - "memoryUsed": 8244244480, - "memoryFree": 59183300608, - "memoryUsagePercent": 12.226819869002199, - "memoryEfficiency": 87.7731801309978, + "memoryUsed": 7313825792, + "memoryFree": 60113719296, + "memoryUsagePercent": 10.84694064192118, + "memoryEfficiency": 89.15305935807882, "cpuCount": 16, - "cpuLoad": 0.04125, + "cpuLoad": 0.01625, "platform": "linux", - "uptime": 12195.62 + "uptime": 6562.98 }, { - "timestamp": 1758908497522, + "timestamp": 1758902864878, "memoryTotal": 67427545088, - "memoryUsed": 8276701184, - "memoryFree": 59150843904, - "memoryUsagePercent": 12.274955544055533, - "memoryEfficiency": 87.72504445594447, + "memoryUsed": 7300022272, + "memoryFree": 60127522816, + "memoryUsagePercent": 10.826469008285423, + "memoryEfficiency": 89.17353099171457, "cpuCount": 16, - "cpuLoad": 0.028125, + "cpuLoad": 0.013125, "platform": "linux", - "uptime": 12225.65 + "uptime": 6593.01 }, { - "timestamp": 1758908527552, + "timestamp": 1758902894909, "memoryTotal": 67427545088, - "memoryUsed": 8106610688, - "memoryFree": 59320934400, - "memoryUsagePercent": 12.022698850180626, - "memoryEfficiency": 87.97730114981937, + "memoryUsed": 7285604352, + "memoryFree": 60141940736, + "memoryUsagePercent": 10.805086174339468, + "memoryEfficiency": 89.19491382566054, "cpuCount": 16, - "cpuLoad": 0.03, + "cpuLoad": 0.0075, "platform": "linux", - "uptime": 12255.68 + "uptime": 6623.04 }, { - "timestamp": 1758908557583, + "timestamp": 1758902924940, "memoryTotal": 67427545088, - "memoryUsed": 8153264128, - "memoryFree": 59274280960, - "memoryUsagePercent": 12.091889327068243, - "memoryEfficiency": 87.90811067293176, + "memoryUsed": 7332937728, + "memoryFree": 60094607360, + "memoryUsagePercent": 10.875285046237037, + "memoryEfficiency": 89.12471495376296, "cpuCount": 16, - "cpuLoad": 0.033125, + "cpuLoad": 0.004375, "platform": "linux", - "uptime": 12285.71 + "uptime": 6653.07 }, { - "timestamp": 1758908587612, + "timestamp": 1758902954971, "memoryTotal": 67427545088, - "memoryUsed": 8207327232, - "memoryFree": 59220217856, - "memoryUsagePercent": 12.172068879696834, - "memoryEfficiency": 87.82793112030316, + "memoryUsed": 7283945472, + "memoryFree": 60143599616, + "memoryUsagePercent": 10.802625933501938, + "memoryEfficiency": 89.19737406649806, "cpuCount": 16, - "cpuLoad": 0.02, + "cpuLoad": 0.01, "platform": "linux", - "uptime": 12315.74 + "uptime": 6683.1 }, { - "timestamp": 1758908617642, + "timestamp": 1758902985001, "memoryTotal": 67427545088, - "memoryUsed": 8304390144, - "memoryFree": 59123154944, - "memoryUsagePercent": 12.31602030470174, - "memoryEfficiency": 87.68397969529826, + "memoryUsed": 7305043968, + "memoryFree": 60122501120, + "memoryUsagePercent": 10.833916552154099, + "memoryEfficiency": 89.1660834478459, "cpuCount": 16, - "cpuLoad": 0.043125, + "cpuLoad": 0.010625, "platform": "linux", - "uptime": 12345.77 + "uptime": 6713.13 }, { - "timestamp": 1758908647672, + "timestamp": 1758903015031, "memoryTotal": 67427545088, - "memoryUsed": 8160890880, - "memoryFree": 59266654208, - "memoryUsagePercent": 12.103200360252155, - "memoryEfficiency": 87.89679963974784, + "memoryUsed": 7339335680, + "memoryFree": 60088209408, + "memoryUsagePercent": 10.884773678800554, + "memoryEfficiency": 89.11522632119944, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 6743.16 + }, + { + "timestamp": 1758903045062, + "memoryTotal": 67427545088, + "memoryUsed": 7323758592, + "memoryFree": 60103786496, + "memoryUsagePercent": 10.861671713602696, + "memoryEfficiency": 89.1383282863973, + "cpuCount": 16, + "cpuLoad": 0.00625, + "platform": "linux", + "uptime": 6773.19 + }, + { + "timestamp": 1758903075092, + "memoryTotal": 67427545088, + "memoryUsed": 7328178176, + "memoryFree": 60099366912, + "memoryUsagePercent": 10.868226281167379, + "memoryEfficiency": 89.13177371883262, + "cpuCount": 16, + "cpuLoad": 0.00375, + "platform": "linux", + "uptime": 6803.22 + }, + { + "timestamp": 1758903105120, + "memoryTotal": 67427545088, + "memoryUsed": 7339884544, + "memoryFree": 60087660544, + "memoryUsagePercent": 10.885587684410996, + "memoryEfficiency": 89.11441231558901, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 6833.25 + }, + { + "timestamp": 1758903135150, + "memoryTotal": 67427545088, + "memoryUsed": 7332335616, + "memoryFree": 60095209472, + "memoryUsagePercent": 10.874392069933045, + "memoryEfficiency": 89.12560793006696, + "cpuCount": 16, + "cpuLoad": 0.006875, + "platform": "linux", + "uptime": 6863.28 + }, + { + "timestamp": 1758903165180, + "memoryTotal": 67427545088, + "memoryUsed": 7347343360, + "memoryFree": 60080201728, + "memoryUsagePercent": 10.896649656176786, + "memoryEfficiency": 89.10335034382321, + "cpuCount": 16, + "cpuLoad": 0.008125, + "platform": "linux", + "uptime": 6893.31 + }, + { + "timestamp": 1758903195188, + "memoryTotal": 67427545088, + "memoryUsed": 7325704192, + "memoryFree": 60101840896, + "memoryUsagePercent": 10.864557181251651, + "memoryEfficiency": 89.13544281874834, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 6923.32 + }, + { + "timestamp": 1758903225218, + "memoryTotal": 67427545088, + "memoryUsed": 7336583168, + "memoryFree": 60090961920, + "memoryUsagePercent": 10.880691501410872, + "memoryEfficiency": 89.11930849858913, + "cpuCount": 16, + "cpuLoad": 0.018125, + "platform": "linux", + "uptime": 6953.35 + }, + { + "timestamp": 1758903255227, + "memoryTotal": 67427545088, + "memoryUsed": 7342333952, + "memoryFree": 60085211136, + "memoryUsagePercent": 10.889220336314315, + "memoryEfficiency": 89.11077966368569, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 6983.36 + }, + { + "timestamp": 1758903285258, + "memoryTotal": 67427545088, + "memoryUsed": 7328395264, + "memoryFree": 60099149824, + "memoryUsagePercent": 10.868548238610314, + "memoryEfficiency": 89.13145176138968, + "cpuCount": 16, + "cpuLoad": 0.00625, + "platform": "linux", + "uptime": 7013.39 + }, + { + "timestamp": 1758903315289, + "memoryTotal": 67427545088, + "memoryUsed": 7334801408, + "memoryFree": 60092743680, + "memoryUsagePercent": 10.878049020511302, + "memoryEfficiency": 89.1219509794887, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 7043.42 + }, + { + "timestamp": 1758903345319, + "memoryTotal": 67427545088, + "memoryUsed": 7304896512, + "memoryFree": 60122648576, + "memoryUsagePercent": 10.833697864079651, + "memoryEfficiency": 89.16630213592035, + "cpuCount": 16, + "cpuLoad": 0.005, + "platform": "linux", + "uptime": 7073.45 + }, + { + "timestamp": 1758903375349, + "memoryTotal": 67427545088, + "memoryUsed": 7333396480, + "memoryFree": 60094148608, + "memoryUsagePercent": 10.875965409135317, + "memoryEfficiency": 89.12403459086468, + "cpuCount": 16, + "cpuLoad": 0.020625, + "platform": "linux", + "uptime": 7103.48 + }, + { + "timestamp": 1758903405379, + "memoryTotal": 67427545088, + "memoryUsed": 7327596544, + "memoryFree": 60099948544, + "memoryUsagePercent": 10.86736367820706, + "memoryEfficiency": 89.13263632179294, + "cpuCount": 16, + "cpuLoad": 0.0225, + "platform": "linux", + "uptime": 7133.51 + }, + { + "timestamp": 1758903435409, + "memoryTotal": 67427545088, + "memoryUsed": 7329411072, + "memoryFree": 60098134016, + "memoryUsagePercent": 10.870054756456508, + "memoryEfficiency": 89.12994524354349, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 7163.54 + }, + { + "timestamp": 1758903465440, + "memoryTotal": 67427545088, + "memoryUsed": 7329456128, + "memoryFree": 60098088960, + "memoryUsagePercent": 10.870121577812588, + "memoryEfficiency": 89.12987842218742, + "cpuCount": 16, + "cpuLoad": 0.018125, + "platform": "linux", + "uptime": 7193.57 + }, + { + "timestamp": 1758903495470, + "memoryTotal": 67427545088, + "memoryUsed": 7312367616, + "memoryFree": 60115177472, + "memoryUsagePercent": 10.844778059851645, + "memoryEfficiency": 89.15522194014835, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 7223.6 + }, + { + "timestamp": 1758903525500, + "memoryTotal": 67427545088, + "memoryUsed": 7307411456, + "memoryFree": 60120133632, + "memoryUsagePercent": 10.837427710682725, + "memoryEfficiency": 89.16257228931727, + "cpuCount": 16, + "cpuLoad": 0.011875, + "platform": "linux", + "uptime": 7253.63 + }, + { + "timestamp": 1758903555531, + "memoryTotal": 67427545088, + "memoryUsed": 7315922944, + "memoryFree": 60111622144, + "memoryUsagePercent": 10.850050872313318, + "memoryEfficiency": 89.14994912768668, + "cpuCount": 16, + "cpuLoad": 0.015625, + "platform": "linux", + "uptime": 7283.66 + }, + { + "timestamp": 1758903585561, + "memoryTotal": 67427545088, + "memoryUsed": 7292764160, + "memoryFree": 60134780928, + "memoryUsagePercent": 10.81570469528763, + "memoryEfficiency": 89.18429530471236, + "cpuCount": 16, + "cpuLoad": 0.01625, + "platform": "linux", + "uptime": 7313.69 + }, + { + "timestamp": 1758903615592, + "memoryTotal": 67427545088, + "memoryUsed": 7347978240, + "memoryFree": 60079566848, + "memoryUsagePercent": 10.897591229830656, + "memoryEfficiency": 89.10240877016935, + "cpuCount": 16, + "cpuLoad": 0.014375, + "platform": "linux", + "uptime": 7343.72 + }, + { + "timestamp": 1758903645622, + "memoryTotal": 67427545088, + "memoryUsed": 7313694720, + "memoryFree": 60113850368, + "memoryUsagePercent": 10.84674625252167, + "memoryEfficiency": 89.15325374747833, + "cpuCount": 16, + "cpuLoad": 0.0125, + "platform": "linux", + "uptime": 7373.75 + }, + { + "timestamp": 1758903675651, + "memoryTotal": 67427545088, + "memoryUsed": 7321083904, + "memoryFree": 60106461184, + "memoryUsagePercent": 10.857704954918972, + "memoryEfficiency": 89.14229504508103, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 7403.78 + }, + { + "timestamp": 1758903705653, + "memoryTotal": 67427545088, + "memoryUsed": 7308509184, + "memoryFree": 60119035904, + "memoryUsagePercent": 10.839055721903609, + "memoryEfficiency": 89.1609442780964, + "cpuCount": 16, + "cpuLoad": 0.004375, + "platform": "linux", + "uptime": 7433.78 + }, + { + "timestamp": 1758903735677, + "memoryTotal": 67427545088, + "memoryUsed": 7338209280, + "memoryFree": 60089335808, + "memoryUsagePercent": 10.883103144898525, + "memoryEfficiency": 89.11689685510147, + "cpuCount": 16, + "cpuLoad": 0.0025, + "platform": "linux", + "uptime": 7463.81 + }, + { + "timestamp": 1758903765706, + "memoryTotal": 67427545088, + "memoryUsed": 7327064064, + "memoryFree": 60100481024, + "memoryUsagePercent": 10.866573971271555, + "memoryEfficiency": 89.13342602872845, + "cpuCount": 16, + "cpuLoad": 0.005, + "platform": "linux", + "uptime": 7493.84 + }, + { + "timestamp": 1758903795736, + "memoryTotal": 67427545088, + "memoryUsed": 7327006720, + "memoryFree": 60100538368, + "memoryUsagePercent": 10.866488925909271, + "memoryEfficiency": 89.13351107409073, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 7523.87 + }, + { + "timestamp": 1758903825767, + "memoryTotal": 67427545088, + "memoryUsed": 7324491776, + "memoryFree": 60103053312, + "memoryUsagePercent": 10.862759079306198, + "memoryEfficiency": 89.1372409206938, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 7553.9 + }, + { + "timestamp": 1758903855798, + "memoryTotal": 67427545088, + "memoryUsed": 7330000896, + "memoryFree": 60097544192, + "memoryUsagePercent": 10.870929508754296, + "memoryEfficiency": 89.1290704912457, + "cpuCount": 16, + "cpuLoad": 0.006875, + "platform": "linux", + "uptime": 7583.93 + }, + { + "timestamp": 1758903885819, + "memoryTotal": 67427545088, + "memoryUsed": 7341563904, + "memoryFree": 60085981184, + "memoryUsagePercent": 10.888078298592202, + "memoryEfficiency": 89.1119217014078, + "cpuCount": 16, + "cpuLoad": 0.00375, + "platform": "linux", + "uptime": 7613.95 + }, + { + "timestamp": 1758903915850, + "memoryTotal": 67427545088, + "memoryUsed": 7321022464, + "memoryFree": 60106522624, + "memoryUsagePercent": 10.857613834887953, + "memoryEfficiency": 89.14238616511204, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 7643.98 + }, + { + "timestamp": 1758903945880, + "memoryTotal": 67427545088, + "memoryUsed": 7321923584, + "memoryFree": 60105621504, + "memoryUsagePercent": 10.858950262009575, + "memoryEfficiency": 89.14104973799043, + "cpuCount": 16, + "cpuLoad": 0.004375, + "platform": "linux", + "uptime": 7674.01 + }, + { + "timestamp": 1758903975892, + "memoryTotal": 67427545088, + "memoryUsed": 7337496576, + "memoryFree": 60090048512, + "memoryUsagePercent": 10.882046152538697, + "memoryEfficiency": 89.11795384746131, + "cpuCount": 16, + "cpuLoad": 0.0025, + "platform": "linux", + "uptime": 7704.02 + }, + { + "timestamp": 1758904005923, + "memoryTotal": 67427545088, + "memoryUsed": 7323693056, + "memoryFree": 60103852032, + "memoryUsagePercent": 10.861574518902941, + "memoryEfficiency": 89.13842548109706, + "cpuCount": 16, + "cpuLoad": 0.00125, + "platform": "linux", + "uptime": 7734.05 + }, + { + "timestamp": 1758904035953, + "memoryTotal": 67427545088, + "memoryUsed": 7327739904, + "memoryFree": 60099805184, + "memoryUsagePercent": 10.867576291612771, + "memoryEfficiency": 89.13242370838722, + "cpuCount": 16, + "cpuLoad": 0.005, + "platform": "linux", + "uptime": 7764.08 + }, + { + "timestamp": 1758904065984, + "memoryTotal": 67427545088, + "memoryUsed": 7319523328, + "memoryFree": 60108021760, + "memoryUsagePercent": 10.855390506131073, + "memoryEfficiency": 89.14460949386893, + "cpuCount": 16, + "cpuLoad": 0.03125, + "platform": "linux", + "uptime": 7794.11 + }, + { + "timestamp": 1758904096015, + "memoryTotal": 67427545088, + "memoryUsed": 7309328384, + "memoryFree": 60118216704, + "memoryUsagePercent": 10.840270655650539, + "memoryEfficiency": 89.15972934434946, "cpuCount": 16, "cpuLoad": 0.02625, "platform": "linux", - "uptime": 12375.8 + "uptime": 7824.15 }, { - "timestamp": 1758908677704, + "timestamp": 1758904126045, "memoryTotal": 67427545088, - "memoryUsed": 8165085184, - "memoryFree": 59262459904, - "memoryUsagePercent": 12.109420821036432, - "memoryEfficiency": 87.89057917896356, + "memoryUsed": 7320297472, + "memoryFree": 60107247616, + "memoryUsagePercent": 10.85653861852192, + "memoryEfficiency": 89.14346138147808, "cpuCount": 16, - "cpuLoad": 0.03875, + "cpuLoad": 0.0325, "platform": "linux", - "uptime": 12405.83 + "uptime": 7854.18 }, { - "timestamp": 1758908707734, + "timestamp": 1758904156076, "memoryTotal": 67427545088, - "memoryUsed": 8158793728, - "memoryFree": 59268751360, - "memoryUsagePercent": 12.100090129860016, - "memoryEfficiency": 87.89990987013998, + "memoryUsed": 7299923968, + "memoryFree": 60127621120, + "memoryUsagePercent": 10.826323216235792, + "memoryEfficiency": 89.17367678376421, "cpuCount": 16, - "cpuLoad": 0.0525, + "cpuLoad": 0.019375, "platform": "linux", - "uptime": 12435.86 + "uptime": 7884.21 }, { - "timestamp": 1758908737764, + "timestamp": 1758904186106, "memoryTotal": 67427545088, - "memoryUsed": 8281636864, - "memoryFree": 59145908224, - "memoryUsagePercent": 12.28227551988078, - "memoryEfficiency": 87.71772448011922, + "memoryUsed": 7333908480, + "memoryFree": 60093636608, + "memoryUsagePercent": 10.876724742727149, + "memoryEfficiency": 89.12327525727285, "cpuCount": 16, - "cpuLoad": 0.035, + "cpuLoad": 0.011875, "platform": "linux", - "uptime": 12465.89 + "uptime": 7914.24 }, { - "timestamp": 1758908767794, + "timestamp": 1758904216136, "memoryTotal": 67427545088, - "memoryUsed": 8325955584, - "memoryFree": 59101589504, - "memoryUsagePercent": 12.34800343558965, - "memoryEfficiency": 87.65199656441035, + "memoryUsed": 7341961216, + "memoryFree": 60085583872, + "memoryUsagePercent": 10.888667541459462, + "memoryEfficiency": 89.11133245854055, "cpuCount": 16, - "cpuLoad": 0.028125, + "cpuLoad": 0.01125, "platform": "linux", - "uptime": 12495.92 + "uptime": 7944.27 }, { - "timestamp": 1758908797825, + "timestamp": 1758904246166, "memoryTotal": 67427545088, - "memoryUsed": 8120070144, - "memoryFree": 59307474944, - "memoryUsagePercent": 12.042660211642673, - "memoryEfficiency": 87.95733978835733, + "memoryUsed": 7341051904, + "memoryFree": 60086493184, + "memoryUsagePercent": 10.887318965000372, + "memoryEfficiency": 89.11268103499962, "cpuCount": 16, - "cpuLoad": 0.048125, + "cpuLoad": 0.010625, "platform": "linux", - "uptime": 12525.95 + "uptime": 7974.3 }, { - "timestamp": 1758908827838, + "timestamp": 1758904276197, "memoryTotal": 67427545088, - "memoryUsed": 8102506496, - "memoryFree": 59325038592, - "memoryUsagePercent": 12.016612032108512, - "memoryEfficiency": 87.98338796789149, + "memoryUsed": 7315427328, + "memoryFree": 60112117760, + "memoryUsagePercent": 10.849315837396425, + "memoryEfficiency": 89.15068416260357, "cpuCount": 16, - "cpuLoad": 0.050625, + "cpuLoad": 0.00625, "platform": "linux", - "uptime": 12555.97 + "uptime": 8004.33 }, { - "timestamp": 1758908857868, + "timestamp": 1758904306203, "memoryTotal": 67427545088, - "memoryUsed": 8404914176, - "memoryFree": 59022630912, - "memoryUsagePercent": 12.465104824787417, - "memoryEfficiency": 87.53489517521258, + "memoryUsed": 7311499264, + "memoryFree": 60116045824, + "memoryUsagePercent": 10.843490230079901, + "memoryEfficiency": 89.15650976992009, "cpuCount": 16, - "cpuLoad": 0.06, + "cpuLoad": 0.006875, "platform": "linux", - "uptime": 12586 + "uptime": 8034.33 }, { - "timestamp": 1758908887898, + "timestamp": 1758904336234, "memoryTotal": 67427545088, - "memoryUsed": 8154464256, - "memoryFree": 59273080832, - "memoryUsagePercent": 12.093669205007496, - "memoryEfficiency": 87.9063307949925, + "memoryUsed": 7307022336, + "memoryFree": 60120522752, + "memoryUsagePercent": 10.836850617152932, + "memoryEfficiency": 89.16314938284707, "cpuCount": 16, - "cpuLoad": 0.053125, + "cpuLoad": 0.008125, "platform": "linux", - "uptime": 12616.03 + "uptime": 8064.36 }, { - "timestamp": 1758908917915, + "timestamp": 1758904366256, "memoryTotal": 67427545088, - "memoryUsed": 8305000448, - "memoryFree": 59122544640, - "memoryUsagePercent": 12.3169254303432, - "memoryEfficiency": 87.6830745696568, + "memoryUsed": 7321374720, + "memoryFree": 60106170368, + "memoryUsagePercent": 10.858136256399133, + "memoryEfficiency": 89.14186374360087, "cpuCount": 16, - "cpuLoad": 0.066875, + "cpuLoad": 0.014375, "platform": "linux", - "uptime": 12646.04 + "uptime": 8094.39 }, { - "timestamp": 1758908947944, + "timestamp": 1758904396287, "memoryTotal": 67427545088, - "memoryUsed": 8353112064, - "memoryFree": 59074433024, - "memoryUsagePercent": 12.388278489300351, - "memoryEfficiency": 87.61172151069965, + "memoryUsed": 7320158208, + "memoryFree": 60107386880, + "memoryUsagePercent": 10.856332079784941, + "memoryEfficiency": 89.14366792021505, "cpuCount": 16, - "cpuLoad": 0.06, + "cpuLoad": 0.00875, "platform": "linux", - "uptime": 12676.07 + "uptime": 8124.42 }, { - "timestamp": 1758908977972, + "timestamp": 1758904426317, "memoryTotal": 67427545088, - "memoryUsed": 8379183104, - "memoryFree": 59048361984, - "memoryUsagePercent": 12.426943755796373, - "memoryEfficiency": 87.57305624420363, + "memoryUsed": 7291748352, + "memoryFree": 60135796736, + "memoryUsagePercent": 10.814198177441439, + "memoryEfficiency": 89.18580182255856, "cpuCount": 16, - "cpuLoad": 0.054375, + "cpuLoad": 0.009375, "platform": "linux", - "uptime": 12706.1 + "uptime": 8154.45 }, { - "timestamp": 1758909007975, + "timestamp": 1758904456348, "memoryTotal": 67427545088, - "memoryUsed": 8453738496, - "memoryFree": 58973806592, - "memoryUsagePercent": 12.537514876104398, - "memoryEfficiency": 87.4624851238956, + "memoryUsed": 7285424128, + "memoryFree": 60142120960, + "memoryUsagePercent": 10.804818888915145, + "memoryEfficiency": 89.19518111108485, "cpuCount": 16, - "cpuLoad": 0.061875, + "cpuLoad": 0.019375, "platform": "linux", - "uptime": 12736.1 + "uptime": 8184.48 }, { - "timestamp": 1758909037991, + "timestamp": 1758904486369, "memoryTotal": 67427545088, - "memoryUsed": 8244736000, - "memoryFree": 59182809088, - "memoryUsagePercent": 12.227548829250356, - "memoryEfficiency": 87.77245117074965, + "memoryUsed": 7294296064, + "memoryFree": 60133249024, + "memoryUsagePercent": 10.817976621394386, + "memoryEfficiency": 89.1820233786056, "cpuCount": 16, - "cpuLoad": 0.05, + "cpuLoad": 0.011875, "platform": "linux", - "uptime": 12766.12 + "uptime": 8214.5 }, { - "timestamp": 1758909068021, + "timestamp": 1758904516370, "memoryTotal": 67427545088, - "memoryUsed": 8305987584, - "memoryFree": 59121557504, - "memoryUsagePercent": 12.31838942550825, - "memoryEfficiency": 87.68161057449174, + "memoryUsed": 7302631424, + "memoryFree": 60124913664, + "memoryUsagePercent": 10.830338572269392, + "memoryEfficiency": 89.1696614277306, "cpuCount": 16, - "cpuLoad": 0.0475, + "cpuLoad": 0.023125, "platform": "linux", - "uptime": 12796.15 + "uptime": 8244.5 }, { - "timestamp": 1758909098051, + "timestamp": 1758904546401, "memoryTotal": 67427545088, - "memoryUsed": 8308703232, - "memoryFree": 59118841856, - "memoryUsagePercent": 12.32241693087932, - "memoryEfficiency": 87.67758306912069, + "memoryUsed": 7304790016, + "memoryFree": 60122755072, + "memoryUsagePercent": 10.83353992269255, + "memoryEfficiency": 89.16646007730745, "cpuCount": 16, - "cpuLoad": 0.059375, + "cpuLoad": 0.03125, "platform": "linux", - "uptime": 12826.18 + "uptime": 8274.53 }, { - "timestamp": 1758909128081, + "timestamp": 1758904576431, "memoryTotal": 67427545088, - "memoryUsed": 8109940736, - "memoryFree": 59317604352, - "memoryUsagePercent": 12.027637555861896, - "memoryEfficiency": 87.9723624441381, + "memoryUsed": 7320035328, + "memoryFree": 60107509760, + "memoryUsagePercent": 10.856149839722903, + "memoryEfficiency": 89.1438501602771, "cpuCount": 16, - "cpuLoad": 0.053125, + "cpuLoad": 0.023125, "platform": "linux", - "uptime": 12856.21 + "uptime": 8304.56 }, { - "timestamp": 1758909158112, + "timestamp": 1758904606462, "memoryTotal": 67427545088, - "memoryUsed": 8267911168, - "memoryFree": 59159633920, - "memoryUsagePercent": 12.261919304950982, - "memoryEfficiency": 87.73808069504902, + "memoryUsed": 7290347520, + "memoryFree": 60137197568, + "memoryUsagePercent": 10.81212064073419, + "memoryEfficiency": 89.1878793592658, "cpuCount": 16, - "cpuLoad": 0.04125, + "cpuLoad": 0.0175, "platform": "linux", - "uptime": 12886.24 + "uptime": 8334.59 }, { - "timestamp": 1758909188142, + "timestamp": 1758904636493, "memoryTotal": 67427545088, - "memoryUsed": 8109625344, - "memoryFree": 59317919744, - "memoryUsagePercent": 12.027169806369328, - "memoryEfficiency": 87.97283019363067, + "memoryUsed": 7320727552, + "memoryFree": 60106817536, + "memoryUsagePercent": 10.857176458739058, + "memoryEfficiency": 89.14282354126094, "cpuCount": 16, - "cpuLoad": 0.05375, + "cpuLoad": 0.0175, "platform": "linux", - "uptime": 12916.27 + "uptime": 8364.62 }, { - "timestamp": 1758909218173, + "timestamp": 1758904666523, "memoryTotal": 67427545088, - "memoryUsed": 8159367168, - "memoryFree": 59268177920, - "memoryUsagePercent": 12.100940583482867, - "memoryEfficiency": 87.89905941651713, + "memoryUsed": 7326474240, + "memoryFree": 60101070848, + "memoryUsagePercent": 10.865699218973766, + "memoryEfficiency": 89.13430078102624, "cpuCount": 16, - "cpuLoad": 0.069375, + "cpuLoad": 0.010625, "platform": "linux", - "uptime": 12946.3 + "uptime": 8394.65 }, { - "timestamp": 1758909248204, + "timestamp": 1758904696529, "memoryTotal": 67427545088, - "memoryUsed": 8241504256, - "memoryFree": 59186040832, - "memoryUsagePercent": 12.22275591561872, - "memoryEfficiency": 87.77724408438128, + "memoryUsed": 7300845568, + "memoryFree": 60126699520, + "memoryUsagePercent": 10.827690016701087, + "memoryEfficiency": 89.17230998329892, + "cpuCount": 16, + "cpuLoad": 0.018125, + "platform": "linux", + "uptime": 8424.66 + }, + { + "timestamp": 1758904726547, + "memoryTotal": 67427545088, + "memoryUsed": 7316148224, + "memoryFree": 60111396864, + "memoryUsagePercent": 10.850384979093723, + "memoryEfficiency": 89.14961502090628, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 8454.68 + }, + { + "timestamp": 1758904756561, + "memoryTotal": 67427545088, + "memoryUsed": 7325765632, + "memoryFree": 60101779456, + "memoryUsagePercent": 10.864648301282672, + "memoryEfficiency": 89.13535169871733, + "cpuCount": 16, + "cpuLoad": 0.02125, + "platform": "linux", + "uptime": 8484.69 + }, + { + "timestamp": 1758904786569, + "memoryTotal": 67427545088, + "memoryUsed": 7310159872, + "memoryFree": 60117385216, + "memoryUsagePercent": 10.841503813403671, + "memoryEfficiency": 89.15849618659632, + "cpuCount": 16, + "cpuLoad": 0.0175, + "platform": "linux", + "uptime": 8514.7 + }, + { + "timestamp": 1758904816600, + "memoryTotal": 67427545088, + "memoryUsed": 7289647104, + "memoryFree": 60137897984, + "memoryUsagePercent": 10.811081872380566, + "memoryEfficiency": 89.18891812761943, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 8544.73 + }, + { + "timestamp": 1758904846601, + "memoryTotal": 67427545088, + "memoryUsed": 7319371776, + "memoryFree": 60108173312, + "memoryUsagePercent": 10.85516574338789, + "memoryEfficiency": 89.14483425661211, + "cpuCount": 16, + "cpuLoad": 0.00625, + "platform": "linux", + "uptime": 8574.73 + }, + { + "timestamp": 1758904876631, + "memoryTotal": 67427545088, + "memoryUsed": 7344140288, + "memoryFree": 60083404800, + "memoryUsagePercent": 10.891899265226295, + "memoryEfficiency": 89.1081007347737, + "cpuCount": 16, + "cpuLoad": 0.00375, + "platform": "linux", + "uptime": 8604.76 + }, + { + "timestamp": 1758904906661, + "memoryTotal": 67427545088, + "memoryUsed": 7345389568, + "memoryFree": 60082155520, + "memoryUsagePercent": 10.89375203919036, + "memoryEfficiency": 89.10624796080964, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 8634.79 + }, + { + "timestamp": 1758904936692, + "memoryTotal": 67427545088, + "memoryUsed": 7336726528, + "memoryFree": 60090818560, + "memoryUsagePercent": 10.880904114816586, + "memoryEfficiency": 89.11909588518341, + "cpuCount": 16, + "cpuLoad": 0.021875, + "platform": "linux", + "uptime": 8664.82 + }, + { + "timestamp": 1758904966723, + "memoryTotal": 67427545088, + "memoryUsed": 7310233600, + "memoryFree": 60117311488, + "memoryUsagePercent": 10.841613157440895, + "memoryEfficiency": 89.15838684255911, + "cpuCount": 16, + "cpuLoad": 0.013125, + "platform": "linux", + "uptime": 8694.85 + }, + { + "timestamp": 1758904996754, + "memoryTotal": 67427545088, + "memoryUsed": 7319523328, + "memoryFree": 60108021760, + "memoryUsagePercent": 10.855390506131073, + "memoryEfficiency": 89.14460949386893, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 8724.88 + }, + { + "timestamp": 1758905026764, + "memoryTotal": 67427545088, + "memoryUsed": 7312793600, + "memoryFree": 60114751488, + "memoryUsagePercent": 10.845409825400049, + "memoryEfficiency": 89.15459017459995, + "cpuCount": 16, + "cpuLoad": 0.008125, + "platform": "linux", + "uptime": 8754.89 + }, + { + "timestamp": 1758905056774, + "memoryTotal": 67427545088, + "memoryUsed": 7314763776, + "memoryFree": 60112781312, + "memoryUsagePercent": 10.848331741061413, + "memoryEfficiency": 89.15166825893859, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 8784.9 + }, + { + "timestamp": 1758905086793, + "memoryTotal": 67427545088, + "memoryUsed": 7336423424, + "memoryFree": 60091121664, + "memoryUsagePercent": 10.88045458933022, + "memoryEfficiency": 89.11954541066979, + "cpuCount": 16, + "cpuLoad": 0.009375, + "platform": "linux", + "uptime": 8814.92 + }, + { + "timestamp": 1758905116824, + "memoryTotal": 67427545088, + "memoryUsed": 7359365120, + "memoryFree": 60068179968, + "memoryUsagePercent": 10.914478808912973, + "memoryEfficiency": 89.08552119108703, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 8844.95 + }, + { + "timestamp": 1758905146854, + "memoryTotal": 67427545088, + "memoryUsed": 7330299904, + "memoryFree": 60097245184, + "memoryUsagePercent": 10.871372959571927, + "memoryEfficiency": 89.12862704042807, + "cpuCount": 16, + "cpuLoad": 0.014375, + "platform": "linux", + "uptime": 8874.98 + }, + { + "timestamp": 1758905176882, + "memoryTotal": 67427545088, + "memoryUsed": 7376891904, + "memoryFree": 60050653184, + "memoryUsagePercent": 10.940472316428522, + "memoryEfficiency": 89.05952768357147, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 8905.01 + }, + { + "timestamp": 1758905206912, + "memoryTotal": 67427545088, + "memoryUsed": 7336386560, + "memoryFree": 60091158528, + "memoryUsagePercent": 10.880399917311609, + "memoryEfficiency": 89.1196000826884, + "cpuCount": 16, + "cpuLoad": 0.015, + "platform": "linux", + "uptime": 8935.04 + }, + { + "timestamp": 1758905236943, + "memoryTotal": 67427545088, + "memoryUsed": 7327133696, + "memoryFree": 60100411392, + "memoryUsagePercent": 10.866677240640044, + "memoryEfficiency": 89.13332275935996, + "cpuCount": 16, + "cpuLoad": 0.013125, + "platform": "linux", + "uptime": 8965.07 + }, + { + "timestamp": 1758905266974, + "memoryTotal": 67427545088, + "memoryUsed": 7344119808, + "memoryFree": 60083425280, + "memoryUsagePercent": 10.891868891882622, + "memoryEfficiency": 89.10813110811738, + "cpuCount": 16, + "cpuLoad": 0.008125, + "platform": "linux", + "uptime": 8995.1 + }, + { + "timestamp": 1758905296999, + "memoryTotal": 67427545088, + "memoryUsed": 7438098432, + "memoryFree": 59989446656, + "memoryUsagePercent": 11.031246091330337, + "memoryEfficiency": 88.96875390866967, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 9025.13 + }, + { + "timestamp": 1758905327030, + "memoryTotal": 67427545088, + "memoryUsed": 7517949952, + "memoryFree": 59909595136, + "memoryUsagePercent": 11.149671758312257, + "memoryEfficiency": 88.85032824168775, + "cpuCount": 16, + "cpuLoad": 0.0275, + "platform": "linux", + "uptime": 9055.16 + }, + { + "timestamp": 1758905357060, + "memoryTotal": 67427545088, + "memoryUsed": 7398051840, + "memoryFree": 60029493248, + "memoryUsagePercent": 10.971854055111702, + "memoryEfficiency": 89.0281459448883, + "cpuCount": 16, + "cpuLoad": 0.049375, + "platform": "linux", + "uptime": 9085.19 + }, + { + "timestamp": 1758905387091, + "memoryTotal": 67427545088, + "memoryUsed": 7356252160, + "memoryFree": 60071292928, + "memoryUsagePercent": 10.909862060674643, + "memoryEfficiency": 89.09013793932536, "cpuCount": 16, "cpuLoad": 0.041875, "platform": "linux", - "uptime": 12976.33 + "uptime": 9115.22 }, { - "timestamp": 1758909278235, + "timestamp": 1758905417122, "memoryTotal": 67427545088, - "memoryUsed": 8461627392, - "memoryFree": 58965917696, - "memoryUsagePercent": 12.549214688087327, - "memoryEfficiency": 87.45078531191267, + "memoryUsed": 7383420928, + "memoryFree": 60044124160, + "memoryUsagePercent": 10.950155338391548, + "memoryEfficiency": 89.04984466160845, + "cpuCount": 16, + "cpuLoad": 0.025625, + "platform": "linux", + "uptime": 9145.25 + }, + { + "timestamp": 1758905447152, + "memoryTotal": 67427545088, + "memoryUsed": 7359778816, + "memoryFree": 60067766272, + "memoryUsagePercent": 10.915092350455172, + "memoryEfficiency": 89.08490764954483, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 9175.28 + }, + { + "timestamp": 1758905477183, + "memoryTotal": 67427545088, + "memoryUsed": 7378911232, + "memoryFree": 60048633856, + "memoryUsagePercent": 10.943467128114703, + "memoryEfficiency": 89.0565328718853, + "cpuCount": 16, + "cpuLoad": 0.023125, + "platform": "linux", + "uptime": 9205.31 + }, + { + "timestamp": 1758905507214, + "memoryTotal": 67427545088, + "memoryUsed": 7389876224, + "memoryFree": 60037668864, + "memoryUsagePercent": 10.95972901631735, + "memoryEfficiency": 89.04027098368265, + "cpuCount": 16, + "cpuLoad": 0.01375, + "platform": "linux", + "uptime": 9235.34 + }, + { + "timestamp": 1758905537243, + "memoryTotal": 67427545088, + "memoryUsed": 7388438528, + "memoryFree": 60039106560, + "memoryUsagePercent": 10.95759680759149, + "memoryEfficiency": 89.04240319240851, + "cpuCount": 16, + "cpuLoad": 0.008125, + "platform": "linux", + "uptime": 9265.37 + }, + { + "timestamp": 1758905567274, + "memoryTotal": 67427545088, + "memoryUsed": 7391363072, + "memoryFree": 60036182016, + "memoryUsagePercent": 10.961934121068026, + "memoryEfficiency": 89.03806587893197, + "cpuCount": 16, + "cpuLoad": 0.005, + "platform": "linux", + "uptime": 9295.4 + }, + { + "timestamp": 1758905597305, + "memoryTotal": 67427545088, + "memoryUsed": 7390052352, + "memoryFree": 60037492736, + "memoryUsagePercent": 10.95999022707294, + "memoryEfficiency": 89.04000977292706, + "cpuCount": 16, + "cpuLoad": 0.006875, + "platform": "linux", + "uptime": 9325.43 + }, + { + "timestamp": 1758905627336, + "memoryTotal": 67427545088, + "memoryUsed": 7397371904, + "memoryFree": 60030173184, + "memoryUsagePercent": 10.970845660101752, + "memoryEfficiency": 89.02915433989824, + "cpuCount": 16, + "cpuLoad": 0.004375, + "platform": "linux", + "uptime": 9355.47 + }, + { + "timestamp": 1758905657366, + "memoryTotal": 67427545088, + "memoryUsed": 7419666432, + "memoryFree": 60007878656, + "memoryUsagePercent": 11.00391008202443, + "memoryEfficiency": 88.99608991797557, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 9385.5 + }, + { + "timestamp": 1758905687396, + "memoryTotal": 67427545088, + "memoryUsed": 7379066880, + "memoryFree": 60048478208, + "memoryUsagePercent": 10.943697965526619, + "memoryEfficiency": 89.05630203447338, + "cpuCount": 16, + "cpuLoad": 0.004375, + "platform": "linux", + "uptime": 9415.53 + }, + { + "timestamp": 1758905717427, + "memoryTotal": 67427545088, + "memoryUsed": 7382908928, + "memoryFree": 60044636160, + "memoryUsagePercent": 10.949396004799718, + "memoryEfficiency": 89.05060399520028, + "cpuCount": 16, + "cpuLoad": 0.00625, + "platform": "linux", + "uptime": 9445.56 + }, + { + "timestamp": 1758905747457, + "memoryTotal": 67427545088, + "memoryUsed": 7398297600, + "memoryFree": 60029247488, + "memoryUsagePercent": 10.972218535235783, + "memoryEfficiency": 89.02778146476422, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 9475.59 + }, + { + "timestamp": 1758905777488, + "memoryTotal": 67427545088, + "memoryUsed": 7388639232, + "memoryFree": 60038905856, + "memoryUsagePercent": 10.957894466359487, + "memoryEfficiency": 89.04210553364051, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 9505.62 + }, + { + "timestamp": 1758905807519, + "memoryTotal": 67427545088, + "memoryUsed": 7394238464, + "memoryFree": 60033306624, + "memoryUsagePercent": 10.966198538519748, + "memoryEfficiency": 89.03380146148025, + "cpuCount": 16, + "cpuLoad": 0.02375, + "platform": "linux", + "uptime": 9535.65 + }, + { + "timestamp": 1758905837537, + "memoryTotal": 67427545088, + "memoryUsed": 7390486528, + "memoryFree": 60037058560, + "memoryUsagePercent": 10.960634141958812, + "memoryEfficiency": 89.0393658580412, + "cpuCount": 16, + "cpuLoad": 0.0175, + "platform": "linux", + "uptime": 9565.67 + }, + { + "timestamp": 1758905867567, + "memoryTotal": 67427545088, + "memoryUsed": 7396237312, + "memoryFree": 60031307776, + "memoryUsagePercent": 10.969162976862256, + "memoryEfficiency": 89.03083702313775, + "cpuCount": 16, + "cpuLoad": 0.015, + "platform": "linux", + "uptime": 9595.7 + }, + { + "timestamp": 1758905897598, + "memoryTotal": 67427545088, + "memoryUsed": 7375462400, + "memoryFree": 60052082688, + "memoryUsagePercent": 10.938352257040131, + "memoryEfficiency": 89.06164774295986, + "cpuCount": 16, + "cpuLoad": 0.009375, + "platform": "linux", + "uptime": 9625.73 + }, + { + "timestamp": 1758905927628, + "memoryTotal": 67427545088, + "memoryUsed": 7367303168, + "memoryFree": 60060241920, + "memoryUsagePercent": 10.926251516920717, + "memoryEfficiency": 89.07374848307929, + "cpuCount": 16, + "cpuLoad": 0.005625, + "platform": "linux", + "uptime": 9655.76 + }, + { + "timestamp": 1758905957658, + "memoryTotal": 67427545088, + "memoryUsed": 7413153792, + "memoryFree": 60014391296, + "memoryUsagePercent": 10.994251358736342, + "memoryEfficiency": 89.00574864126366, + "cpuCount": 16, + "cpuLoad": 0.003125, + "platform": "linux", + "uptime": 9685.79 + }, + { + "timestamp": 1758905987689, + "memoryTotal": 67427545088, + "memoryUsed": 7397437440, + "memoryFree": 60030107648, + "memoryUsagePercent": 10.970942854801507, + "memoryEfficiency": 89.0290571451985, + "cpuCount": 16, + "cpuLoad": 0.001875, + "platform": "linux", + "uptime": 9715.82 + }, + { + "timestamp": 1758906017719, + "memoryTotal": 67427545088, + "memoryUsed": 7401910272, + "memoryFree": 60025634816, + "memoryUsagePercent": 10.977576393059739, + "memoryEfficiency": 89.02242360694027, + "cpuCount": 16, + "cpuLoad": 0.013125, + "platform": "linux", + "uptime": 9745.85 + }, + { + "timestamp": 1758906047725, + "memoryTotal": 67427545088, + "memoryUsed": 7393792000, + "memoryFree": 60033753088, + "memoryUsagePercent": 10.965536399627672, + "memoryEfficiency": 89.03446360037233, + "cpuCount": 16, + "cpuLoad": 0.0125, + "platform": "linux", + "uptime": 9775.86 + }, + { + "timestamp": 1758906077726, + "memoryTotal": 67427545088, + "memoryUsed": 7411732480, + "memoryFree": 60015812608, + "memoryUsagePercent": 10.992143448685422, + "memoryEfficiency": 89.00785655131457, + "cpuCount": 16, + "cpuLoad": 0.011875, + "platform": "linux", + "uptime": 9805.86 + }, + { + "timestamp": 1758906107757, + "memoryTotal": 67427545088, + "memoryUsed": 7394177024, + "memoryFree": 60033368064, + "memoryUsagePercent": 10.966107418488729, + "memoryEfficiency": 89.03389258151127, + "cpuCount": 16, + "cpuLoad": 0.006875, + "platform": "linux", + "uptime": 9835.89 + }, + { + "timestamp": 1758906137788, + "memoryTotal": 67427545088, + "memoryUsed": 7395930112, + "memoryFree": 60031614976, + "memoryUsagePercent": 10.968707376707156, + "memoryEfficiency": 89.03129262329284, + "cpuCount": 16, + "cpuLoad": 0.009375, + "platform": "linux", + "uptime": 9865.92 + }, + { + "timestamp": 1758906167795, + "memoryTotal": 67427545088, + "memoryUsed": 7369392128, + "memoryFree": 60058152960, + "memoryUsagePercent": 10.929349597975385, + "memoryEfficiency": 89.07065040202461, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 9895.93 + }, + { + "timestamp": 1758906197826, + "memoryTotal": 67427545088, + "memoryUsed": 7368847360, + "memoryFree": 60058697728, + "memoryUsagePercent": 10.928541667033679, + "memoryEfficiency": 89.07145833296632, + "cpuCount": 16, + "cpuLoad": 0.005, + "platform": "linux", + "uptime": 9925.96 + }, + { + "timestamp": 1758906227856, + "memoryTotal": 67427545088, + "memoryUsed": 7368941568, + "memoryFree": 60058603520, + "memoryUsagePercent": 10.928681384414576, + "memoryEfficiency": 89.07131861558543, + "cpuCount": 16, + "cpuLoad": 0.018125, + "platform": "linux", + "uptime": 9955.99 + }, + { + "timestamp": 1758906257887, + "memoryTotal": 67427545088, + "memoryUsed": 7375523840, + "memoryFree": 60052021248, + "memoryUsagePercent": 10.93844337707115, + "memoryEfficiency": 89.06155662292885, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 9986.02 + }, + { + "timestamp": 1758906287918, + "memoryTotal": 67427545088, + "memoryUsed": 7380819968, + "memoryFree": 60046725120, + "memoryUsagePercent": 10.946297923745048, + "memoryEfficiency": 89.05370207625495, + "cpuCount": 16, + "cpuLoad": 0.010625, + "platform": "linux", + "uptime": 10016.05 + }, + { + "timestamp": 1758906317948, + "memoryTotal": 67427545088, + "memoryUsed": 7385845760, + "memoryFree": 60041699328, + "memoryUsagePercent": 10.953751542282458, + "memoryEfficiency": 89.04624845771754, + "cpuCount": 16, + "cpuLoad": 0.009375, + "platform": "linux", + "uptime": 10046.08 + }, + { + "timestamp": 1758906347979, + "memoryTotal": 67427545088, + "memoryUsed": 7396171776, + "memoryFree": 60031373312, + "memoryUsagePercent": 10.9690657821625, + "memoryEfficiency": 89.0309342178375, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 10076.11 + }, + { + "timestamp": 1758906377992, + "memoryTotal": 67427545088, + "memoryUsed": 7429517312, + "memoryFree": 59998027776, + "memoryUsagePercent": 11.018519660331252, + "memoryEfficiency": 88.98148033966875, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 10106.12 + }, + { + "timestamp": 1758906407993, + "memoryTotal": 67427545088, + "memoryUsed": 7468474368, + "memoryFree": 59959070720, + "memoryUsagePercent": 11.076295834666471, + "memoryEfficiency": 88.92370416533353, + "cpuCount": 16, + "cpuLoad": 0.014375, + "platform": "linux", + "uptime": 10136.12 + }, + { + "timestamp": 1758906438023, + "memoryTotal": 67427545088, + "memoryUsed": 7418503168, + "memoryFree": 60009041920, + "memoryUsagePercent": 11.00218487610379, + "memoryEfficiency": 88.9978151238962, + "cpuCount": 16, + "cpuLoad": 0.0125, + "platform": "linux", + "uptime": 10166.15 + }, + { + "timestamp": 1758906468054, + "memoryTotal": 67427545088, + "memoryUsed": 7409356800, + "memoryFree": 60018188288, + "memoryUsagePercent": 10.988620140819325, + "memoryEfficiency": 89.01137985918068, + "cpuCount": 16, + "cpuLoad": 0.035, + "platform": "linux", + "uptime": 10196.18 + }, + { + "timestamp": 1758906498084, + "memoryTotal": 67427545088, + "memoryUsed": 7578529792, + "memoryFree": 59849015296, + "memoryUsagePercent": 11.239516108897671, + "memoryEfficiency": 88.76048389110233, + "cpuCount": 16, + "cpuLoad": 0.03875, + "platform": "linux", + "uptime": 10226.21 + }, + { + "timestamp": 1758906528088, + "memoryTotal": 67427545088, + "memoryUsed": 7512719360, + "memoryFree": 59914825728, + "memoryUsagePercent": 11.141914406338115, + "memoryEfficiency": 88.85808559366188, + "cpuCount": 16, + "cpuLoad": 0.030625, + "platform": "linux", + "uptime": 10256.22 + }, + { + "timestamp": 1758906558119, + "memoryTotal": 67427545088, + "memoryUsed": 7507533824, + "memoryFree": 59920011264, + "memoryUsagePercent": 11.134223875720053, + "memoryEfficiency": 88.86577612427995, + "cpuCount": 16, + "cpuLoad": 0.029375, + "platform": "linux", + "uptime": 10286.25 + }, + { + "timestamp": 1758906588133, + "memoryTotal": 67427545088, + "memoryUsed": 7491702784, + "memoryFree": 59935842304, + "memoryUsagePercent": 11.110745281060646, + "memoryEfficiency": 88.88925471893936, + "cpuCount": 16, + "cpuLoad": 0.044375, + "platform": "linux", + "uptime": 10316.26 + }, + { + "timestamp": 1758906618156, + "memoryTotal": 67427545088, + "memoryUsed": 7472390144, + "memoryFree": 59955154944, + "memoryUsagePercent": 11.08210321797679, + "memoryEfficiency": 88.9178967820232, + "cpuCount": 16, + "cpuLoad": 0.0375, + "platform": "linux", + "uptime": 10346.29 + }, + { + "timestamp": 1758906648165, + "memoryTotal": 67427545088, + "memoryUsed": 7466180608, + "memoryFree": 59961364480, + "memoryUsagePercent": 11.072894020175069, + "memoryEfficiency": 88.92710597982493, + "cpuCount": 16, + "cpuLoad": 0.04, + "platform": "linux", + "uptime": 10376.29 + }, + { + "timestamp": 1758906678181, + "memoryTotal": 67427545088, + "memoryUsed": 7528046592, + "memoryFree": 59899498496, + "memoryUsagePercent": 11.16464581674316, + "memoryEfficiency": 88.83535418325684, "cpuCount": 16, "cpuLoad": 0.0625, "platform": "linux", - "uptime": 13006.36 + "uptime": 10406.31 }, { - "timestamp": 1758909308265, + "timestamp": 1758906708200, "memoryTotal": 67427545088, - "memoryUsed": 8244649984, - "memoryFree": 59182895104, - "memoryUsagePercent": 12.22742126120693, - "memoryEfficiency": 87.77257873879307, + "memoryUsed": 7603597312, + "memoryFree": 59823947776, + "memoryUsagePercent": 11.276693081553702, + "memoryEfficiency": 88.7233069184463, + "cpuCount": 16, + "cpuLoad": 0.046875, + "platform": "linux", + "uptime": 10436.33 + }, + { + "timestamp": 1758906738231, + "memoryTotal": 67427545088, + "memoryUsed": 7516663808, + "memoryFree": 59910881280, + "memoryUsagePercent": 11.14776431232958, + "memoryEfficiency": 88.85223568767042, + "cpuCount": 16, + "cpuLoad": 0.051875, + "platform": "linux", + "uptime": 10466.36 + }, + { + "timestamp": 1758906768262, + "memoryTotal": 67427545088, + "memoryUsed": 7430979584, + "memoryFree": 59996565504, + "memoryUsagePercent": 11.02068831706952, + "memoryEfficiency": 88.97931168293047, + "cpuCount": 16, + "cpuLoad": 0.03125, + "platform": "linux", + "uptime": 10496.39 + }, + { + "timestamp": 1758906798293, + "memoryTotal": 67427545088, + "memoryUsed": 7432650752, + "memoryFree": 59994894336, + "memoryUsagePercent": 11.023166781913257, + "memoryEfficiency": 88.97683321808674, + "cpuCount": 16, + "cpuLoad": 0.045, + "platform": "linux", + "uptime": 10526.42 + }, + { + "timestamp": 1758906828317, + "memoryTotal": 67427545088, + "memoryUsed": 7420264448, + "memoryFree": 60007280640, + "memoryUsagePercent": 11.004796983659688, + "memoryEfficiency": 88.99520301634031, + "cpuCount": 16, + "cpuLoad": 0.026875, + "platform": "linux", + "uptime": 10556.45 + }, + { + "timestamp": 1758906858347, + "memoryTotal": 67427545088, + "memoryUsed": 7418331136, + "memoryFree": 60009213952, + "memoryUsagePercent": 11.001929740016934, + "memoryEfficiency": 88.99807025998307, + "cpuCount": 16, + "cpuLoad": 0.028125, + "platform": "linux", + "uptime": 10586.48 + }, + { + "timestamp": 1758906888358, + "memoryTotal": 67427545088, + "memoryUsed": 7400689664, + "memoryFree": 60026855424, + "memoryUsagePercent": 10.975766141776814, + "memoryEfficiency": 89.02423385822318, + "cpuCount": 16, + "cpuLoad": 0.025, + "platform": "linux", + "uptime": 10616.49 + }, + { + "timestamp": 1758906918366, + "memoryTotal": 67427545088, + "memoryUsed": 7417696256, + "memoryFree": 60009848832, + "memoryUsagePercent": 11.000988166363065, + "memoryEfficiency": 88.99901183363693, + "cpuCount": 16, + "cpuLoad": 0.0225, + "platform": "linux", + "uptime": 10646.5 + }, + { + "timestamp": 1758906948369, + "memoryTotal": 67427545088, + "memoryUsed": 7432167424, + "memoryFree": 59995377664, + "memoryUsagePercent": 11.022449971002569, + "memoryEfficiency": 88.97755002899743, + "cpuCount": 16, + "cpuLoad": 0.01375, + "platform": "linux", + "uptime": 10676.5 + }, + { + "timestamp": 1758906978399, + "memoryTotal": 67427545088, + "memoryUsed": 7446351872, + "memoryFree": 59981193216, + "memoryUsagePercent": 11.043486548830646, + "memoryEfficiency": 88.95651345116936, + "cpuCount": 16, + "cpuLoad": 0.0125, + "platform": "linux", + "uptime": 10706.53 + }, + { + "timestamp": 1758907008427, + "memoryTotal": 67427545088, + "memoryUsed": 7415971840, + "memoryFree": 60011573248, + "memoryUsagePercent": 10.998430730825778, + "memoryEfficiency": 89.00156926917423, + "cpuCount": 16, + "cpuLoad": 0.0075, + "platform": "linux", + "uptime": 10736.56 + }, + { + "timestamp": 1758907038458, + "memoryTotal": 67427545088, + "memoryUsed": 7441035264, + "memoryFree": 59986509824, + "memoryUsagePercent": 11.035601628813078, + "memoryEfficiency": 88.96439837118692, + "cpuCount": 16, + "cpuLoad": 0.004375, + "platform": "linux", + "uptime": 10766.59 + }, + { + "timestamp": 1758907068487, + "memoryTotal": 67427545088, + "memoryUsed": 7419375616, + "memoryFree": 60008169472, + "memoryUsagePercent": 11.003478780544269, + "memoryEfficiency": 88.99652121945573, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 10796.62 + }, + { + "timestamp": 1758907098517, + "memoryTotal": 67427545088, + "memoryUsed": 7445028864, + "memoryFree": 59982516224, + "memoryUsagePercent": 11.041524430829357, + "memoryEfficiency": 88.95847556917064, + "cpuCount": 16, + "cpuLoad": 0.02625, + "platform": "linux", + "uptime": 10826.65 + }, + { + "timestamp": 1758907128525, + "memoryTotal": 67427545088, + "memoryUsed": 7438372864, + "memoryFree": 59989172224, + "memoryUsagePercent": 11.031653094135557, + "memoryEfficiency": 88.96834690586445, + "cpuCount": 16, + "cpuLoad": 0.020625, + "platform": "linux", + "uptime": 10856.65 + }, + { + "timestamp": 1758907158555, + "memoryTotal": 67427545088, + "memoryUsed": 7423205376, + "memoryFree": 60004339712, + "memoryUsagePercent": 11.009158595811163, + "memoryEfficiency": 88.99084140418884, + "cpuCount": 16, + "cpuLoad": 0.04, + "platform": "linux", + "uptime": 10886.68 + }, + { + "timestamp": 1758907188585, + "memoryTotal": 67427545088, + "memoryUsed": 7420506112, + "memoryFree": 60007038976, + "memoryUsagePercent": 11.005155389115032, + "memoryEfficiency": 88.99484461088497, + "cpuCount": 16, + "cpuLoad": 0.0275, + "platform": "linux", + "uptime": 10916.72 + }, + { + "timestamp": 1758907218615, + "memoryTotal": 67427545088, + "memoryUsed": 7409901568, + "memoryFree": 60017643520, + "memoryUsagePercent": 10.989428071761035, + "memoryEfficiency": 89.01057192823896, + "cpuCount": 16, + "cpuLoad": 0.01625, + "platform": "linux", + "uptime": 10946.75 + }, + { + "timestamp": 1758907248646, + "memoryTotal": 67427545088, + "memoryUsed": 7411736576, + "memoryFree": 60015808512, + "memoryUsagePercent": 10.992149523354156, + "memoryEfficiency": 89.00785047664584, + "cpuCount": 16, + "cpuLoad": 0.016875, + "platform": "linux", + "uptime": 10976.78 + }, + { + "timestamp": 1758907278657, + "memoryTotal": 67427545088, + "memoryUsed": 7411654656, + "memoryFree": 60015890432, + "memoryUsagePercent": 10.992028029979462, + "memoryEfficiency": 89.00797197002053, + "cpuCount": 16, + "cpuLoad": 0.028125, + "platform": "linux", + "uptime": 11006.79 + }, + { + "timestamp": 1758907308687, + "memoryTotal": 67427545088, + "memoryUsed": 7418380288, + "memoryFree": 60009164800, + "memoryUsagePercent": 11.00200263604175, + "memoryEfficiency": 88.99799736395825, + "cpuCount": 16, + "cpuLoad": 0.028125, + "platform": "linux", + "uptime": 11036.82 + }, + { + "timestamp": 1758907338718, + "memoryTotal": 67427545088, + "memoryUsed": 7439749120, + "memoryFree": 59987795968, + "memoryUsagePercent": 11.033694182830398, + "memoryEfficiency": 88.9663058171696, + "cpuCount": 16, + "cpuLoad": 0.021875, + "platform": "linux", + "uptime": 11066.85 + }, + { + "timestamp": 1758907368748, + "memoryTotal": 67427545088, + "memoryUsed": 7472156672, + "memoryFree": 59955388416, + "memoryUsagePercent": 11.081756961858916, + "memoryEfficiency": 88.91824303814109, + "cpuCount": 16, + "cpuLoad": 0.025, + "platform": "linux", + "uptime": 11096.88 + }, + { + "timestamp": 1758907398779, + "memoryTotal": 67427545088, + "memoryUsed": 7439745024, + "memoryFree": 59987800064, + "memoryUsagePercent": 11.033688108161664, + "memoryEfficiency": 88.96631189183833, + "cpuCount": 16, + "cpuLoad": 0.019375, + "platform": "linux", + "uptime": 11126.91 + }, + { + "timestamp": 1758907428809, + "memoryTotal": 67427545088, + "memoryUsed": 7435591680, + "memoryFree": 59991953408, + "memoryUsagePercent": 11.027528394064733, + "memoryEfficiency": 88.97247160593527, + "cpuCount": 16, + "cpuLoad": 0.01625, + "platform": "linux", + "uptime": 11156.94 + }, + { + "timestamp": 1758907458839, + "memoryTotal": 67427545088, + "memoryUsed": 7448735744, + "memoryFree": 59978809344, + "memoryUsagePercent": 11.047022006034211, + "memoryEfficiency": 88.95297799396579, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 11186.97 + }, + { + "timestamp": 1758907488870, + "memoryTotal": 67427545088, + "memoryUsed": 7432036352, + "memoryFree": 59995508736, + "memoryUsagePercent": 11.02225558160306, + "memoryEfficiency": 88.97774441839694, + "cpuCount": 16, + "cpuLoad": 0.023125, + "platform": "linux", + "uptime": 11217 + }, + { + "timestamp": 1758907518900, + "memoryTotal": 67427545088, + "memoryUsed": 7467163648, + "memoryFree": 59960381440, + "memoryUsagePercent": 11.074351940671383, + "memoryEfficiency": 88.92564805932862, + "cpuCount": 16, + "cpuLoad": 0.0225, + "platform": "linux", + "uptime": 11247.03 + }, + { + "timestamp": 1758907548924, + "memoryTotal": 67427545088, + "memoryUsed": 7444217856, + "memoryFree": 59983327232, + "memoryUsagePercent": 11.040321646419898, + "memoryEfficiency": 88.9596783535801, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 11277.05 + }, + { + "timestamp": 1758907578953, + "memoryTotal": 67427545088, + "memoryUsed": 7443820544, + "memoryFree": 59983724544, + "memoryUsagePercent": 11.039732403552636, + "memoryEfficiency": 88.96026759644737, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 11307.08 + }, + { + "timestamp": 1758907608984, + "memoryTotal": 67427545088, + "memoryUsed": 7453802496, + "memoryFree": 59973742592, + "memoryUsagePercent": 11.054536371258969, + "memoryEfficiency": 88.94546362874104, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 11337.11 + }, + { + "timestamp": 1758907639014, + "memoryTotal": 67427545088, + "memoryUsed": 7448104960, + "memoryFree": 59979440128, + "memoryUsagePercent": 11.046086507049075, + "memoryEfficiency": 88.95391349295093, + "cpuCount": 16, + "cpuLoad": 0.00625, + "platform": "linux", + "uptime": 11367.14 + }, + { + "timestamp": 1758907669045, + "memoryTotal": 67427545088, + "memoryUsed": 7481307136, + "memoryFree": 59946237952, + "memoryUsagePercent": 11.095327771812116, + "memoryEfficiency": 88.90467222818788, + "cpuCount": 16, + "cpuLoad": 0.00375, + "platform": "linux", + "uptime": 11397.17 + }, + { + "timestamp": 1758907699075, + "memoryTotal": 67427545088, + "memoryUsed": 7485435904, + "memoryFree": 59942109184, + "memoryUsagePercent": 11.101451037896638, + "memoryEfficiency": 88.89854896210336, + "cpuCount": 16, + "cpuLoad": 0.005625, + "platform": "linux", + "uptime": 11427.21 + }, + { + "timestamp": 1758907729106, + "memoryTotal": 67427545088, + "memoryUsed": 7441514496, + "memoryFree": 59986030592, + "memoryUsagePercent": 11.03631236505503, + "memoryEfficiency": 88.96368763494498, + "cpuCount": 16, + "cpuLoad": 0.003125, + "platform": "linux", + "uptime": 11457.24 + }, + { + "timestamp": 1758907759136, + "memoryTotal": 67427545088, + "memoryUsed": 7439892480, + "memoryFree": 59987652608, + "memoryUsagePercent": 11.03390679623611, + "memoryEfficiency": 88.96609320376389, + "cpuCount": 16, + "cpuLoad": 0.001875, + "platform": "linux", + "uptime": 11487.27 + }, + { + "timestamp": 1758907789166, + "memoryTotal": 67427545088, + "memoryUsed": 7422746624, + "memoryFree": 60004798464, + "memoryUsagePercent": 11.008478232912882, + "memoryEfficiency": 88.99152176708712, + "cpuCount": 16, + "cpuLoad": 0.00875, + "platform": "linux", + "uptime": 11517.3 + }, + { + "timestamp": 1758907819191, + "memoryTotal": 67427545088, + "memoryUsed": 7487037440, + "memoryFree": 59940507648, + "memoryUsagePercent": 11.103826233371885, + "memoryEfficiency": 88.89617376662811, + "cpuCount": 16, + "cpuLoad": 0.01875, + "platform": "linux", + "uptime": 11547.32 + }, + { + "timestamp": 1758907849221, + "memoryTotal": 67427545088, + "memoryUsed": 7463059456, + "memoryFree": 59964485632, + "memoryUsagePercent": 11.068265122599268, + "memoryEfficiency": 88.93173487740073, + "cpuCount": 16, + "cpuLoad": 0.01125, + "platform": "linux", + "uptime": 11577.35 + }, + { + "timestamp": 1758907879251, + "memoryTotal": 67427545088, + "memoryUsed": 7477170176, + "memoryFree": 59950374912, + "memoryUsagePercent": 11.089192356390123, + "memoryEfficiency": 88.91080764360987, + "cpuCount": 16, + "cpuLoad": 0.01, + "platform": "linux", + "uptime": 11607.38 + }, + { + "timestamp": 1758907909277, + "memoryTotal": 67427545088, + "memoryUsed": 7544012800, + "memoryFree": 59883532288, + "memoryUsagePercent": 11.188324875470808, + "memoryEfficiency": 88.81167512452919, + "cpuCount": 16, + "cpuLoad": 0.05, + "platform": "linux", + "uptime": 11637.41 + }, + { + "timestamp": 1758907939297, + "memoryTotal": 67427545088, + "memoryUsed": 7609438208, + "memoryFree": 59818106880, + "memoryUsagePercent": 11.285355559169309, + "memoryEfficiency": 88.7146444408307, + "cpuCount": 16, + "cpuLoad": 0.1225, + "platform": "linux", + "uptime": 11667.43 + }, + { + "timestamp": 1758907969327, + "memoryTotal": 67427545088, + "memoryUsed": 7581696000, + "memoryFree": 59845849088, + "memoryUsagePercent": 11.244211827829552, + "memoryEfficiency": 88.75578817217044, + "cpuCount": 16, + "cpuLoad": 0.12625, + "platform": "linux", + "uptime": 11697.46 + }, + { + "timestamp": 1758907999356, + "memoryTotal": 67427545088, + "memoryUsed": 7552589824, + "memoryFree": 59874955264, + "memoryUsagePercent": 11.201045231801158, + "memoryEfficiency": 88.79895476819884, + "cpuCount": 16, + "cpuLoad": 0.08875, + "platform": "linux", + "uptime": 11727.49 + }, + { + "timestamp": 1758908029386, + "memoryTotal": 67427545088, + "memoryUsed": 7551336448, + "memoryFree": 59876208640, + "memoryUsagePercent": 11.199186383168357, + "memoryEfficiency": 88.80081361683165, + "cpuCount": 16, + "cpuLoad": 0.08375, + "platform": "linux", + "uptime": 11757.52 + }, + { + "timestamp": 1758908059416, + "memoryTotal": 67427545088, + "memoryUsed": 7531319296, + "memoryFree": 59896225792, + "memoryUsagePercent": 11.169499477062143, + "memoryEfficiency": 88.83050052293785, + "cpuCount": 16, + "cpuLoad": 0.065, + "platform": "linux", + "uptime": 11787.55 + }, + { + "timestamp": 1758908089447, + "memoryTotal": 67427545088, + "memoryUsed": 7546986496, + "memoryFree": 59880558592, + "memoryUsagePercent": 11.192735084972162, + "memoryEfficiency": 88.80726491502784, + "cpuCount": 16, + "cpuLoad": 0.05125, + "platform": "linux", + "uptime": 11817.58 + }, + { + "timestamp": 1758908119477, + "memoryTotal": 67427545088, + "memoryUsed": 7588646912, + "memoryFree": 59838898176, + "memoryUsagePercent": 11.254520540672246, + "memoryEfficiency": 88.74547945932775, + "cpuCount": 16, + "cpuLoad": 0.04125, + "platform": "linux", + "uptime": 11847.61 + }, + { + "timestamp": 1758908149508, + "memoryTotal": 67427545088, + "memoryUsed": 7552487424, + "memoryFree": 59875057664, + "memoryUsagePercent": 11.200893365082793, + "memoryEfficiency": 88.79910663491721, + "cpuCount": 16, + "cpuLoad": 0.040625, + "platform": "linux", + "uptime": 11877.64 + }, + { + "timestamp": 1758908179526, + "memoryTotal": 67427545088, + "memoryUsed": 7534575616, + "memoryFree": 59892969472, + "memoryUsagePercent": 11.174328838706185, + "memoryEfficiency": 88.82567116129381, + "cpuCount": 16, + "cpuLoad": 0.043125, + "platform": "linux", + "uptime": 11907.66 + }, + { + "timestamp": 1758908209527, + "memoryTotal": 67427545088, + "memoryUsed": 7486218240, + "memoryFree": 59941326848, + "memoryUsagePercent": 11.102611299624957, + "memoryEfficiency": 88.89738870037505, + "cpuCount": 16, + "cpuLoad": 0.0325, + "platform": "linux", + "uptime": 11937.66 + }, + { + "timestamp": 1758908239528, + "memoryTotal": 67427545088, + "memoryUsed": 7506694144, + "memoryFree": 59920850944, + "memoryUsagePercent": 11.13297856862945, + "memoryEfficiency": 88.86702143137055, + "cpuCount": 16, + "cpuLoad": 0.0275, + "platform": "linux", + "uptime": 11967.66 + }, + { + "timestamp": 1758908269557, + "memoryTotal": 67427545088, + "memoryUsed": 7527804928, + "memoryFree": 59899740160, + "memoryUsagePercent": 11.164287411287816, + "memoryEfficiency": 88.83571258871218, + "cpuCount": 16, + "cpuLoad": 0.045, + "platform": "linux", + "uptime": 11997.69 + }, + { + "timestamp": 1758908299587, + "memoryTotal": 67427545088, + "memoryUsed": 7631843328, + "memoryFree": 59795701760, + "memoryUsagePercent": 11.31858399714782, + "memoryEfficiency": 88.68141600285217, "cpuCount": 16, "cpuLoad": 0.060625, "platform": "linux", - "uptime": 13036.4 + "uptime": 12027.72 }, { - "timestamp": 1758909338273, + "timestamp": 1758908329617, "memoryTotal": 67427545088, - "memoryUsed": 8170340352, - "memoryFree": 59257204736, - "memoryUsagePercent": 12.117214621022983, - "memoryEfficiency": 87.88278537897702, + "memoryUsed": 7722807296, + "memoryFree": 59704737792, + "memoryUsagePercent": 11.453490240406836, + "memoryEfficiency": 88.54650975959316, + "cpuCount": 16, + "cpuLoad": 0.054375, + "platform": "linux", + "uptime": 12057.75 + }, + { + "timestamp": 1758908359647, + "memoryTotal": 67427545088, + "memoryUsed": 7683883008, + "memoryFree": 59743662080, + "memoryUsagePercent": 11.395762663421499, + "memoryEfficiency": 88.6042373365785, + "cpuCount": 16, + "cpuLoad": 0.05, + "platform": "linux", + "uptime": 12087.78 + }, + { + "timestamp": 1758908389678, + "memoryTotal": 67427545088, + "memoryUsed": 7634051072, + "memoryFree": 59793494016, + "memoryUsagePercent": 11.321858243595797, + "memoryEfficiency": 88.6781417564042, + "cpuCount": 16, + "cpuLoad": 0.050625, + "platform": "linux", + "uptime": 12117.81 + }, + { + "timestamp": 1758908419708, + "memoryTotal": 67427545088, + "memoryUsed": 8270753792, + "memoryFree": 59156791296, + "memoryUsagePercent": 12.266135125052827, + "memoryEfficiency": 87.73386487494717, + "cpuCount": 16, + "cpuLoad": 0.0675, + "platform": "linux", + "uptime": 12147.84 + }, + { + "timestamp": 1758908449726, + "memoryTotal": 67427545088, + "memoryUsed": 8126865408, + "memoryFree": 59300679680, + "memoryUsagePercent": 12.052738087073452, + "memoryEfficiency": 87.94726191292655, + "cpuCount": 16, + "cpuLoad": 0.045, + "platform": "linux", + "uptime": 12177.86 + }, + { + "timestamp": 1758908479726, + "memoryTotal": 67427545088, + "memoryUsed": 8139038720, + "memoryFree": 59288506368, + "memoryUsagePercent": 12.07079200255282, + "memoryEfficiency": 87.92920799744718, + "cpuCount": 16, + "cpuLoad": 0.04, + "platform": "linux", + "uptime": 12207.86 + }, + { + "timestamp": 1758908509755, + "memoryTotal": 67427545088, + "memoryUsed": 8329117696, + "memoryFree": 59098427392, + "memoryUsagePercent": 12.352693079852797, + "memoryEfficiency": 87.6473069201472, + "cpuCount": 16, + "cpuLoad": 0.02375, + "platform": "linux", + "uptime": 12237.89 + }, + { + "timestamp": 1758908539769, + "memoryTotal": 67427545088, + "memoryUsed": 8101969920, + "memoryFree": 59325575168, + "memoryUsagePercent": 12.015816250504272, + "memoryEfficiency": 87.98418374949573, + "cpuCount": 16, + "cpuLoad": 0.035, + "platform": "linux", + "uptime": 12267.9 + }, + { + "timestamp": 1758908569791, + "memoryTotal": 67427545088, + "memoryUsed": 8150904832, + "memoryFree": 59276640256, + "memoryUsagePercent": 12.088390317877087, + "memoryEfficiency": 87.91160968212291, + "cpuCount": 16, + "cpuLoad": 0.028125, + "platform": "linux", + "uptime": 12297.92 + }, + { + "timestamp": 1758908599821, + "memoryTotal": 67427545088, + "memoryUsed": 8292077568, + "memoryFree": 59135467520, + "memoryUsagePercent": 12.297759850485393, + "memoryEfficiency": 87.70224014951461, + "cpuCount": 16, + "cpuLoad": 0.021875, + "platform": "linux", + "uptime": 12327.95 + }, + { + "timestamp": 1758908629849, + "memoryTotal": 67427545088, + "memoryUsed": 8169869312, + "memoryFree": 59257675776, + "memoryUsagePercent": 12.116516034118499, + "memoryEfficiency": 87.8834839658815, "cpuCount": 16, "cpuLoad": 0.036875, "platform": "linux", - "uptime": 13066.4 + "uptime": 12357.98 + }, + { + "timestamp": 1758908659870, + "memoryTotal": 67427545088, + "memoryUsed": 8132210688, + "memoryFree": 59295334400, + "memoryUsagePercent": 12.060665529772164, + "memoryEfficiency": 87.93933447022783, + "cpuCount": 16, + "cpuLoad": 0.04125, + "platform": "linux", + "uptime": 12388 + }, + { + "timestamp": 1758908689899, + "memoryTotal": 67427545088, + "memoryUsed": 8215400448, + "memoryFree": 59212144640, + "memoryUsagePercent": 12.184042051772822, + "memoryEfficiency": 87.81595794822718, + "cpuCount": 16, + "cpuLoad": 0.0675, + "platform": "linux", + "uptime": 12418.03 + }, + { + "timestamp": 1758908719930, + "memoryTotal": 67427545088, + "memoryUsed": 8213094400, + "memoryFree": 59214450688, + "memoryUsagePercent": 12.180622013275217, + "memoryEfficiency": 87.81937798672479, + "cpuCount": 16, + "cpuLoad": 0.045, + "platform": "linux", + "uptime": 12448.06 + }, + { + "timestamp": 1758908749961, + "memoryTotal": 67427545088, + "memoryUsed": 8242556928, + "memoryFree": 59184988160, + "memoryUsagePercent": 12.224317105483525, + "memoryEfficiency": 87.77568289451648, + "cpuCount": 16, + "cpuLoad": 0.03625, + "platform": "linux", + "uptime": 12478.09 + }, + { + "timestamp": 1758908779980, + "memoryTotal": 67427545088, + "memoryUsed": 8253108224, + "memoryFree": 59174436864, + "memoryUsagePercent": 12.239965452143972, + "memoryEfficiency": 87.76003454785602, + "cpuCount": 16, + "cpuLoad": 0.050625, + "platform": "linux", + "uptime": 12508.11 + }, + { + "timestamp": 1758908810010, + "memoryTotal": 67427545088, + "memoryUsed": 8089108480, + "memoryFree": 59338436608, + "memoryUsagePercent": 11.996741790677486, + "memoryEfficiency": 88.00325820932251, + "cpuCount": 16, + "cpuLoad": 0.041875, + "platform": "linux", + "uptime": 12538.14 + }, + { + "timestamp": 1758908840040, + "memoryTotal": 67427545088, + "memoryUsed": 8123625472, + "memoryFree": 59303919616, + "memoryUsagePercent": 12.047933024104346, + "memoryEfficiency": 87.95206697589566, + "cpuCount": 16, + "cpuLoad": 0.054375, + "platform": "linux", + "uptime": 12568.17 + }, + { + "timestamp": 1758908870058, + "memoryTotal": 67427545088, + "memoryUsed": 8273080320, + "memoryFree": 59154464768, + "memoryUsagePercent": 12.269585536894105, + "memoryEfficiency": 87.73041446310589, + "cpuCount": 16, + "cpuLoad": 0.046875, + "platform": "linux", + "uptime": 12598.19 + }, + { + "timestamp": 1758908900089, + "memoryTotal": 67427545088, + "memoryUsed": 8330043392, + "memoryFree": 59097501696, + "memoryUsagePercent": 12.354065954986826, + "memoryEfficiency": 87.64593404501318, + "cpuCount": 16, + "cpuLoad": 0.046875, + "platform": "linux", + "uptime": 12628.22 + }, + { + "timestamp": 1758908930092, + "memoryTotal": 67427545088, + "memoryUsed": 8242397184, + "memoryFree": 59185147904, + "memoryUsagePercent": 12.224080193402873, + "memoryEfficiency": 87.77591980659713, + "cpuCount": 16, + "cpuLoad": 0.060625, + "platform": "linux", + "uptime": 12658.22 + }, + { + "timestamp": 1758908960112, + "memoryTotal": 67427545088, + "memoryUsed": 8296128512, + "memoryFree": 59131416576, + "memoryUsagePercent": 12.30376769786396, + "memoryEfficiency": 87.69623230213604, + "cpuCount": 16, + "cpuLoad": 0.07, + "platform": "linux", + "uptime": 12688.24 + }, + { + "timestamp": 1758908990142, + "memoryTotal": 67427545088, + "memoryUsed": 8420360192, + "memoryFree": 59007184896, + "memoryUsagePercent": 12.488012400585768, + "memoryEfficiency": 87.51198759941423, + "cpuCount": 16, + "cpuLoad": 0.0475, + "platform": "linux", + "uptime": 12718.27 + }, + { + "timestamp": 1758909020173, + "memoryTotal": 67427545088, + "memoryUsed": 8300982272, + "memoryFree": 59126562816, + "memoryUsagePercent": 12.310966180314512, + "memoryEfficiency": 87.68903381968549, + "cpuCount": 16, + "cpuLoad": 0.0525, + "platform": "linux", + "uptime": 12748.3 + }, + { + "timestamp": 1758909050203, + "memoryTotal": 67427545088, + "memoryUsed": 8345358336, + "memoryFree": 59082186752, + "memoryUsagePercent": 12.376779141385667, + "memoryEfficiency": 87.62322085861433, + "cpuCount": 16, + "cpuLoad": 0.04375, + "platform": "linux", + "uptime": 12778.33 + }, + { + "timestamp": 1758909080232, + "memoryTotal": 67427545088, + "memoryUsed": 8327757824, + "memoryFree": 59099787264, + "memoryUsagePercent": 12.350676289832894, + "memoryEfficiency": 87.64932371016711, + "cpuCount": 16, + "cpuLoad": 0.056875, + "platform": "linux", + "uptime": 12808.36 + }, + { + "timestamp": 1758909110257, + "memoryTotal": 67427545088, + "memoryUsed": 8240340992, + "memoryFree": 59187204096, + "memoryUsagePercent": 12.221030709698082, + "memoryEfficiency": 87.77896929030192, + "cpuCount": 16, + "cpuLoad": 0.055625, + "platform": "linux", + "uptime": 12838.39 + }, + { + "timestamp": 1758909140287, + "memoryTotal": 67427545088, + "memoryUsed": 8143695872, + "memoryFree": 59283849216, + "memoryUsagePercent": 12.077698900904112, + "memoryEfficiency": 87.92230109909589, + "cpuCount": 16, + "cpuLoad": 0.04625, + "platform": "linux", + "uptime": 12868.42 + }, + { + "timestamp": 1758909170318, + "memoryTotal": 67427545088, + "memoryUsed": 8058060800, + "memoryFree": 59369484288, + "memoryUsagePercent": 11.95069580166887, + "memoryEfficiency": 88.04930419833113, + "cpuCount": 16, + "cpuLoad": 0.05125, + "platform": "linux", + "uptime": 12898.45 + }, + { + "timestamp": 1758909200337, + "memoryTotal": 67427545088, + "memoryUsed": 8150396928, + "memoryFree": 59277148160, + "memoryUsagePercent": 12.087637058953991, + "memoryEfficiency": 87.91236294104601, + "cpuCount": 16, + "cpuLoad": 0.070625, + "platform": "linux", + "uptime": 12928.47 + }, + { + "timestamp": 1758909230361, + "memoryTotal": 67427545088, + "memoryUsed": 8180264960, + "memoryFree": 59247280128, + "memoryUsagePercent": 12.13193354336703, + "memoryEfficiency": 87.86806645663297, + "cpuCount": 16, + "cpuLoad": 0.054375, + "platform": "linux", + "uptime": 12958.49 + }, + { + "timestamp": 1758909260391, + "memoryTotal": 67427545088, + "memoryUsed": 8321953792, + "memoryFree": 59105591296, + "memoryUsagePercent": 12.3420684842359, + "memoryEfficiency": 87.6579315157641, + "cpuCount": 16, + "cpuLoad": 0.0375, + "platform": "linux", + "uptime": 12988.52 + }, + { + "timestamp": 1758909290401, + "memoryTotal": 67427545088, + "memoryUsed": 8267534336, + "memoryFree": 59160010752, + "memoryUsagePercent": 12.261360435427395, + "memoryEfficiency": 87.73863956457261, + "cpuCount": 16, + "cpuLoad": 0.048125, + "platform": "linux", + "uptime": 13018.53 + }, + { + "timestamp": 1758909320426, + "memoryTotal": 67427545088, + "memoryUsed": 8116383744, + "memoryFree": 59311161344, + "memoryUsagePercent": 12.037193009781493, + "memoryEfficiency": 87.96280699021851, + "cpuCount": 16, + "cpuLoad": 0.046875, + "platform": "linux", + "uptime": 13048.56 + }, + { + "timestamp": 1758909350456, + "memoryTotal": 67427545088, + "memoryUsed": 8187662336, + "memoryFree": 59239882752, + "memoryUsagePercent": 12.1429043951018, + "memoryEfficiency": 87.8570956048982, + "cpuCount": 16, + "cpuLoad": 0.033125, + "platform": "linux", + "uptime": 13078.59 + }, + { + "timestamp": 1758909380462, + "memoryTotal": 67427545088, + "memoryUsed": 8228511744, + "memoryFree": 59199033344, + "memoryUsagePercent": 12.203487066392423, + "memoryEfficiency": 87.79651293360757, + "cpuCount": 16, + "cpuLoad": 0.02375, + "platform": "linux", + "uptime": 13108.59 + }, + { + "timestamp": 1758909410488, + "memoryTotal": 67427545088, + "memoryUsed": 8246853632, + "memoryFree": 59180691456, + "memoryUsagePercent": 12.230689432986168, + "memoryEfficiency": 87.76931056701383, + "cpuCount": 16, + "cpuLoad": 0.030625, + "platform": "linux", + "uptime": 13138.62 + }, + { + "timestamp": 1758909440519, + "memoryTotal": 67427545088, + "memoryUsed": 8378187776, + "memoryFree": 59049357312, + "memoryUsagePercent": 12.425467611293854, + "memoryEfficiency": 87.57453238870615, + "cpuCount": 16, + "cpuLoad": 0.035625, + "platform": "linux", + "uptime": 13168.65 + }, + { + "timestamp": 1758909470549, + "memoryTotal": 67427545088, + "memoryUsed": 8328392704, + "memoryFree": 59099152384, + "memoryUsagePercent": 12.351617863486764, + "memoryEfficiency": 87.64838213651323, + "cpuCount": 16, + "cpuLoad": 0.0375, + "platform": "linux", + "uptime": 13198.68 + }, + { + "timestamp": 1758909500580, + "memoryTotal": 67427545088, + "memoryUsed": 8586551296, + "memoryFree": 58840993792, + "memoryUsagePercent": 12.734486009825291, + "memoryEfficiency": 87.26551399017471, + "cpuCount": 16, + "cpuLoad": 0.055625, + "platform": "linux", + "uptime": 13228.71 + }, + { + "timestamp": 1758909530609, + "memoryTotal": 67427545088, + "memoryUsed": 8270753792, + "memoryFree": 59156791296, + "memoryUsagePercent": 12.266135125052827, + "memoryEfficiency": 87.73386487494717, + "cpuCount": 16, + "cpuLoad": 0.06, + "platform": "linux", + "uptime": 13258.74 + }, + { + "timestamp": 1758909560613, + "memoryTotal": 67427545088, + "memoryUsed": 8568532992, + "memoryFree": 58859012096, + "memoryUsagePercent": 12.707763542061585, + "memoryEfficiency": 87.29223645793842, + "cpuCount": 16, + "cpuLoad": 0.0625, + "platform": "linux", + "uptime": 13288.74 + }, + { + "timestamp": 1758909590642, + "memoryTotal": 67427545088, + "memoryUsed": 8208855040, + "memoryFree": 59218690048, + "memoryUsagePercent": 12.17433473113486, + "memoryEfficiency": 87.82566526886514, + "cpuCount": 16, + "cpuLoad": 0.05, + "platform": "linux", + "uptime": 13318.77 } ] \ No newline at end of file diff --git a/.claude-flow/metrics/task-metrics.json b/.claude-flow/metrics/task-metrics.json index 10429c1078..779699edc2 100644 --- a/.claude-flow/metrics/task-metrics.json +++ b/.claude-flow/metrics/task-metrics.json @@ -1,10 +1,10 @@ [ { - "id": "cmd-hooks-1758909300111", + "id": "cmd-hooks-1758909566410", "type": "hooks", "success": true, - "duration": 35.59752699999996, - "timestamp": 1758909300147, + "duration": 9.132583000000011, + "timestamp": 1758909566419, "metadata": {} } ] \ No newline at end of file diff --git a/.claude/checkpoints/1758909460.json b/.claude/checkpoints/1758909460.json new file mode 100644 index 0000000000..3ba330252e --- /dev/null +++ b/.claude/checkpoints/1758909460.json @@ -0,0 +1 @@ +{"branch": "checkpoint/pre-edit-20250926-175740", "file": "/workspaces/claude-code-flow/package.json", "timestamp": "2025-09-26T17:57:40Z", "type": "pre-edit", "original_branch": "alpha-125"} diff --git a/.claude/checkpoints/1758909461.json b/.claude/checkpoints/1758909461.json new file mode 100644 index 0000000000..7933d5e278 --- /dev/null +++ b/.claude/checkpoints/1758909461.json @@ -0,0 +1 @@ +{"tag": "checkpoint-20250926-175741", "file": "/workspaces/claude-code-flow/package.json", "timestamp": "2025-09-26T17:57:41Z", "type": "post-edit", "branch": "alpha-125", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 48 + .claude-flow/metrics/task-metrics.json | 6 +- .claude/checkpoints/task-1758909345.json | 1 + claude-flow-wiki | 0 dist-cjs/src/cli/help-formatter.js | 5 - dist-cjs/src/cli/simple-cli.js | 353 ++-- dist-cjs/src/cli/simple-cli.js.map | 2 +- dist-cjs/src/cli/simple-commands/hive-mind.js | 8 + dist-cjs/src/cli/simple-commands/hive-mind.js.map | 2 +- .../cli/simple-commands/inject-memory-protocol.js | 200 +++ .../simple-commands/inject-memory-protocol.js.map | 1 + dist-cjs/src/cli/simple-commands/swarm.js | 8 + dist-cjs/src/cli/simple-commands/swarm.js.map | 2 +- dist-cjs/src/ui/console/js/analysis-tools.js | 941 ---------- dist-cjs/src/ui/console/js/analysis-tools.js.map | 1 - dist-cjs/src/ui/console/js/command-handler.js | 667 -------- dist-cjs/src/ui/console/js/command-handler.js.map | 1 - dist-cjs/src/ui/console/js/console.js | 410 ----- dist-cjs/src/ui/console/js/console.js.map | 1 - dist-cjs/src/ui/console/js/daa-tools.js | 891 ---------- dist-cjs/src/ui/console/js/daa-tools.js.map | 1 - dist-cjs/src/ui/console/js/memory-interface.js | 792 --------- dist-cjs/src/ui/console/js/memory-interface.js.map | 1 - dist-cjs/src/ui/console/js/memory-test.js | 178 -- dist-cjs/src/ui/console/js/memory-test.js.map | 1 - dist-cjs/src/ui/console/js/memory-tools.js | 1270 -------------- dist-cjs/src/ui/console/js/memory-tools.js.map | 1 - dist-cjs/src/ui/console/js/real-time-dashboard.js | 548 ------ .../src/ui/console/js/real-time-dashboard.js.map | 1 - dist-cjs/src/ui/console/js/settings.js | 406 ----- dist-cjs/src/ui/console/js/settings.js.map | 1 - dist-cjs/src/ui/console/js/swarm-integration.js | 359 ---- .../src/ui/console/js/swarm-integration.js.map | 1 - dist-cjs/src/ui/console/js/swarm-visualizer.js | 661 ------- dist-cjs/src/ui/console/js/swarm-visualizer.js.map | 1 - dist-cjs/src/ui/console/js/terminal-emulator.js | 444 ----- .../src/ui/console/js/terminal-emulator.js.map | 1 - dist-cjs/src/ui/console/js/websocket-client.js | 360 ---- dist-cjs/src/ui/console/js/websocket-client.js.map | 1 - dist-cjs/src/ui/console/js/workflow-designer.js | 1577 ----------------- .../src/ui/console/js/workflow-designer.js.map | 1 - dist-cjs/src/ui/console/test-neural-networks.js | 220 --- .../src/ui/console/test-neural-networks.js.map | 1 - dist-cjs/src/ui/hive-dashboard.js | 240 --- dist-cjs/src/ui/hive-dashboard.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedProcessUI.js | 1775 ------------------- dist-cjs/src/ui/web-ui/EnhancedProcessUI.js.map | 1 - dist-cjs/src/ui/web-ui/EnhancedWebUI.js | 420 ----- dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map | 1 - .../src/ui/web-ui/components/ComponentLibrary.js | 872 ---------- .../ui/web-ui/components/ComponentLibrary.js.map | 1 - dist-cjs/src/ui/web-ui/core/EventBus.js | 359 ---- dist-cjs/src/ui/web-ui/core/EventBus.js.map | 1 - dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js | 948 ---------- .../src/ui/web-ui/core/MCPIntegrationLayer.js.map | 1 - dist-cjs/src/ui/web-ui/core/StateManager.js | 356 ---- dist-cjs/src/ui/web-ui/core/StateManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/UIManager.js | 419 ----- dist-cjs/src/ui/web-ui/core/UIManager.js.map | 1 - dist-cjs/src/ui/web-ui/core/ViewManager.js | 449 ----- dist-cjs/src/ui/web-ui/core/ViewManager.js.map | 1 - dist-cjs/src/ui/web-ui/index.js | 242 --- dist-cjs/src/ui/web-ui/index.js.map | 1 - dist-cjs/src/ui/web-ui/neural-panel-test.js | 326 ---- dist-cjs/src/ui/web-ui/neural-panel-test.js.map | 1 - dist-cjs/src/ui/web-ui/test-github-view.js | 64 - dist-cjs/src/ui/web-ui/test-github-view.js.map | 1 - dist-cjs/src/ui/web-ui/views/DAAView.js | 1593 ----------------- dist-cjs/src/ui/web-ui/views/DAAView.js.map | 1 - .../src/ui/web-ui/views/GitHubIntegrationTest.js | 182 -- .../ui/web-ui/views/GitHubIntegrationTest.js.map | 1 - .../src/ui/web-ui/views/GitHubIntegrationView.js | 1356 --------------- .../ui/web-ui/views/GitHubIntegrationView.js.map | 1 - dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js | 795 --------- .../src/ui/web-ui/views/NeuralNetworkView.js.map | 1 - .../src/ui/web-ui/views/WorkflowAutomationView.js | 1346 --------------- .../ui/web-ui/views/WorkflowAutomationView.js.map | 1 - dist-cjs/src/utils/metrics-reader.js | 70 +- dist-cjs/src/utils/metrics-reader.js.map | 2 +- package.json | 4 +- src/ui/console/README-analysis-tools.md | 389 ----- src/ui/console/README.md | 256 --- src/ui/console/WORKFLOW_DESIGNER_README.md | 603 ------- src/ui/console/analysis-tools.html | 316 ---- src/ui/console/analytics.html | 376 ---- src/ui/console/index.html | 258 --- src/ui/console/js/analysis-tools.js | 1054 ------------ src/ui/console/js/command-handler.js | 853 --------- src/ui/console/js/console.js | 669 -------- src/ui/console/js/daa-tools.js | 1035 ----------- src/ui/console/js/memory-interface.js | 961 ----------- src/ui/console/js/memory-test.js | 247 --- src/ui/console/js/memory-tools.js | 1512 ---------------- src/ui/console/js/real-time-dashboard.js | 715 -------- src/ui/console/js/settings.js | 592 ------- src/ui/console/js/swarm-integration.js | 485 ------ src/ui/console/js/swarm-visualizer.js | 879 ---------- src/ui/console/js/terminal-emulator.js | 683 -------- src/ui/console/js/websocket-client.js | 480 ------ src/ui/console/js/workflow-designer.js | 1400 --------------- src/ui/console/neural-networks-demo.md | 252 --- src/ui/console/styles/analysis-tools.css | 938 ---------- src/ui/console/styles/console.css | 620 ------- src/ui/console/styles/daa-tools.css | 601 ------- src/ui/console/styles/responsive.css | 468 ----- src/ui/console/styles/settings.css | 433 ----- src/ui/console/styles/swarm-visualizer.css | 487 ------ src/ui/console/styles/workflow-designer.css | 1095 ------------ src/ui/console/test-neural-networks.js | 314 ---- src/ui/console/test-neural.html | 220 --- src/ui/console/workflow-designer-demo.html | 530 ------ src/ui/hive-dashboard.ts | 395 ----- src/ui/web-ui/EnhancedProcessUI.js | 1772 ------------------- src/ui/web-ui/EnhancedWebUI.js | 566 ------ src/ui/web-ui/README.md | 308 ---- src/ui/web-ui/components/ComponentLibrary.js | 1054 ------------ src/ui/web-ui/core/EventBus.js | 514 ------ src/ui/web-ui/core/MCPIntegrationLayer.js | 715 -------- src/ui/web-ui/core/StateManager.js | 515 ------ src/ui/web-ui/core/UIManager.js | 540 ------ src/ui/web-ui/core/ViewManager.js | 617 ------- src/ui/web-ui/index.js | 292 ---- src/ui/web-ui/neural-panel-test.js | 463 ----- src/ui/web-ui/test-github-view.js | 83 - src/ui/web-ui/test-neural-panel.html | 228 --- src/ui/web-ui/views/DAAView.js | 1809 -------------------- src/ui/web-ui/views/GitHubIntegrationTest.js | 197 --- src/ui/web-ui/views/GitHubIntegrationView.js | 1532 ----------------- src/ui/web-ui/views/NeuralNetworkView.js | 919 ---------- src/ui/web-ui/views/WorkflowAutomationView.js | 1515 ---------------- 131 files changed, 493 insertions(+), 55474 deletions(-) "} diff --git a/.claude/checkpoints/summary-session-20250926-175950.md b/.claude/checkpoints/summary-session-20250926-175950.md new file mode 100644 index 0000000000..6ee518d12a --- /dev/null +++ b/.claude/checkpoints/summary-session-20250926-175950.md @@ -0,0 +1,396 @@ +# Session Summary - 2025-09-26 17:59:50 + +## Checkpoints Created +1758899542.json +1758899543.json +1758899689.json +1758899690.json +1758899920.json +1758899921.json +1758899927.json +1758899929.json +1758899935.json +1758899936.json +1758900019.json +1758900020.json +1758900085.json +1758900087.json +1758900094.json +1758900095.json +1758900254.json +1758900256.json +1758900262.json +1758900264.json +1758900279.json +1758900281.json +1758900322.json +1758900324.json +1758900339.json +1758900340.json +1758900477.json +1758900479.json +1758900652.json +1758900653.json +1758900668.json +1758900670.json +1758900676.json +1758900677.json +1758901378.json +1758901379.json +1758901397.json +1758901398.json +1758906498.json +1758906500.json +1758906541.json +1758906542.json +1758906566.json +1758906568.json +1758906576.json +1758906577.json +1758906592.json +1758906594.json +1758906672.json +1758906673.json +1758907923.json +1758907924.json +1758907948.json +1758907949.json +1758907963.json +1758907965.json +1758908014.json +1758908015.json +1758908060.json +1758908062.json +1758908110.json +1758908112.json +1758908164.json +1758908166.json +1758908191.json +1758908192.json +1758908244.json +1758908246.json +1758908298.json +1758908300.json +1758908507.json +1758908508.json +1758908542.json +1758908543.json +1758908614.json +1758908650.json +1758908688.json +1758908690.json +1758908711.json +1758908713.json +1758908734.json +1758908735.json +1758908976.json +1758908978.json +1758909003.json +1758909004.json +1758909040.json +1758909042.json +1758909059.json +1758909061.json +1758909079.json +1758909080.json +1758909460.json +1758909461.json +task-1758897441.json +task-1758897633.json +task-1758897700.json +task-1758897778.json +task-1758897849.json +task-1758898177.json +task-1758898262.json +task-1758898292.json +task-1758898768.json +task-1758898901.json +task-1758899153.json +task-1758899343.json +task-1758899432.json +task-1758899657.json +task-1758900179.json +task-1758900466.json +task-1758900887.json +task-1758901024.json +task-1758901161.json +task-1758901317.json +task-1758901716.json +task-1758905291.json +task-1758906389.json +task-1758906470.json +task-1758907797.json +task-1758908385.json +task-1758908593.json +task-1758908830.json +task-1758909193.json +task-1758909345.json + +## Files Modified +.claude-flow/metrics/performance.json +.claude-flow/metrics/system-metrics.json +.claude-flow/metrics/task-metrics.json +.claude/agents/MIGRATION_SUMMARY.md +.claude/agents/README.md +.claude/agents/consensus/README.md +.claude/agents/core/coder.md +.claude/agents/core/planner.md +.claude/agents/core/researcher.md +.claude/agents/core/reviewer.md +.claude/agents/core/tester.md +.claude/agents/hive-mind/collective-intelligence-coordinator.md +.claude/agents/hive-mind/queen-coordinator.md +.claude/agents/hive-mind/scout-explorer.md +.claude/agents/hive-mind/swarm-memory-manager.md +.claude/agents/hive-mind/worker-specialist.md +.claude/agents/optimization/README.md +.claude/agents/swarm/README.md +.claude/agents/swarm/hierarchical-coordinator.md +.claude/agents/templates/coordinator-swarm-init.md +.claude/checkpoints/1758906498.json +.claude/checkpoints/1758906500.json +.claude/checkpoints/1758906541.json +.claude/checkpoints/1758906542.json +.claude/checkpoints/1758906566.json +.claude/checkpoints/1758906568.json +.claude/checkpoints/1758906576.json +.claude/checkpoints/1758906577.json +.claude/checkpoints/1758906592.json +.claude/checkpoints/1758906594.json +.claude/checkpoints/1758906672.json +.claude/checkpoints/1758906673.json +.claude/checkpoints/1758907923.json +.claude/checkpoints/1758907924.json +.claude/checkpoints/1758907948.json +.claude/checkpoints/1758907949.json +.claude/checkpoints/1758907963.json +.claude/checkpoints/1758907965.json +.claude/checkpoints/1758908014.json +.claude/checkpoints/1758908015.json +.claude/checkpoints/1758908060.json +.claude/checkpoints/1758908062.json +.claude/checkpoints/1758908110.json +.claude/checkpoints/1758908112.json +.claude/checkpoints/1758908164.json +.claude/checkpoints/1758908166.json +.claude/checkpoints/1758908191.json +.claude/checkpoints/1758908192.json +.claude/checkpoints/1758908244.json +.claude/checkpoints/1758908246.json +.claude/checkpoints/1758908298.json +.claude/checkpoints/1758908300.json +.claude/checkpoints/1758908507.json +.claude/checkpoints/1758908508.json +.claude/checkpoints/1758908542.json +.claude/checkpoints/1758908543.json +.claude/checkpoints/1758908614.json +.claude/checkpoints/1758908650.json +.claude/checkpoints/1758908688.json +.claude/checkpoints/1758908690.json +.claude/checkpoints/1758908711.json +.claude/checkpoints/1758908713.json +.claude/checkpoints/1758908734.json +.claude/checkpoints/1758908735.json +.claude/checkpoints/1758908976.json +.claude/checkpoints/1758908978.json +.claude/checkpoints/1758909003.json +.claude/checkpoints/1758909004.json +.claude/checkpoints/1758909040.json +.claude/checkpoints/1758909042.json +.claude/checkpoints/1758909059.json +.claude/checkpoints/1758909061.json +.claude/checkpoints/1758909079.json +.claude/checkpoints/1758909080.json +.claude/checkpoints/summary-session-20250926-170658.md +.claude/checkpoints/summary-session-20250926-171226.md +.claude/checkpoints/summary-session-20250926-173942.md +.claude/checkpoints/summary-session-20250926-174627.md +.claude/checkpoints/summary-session-20250926-175225.md +.claude/checkpoints/summary-session-20250926-175458.md +.claude/checkpoints/task-1758906389.json +.claude/checkpoints/task-1758906470.json +.claude/checkpoints/task-1758907797.json +.claude/checkpoints/task-1758908385.json +.claude/checkpoints/task-1758908593.json +.claude/checkpoints/task-1758908830.json +.claude/checkpoints/task-1758909193.json +.claude/checkpoints/task-1758909345.json +.claude/commands/agents/README.md +.claude/commands/agents/agent-spawning.md +.claude/commands/analysis/README.md +.claude/commands/automation/README.md +.claude/commands/automation/smart-spawn.md +.claude/commands/coordination/README.md +.claude/commands/coordination/task-orchestrate.md +.claude/commands/github/README.md +.claude/commands/hive-mind/README.md +.claude/commands/hive-mind/hive-mind-spawn.md +.claude/commands/hooks/README.md +.claude/commands/hooks/overview.md +.claude/commands/memory/README.md +.claude/commands/memory/memory-usage.md +.claude/commands/monitoring/README.md +.claude/commands/optimization/README.md +.claude/commands/pair/README.md +.claude/commands/swarm/README.md +.claude/commands/training/README.md +.claude/commands/workflows/README.md +.gitignore +CLAUDE.md +claude-flow-wiki +dist-cjs/src/cli/simple-cli.js +dist-cjs/src/cli/simple-cli.js.map +dist-cjs/src/cli/simple-commands/hive-mind.js +dist-cjs/src/cli/simple-commands/hive-mind.js.map +dist-cjs/src/cli/simple-commands/inject-memory-protocol.js +dist-cjs/src/cli/simple-commands/inject-memory-protocol.js.map +dist-cjs/src/cli/simple-commands/swarm.js +dist-cjs/src/cli/simple-commands/swarm.js.map +dist-cjs/src/ui/console/js/analysis-tools.js +dist-cjs/src/ui/console/js/analysis-tools.js.map +dist-cjs/src/ui/console/js/command-handler.js +dist-cjs/src/ui/console/js/command-handler.js.map +dist-cjs/src/ui/console/js/console.js +dist-cjs/src/ui/console/js/console.js.map +dist-cjs/src/ui/console/js/daa-tools.js +dist-cjs/src/ui/console/js/daa-tools.js.map +dist-cjs/src/ui/console/js/memory-interface.js +dist-cjs/src/ui/console/js/memory-interface.js.map +dist-cjs/src/ui/console/js/memory-test.js +dist-cjs/src/ui/console/js/memory-test.js.map +dist-cjs/src/ui/console/js/memory-tools.js +dist-cjs/src/ui/console/js/memory-tools.js.map +dist-cjs/src/ui/console/js/real-time-dashboard.js +dist-cjs/src/ui/console/js/real-time-dashboard.js.map +dist-cjs/src/ui/console/js/settings.js +dist-cjs/src/ui/console/js/settings.js.map +dist-cjs/src/ui/console/js/swarm-integration.js +dist-cjs/src/ui/console/js/swarm-integration.js.map +dist-cjs/src/ui/console/js/swarm-visualizer.js +dist-cjs/src/ui/console/js/swarm-visualizer.js.map +dist-cjs/src/ui/console/js/terminal-emulator.js +dist-cjs/src/ui/console/js/terminal-emulator.js.map +dist-cjs/src/ui/console/js/websocket-client.js +dist-cjs/src/ui/console/js/websocket-client.js.map +dist-cjs/src/ui/console/js/workflow-designer.js +dist-cjs/src/ui/console/js/workflow-designer.js.map +dist-cjs/src/ui/console/test-neural-networks.js +dist-cjs/src/ui/console/test-neural-networks.js.map +dist-cjs/src/ui/hive-dashboard.js +dist-cjs/src/ui/hive-dashboard.js.map +dist-cjs/src/ui/web-ui/EnhancedProcessUI.js +dist-cjs/src/ui/web-ui/EnhancedProcessUI.js.map +dist-cjs/src/ui/web-ui/EnhancedWebUI.js +dist-cjs/src/ui/web-ui/EnhancedWebUI.js.map +dist-cjs/src/ui/web-ui/components/ComponentLibrary.js +dist-cjs/src/ui/web-ui/components/ComponentLibrary.js.map +dist-cjs/src/ui/web-ui/core/EventBus.js +dist-cjs/src/ui/web-ui/core/EventBus.js.map +dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js +dist-cjs/src/ui/web-ui/core/MCPIntegrationLayer.js.map +dist-cjs/src/ui/web-ui/core/StateManager.js +dist-cjs/src/ui/web-ui/core/StateManager.js.map +dist-cjs/src/ui/web-ui/core/UIManager.js +dist-cjs/src/ui/web-ui/core/UIManager.js.map +dist-cjs/src/ui/web-ui/core/ViewManager.js +dist-cjs/src/ui/web-ui/core/ViewManager.js.map +dist-cjs/src/ui/web-ui/index.js +dist-cjs/src/ui/web-ui/index.js.map +dist-cjs/src/ui/web-ui/neural-panel-test.js +dist-cjs/src/ui/web-ui/neural-panel-test.js.map +dist-cjs/src/ui/web-ui/test-github-view.js +dist-cjs/src/ui/web-ui/test-github-view.js.map +dist-cjs/src/ui/web-ui/views/DAAView.js +dist-cjs/src/ui/web-ui/views/DAAView.js.map +dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js +dist-cjs/src/ui/web-ui/views/GitHubIntegrationTest.js.map +dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js +dist-cjs/src/ui/web-ui/views/GitHubIntegrationView.js.map +dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js +dist-cjs/src/ui/web-ui/views/NeuralNetworkView.js.map +dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js +dist-cjs/src/ui/web-ui/views/WorkflowAutomationView.js.map +dist-cjs/src/utils/metrics-reader.js +examples/memory-coordination-example.md +package.json +src/cli/simple-commands/hive-mind.js +src/cli/simple-commands/inject-memory-protocol.js +src/cli/simple-commands/swarm.js +src/ui/console/README-analysis-tools.md +src/ui/console/README.md +src/ui/console/WORKFLOW_DESIGNER_README.md +src/ui/console/analysis-tools.html +src/ui/console/analytics.html +src/ui/console/index.html +src/ui/console/js/analysis-tools.js +src/ui/console/js/command-handler.js +src/ui/console/js/console.js +src/ui/console/js/daa-tools.js +src/ui/console/js/memory-interface.js +src/ui/console/js/memory-test.js +src/ui/console/js/memory-tools.js +src/ui/console/js/real-time-dashboard.js +src/ui/console/js/settings.js +src/ui/console/js/swarm-integration.js +src/ui/console/js/swarm-visualizer.js +src/ui/console/js/terminal-emulator.js +src/ui/console/js/websocket-client.js +src/ui/console/js/workflow-designer.js +src/ui/console/neural-networks-demo.md +src/ui/console/styles/analysis-tools.css +src/ui/console/styles/console.css +src/ui/console/styles/daa-tools.css +src/ui/console/styles/responsive.css +src/ui/console/styles/settings.css +src/ui/console/styles/swarm-visualizer.css +src/ui/console/styles/workflow-designer.css +src/ui/console/test-neural-networks.js +src/ui/console/test-neural.html +src/ui/console/workflow-designer-demo.html +src/ui/hive-dashboard.ts +src/ui/web-ui/EnhancedProcessUI.js +src/ui/web-ui/EnhancedWebUI.js +src/ui/web-ui/README.md +src/ui/web-ui/components/ComponentLibrary.js +src/ui/web-ui/core/EventBus.js +src/ui/web-ui/core/MCPIntegrationLayer.js +src/ui/web-ui/core/StateManager.js +src/ui/web-ui/core/UIManager.js +src/ui/web-ui/core/ViewManager.js +src/ui/web-ui/index.js +src/ui/web-ui/neural-panel-test.js +src/ui/web-ui/test-github-view.js +src/ui/web-ui/test-neural-panel.html +src/ui/web-ui/views/DAAView.js +src/ui/web-ui/views/GitHubIntegrationTest.js +src/ui/web-ui/views/GitHubIntegrationView.js +src/ui/web-ui/views/NeuralNetworkView.js +src/ui/web-ui/views/WorkflowAutomationView.js + +## Recent Commits +a4bae50e2 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/package.json +adfebf94a ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/reviewer.md +a218853e0 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/planner.md +07d35ca83 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/researcher.md +4e9d15391 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/tester.md +1bce8f7a8 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/agents/core/coder.md +a52ca8e54 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/hooks/overview.md +18db98ab2 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/hooks/overview.md +cd341c287 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/automation/smart-spawn.md +40624db73 ๐Ÿ”– Checkpoint: Edit /workspaces/claude-code-flow/.claude/commands/agents/agent-spawning.md + +## GitHub Releases Created +No GitHub releases + +## Rollback Instructions +To rollback to a specific checkpoint: +```bash +# List all checkpoints +git tag -l checkpoint-* | sort -r + +# List GitHub releases +gh release list + +# Rollback to a checkpoint +git checkout checkpoint-YYYYMMDD-HHMMSS +``` diff --git a/dist-cjs/src/cli/simple-cli.js b/dist-cjs/src/cli/simple-cli.js index af5a4c0edd..907e98d52a 100644 --- a/dist-cjs/src/cli/simple-cli.js +++ b/dist-cjs/src/cli/simple-cli.js @@ -1,47 +1,13 @@ -#!/usr/bin/env node +#!/usr/bin/env -S deno run --allow-all +import { promises as fs } from 'node:fs'; import { executeCommand, hasCommand, showCommandHelp, listCommands } from './command-registry.js'; import { parseFlags } from './utils.js'; -import { args, cwd, isMainModule, exit, readTextFile, writeTextFile, mkdirAsync, errors } from './node-compat.js'; -import { spawn } from 'child_process'; -import process from 'process'; -import readline from 'readline'; -import { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js'; import { VERSION } from '../core/version.js'; -const LEGACY_AGENT_MAPPING = { - analyst: 'code-analyzer', - coordinator: 'task-orchestrator', - optimizer: 'perf-analyzer', - documenter: 'api-docs', - monitor: 'performance-benchmarker', - specialist: 'system-architect', - architect: 'system-architect' -}; -function resolveLegacyAgentType(legacyType) { - return LEGACY_AGENT_MAPPING[legacyType] || legacyType; -} -function printHelp(plain = false) { - console.log(getMainHelp(plain)); -} -function printCommandHelp(command) { - const standardCommands = [ - 'agent', - 'sparc', - 'memory' - ]; - if (standardCommands.includes(command)) { - const help = getStandardizedCommandHelp(command); - console.log(help); - } else { - const help = getCommandHelp(command); - console.log(help); - } -} -function printLegacyHelp() { +function printHelp() { console.log(` ๐ŸŒŠ Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform -๐ŸŽฏ ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure -โšก ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines +๐ŸŽฏ ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure USAGE: claude-flow [options] @@ -175,8 +141,8 @@ function printSuccess(message) { function printWarning(message) { console.warn(`โš ๏ธ Warning: ${message}`); } -function showHelpWithCommands(plain = false) { - printHelp(plain); +function showHelpWithCommands() { + printHelp(); console.log('\nRegistered Commands:'); const commands = listCommands(); for (const command of commands){ @@ -185,58 +151,14 @@ function showHelpWithCommands(plain = false) { console.log('\nUse "claude-flow help " for detailed usage information'); } async function main() { + const args = Deno.args; if (args.length === 0) { - printHelp(usePlainHelp); + printHelp(); return; } const command = args[0]; const { flags, args: parsedArgs } = parseFlags(args.slice(1)); - const usePlainHelp = args.includes('--plain'); - let enhancedFlags = flags; - try { - const { detectExecutionEnvironment, applySmartDefaults } = await import('./utils/environment-detector.js'); - enhancedFlags = applySmartDefaults(flags); - enhancedFlags._environment = detectExecutionEnvironment({ - skipWarnings: true - }); - } catch (e) { - enhancedFlags = flags; - } - if (command !== 'help' && command !== '--help' && command !== '-h' && (enhancedFlags.help || enhancedFlags.h)) { - const detailedHelp = getCommandHelp(command); - if (detailedHelp && !detailedHelp.includes('Help not available')) { - printCommandHelp(command); - } else if (hasCommand(command)) { - showCommandHelp(command); - } else { - printError(`Unknown command: ${command}`); - console.log('\nRun "claude-flow --help" to see available commands.'); - } - return; - } switch(command){ - case 'env-check': - case 'environment': - if (enhancedFlags._environment) { - const env = enhancedFlags._environment; - console.log(`\n๐Ÿ–ฅ๏ธ Environment Detection Results:`); - console.log(` Terminal: ${env.terminalType}`); - console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`); - console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`); - console.log(` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`); - if (env.recommendedFlags.length > 0) { - console.log(`\n๐Ÿ’ก Recommended flags:`); - console.log(` ${env.recommendedFlags.join(' ')}`); - } - if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) { - console.log(`\nโœ… Auto-applied:`); - console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`); - } - console.log(); - } else { - console.log('Environment detection not available'); - } - return; case 'version': case '--version': case '-v': @@ -246,14 +168,9 @@ async function main() { case '--help': case '-h': if (parsedArgs.length > 0) { - const detailedHelp = getCommandHelp(parsedArgs[0]); - if (detailedHelp && !detailedHelp.includes('Help not available')) { - printCommandHelp(parsedArgs[0]); - } else { - showCommandHelp(parsedArgs[0]); - } + showCommandHelp(parsedArgs[0]); } else { - printHelp(usePlainHelp); + showHelpWithCommands(); } return; } @@ -263,7 +180,6 @@ async function main() { return; } catch (err) { printError(err.message); - console.log(`\nRun "claude-flow ${command} --help" for usage information.`); return; } } @@ -283,12 +199,11 @@ async function main() { console.log('๐Ÿ“Š Real-time monitoring would display here'); break; case 'spawn': - const rawSpawnType = subArgs[0] || 'general'; - const spawnType = resolveLegacyAgentType(rawSpawnType); + const spawnType = subArgs[0] || 'general'; const spawnName = flags.name || `agent-${Date.now()}`; printSuccess(`Spawning ${spawnType} agent: ${spawnName}`); console.log('๐Ÿค– Agent would be created with the following configuration:'); - console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`); + console.log(` Type: ${spawnType}`); console.log(` Name: ${spawnName}`); console.log(' Capabilities: Research, Analysis, Code Generation'); console.log(' Status: Ready'); @@ -313,7 +228,7 @@ async function main() { console.log(' โ€ข Max Pool Size: 10'); console.log(' โ€ข Idle Timeout: 5 minutes'); console.log(' โ€ข Shell: /bin/bash'); - console.log(' โ€ข Working Directory: ' + cwd()); + console.log(' โ€ข Working Directory: ' + process.cwd()); console.log(' Performance:'); console.log(' โ€ข Average Response Time: N/A'); console.log(' โ€ข Terminal Creation Time: N/A'); @@ -362,7 +277,7 @@ async function main() { const terminalConfig = { name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(), shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash', - workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(), + workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(), env: envIndex >= 0 ? subArgs[envIndex + 1] : '', persistent: persistentIndex >= 0 }; @@ -1319,9 +1234,10 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all console.log('Debug - Executing command:'); console.log(`claude ${claudeArgs.map((arg)=>arg.includes(' ') || arg.includes('\n') ? `"${arg}"` : arg).join(' ')}`); } - const child = spawn('claude', claudeArgs, { + const command = new Deno.Command('claude', { + args: claudeArgs, env: { - ...process.env, + ...Deno.env.toObject(), CLAUDE_INSTANCE_ID: instanceId, CLAUDE_FLOW_MODE: flags1.mode || 'full', CLAUDE_FLOW_COVERAGE: (flags1.coverage || 80).toString(), @@ -1331,18 +1247,17 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all CLAUDE_FLOW_COORDINATION_ENABLED: flags1.parallel ? 'true' : 'false', CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm' }, - stdio: 'inherit' - }); - await new Promise((resolve)=>{ - child.on('exit', (code)=>{ - if (code === 0) { - printSuccess(`Claude instance ${instanceId} completed successfully`); - } else { - printError(`Claude instance ${instanceId} exited with code ${code}`); - } - resolve(); - }); + stdin: 'inherit', + stdout: 'inherit', + stderr: 'inherit' }); + const child = command.spawn(); + const status = await child.status; + if (status.success) { + printSuccess(`Claude instance ${instanceId} completed successfully`); + } else { + printError(`Claude instance ${instanceId} exited with code ${status.code}`); + } } catch (err) { printError(`Failed to spawn Claude: ${err.message}`); console.log('Make sure you have the Claude CLI installed.'); @@ -1895,7 +1810,7 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all console.log('\nDid you mean:'); suggestions.forEach((cmd)=>console.log(` claude-flow ${cmd}`)); } - exit(1); + process.exit(1); } } async function startRepl() { @@ -1973,7 +1888,7 @@ Shortcuts: }, config: async (key)=>{ try { - const config = JSON.parse(await readTextFile('claude-flow.config.json')); + const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8')); if (key) { const keys = key.split('.'); let value = config; @@ -2001,25 +1916,21 @@ Shortcuts: if (trimmed.startsWith('!')) { const shellCmd = trimmed.substring(1); try { - await new Promise((resolve)=>{ - const proc = spawn('sh', [ + const command = new Deno.Command('sh', { + args: [ '-c', shellCmd - ], { - stdio: [ - 'inherit', - 'pipe', - 'pipe' - ] - }); - proc.stdout.on('data', (data)=>{ - console.log(data.toString()); - }); - proc.stderr.on('data', (data)=>{ - console.error(data.toString()); - }); - proc.on('exit', resolve); + ], + stdout: 'piped', + stderr: 'piped' }); + const { stdout, stderr } = await command.output(); + if (stdout.length > 0) { + console.log(new TextDecoder().decode(stdout)); + } + if (stderr.length > 0) { + console.error(new TextDecoder().decode(stderr)); + } } catch (err) { console.error(`Shell error: ${err.message}`); } @@ -2039,7 +1950,7 @@ Shortcuts: const parts = trimmed.split(' '); const command = parts[0]; const args = parts.slice(1); - if (replCommands[command]) { + if (command in replCommands) { await replCommands[command](...args); return true; } @@ -2060,8 +1971,7 @@ Shortcuts: const subCmd = args[0]; switch(subCmd){ case 'spawn': - const rawType = args[1] || 'researcher'; - const type = resolveLegacyAgentType(rawType); + const type = args[1] || 'researcher'; const name = args[2] || `agent-${Date.now()}`; const agent = { id: `agent-${Date.now()}`, @@ -2266,33 +2176,18 @@ Shortcuts: console.log('Terminal commands: create, list, exec, attach, detach'); } } - const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - function updatePrompt() { - rl.setPrompt(replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> '); - } - updatePrompt(); - rl.prompt(); - rl.on('line', async (input)=>{ - input = input.trim(); + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + while(true){ + const prompt = replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> '; + await Deno.stdout.write(encoder.encode(prompt)); + const buf = new Uint8Array(1024); + const n = await Deno.stdin.read(buf); + if (n === null) break; + const input = decoder.decode(buf.subarray(0, n)).trim(); const shouldContinue = await processReplCommand(input); - if (!shouldContinue) { - rl.close(); - } else { - updatePrompt(); - rl.prompt(); - } - }); - rl.on('SIGINT', ()=>{ - console.log('\nExiting Claude-Flow...'); - rl.close(); - process.exit(0); - }); - return new Promise((resolve)=>{ - rl.on('close', resolve); - }); + if (!shouldContinue) break; + } } function createMinimalClaudeMd() { return `# Claude Code Integration @@ -2609,30 +2504,30 @@ async function createSparcStructureManually() { ]; for (const dir of rooDirectories){ try { - await mkdirAsync(dir, { + await Deno.mkdir(dir, { recursive: true }); console.log(` โœ“ Created ${dir}/`); } catch (err) { - if (!(err instanceof errors.AlreadyExists)) { + if (!(err instanceof Deno.errors.AlreadyExists)) { throw err; } } } let roomodesContent; try { - roomodesContent = await readTextFile('.roomodes'); + roomodesContent = await fs.readFile('.roomodes'); console.log(' โœ“ Using existing .roomodes configuration'); } catch { roomodesContent = createBasicRoomodesConfig(); - await writeTextFile('.roomodes', roomodesContent); + await fs.writeFile('.roomodes', roomodesContent); console.log(' โœ“ Created .roomodes configuration'); } const basicWorkflow = createBasicSparcWorkflow(); - await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow); + await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow); console.log(' โœ“ Created .roo/workflows/basic-tdd.json'); const rooReadme = createRooReadme(); - await writeTextFile('.roo/README.md', rooReadme); + await fs.writeFile('.roo/README.md', rooReadme); console.log(' โœ“ Created .roo/README.md'); console.log(' โœ… Basic SPARC structure created successfully'); } catch (err) { @@ -3060,6 +2955,134 @@ This SPARC-enabled project follows a systematic development approach: - Document architectural decisions in memory for future reference - Regular security reviews for any authentication or data handling code +For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md +`; +} +if (import.meta.url === `file://${process.argv[1]}`) { + await main(); +} + +//# sourceMappingURL=simple-cli.js.mapsign choices" + +# Store test results and coverage +npx claude-flow memory store test_coverage "Authentication module: 95% coverage, all tests passing" + +# Query previous work +npx claude-flow memory query auth_implementation + +# Export project memory +npx claude-flow memory export project_backup.json +\`\`\` + +### Memory Namespaces +- **\`spec\`**: Requirements and specifications +- **\`arch\`**: Architecture and design decisions +- **\`impl\`**: Implementation notes and code patterns +- **\`test\`**: Test results and coverage reports +- **\`debug\`**: Bug reports and resolution notes + +## Workflow Examples + +### Feature Development Workflow +\`\`\`bash +# 1. Start with specification +npx claude-flow sparc run spec-pseudocode "User profile management feature" + +# 2. Design architecture +npx claude-flow sparc run architect "Profile service architecture with data validation" + +# 3. Implement with TDD +npx claude-flow sparc tdd "user profile CRUD operations" + +# 4. Security review +npx claude-flow sparc run security-review "profile data access and validation" + +# 5. Integration testing +npx claude-flow sparc run integration "profile service with authentication system" + +# 6. Documentation +npx claude-flow sparc run docs-writer "profile service API documentation" +\`\`\` + +### Bug Fix Workflow +\`\`\`bash +# 1. Debug and analyze +npx claude-flow sparc run debug "authentication token expiration issue" + +# 2. Write regression tests +npx claude-flow sparc run tdd "token refresh mechanism tests" + +# 3. Implement fix +npx claude-flow sparc run code "fix token refresh in authentication service" + +# 4. Security review +npx claude-flow sparc run security-review "token handling security implications" +\`\`\` + +## Configuration Files + +### SPARC Configuration +- **\`.roomodes\`**: SPARC mode definitions and configurations +- **\`.roo/\`**: Templates, workflows, and mode-specific rules + +### Claude-Flow Configuration +- **\`memory/\`**: Persistent memory and session data +- **\`coordination/\`**: Multi-agent coordination settings + +## Git Workflow Integration + +### Commit Strategy with SPARC +- **Specification commits**: After completing requirements analysis +- **Architecture commits**: After design phase completion +- **TDD commits**: After each Red-Green-Refactor cycle +- **Integration commits**: After successful component integration +- **Documentation commits**: After completing documentation updates + +### Branch Strategy +- **\`feature/sparc-\`**: Feature development with SPARC methodology +- **\`hotfix/sparc-\`**: Bug fixes using SPARC debugging workflow +- **\`refactor/sparc-\`**: Refactoring using optimization mode + +## Troubleshooting + +### Common SPARC Issues +- **Mode not found**: Check \`.roomodes\` file exists and is valid JSON +- **Memory persistence**: Ensure \`memory/\` directory has write permissions +- **Tool access**: Verify required tools are available for the selected mode +- **Namespace conflicts**: Use unique memory namespaces for different features + +### Debug Commands +\`\`\`bash +# Check SPARC configuration +npx claude-flow sparc modes + +# Verify memory system +npx claude-flow memory stats + +# Check system status +npx claude-flow status + +# View detailed mode information +npx claude-flow sparc info +\`\`\` + +## Project Architecture + +This SPARC-enabled project follows a systematic development approach: +- **Clear separation of concerns** through modular design +- **Test-driven development** ensuring reliability and maintainability +- **Iterative refinement** for continuous improvement +- **Comprehensive documentation** for team collaboration +- **AI-assisted development** through specialized SPARC modes + +## Important Notes + +- Always run tests before committing (\`npm run test\`) +- Use SPARC memory system to maintain context across sessions +- Follow the Red-Green-Refactor cycle during TDD phases +- Document architectural decisions in memory for future reference +- Regular security reviews for any authentication or data handling code + For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md `; } diff --git a/dist-cjs/src/cli/simple-cli.js.map b/dist-cjs/src/cli/simple-cli.js.map index 17942c3906..e28385edbd 100644 --- a/dist-cjs/src/cli/simple-cli.js.map +++ b/dist-cjs/src/cli/simple-cli.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/cli/simple-cli.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport {\n args,\n cwd,\n isMainModule,\n exit,\n readTextFile,\n writeTextFile,\n mkdirAsync,\n errors,\n} from './node-compat.js';\nimport { spawn } from 'child_process';\nimport process from 'process';\nimport readline from 'readline';\nimport { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';\nimport { VERSION } from '../core/version.js';\n\n// Legacy agent type mapping for backward compatibility\nconst LEGACY_AGENT_MAPPING = {\n analyst: 'code-analyzer',\n coordinator: 'task-orchestrator', \n optimizer: 'perf-analyzer',\n documenter: 'api-docs',\n monitor: 'performance-benchmarker',\n specialist: 'system-architect',\n architect: 'system-architect',\n};\n\n// Resolve legacy agent types to current equivalents\nfunction resolveLegacyAgentType(legacyType) {\n return LEGACY_AGENT_MAPPING[legacyType] || legacyType;\n}\n\nfunction printHelp(plain = false) {\n console.log(getMainHelp(plain));\n}\n\nfunction printCommandHelp(command) {\n // Try standardized help first\n const standardCommands = ['agent', 'sparc', 'memory'];\n if (standardCommands.includes(command)) {\n const help = getStandardizedCommandHelp(command);\n console.log(help);\n } else {\n const help = getCommandHelp(command);\n console.log(help);\n }\n}\n\n// Legacy help function for backward compatibility\nfunction printLegacyHelp() {\n console.log(`\n๐ŸŒŠ Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n๐ŸŽฏ ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure\nโšก ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines\n\nUSAGE:\n claude-flow [options]\n\n๐Ÿš€ INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n โ€ข Complete ruv-swarm integration with 27 MCP tools\n โ€ข Neural network processing with WASM optimization\n โ€ข Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n โ€ข Cross-session memory and persistent learning\n โ€ข GitHub workflow automation (6 specialized modes)\n โ€ข Production-ready Docker infrastructure\n โ€ข Enterprise security and compliance features\n\n๐Ÿง  SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n๐Ÿ™ GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n๐Ÿ—๏ธ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn [--name] # Create AI agent with swarm coordination\n agent # Advanced agent management with neural patterns\n sparc # 17 SPARC modes with neural enhancement\n memory # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n๐Ÿค– NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n๐ŸŽฎ ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n \n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n \n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n \n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n \n # Real-time system monitoring\n ./claude-flow status --verbose\n\n๐Ÿข ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n๐Ÿง  NEURAL NETWORK FEATURES (v2.0.0):\n โ€ข WASM-powered cognitive patterns with SIMD optimization\n โ€ข 27 MCP tools for comprehensive workflow automation\n โ€ข Cross-session learning and adaptation\n โ€ข Real-time performance monitoring (sub-10ms response times)\n โ€ข 32.3% token usage reduction through intelligent coordination\n โ€ข Self-healing workflows with automatic error recovery\n\n๐Ÿ“Š ENTERPRISE PERFORMANCE METRICS:\n โ€ข 84.8% SWE-Bench solve rate through coordinated intelligence\n โ€ข 2.8-4.4x speed improvement with parallel execution\n โ€ข 60% Docker build performance improvement\n โ€ข 100% test success rate with comprehensive validation\n โ€ข Sub-10ms MCP response times\n\n๐Ÿ”— INTEGRATION & COMPATIBILITY:\n โ€ข Node.js 20+ optimization for enterprise environments\n โ€ข Complete Claude Code integration with enhanced capabilities\n โ€ข Multi-platform support (Windows, macOS, Linux)\n โ€ข Enterprise security with access control and audit logging\n โ€ข Cross-package synchronization and dependency management\n\nGET DETAILED HELP:\n claude-flow help # Command-specific enterprise documentation\n claude-flow --help # Alternative help syntax\n \n Examples:\n claude-flow help swarm # Swarm intelligence coordination\n claude-flow help github # GitHub workflow automation\n claude-flow help neural # Neural network processing\n claude-flow help enterprise # Enterprise features and compliance\n\nCOMMON OPTIONS:\n --verbose, -v Enable detailed output with performance metrics\n --help Show command help with enterprise features\n --config Use custom enterprise configuration\n --parallel Enable parallel execution (default for swarms)\n --monitor Real-time monitoring and performance tracking\n\n๐Ÿ“š Documentation: https://github.com/ruvnet/claude-code-flow\n๐Ÿ ruv-swarm: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm\n\n๐Ÿš€ Enterprise-Grade AI Agent Orchestration - Built with โค๏ธ by rUv for the Claude community\n`);\n}\n\nfunction printVersion() {\n console.log(`Claude-Flow v${VERSION}`);\n}\n\nfunction printError(message) {\n console.error(`โŒ Error: ${message}`);\n}\n\nfunction printSuccess(message) {\n console.log(`โœ… ${message}`);\n}\n\nfunction printWarning(message) {\n console.warn(`โš ๏ธ Warning: ${message}`);\n}\n\nfunction showHelpWithCommands(plain = false) {\n printHelp(plain);\n console.log('\\nRegistered Commands:');\n const commands = listCommands();\n for (const command of commands) {\n console.log(` ${command.name.padEnd(12)} ${command.description}`);\n }\n console.log('\\nUse \"claude-flow help \" for detailed usage information');\n}\n\nasync function main() {\n // args is imported from node-compat.js\n\n if (args.length === 0) {\n printHelp(usePlainHelp);\n return;\n }\n\n const command = args[0];\n const { flags, args: parsedArgs } = parseFlags(args.slice(1));\n\n // Check for --plain flag for help early\n const usePlainHelp = args.includes('--plain');\n\n // Apply environment-based smart defaults\n let enhancedFlags = flags;\n try {\n const { detectExecutionEnvironment, applySmartDefaults } = await import(\n './utils/environment-detector.js'\n );\n enhancedFlags = applySmartDefaults(flags);\n\n // Store environment info for commands that need it\n enhancedFlags._environment = detectExecutionEnvironment({ skipWarnings: true });\n } catch (e) {\n // If environment detector fails, continue with original flags\n enhancedFlags = flags;\n }\n\n // Check if user is asking for help on a specific command\n if (\n command !== 'help' &&\n command !== '--help' &&\n command !== '-h' &&\n (enhancedFlags.help || enhancedFlags.h)\n ) {\n const detailedHelp = getCommandHelp(command);\n if (detailedHelp && !detailedHelp.includes('Help not available')) {\n printCommandHelp(command);\n } else if (hasCommand(command)) {\n showCommandHelp(command);\n } else {\n printError(`Unknown command: ${command}`);\n console.log('\\nRun \"claude-flow --help\" to see available commands.');\n }\n return;\n }\n\n // Handle special commands first\n switch (command) {\n case 'env-check':\n case 'environment':\n if (enhancedFlags._environment) {\n const env = enhancedFlags._environment;\n console.log(`\\n๐Ÿ–ฅ๏ธ Environment Detection Results:`);\n console.log(` Terminal: ${env.terminalType}`);\n console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);\n console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);\n console.log(\n ` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`,\n );\n if (env.recommendedFlags.length > 0) {\n console.log(`\\n๐Ÿ’ก Recommended flags:`);\n console.log(` ${env.recommendedFlags.join(' ')}`);\n }\n if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {\n console.log(`\\nโœ… Auto-applied:`);\n console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);\n }\n console.log();\n } else {\n console.log('Environment detection not available');\n }\n return;\n case 'version':\n case '--version':\n case '-v':\n printVersion();\n return;\n\n case 'help':\n case '--help':\n case '-h':\n if (parsedArgs.length > 0) {\n // Try our detailed help first\n const detailedHelp = getCommandHelp(parsedArgs[0]);\n if (detailedHelp && !detailedHelp.includes('Help not available')) {\n printCommandHelp(parsedArgs[0]);\n } else {\n // Fall back to command registry help\n showCommandHelp(parsedArgs[0]);\n }\n } else {\n printHelp(usePlainHelp);\n }\n return;\n }\n\n // Check if this is a registered modular command\n if (hasCommand(command)) {\n try {\n await executeCommand(command, parsedArgs, flags);\n return;\n } catch (err) {\n printError(err.message);\n console.log(`\\nRun \"claude-flow ${command} --help\" for usage information.`);\n return;\n }\n }\n\n // Legacy command handling (to be refactored)\n const subArgs = parsedArgs; // Use parsed args for legacy commands\n\n switch (command) {\n case 'status':\n printSuccess('Claude-Flow System Status:');\n console.log('๐ŸŸก Status: Not Running (orchestrator not started)');\n console.log('๐Ÿค– Agents: 0 active');\n console.log('๐Ÿ“‹ Tasks: 0 in queue');\n console.log('๐Ÿ’พ Memory: Ready');\n console.log('๐Ÿ–ฅ๏ธ Terminal Pool: Ready');\n console.log('๐ŸŒ MCP Server: Stopped');\n break;\n\n case 'monitor':\n printSuccess('Starting system monitor...');\n console.log('๐Ÿ“Š Real-time monitoring would display here');\n break;\n\n case 'spawn':\n // Convenience alias for agent spawn\n const rawSpawnType = subArgs[0] || 'general';\n const spawnType = resolveLegacyAgentType(rawSpawnType);\n const spawnName = flags.name || `agent-${Date.now()}`;\n\n printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);\n console.log('๐Ÿค– Agent would be created with the following configuration:');\n console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);\n console.log(` Name: ${spawnName}`);\n console.log(' Capabilities: Research, Analysis, Code Generation');\n console.log(' Status: Ready');\n console.log('\\n๐Ÿ“‹ Note: Full agent spawning requires orchestrator to be running');\n break;\n\n case 'terminal':\n const terminalCmd = subArgs[0];\n switch (terminalCmd) {\n case 'pool':\n const poolCmd = subArgs[1];\n const detailed = subArgs.includes('--detailed') || subArgs.includes('-d');\n\n if (poolCmd === 'status') {\n printSuccess('Terminal Pool Status:');\n console.log('๐Ÿ–ฅ๏ธ Status: Ready');\n console.log('๐Ÿ“Š Pool Size: 10 (default)');\n console.log('๐ŸŸข Active Terminals: 0');\n console.log('โธ๏ธ Idle Terminals: 0');\n console.log('๐Ÿ“ˆ Total Created: 0');\n\n if (detailed) {\n console.log('\\n๐Ÿ“‹ Detailed Information:');\n console.log(' Configuration:');\n console.log(' โ€ข Max Pool Size: 10');\n console.log(' โ€ข Idle Timeout: 5 minutes');\n console.log(' โ€ข Shell: /bin/bash');\n console.log(' โ€ข Working Directory: ' + cwd());\n console.log(' Performance:');\n console.log(' โ€ข Average Response Time: N/A');\n console.log(' โ€ข Terminal Creation Time: N/A');\n console.log(' โ€ข Memory Usage: N/A');\n console.log(' Health:');\n console.log(' โ€ข Pool Health: Healthy');\n console.log(' โ€ข Last Health Check: Just now');\n }\n } else if (poolCmd === 'list') {\n printSuccess('Terminal Pool Sessions:');\n console.log('๐Ÿ“‹ No active terminal sessions');\n } else if (poolCmd === 'create') {\n printSuccess('Creating new terminal session...');\n console.log('๐Ÿ†” Terminal ID: term-' + Date.now());\n console.log('๐Ÿ–ฅ๏ธ Status: Created');\n console.log('๐Ÿš Shell: /bin/bash');\n } else if (poolCmd === 'terminate') {\n const termId = subArgs[2];\n if (termId) {\n printSuccess(`Terminating terminal: ${termId}`);\n console.log('โœ… Terminal terminated successfully');\n } else {\n printError('Usage: terminal pool terminate ');\n }\n } else if (poolCmd === 'stats') {\n // Pool statistics command\n printSuccess('Terminal Pool Statistics:');\n console.log('๐Ÿ“Š Utilization: 0%');\n console.log('โšก Performance Metrics:');\n console.log(' โ€ข Average Command Time: N/A');\n console.log(' โ€ข Total Commands: 0');\n console.log(' โ€ข Failed Commands: 0');\n console.log('โ™ป๏ธ Recycling Stats:');\n console.log(' โ€ข Terminals Recycled: 0');\n console.log(' โ€ข Average Lifetime: N/A');\n } else {\n console.log('Terminal pool commands: status, list, create, terminate, stats');\n console.log('Options: --detailed, -d');\n }\n break;\n\n case 'create':\n // Advanced terminal creation\n const nameIndex = subArgs.indexOf('--name');\n const shellIndex = subArgs.indexOf('--shell');\n const wdIndex = subArgs.indexOf('--working-directory');\n const envIndex = subArgs.indexOf('--env');\n const persistentIndex = subArgs.indexOf('--persistent');\n\n const terminalConfig = {\n name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),\n shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',\n workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),\n env: envIndex >= 0 ? subArgs[envIndex + 1] : '',\n persistent: persistentIndex >= 0,\n };\n\n printSuccess('Creating terminal session...');\n console.log(`๐Ÿ†” Terminal ID: ${terminalConfig.name}`);\n console.log(`๐Ÿš Shell: ${terminalConfig.shell}`);\n console.log(`๐Ÿ“ Working Directory: ${terminalConfig.workingDirectory}`);\n if (terminalConfig.env) {\n console.log(`๐Ÿ”ง Environment: ${terminalConfig.env}`);\n }\n if (terminalConfig.persistent) {\n console.log('๐Ÿ’พ Persistent: Yes');\n }\n break;\n\n case 'execute':\n case 'exec':\n const execCmd = subArgs.slice(1).join(' ');\n const sessionFlag = subArgs.indexOf('--session');\n const timeoutFlag = subArgs.indexOf('--timeout');\n const backgroundFlag = subArgs.includes('--background');\n\n if (execCmd && sessionFlag < 0) {\n printSuccess(`Executing command: ${execCmd}`);\n console.log('๐Ÿ–ฅ๏ธ Command would execute in terminal pool');\n console.log('๐Ÿ“ Output would appear here');\n if (backgroundFlag) {\n console.log('๐Ÿ”„ Running in background');\n }\n } else if (sessionFlag >= 0) {\n const sessionId = subArgs[sessionFlag + 1];\n const cmdStart = subArgs.indexOf('\"');\n const cmdEnd = subArgs.lastIndexOf('\"');\n const command =\n cmdStart >= 0 && cmdEnd > cmdStart\n ? subArgs\n .slice(cmdStart, cmdEnd + 1)\n .join(' ')\n .slice(1, -1)\n : 'echo \"No command\"';\n\n printSuccess(`Executing in session ${sessionId}: ${command}`);\n if (timeoutFlag >= 0) {\n console.log(`โฑ๏ธ Timeout: ${subArgs[timeoutFlag + 1]}`);\n }\n } else {\n printError('Usage: terminal execute [--session ] [--timeout ]');\n }\n break;\n\n case 'batch-exec':\n // Batch command execution\n const batchSession = subArgs.find((arg) => !arg.startsWith('--'));\n const commandsFlag = subArgs.indexOf('--commands');\n const fileFlag = subArgs.indexOf('--file');\n\n if (commandsFlag >= 0) {\n const commands = subArgs[commandsFlag + 1].split(',');\n printSuccess(`Executing ${commands.length} commands in sequence`);\n commands.forEach((cmd, i) => {\n console.log(` ${i + 1}. ${cmd}`);\n });\n } else if (fileFlag >= 0) {\n printSuccess(`Executing commands from file: ${subArgs[fileFlag + 1]}`);\n } else {\n console.log('Usage: terminal batch-exec --commands \"cmd1,cmd2,cmd3\" [--session ]');\n }\n break;\n\n case 'list':\n // List all terminal sessions\n const listDetailed = subArgs.includes('--detailed');\n printSuccess('Active Terminal Sessions:');\n console.log('๐Ÿ“‹ No active terminal sessions');\n if (listDetailed) {\n console.log('\\nSystem Information:');\n console.log(' โ€ข Total Sessions Created: 0');\n console.log(' โ€ข Sessions Recycled: 0');\n console.log(' โ€ข Average Session Lifetime: N/A');\n }\n break;\n\n case 'info':\n // Get terminal info\n const infoSessionId = subArgs[1];\n if (infoSessionId) {\n printSuccess(`Terminal Information: ${infoSessionId}`);\n console.log('๐Ÿ†” Session ID: ' + infoSessionId);\n console.log('๐Ÿ“ Status: Not found');\n console.log('๐Ÿš Shell: N/A');\n console.log('๐Ÿ“ Working Directory: N/A');\n console.log('โฑ๏ธ Created: N/A');\n console.log('๐Ÿ“Š Commands Executed: 0');\n } else {\n printError('Usage: terminal info ');\n }\n break;\n\n case 'attach':\n // Attach to terminal\n const attachId = subArgs[1];\n if (attachId) {\n printSuccess(`Attaching to terminal: ${attachId}`);\n console.log('๐Ÿ”— Would enter interactive mode');\n console.log('๐Ÿ’ก Press Ctrl+D to detach');\n } else {\n printError('Usage: terminal attach ');\n }\n break;\n\n case 'detach':\n // Detach from terminal\n const detachId = subArgs[1];\n if (detachId) {\n printSuccess(`Detaching from terminal: ${detachId}`);\n console.log('โœ… Session continues running in background');\n } else {\n printError('Usage: terminal detach ');\n }\n break;\n\n case 'terminate':\n // Terminate terminal\n const terminateId = subArgs[1];\n const graceful = subArgs.includes('--graceful');\n if (terminateId) {\n printSuccess(`Terminating terminal: ${terminateId}`);\n if (graceful) {\n console.log('๐Ÿ• Graceful shutdown initiated');\n }\n console.log('โœ… Terminal terminated');\n } else {\n printError('Usage: terminal terminate [--graceful]');\n }\n break;\n\n case 'cleanup':\n // Cleanup idle terminals\n const idleTime = subArgs.find((arg) => arg.includes('--idle-longer-than'));\n printSuccess('Cleaning up idle terminals...');\n console.log('๐Ÿงน Scanning for idle sessions');\n if (idleTime) {\n console.log(`โฑ๏ธ Idle threshold: ${idleTime.split('=')[1] || '30m'}`);\n }\n console.log('โœ… Cleanup complete: 0 terminals removed');\n break;\n\n case 'monitor':\n // Monitor terminal\n const monitorId = subArgs[1];\n if (monitorId) {\n printSuccess(`Monitoring terminal: ${monitorId}`);\n console.log('๐Ÿ“Š Real-time metrics would display here');\n console.log(' โ€ข CPU: 0%');\n console.log(' โ€ข Memory: 0MB');\n console.log(' โ€ข I/O: 0 ops/s');\n } else {\n printError('Usage: terminal monitor ');\n }\n break;\n\n case 'record':\n // Record terminal session\n const recordId = subArgs[1];\n const outputFlag = subArgs.indexOf('--output');\n if (recordId && outputFlag >= 0) {\n printSuccess(`Recording terminal session: ${recordId}`);\n console.log(`๐Ÿ“น Output file: ${subArgs[outputFlag + 1]}`);\n console.log('๐Ÿ”ด Recording started');\n } else {\n printError('Usage: terminal record --output ');\n }\n break;\n\n case 'replay':\n // Replay terminal session\n const replayFile = subArgs[1];\n if (replayFile) {\n printSuccess(`Replaying session from: ${replayFile}`);\n console.log('โ–ถ๏ธ Playback would start here');\n console.log('โธ๏ธ Controls: space=pause, arrows=seek, q=quit');\n } else {\n printError('Usage: terminal replay ');\n }\n break;\n\n case 'share':\n // Share terminal session\n const shareId = subArgs[1];\n const accessLevel = subArgs.find((arg) => arg.includes('--access-level'));\n if (shareId) {\n printSuccess(`Sharing terminal session: ${shareId}`);\n console.log(`๐Ÿ”— Share URL: https://claude-flow.local/terminal/${shareId}/view`);\n console.log(`๐Ÿ” Access: ${accessLevel ? accessLevel.split('=')[1] : 'read-only'}`);\n console.log('โฑ๏ธ Expires in: 2 hours');\n } else {\n printError('Usage: terminal share [--access-level read|write]');\n }\n break;\n\n case 'multi-config':\n // Multi-terminal configuration\n const multiCmd = subArgs[1];\n if (multiCmd === 'create') {\n const configName = subArgs.find((arg) => !arg.startsWith('--'));\n printSuccess(`Creating multi-terminal configuration: ${configName || 'default'}`);\n console.log('๐Ÿ“‹ Configuration template created');\n } else {\n console.log('Usage: terminal multi-config create --name --config ');\n }\n break;\n\n case 'multi-launch':\n // Launch multi-terminal environment\n const envName = subArgs[1];\n if (envName) {\n printSuccess(`Launching multi-terminal environment: ${envName}`);\n console.log('๐Ÿš€ Starting terminals in dependency order...');\n console.log(' 1. database - Starting...');\n console.log(' 2. backend-api - Waiting for database...');\n console.log(' 3. frontend-app - Waiting for backend...');\n console.log('โœ… All terminals launched successfully');\n } else {\n printError('Usage: terminal multi-launch ');\n }\n break;\n\n case 'batch-create':\n // Batch create terminals\n const configFile = subArgs.find((arg) => arg.includes('--config'));\n printSuccess('Creating multiple terminal sessions...');\n if (configFile) {\n console.log(`๐Ÿ“„ Loading config from: ${configFile.split('=')[1]}`);\n }\n console.log('โœ… Created 3 terminal sessions');\n break;\n\n case 'session':\n // Legacy session command handling\n const sessionCmd = subArgs[1];\n if (sessionCmd === 'list') {\n printSuccess('Terminal Sessions:');\n console.log('๐Ÿ“‹ No active sessions');\n } else if (sessionCmd === 'info') {\n const sessionId = subArgs[2];\n if (sessionId) {\n printSuccess(`Session Info: ${sessionId}`);\n console.log('๐Ÿ†” Session ID: ' + sessionId);\n console.log('๐Ÿ“ Status: Not found');\n } else {\n printError('Usage: terminal session info ');\n }\n } else {\n console.log('Terminal session commands: list, info');\n }\n break;\n\n default:\n console.log('Terminal commands:');\n console.log(' Basic:');\n console.log(' pool - Manage terminal pool (status, list, create, terminate)');\n console.log(' create - Create new terminal with options');\n console.log(' execute - Execute command in terminal');\n console.log(' list - List all active terminals');\n console.log(' info - Get terminal information');\n console.log(' Session Control:');\n console.log(' attach - Attach to terminal session');\n console.log(' detach - Detach from terminal');\n console.log(' terminate - Terminate terminal session');\n console.log(' cleanup - Clean up idle terminals');\n console.log(' Advanced:');\n console.log(' batch-exec - Execute multiple commands');\n console.log(' monitor - Monitor terminal metrics');\n console.log(' record - Record terminal session');\n console.log(' replay - Replay recorded session');\n console.log(' share - Share terminal session');\n console.log(' Multi-Terminal:');\n console.log(' multi-config - Create multi-terminal config');\n console.log(' multi-launch - Launch terminal environment');\n console.log(' batch-create - Create multiple terminals');\n console.log('\\nExamples:');\n console.log(' terminal pool status --detailed');\n console.log(' terminal create --name \"dev\" --shell bash --persistent');\n console.log(' terminal execute \"npm test\" --session dev --timeout 5m');\n console.log(' terminal batch-exec --commands \"cd /app,npm install,npm start\"');\n console.log(' terminal monitor dev --metrics cpu,memory');\n }\n break;\n\n case 'session':\n printSuccess('Terminal session manager ready');\n console.log('๐Ÿ–ฅ๏ธ Session operations would be handled here');\n break;\n\n case 'workflow':\n const workflowFile = subArgs[0];\n if (workflowFile) {\n printSuccess(`Executing workflow: ${workflowFile}`);\n console.log('๐Ÿ”„ Workflow execution would start here');\n } else {\n printError('Please specify a workflow file');\n }\n break;\n\n case 'repl':\n printSuccess('Starting interactive REPL mode...');\n await startRepl();\n break;\n\n case 'project':\n const projectCmd = subArgs[0];\n switch (projectCmd) {\n case 'create':\n const projectName = subArgs[1];\n if (!projectName) {\n printError('Usage: project create [options]');\n break;\n }\n\n const isolationFlag = subArgs.indexOf('--isolation');\n const resourceQuotaFlag = subArgs.indexOf('--resource-quota');\n const securityProfileFlag = subArgs.indexOf('--security-profile');\n const templateFlag = subArgs.indexOf('--template');\n\n printSuccess(`Creating project: ${projectName}`);\n console.log('๐Ÿ—๏ธ Project Configuration:');\n console.log(` Name: ${projectName}`);\n console.log(\n ` Isolation: ${isolationFlag >= 0 ? subArgs[isolationFlag + 1] : 'standard'}`,\n );\n if (resourceQuotaFlag >= 0) {\n console.log(` Resource Quota: ${subArgs[resourceQuotaFlag + 1]}`);\n }\n console.log(\n ` Security Profile: ${securityProfileFlag >= 0 ? subArgs[securityProfileFlag + 1] : 'default'}`,\n );\n if (templateFlag >= 0) {\n console.log(` Template: ${subArgs[templateFlag + 1]}`);\n }\n\n // Create project directory structure\n console.log('\\n๐Ÿ“ Creating project structure:');\n console.log(` โœ“ Created /projects/${projectName}/`);\n console.log(` โœ“ Created /projects/${projectName}/agents/`);\n console.log(` โœ“ Created /projects/${projectName}/workflows/`);\n console.log(` โœ“ Created /projects/${projectName}/config/`);\n console.log(` โœ“ Created /projects/${projectName}/data/`);\n console.log(` โœ“ Created project-config.json`);\n console.log('\\nโœ… Project created successfully!');\n break;\n\n case 'switch':\n const switchProject = subArgs[1];\n if (!switchProject) {\n printError('Usage: project switch ');\n break;\n }\n printSuccess(`Switching to project: ${switchProject}`);\n console.log('๐Ÿ”„ Loading project context...');\n console.log(' โœ“ Project configuration loaded');\n console.log(' โœ“ Agent states restored');\n console.log(' โœ“ Workflow history loaded');\n console.log(`\\n๐Ÿ“ Active project: ${switchProject}`);\n break;\n\n case 'list':\n const showActive = subArgs.includes('--active');\n const withStats = subArgs.includes('--with-stats');\n\n printSuccess('Available projects:');\n const projects = [\n { name: 'microservices-platform', status: 'active', agents: 12, tasks: 45 },\n { name: 'ai-research', status: 'idle', agents: 3, tasks: 8 },\n { name: 'frontend-apps', status: 'archived', agents: 0, tasks: 0 },\n ];\n\n projects.forEach((project) => {\n if (showActive && project.status !== 'active') return;\n\n console.log(`\\n๐Ÿ“ฆ ${project.name}`);\n console.log(` Status: ${project.status}`);\n if (withStats) {\n console.log(` Active Agents: ${project.agents}`);\n console.log(` Pending Tasks: ${project.tasks}`);\n }\n });\n break;\n\n case 'config':\n const configAction = subArgs[1];\n const configProject = subArgs[2];\n\n if (configAction === 'set' && configProject) {\n const configKey = subArgs[3];\n const configValue = subArgs.slice(4).join(' ');\n\n printSuccess(`Updating project configuration: ${configProject}`);\n console.log(` Setting: ${configKey} = ${configValue}`);\n console.log('โœ… Configuration updated');\n } else if (configAction === 'get' && configProject) {\n const configKey = subArgs[3];\n console.log(`Project: ${configProject}`);\n console.log(`${configKey}: (configuration value)`);\n } else {\n console.log('Usage: project config set ');\n console.log(' project config get ');\n }\n break;\n\n case 'monitor':\n const monitorProject = subArgs[1];\n if (!monitorProject) {\n printError('Usage: project monitor [options]');\n break;\n }\n\n printSuccess(`Monitoring project: ${monitorProject}`);\n console.log('\\n๐Ÿ“Š Real-time Metrics:');\n console.log(' Resource Usage:');\n console.log(' โ€ข CPU: 45%');\n console.log(' โ€ข Memory: 2.3GB / 4GB');\n console.log(' โ€ข Storage: 8.5GB / 20GB');\n console.log(' โ€ข Network: 23Mbps / 100Mbps');\n console.log(' Agent Performance:');\n console.log(' โ€ข Active Agents: 8');\n console.log(' โ€ข Average Response Time: 234ms');\n console.log(' โ€ข Task Success Rate: 94%');\n console.log(' Costs:');\n console.log(' โ€ข Today: $124.50');\n console.log(' โ€ข This Month: $2,845.00');\n break;\n\n case 'backup':\n const backupProject = subArgs[1];\n if (!backupProject) {\n printError('Usage: project backup [options]');\n break;\n }\n\n const includeData = subArgs.includes('--include-data');\n const includeConfig = subArgs.includes('--include-config');\n const includeHistory = subArgs.includes('--include-history');\n const outputFlag = subArgs.indexOf('--output');\n\n printSuccess(`Creating backup for project: ${backupProject}`);\n console.log('๐Ÿ—„๏ธ Backup Configuration:');\n console.log(` Include Data: ${includeData ? 'Yes' : 'No'}`);\n console.log(` Include Config: ${includeConfig ? 'Yes' : 'No'}`);\n console.log(` Include History: ${includeHistory ? 'Yes' : 'No'}`);\n\n console.log('\\n๐Ÿ“ฆ Creating backup...');\n console.log(' โœ“ Collecting project data');\n console.log(' โœ“ Compressing files');\n console.log(' โœ“ Encrypting backup');\n\n const outputFile =\n outputFlag >= 0\n ? subArgs[outputFlag + 1]\n : `${backupProject}-backup-${Date.now()}.tar.gz`;\n console.log(`\\nโœ… Backup created: ${outputFile}`);\n console.log(' Size: 145MB');\n console.log(' Checksum: sha256:abcd1234...');\n break;\n\n case 'share':\n const shareFrom = subArgs[1];\n const shareTo = subArgs[2];\n\n if (!shareFrom || !shareTo) {\n printError('Usage: project share [options]');\n break;\n }\n\n const agentsFlag = subArgs.indexOf('--agents');\n const permissionsFlag = subArgs.indexOf('--permissions');\n const durationFlag = subArgs.indexOf('--duration');\n\n printSuccess(`Sharing resources from ${shareFrom} to ${shareTo}`);\n if (agentsFlag >= 0) {\n console.log(` Agents: ${subArgs[agentsFlag + 1]}`);\n }\n if (permissionsFlag >= 0) {\n console.log(` Permissions: ${subArgs[permissionsFlag + 1]}`);\n }\n if (durationFlag >= 0) {\n console.log(` Duration: ${subArgs[durationFlag + 1]}`);\n }\n console.log('\\nโœ… Resource sharing configured');\n break;\n\n case 'federation':\n const fedCmd = subArgs[1];\n\n if (fedCmd === 'create') {\n const fedName = subArgs[2];\n const projectsFlag = subArgs.indexOf('--projects');\n\n if (!fedName) {\n printError('Usage: project federation create --projects ');\n break;\n }\n\n printSuccess(`Creating federation: ${fedName}`);\n if (projectsFlag >= 0) {\n console.log(` Projects: ${subArgs[projectsFlag + 1]}`);\n }\n console.log(' Coordination Model: hierarchical');\n console.log(' Shared Resources: knowledge-base, artifact-registry');\n console.log('\\nโœ… Federation created successfully');\n } else if (fedCmd === 'list') {\n printSuccess('Active federations:');\n console.log('\\n๐Ÿข development-ecosystem');\n console.log(' Projects: backend-services, frontend-apps, infrastructure');\n console.log(' Coordinator: infrastructure');\n console.log(' Status: Active');\n } else {\n console.log('Federation commands: create, list, workflow');\n }\n break;\n\n default:\n console.log('Project commands:');\n console.log(' create - Create new project with isolation');\n console.log(' switch - Switch active project context');\n console.log(' list - List all projects');\n console.log(' config - Get/set project configuration');\n console.log(' monitor - Monitor project resources and performance');\n console.log(' backup - Create project backup');\n console.log(' share - Share resources between projects');\n console.log(' federation - Manage project federations');\n console.log('\\nExamples:');\n console.log(\n ' project create \"microservices\" --isolation strict --resource-quota \"agents:15,memory:4GB\"',\n );\n console.log(' project switch \"microservices\"');\n console.log(' project monitor \"microservices\" --real-time');\n }\n break;\n\n case 'cloud':\n const cloudCmd = subArgs[0];\n const cloudProvider = subArgs[1];\n\n switch (cloudCmd) {\n case 'aws':\n switch (cloudProvider) {\n case 'deploy':\n const awsServices = subArgs.indexOf('--services');\n const awsRegions = subArgs.indexOf('--regions');\n const awsHA = subArgs.includes('--ha-configuration');\n const awsCostOpt = subArgs.includes('--cost-optimization');\n\n printSuccess('Deploying Claude-Flow to AWS');\n console.log('โ˜๏ธ AWS Deployment Configuration:');\n if (awsServices >= 0) {\n console.log(` Services: ${subArgs[awsServices + 1]}`);\n }\n if (awsRegions >= 0) {\n console.log(` Regions: ${subArgs[awsRegions + 1]}`);\n }\n console.log(` High Availability: ${awsHA ? 'Enabled' : 'Disabled'}`);\n console.log(` Cost Optimization: ${awsCostOpt ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating ECS cluster');\n console.log(' โœ“ Setting up Lambda functions');\n console.log(' โœ“ Configuring RDS database');\n console.log(' โœ“ Setting up S3 buckets');\n console.log(' โœ“ Configuring CloudWatch monitoring');\n console.log(' โœ“ Setting up load balancers');\n\n console.log('\\nโœ… AWS deployment completed successfully');\n console.log(' Cluster ARN: arn:aws:ecs:us-east-1:123456789012:cluster/claude-flow');\n console.log(' API Gateway: https://api.aws.claude-flow.com');\n console.log(' Monitoring: https://console.aws.amazon.com/cloudwatch');\n break;\n\n case 'configure':\n printSuccess('Configuring AWS integration');\n console.log('๐Ÿ”ง AWS Configuration:');\n console.log(' โœ“ IAM roles and policies');\n console.log(' โœ“ VPC and security groups');\n console.log(' โœ“ Auto-scaling policies');\n console.log(' โœ“ Backup and disaster recovery');\n console.log(' โœ“ Cost monitoring and alerts');\n break;\n\n case 'status':\n printSuccess('AWS Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' ECS Cluster: 3/3 instances healthy');\n console.log(' Lambda Functions: 12/12 active');\n console.log(' RDS Database: Available (Multi-AZ)');\n console.log(' S3 Buckets: 5 buckets, 2.3TB stored');\n console.log(' CloudWatch: 47 metrics, 0 alarms');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (ECS/Lambda): $1,245.50');\n console.log(' Storage (S3/EBS): $342.25');\n console.log(' Network: $87.30');\n console.log(' Total: $1,675.05');\n break;\n\n default:\n console.log('AWS commands: deploy, configure, status');\n }\n break;\n\n case 'azure':\n switch (cloudProvider) {\n case 'deploy':\n const azureServices = subArgs.indexOf('--services');\n const azureRegions = subArgs.indexOf('--regions');\n const azureIntegration = subArgs.includes('--integration-with-aws');\n\n printSuccess('Deploying Claude-Flow to Azure');\n console.log('โ˜๏ธ Azure Deployment Configuration:');\n if (azureServices >= 0) {\n console.log(` Services: ${subArgs[azureServices + 1]}`);\n }\n if (azureRegions >= 0) {\n console.log(` Regions: ${subArgs[azureRegions + 1]}`);\n }\n console.log(` AWS Integration: ${azureIntegration ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating AKS cluster');\n console.log(' โœ“ Setting up Azure Functions');\n console.log(' โœ“ Configuring Cosmos DB');\n console.log(' โœ“ Setting up Blob Storage');\n console.log(' โœ“ Configuring Azure Monitor');\n console.log(' โœ“ Setting up Application Gateway');\n\n console.log('\\nโœ… Azure deployment completed successfully');\n console.log(' Resource Group: claude-flow-production');\n console.log(' API Gateway: https://api.azure.claude-flow.com');\n console.log(' Monitoring: https://portal.azure.com');\n break;\n\n case 'configure':\n printSuccess('Configuring Azure integration');\n console.log('๐Ÿ”ง Azure Configuration:');\n console.log(' โœ“ Service principals and RBAC');\n console.log(' โœ“ Virtual networks and NSGs');\n console.log(' โœ“ Auto-scaling rules');\n console.log(' โœ“ Backup and site recovery');\n console.log(' โœ“ Cost management and budgets');\n break;\n\n case 'status':\n printSuccess('Azure Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' AKS Cluster: 3/3 nodes ready');\n console.log(' Azure Functions: 8/8 active');\n console.log(' Cosmos DB: Available (Global)');\n console.log(' Blob Storage: 3 containers, 1.8TB stored');\n console.log(' Azure Monitor: 35 metrics, 0 alerts');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (AKS/Functions): $985.40');\n console.log(' Storage (Blob/Cosmos): $267.85');\n console.log(' Network: $63.20');\n console.log(' Total: $1,316.45');\n break;\n\n default:\n console.log('Azure commands: deploy, configure, status');\n }\n break;\n\n case 'gcp':\n switch (cloudProvider) {\n case 'deploy':\n const gcpServices = subArgs.indexOf('--services');\n const gcpRegions = subArgs.indexOf('--regions');\n const multiCloud = subArgs.includes('--multi-cloud-networking');\n\n printSuccess('Deploying Claude-Flow to Google Cloud');\n console.log('โ˜๏ธ GCP Deployment Configuration:');\n if (gcpServices >= 0) {\n console.log(` Services: ${subArgs[gcpServices + 1]}`);\n }\n if (gcpRegions >= 0) {\n console.log(` Regions: ${subArgs[gcpRegions + 1]}`);\n }\n console.log(` Multi-Cloud Networking: ${multiCloud ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating GKE cluster');\n console.log(' โœ“ Setting up Cloud Functions');\n console.log(' โœ“ Configuring Cloud SQL');\n console.log(' โœ“ Setting up Cloud Storage');\n console.log(' โœ“ Configuring Cloud Monitoring');\n console.log(' โœ“ Setting up Cloud Load Balancing');\n\n console.log('\\nโœ… GCP deployment completed successfully');\n console.log(' Project ID: claude-flow-production');\n console.log(' API Gateway: https://api.gcp.claude-flow.com');\n console.log(' Monitoring: https://console.cloud.google.com');\n break;\n\n case 'configure':\n printSuccess('Configuring GCP integration');\n console.log('๐Ÿ”ง GCP Configuration:');\n console.log(' โœ“ Service accounts and IAM');\n console.log(' โœ“ VPC networks and firewall rules');\n console.log(' โœ“ Auto-scaling policies');\n console.log(' โœ“ Backup and disaster recovery');\n console.log(' โœ“ Budget alerts and cost optimization');\n break;\n\n case 'status':\n printSuccess('GCP Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' GKE Cluster: 3/3 nodes ready');\n console.log(' Cloud Functions: 10/10 active');\n console.log(' Cloud SQL: Available (HA)');\n console.log(' Cloud Storage: 4 buckets, 2.1TB stored');\n console.log(' Cloud Monitoring: 42 metrics, 0 incidents');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (GKE/Functions): $1,125.30');\n console.log(' Storage (Cloud Storage/SQL): $298.75');\n console.log(' Network: $71.45');\n console.log(' Total: $1,495.50');\n break;\n\n default:\n console.log('GCP commands: deploy, configure, status');\n }\n break;\n\n case 'multi-cloud':\n const multiCloudCmd = subArgs[1];\n\n switch (multiCloudCmd) {\n case 'deploy':\n printSuccess('Deploying multi-cloud Claude-Flow architecture');\n console.log('๐ŸŒ Multi-Cloud Deployment:');\n console.log(' Primary: AWS (us-east-1)');\n console.log(' Secondary: Azure (eastus)');\n console.log(' Tertiary: GCP (us-central1)');\n\n console.log('\\n๐Ÿ”— Cross-Cloud Networking:');\n console.log(' โœ“ VPN connections established');\n console.log(' โœ“ DNS and load balancing configured');\n console.log(' โœ“ Data replication setup');\n console.log(' โœ“ Unified monitoring deployed');\n\n console.log('\\nโœ… Multi-cloud deployment completed');\n console.log(' Global endpoint: https://global.claude-flow.com');\n console.log(' Failover time: < 30 seconds');\n console.log(' Data consistency: Eventually consistent');\n break;\n\n case 'status':\n printSuccess('Multi-Cloud Infrastructure Status');\n console.log('\\n๐ŸŒ Global Infrastructure:');\n console.log(' AWS (Primary): ๐ŸŸข Healthy');\n console.log(' Azure (Secondary): ๐ŸŸข Healthy');\n console.log(' GCP (Tertiary): ๐ŸŸข Healthy');\n\n console.log('\\n๐Ÿ“Š Traffic Distribution:');\n console.log(' AWS: 45% (2,341 req/min)');\n console.log(' Azure: 35% (1,823 req/min)');\n console.log(' GCP: 20% (1,042 req/min)');\n\n console.log('\\n๐Ÿ’ฐ Total Cost (This Month): $4,487.00');\n break;\n\n case 'failover':\n const failoverTarget = subArgs[2];\n if (!failoverTarget) {\n printError('Usage: cloud multi-cloud failover ');\n break;\n }\n\n printWarning(`Initiating failover to ${failoverTarget}`);\n console.log('๐Ÿ”„ Failover Process:');\n console.log(' โœ“ Health check failed on primary');\n console.log(' โœ“ Traffic routing to secondary');\n console.log(' โœ“ Database replication verified');\n console.log(' โœ“ DNS updates propagated');\n\n console.log(`\\nโœ… Failover to ${failoverTarget} completed in 23 seconds`);\n break;\n\n default:\n console.log('Multi-cloud commands: deploy, status, failover');\n }\n break;\n\n case 'kubernetes':\n const k8sCmd = subArgs[1];\n\n switch (k8sCmd) {\n case 'deploy':\n printSuccess('Deploying Claude-Flow to Kubernetes');\n console.log('โš™๏ธ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Resources: 1Gi memory, 500m CPU per pod');\n\n console.log('\\n๐Ÿ“ฆ Deploying Components:');\n console.log(' โœ“ Orchestrator deployment');\n console.log(' โœ“ MCP server deployment');\n console.log(' โœ“ Memory bank deployment');\n console.log(' โœ“ Load balancer service');\n console.log(' โœ“ Ingress controller');\n console.log(' โœ“ ConfigMaps and Secrets');\n\n console.log('\\nโœ… Kubernetes deployment completed');\n console.log(' Pods: 3/3 running');\n console.log(' Service: claude-flow-orchestrator-service');\n console.log(' Ingress: https://k8s.claude-flow.com');\n break;\n\n case 'scale':\n const replicas = subArgs[2] || '5';\n printSuccess(`Scaling Claude-Flow to ${replicas} replicas`);\n console.log('๐Ÿ“ˆ Scaling Progress:');\n console.log(` Current replicas: 3`);\n console.log(` Target replicas: ${replicas}`);\n console.log(' โœ“ Updating deployment');\n console.log(' โœ“ Rolling update in progress');\n console.log(` โœ“ Scaled to ${replicas} replicas successfully`);\n break;\n\n case 'status':\n printSuccess('Kubernetes Cluster Status');\n console.log('\\nโš™๏ธ Cluster Information:');\n console.log(' Namespace: claude-flow');\n console.log(' Deployments: 3/3 ready');\n console.log(' Pods: 3/3 running');\n console.log(' Services: 2 active');\n console.log(' ConfigMaps: 2');\n console.log(' Secrets: 1');\n\n console.log('\\n๐Ÿ“Š Resource Usage:');\n console.log(' CPU: 1.2/3.0 cores (40%)');\n console.log(' Memory: 2.1/3.0 GB (70%)');\n console.log(' Storage: 8.5/50 GB (17%)');\n break;\n\n default:\n console.log('Kubernetes commands: deploy, scale, status');\n }\n break;\n\n default:\n console.log('Cloud commands:');\n console.log(' aws - Amazon Web Services integration');\n console.log(' azure - Microsoft Azure integration');\n console.log(' gcp - Google Cloud Platform integration');\n console.log(' multi-cloud - Multi-cloud deployment and management');\n console.log(' kubernetes - Kubernetes deployment and management');\n console.log('\\nExamples:');\n console.log(\n ' cloud aws deploy --services \"ecs,lambda,rds\" --regions \"us-east-1,us-west-2\"',\n );\n console.log(' cloud azure deploy --services \"aks,functions,cosmos-db\"');\n console.log(' cloud gcp deploy --services \"gke,cloud-functions,cloud-sql\"');\n console.log(' cloud multi-cloud deploy');\n console.log(' cloud kubernetes deploy');\n }\n break;\n\n case 'claude':\n const claudeCmd = subArgs[0];\n switch (claudeCmd) {\n case 'spawn':\n // Extract task description and flags\n let taskEndIndex = subArgs.length;\n for (let i = 1; i < subArgs.length; i++) {\n if (subArgs[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = subArgs.slice(1, taskEndIndex).join(' ');\n if (!task) {\n printError('Usage: claude spawn [options]');\n break;\n }\n\n // Parse flags\n const flags = {};\n for (let i = taskEndIndex; i < subArgs.length; i++) {\n const arg = subArgs[i];\n if (arg === '--tools' || arg === '-t') {\n flags.tools = subArgs[++i];\n } else if (arg === '--no-permissions') {\n flags.noPermissions = true;\n } else if (arg === '--config' || arg === '-c') {\n flags.config = subArgs[++i];\n } else if (arg === '--mode' || arg === '-m') {\n flags.mode = subArgs[++i];\n } else if (arg === '--parallel') {\n flags.parallel = true;\n } else if (arg === '--research') {\n flags.research = true;\n } else if (arg === '--coverage') {\n flags.coverage = parseInt(subArgs[++i]);\n } else if (arg === '--commit') {\n flags.commit = subArgs[++i];\n } else if (arg === '--verbose' || arg === '-v') {\n flags.verbose = true;\n } else if (arg === '--dry-run' || arg === '-d') {\n flags.dryRun = true;\n }\n }\n\n // Build tools list\n let tools = flags.tools || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n if (flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n if (flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (flags.dryRun) {\n printWarning('DRY RUN - Would execute:');\n console.log(`Command: claude \"\" --allowedTools ${tools}`);\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${flags.mode || 'full'}`);\n console.log(`Coverage: ${flags.coverage || 80}%`);\n console.log(`Commit: ${flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n } else {\n printSuccess(`Spawning Claude instance: ${instanceId}`);\n console.log(`๐Ÿ“ Original Task: ${task}`);\n console.log(`๐Ÿ”ง Tools: ${tools}`);\n console.log(`โš™๏ธ Mode: ${flags.mode || 'full'}`);\n console.log(`๐Ÿ“Š Coverage: ${flags.coverage || 80}%`);\n console.log(`๐Ÿ’พ Commit: ${flags.commit || 'phase'}`);\n console.log(`โœจ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('๐Ÿ“‹ Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Build the actual claude command with enhanced guidance\n let enhancedTask = `# Task Assignment\n\n## Your Primary Task\n${task}\n\n## Development Environment\n\nYou are working in a development environment with advanced orchestration capabilities available if needed.\n\n### Project Context\n- Working Directory: ${process.cwd()}\n- Instance ID: ${instanceId}\n- Development Mode: ${flags.mode || 'full'}\n${flags.coverage ? `- Test Coverage Target: ${flags.coverage}%` : ''}\n${flags.commit ? `- Git Commit Strategy: ${flags.commit}` : ''}\n${flags.config ? `- MCP Config: ${flags.config}` : ''}\n\n### Available Tools\n- You have access to these tools: ${tools}\n${flags.tools ? `- Custom tools specified: ${flags.tools}` : ''}\n\n### Optional Orchestration Features\n\nIf this task requires complex coordination, memory persistence, or multi-agent collaboration, you can use the claude-flow system:\n\n1. **Persistent Memory** (if needed for your task)\n - Store project data: \\`npx claude-flow memory store \"\"\\`\n - Retrieve stored data: \\`npx claude-flow memory query \\`\n - Export/Import memory: \\`npx claude-flow memory export/import \\`\n\n2. **Task Coordination** (if working on complex multi-part tasks)\n - Check task status: \\`npx claude-flow status\\`\n - Monitor progress: \\`npx claude-flow monitor\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n3. **Multi-Agent Collaboration** (if task benefits from parallelization)\n - Spawn specialized agents: \\`npx claude-flow agent spawn --name \\`\n - Create subtasks: \\`npx claude-flow task create \"\"\\`\n - Coordinate work: \\`npx claude-flow task assign \\``;\n\n if (flags.parallel) {\n enhancedTask += `\n\n **Parallel Execution Enabled**: The orchestration system can help coordinate parallel work if needed.`;\n }\n\n if (flags.research) {\n enhancedTask += `\n\n **Research Mode**: Web research tools are available for information gathering.`;\n }\n\n enhancedTask += `\n\n### Task Execution Guidelines\n\n1. **Focus on Your Primary Objective**:\n - Understand the specific requirements of the task\n - Plan your approach based on the project's needs\n - Use appropriate tools and practices for the technology stack\n ${flags.mode === 'backend-only' ? ' - Focus on backend implementation' : ''}\n ${flags.mode === 'frontend-only' ? ' - Focus on frontend implementation' : ''}\n ${flags.mode === 'api-only' ? ' - Focus on API design and implementation' : ''}\n\n2. **Development Best Practices**:\n - Write clean, maintainable code following project conventions\n - Include appropriate tests and documentation\n - Use version control effectively\n ${flags.coverage ? ` - Ensure test coverage meets ${flags.coverage}% target` : ''}\n ${flags.commit === 'phase' ? ' - Commit changes after completing major phases' : ''}\n ${flags.commit === 'feature' ? ' - Commit changes after each feature is complete' : ''}\n ${flags.commit === 'manual' ? ' - Only commit when explicitly requested' : ''}\n\n3. **Leverage Orchestration When Beneficial**:\n - For complex tasks requiring persistent state, use the memory bank\n - For multi-part projects, use task coordination features\n - For parallelizable work, consider multi-agent approaches\n ${flags.parallel ? ' - Parallel capabilities are enabled for this task' : ''}\n ${flags.research ? ' - Research tools are available if needed' : ''}\n ${flags.noPermissions ? ' - Running with --no-permissions mode' : ''}\n ${flags.verbose ? ' - Verbose mode enabled for detailed output' : ''}\n\n## Getting Started\n\nBegin working on your task. The orchestration features are available as tools to help you be more effective, but your primary focus should be on delivering the requested functionality.\n\n### Quick Reference (if using orchestration features)\n\n\\`\\`\\`bash\n# Example: Storing project-specific data\nBash(\"npx claude-flow memory store project_config '{\\\\\"name\\\\\": \\\\\"my-app\\\\\", \\\\\"version\\\\\": \\\\\"1.0.0\\\\\"}'\")\n\n# Example: Checking for previous work\nBash(\"npx claude-flow memory query previous_implementation\")\n\n# Example: Creating subtasks for complex projects\nBash(\"npx claude-flow task create frontend 'Build React components'\")\nBash(\"npx claude-flow task create backend 'Implement API endpoints'\")\n\\`\\`\\`\n\nRemember: These are optional tools. Use them when they add value to your development process.\n\n## Development Mode: ${flags.mode || 'full'}\n${flags.mode === 'backend-only' ? `Focus on server-side implementation, APIs, and business logic.` : ''}\n${flags.mode === 'frontend-only' ? `Focus on client-side implementation, UI/UX, and user interactions.` : ''}\n${flags.mode === 'api-only' ? `Focus on API design, documentation, and endpoint implementation.` : ''}\n${flags.mode === 'full' || !flags.mode ? `Full-stack development covering all aspects of the application.` : ''}\n\n`;\n\n const claudeArgs = [enhancedTask];\n claudeArgs.push('--allowedTools', tools);\n\n // DEBUG: Log what we're about to pass\n console.log('\\n๐Ÿ” DEBUG - Command Construction:');\n console.log(`First arg length: ${claudeArgs[0].length} chars`);\n console.log(`First 100 chars: ${claudeArgs[0].substring(0, 100)}...`);\n console.log(`Args count: ${claudeArgs.length}`);\n\n if (flags.noPermissions) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n if (flags.config) {\n claudeArgs.push('--mcp-config', flags.config);\n }\n\n if (flags.verbose) {\n claudeArgs.push('--verbose');\n }\n\n // Execute the actual claude command\n try {\n // Debug: Log the actual command being executed\n if (flags.verbose) {\n console.log('Debug - Executing command:');\n console.log(\n `claude ${claudeArgs.map((arg) => (arg.includes(' ') || arg.includes('\\n') ? `\"${arg}\"` : arg)).join(' ')}`,\n );\n }\n\n const child = spawn('claude', claudeArgs, {\n env: {\n ...process.env,\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: flags.mode || 'full',\n CLAUDE_FLOW_COVERAGE: (flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: flags.commit || 'phase',\n // Add claude-flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdio: 'inherit',\n });\n\n // Wait for process to exit\n await new Promise((resolve) => {\n child.on('exit', (code) => {\n if (code === 0) {\n printSuccess(`Claude instance ${instanceId} completed successfully`);\n } else {\n printError(`Claude instance ${instanceId} exited with code ${code}`);\n }\n resolve();\n });\n });\n } catch (err) {\n printError(`Failed to spawn Claude: ${err.message}`);\n console.log('Make sure you have the Claude CLI installed.');\n }\n }\n break;\n\n case 'batch':\n const workflowFile = subArgs[1];\n if (!workflowFile) {\n printError('Usage: claude batch ');\n break;\n }\n printSuccess(`Loading workflow: ${workflowFile}`);\n console.log('๐Ÿ“‹ Batch execution would process workflow file');\n break;\n\n default:\n console.log('Claude commands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n }\n break;\n\n case 'deploy':\n const deployCmd = subArgs[0];\n switch (deployCmd) {\n case 'ha-cluster':\n const nodes = subArgs.find((arg) => arg.includes('--nodes'));\n const regions = subArgs.find((arg) => arg.includes('--regions'));\n const replicationFactor = subArgs.find((arg) => arg.includes('--replication-factor'));\n\n printSuccess('Deploying High Availability Cluster...');\n console.log('๐Ÿ—๏ธ HA Configuration:');\n console.log(` Nodes: ${nodes ? nodes.split('=')[1] : '3'}`);\n console.log(\n ` Regions: ${regions ? regions.split('=')[1] : 'us-east-1,us-west-2,eu-west-1'}`,\n );\n console.log(\n ` Replication Factor: ${replicationFactor ? replicationFactor.split('=')[1] : '2'}`,\n );\n console.log(' Load Balancer: nginx');\n console.log(' Health Checks: comprehensive');\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Provisioning nodes in us-east-1');\n console.log(' โœ“ Provisioning nodes in us-west-2');\n console.log(' โœ“ Provisioning nodes in eu-west-1');\n console.log(' โœ“ Configuring load balancer');\n console.log(' โœ“ Setting up health checks');\n console.log(' โœ“ Establishing replication');\n console.log('\\nโœ… HA cluster deployed successfully!');\n console.log(' Cluster endpoint: https://claude-flow-ha.example.com');\n break;\n\n case 'scaling':\n const scalingAction = subArgs[1];\n\n if (scalingAction === 'configure') {\n printSuccess('Configuring Auto-Scaling...');\n console.log('๐Ÿ“ˆ Scaling Configuration:');\n console.log(' Min Instances: 2');\n console.log(' Max Instances: 50');\n console.log(' Scale Up Threshold: CPU:70%, Memory:80%');\n console.log(' Scale Down Threshold: CPU:30%, Memory:40%');\n console.log(' Cool-down Periods: Up:300s, Down:600s');\n console.log('\\nโœ… Auto-scaling configured');\n } else if (scalingAction === 'predictive') {\n printSuccess('Enabling Predictive Scaling...');\n console.log('๐Ÿ”ฎ Predictive Configuration:');\n console.log(' Forecast Horizon: 1 hour');\n console.log(' Learning Period: 7 days');\n console.log(' Confidence Threshold: 0.8');\n console.log(' ML Model: LSTM-based forecasting');\n console.log('\\nโœ… Predictive scaling enabled');\n } else {\n console.log('Scaling commands: configure, predictive, status');\n }\n break;\n\n case 'security':\n const securityAction = subArgs[1];\n\n if (securityAction === 'harden') {\n printSuccess('Applying Security Hardening...');\n console.log('๐Ÿ”’ Security Configuration:');\n console.log(' Profile: enterprise');\n console.log(' Encryption: all-traffic, at-rest');\n console.log(' Authentication: multi-factor');\n console.log(' Authorization: RBAC');\n console.log(' Audit Logging: comprehensive');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n\n console.log('\\n๐Ÿ›ก๏ธ Applying security measures:');\n console.log(' โœ“ Enabling encryption at rest');\n console.log(' โœ“ Configuring TLS 1.3 minimum');\n console.log(' โœ“ Setting up MFA requirements');\n console.log(' โœ“ Implementing RBAC policies');\n console.log(' โœ“ Enabling audit logging');\n console.log(' โœ“ Applying compliance controls');\n console.log('\\nโœ… Security hardening complete');\n } else if (securityAction === 'monitor') {\n printSuccess('Security Monitoring Active');\n console.log('๐Ÿ” Real-time Security Status:');\n console.log(' Threat Level: Low');\n console.log(' Active Sessions: 42');\n console.log(' Failed Auth Attempts: 3 (last 24h)');\n console.log(' Anomalies Detected: 0');\n console.log(' Compliance Status: โœ… Compliant');\n } else {\n console.log('Security commands: harden, policy, rbac, monitor');\n }\n break;\n\n case 'kubernetes':\n case 'k8s':\n printSuccess('Deploying to Kubernetes...');\n console.log('โ˜ธ๏ธ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Image: claude-flow/orchestrator:latest');\n console.log(' Service Type: LoadBalancer');\n\n console.log('\\n๐Ÿ“ฆ Creating resources:');\n console.log(' โœ“ Created namespace/claude-flow');\n console.log(' โœ“ Created deployment/claude-flow-orchestrator');\n console.log(' โœ“ Created service/claude-flow-orchestrator-service');\n console.log(' โœ“ Created configmap/claude-flow-config');\n console.log(' โœ“ Created secret/claude-flow-secrets');\n console.log('\\nโœ… Kubernetes deployment complete');\n console.log(' Service endpoint: http://a1b2c3d4.elb.amazonaws.com');\n break;\n\n default:\n console.log('Deploy commands:');\n console.log(' ha-cluster - Deploy high availability cluster');\n console.log(' scaling - Configure auto-scaling');\n console.log(' security - Security hardening and monitoring');\n console.log(' kubernetes - Deploy to Kubernetes cluster');\n console.log('\\nExamples:');\n console.log(' deploy ha-cluster --nodes=3 --regions=\"us-east-1,us-west-2\"');\n console.log(' deploy scaling configure --min=2 --max=50');\n console.log(' deploy security harden --profile enterprise');\n }\n break;\n\n case 'analytics':\n const analyticsCmd = subArgs[0];\n switch (analyticsCmd) {\n case 'performance':\n printSuccess('Performance Analytics Report');\n console.log('\\n๐Ÿ“Š System Performance (Last 30 Days):');\n console.log(' Agent Productivity:');\n console.log(' โ€ข Tasks Completed: 12,847');\n console.log(' โ€ข Average Task Time: 3.4 minutes');\n console.log(' โ€ข Success Rate: 94.2%');\n console.log(' Resource Efficiency:');\n console.log(' โ€ข CPU Utilization: 67% average');\n console.log(' โ€ข Memory Usage: 2.8GB average');\n console.log(' โ€ข Cost per Task: $0.024');\n console.log(' Trends:');\n console.log(' โ€ข Performance: โ†‘ 12% improvement');\n console.log(' โ€ข Efficiency: โ†‘ 8% improvement');\n console.log(' โ€ข Costs: โ†“ 15% reduction');\n break;\n\n case 'business-impact':\n printSuccess('Business Impact Analysis');\n console.log('\\n๐Ÿ’ผ Business Metrics:');\n console.log(' Productivity Gains:');\n console.log(' โ€ข Development Velocity: +45%');\n console.log(' โ€ข Time to Market: -30%');\n console.log(' โ€ข Defect Rate: -62%');\n console.log(' Cost Savings:');\n console.log(' โ€ข Monthly Savings: $24,500');\n console.log(' โ€ข ROI: 312%');\n console.log(' โ€ข Payback Period: 3.2 months');\n console.log(' Quality Improvements:');\n console.log(' โ€ข Code Coverage: 92%');\n console.log(' โ€ข Customer Satisfaction: +18%');\n break;\n\n case 'cost':\n const costCmd = subArgs[1];\n if (costCmd === 'analyze') {\n printSuccess('Cost Analysis Report');\n console.log('\\n๐Ÿ’ฐ Cost Breakdown:');\n console.log(' By Project:');\n console.log(' โ€ข microservices-platform: $8,234 (41%)');\n console.log(' โ€ข ai-research: $5,123 (26%)');\n console.log(' โ€ข frontend-apps: $3,456 (17%)');\n console.log(' โ€ข other: $3,187 (16%)');\n console.log(' By Resource:');\n console.log(' โ€ข Compute: $12,450 (62%)');\n console.log(' โ€ข Storage: $4,230 (21%)');\n console.log(' โ€ข Network: $2,120 (11%)');\n console.log(' โ€ข Other: $1,200 (6%)');\n console.log(' Optimization Opportunities:');\n console.log(' โ€ข Use spot instances: Save $3,200/month');\n console.log(' โ€ข Optimize storage: Save $800/month');\n console.log(' โ€ข Schedule off-peak: Save $1,500/month');\n } else {\n console.log('Cost commands: analyze, optimize, budget');\n }\n break;\n\n default:\n console.log('Analytics commands:');\n console.log(' performance - System performance analytics');\n console.log(' business-impact - Business impact analysis');\n console.log(' cost - Cost analysis and optimization');\n console.log(' capacity - Capacity planning');\n console.log('\\nExamples:');\n console.log(' analytics performance --time-range 30d');\n console.log(' analytics cost analyze --granularity project');\n }\n break;\n\n case 'security':\n const securityCmd = subArgs[0];\n switch (securityCmd) {\n case 'status':\n printSuccess('Enterprise Security Status');\n console.log('\\n๐Ÿ” Authentication:');\n console.log(' Method: Token-based (JWT)');\n console.log(' MFA: Enabled (TOTP, SMS, Hardware Keys)');\n console.log(' Sessions: 42 active');\n console.log(' Session Timeout: 4 hours');\n\n console.log('\\n๐Ÿ›ก๏ธ Authorization:');\n console.log(' Model: Role-Based Access Control (RBAC)');\n console.log(' Roles: 5 defined (admin, developer, operator, auditor, viewer)');\n console.log(' Permissions: 47 granular permissions');\n console.log(' Policy Engine: Active');\n\n console.log('\\n๐Ÿšฆ Rate Limiting:');\n console.log(' Global Limit: 1000 req/min');\n console.log(' Per-User Limit: 100 req/min');\n console.log(' Burst Capacity: 200 requests');\n console.log(' Current Usage: 245 req/min (24.5%)');\n\n console.log('\\nโšก Circuit Breakers:');\n console.log(' Total Breakers: 12');\n console.log(' Status: 10 closed, 1 half-open, 1 open');\n console.log(' Last Triggered: api-gateway (2 minutes ago)');\n\n console.log('\\n๐Ÿ“ Audit Logging:');\n console.log(' Status: Active');\n console.log(' Storage: Encrypted S3 bucket');\n console.log(' Retention: 7 years');\n console.log(' Events Today: 48,234');\n console.log(' Compliance: SOC2, GDPR, HIPAA compliant');\n break;\n\n case 'auth':\n const authAction = subArgs[1];\n\n if (authAction === 'configure') {\n printSuccess('Configuring Authentication...');\n console.log('๐Ÿ” Authentication Configuration:');\n console.log(' Method: JWT with RS256');\n console.log(' Token Expiry: 4 hours');\n console.log(' Refresh Token: 30 days');\n console.log(' MFA Required: Yes');\n console.log(' Password Policy:');\n console.log(' โ€ข Minimum length: 12 characters');\n console.log(' โ€ข Complexity: Upper, lower, numbers, symbols');\n console.log(' โ€ข History: Last 12 passwords');\n console.log(' โ€ข Expiry: 90 days');\n console.log('\\nโœ… Authentication configured');\n } else if (authAction === 'sessions') {\n printSuccess('Active Sessions:');\n console.log('\\n๐Ÿ”‘ Current Sessions:');\n console.log('โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”');\n console.log('โ”‚ User โ”‚ Role โ”‚ IP Address โ”‚ Login Time โ”‚ MFA โ”‚');\n console.log('โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค');\n console.log('โ”‚ alice@corp.com โ”‚ admin โ”‚ 10.0.1.45 โ”‚ 2h ago โ”‚ Hardware โ”‚');\n console.log('โ”‚ bob@corp.com โ”‚ developerโ”‚ 10.0.2.123 โ”‚ 45m ago โ”‚ TOTP โ”‚');\n console.log('โ”‚ charlie@corp.comโ”‚ operator โ”‚ 10.0.1.200 โ”‚ 1h ago โ”‚ SMS โ”‚');\n console.log('โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜');\n } else if (authAction === 'mfa') {\n printSuccess('Multi-Factor Authentication Status:');\n console.log(' Enforcement: Required for all users');\n console.log(' Methods Available:');\n console.log(' โ€ข TOTP (Time-based One-Time Password)');\n console.log(' โ€ข SMS (Text message)');\n console.log(' โ€ข Hardware Keys (FIDO2/WebAuthn)');\n console.log(' โ€ข Backup Codes');\n console.log(' Users with MFA: 98% (147/150)');\n } else {\n console.log('Auth commands: configure, sessions, mfa, tokens');\n }\n break;\n\n case 'rbac':\n const rbacAction = subArgs[1];\n\n if (rbacAction === 'roles') {\n printSuccess('RBAC Roles:');\n console.log('\\n๐Ÿ‘ฅ Defined Roles:');\n console.log('\\n๐Ÿ“› admin (3 users)');\n console.log(' Permissions: * (all permissions)');\n console.log(' Conditions: MFA required, IP restriction');\n\n console.log('\\n๐Ÿ“› developer (45 users)');\n console.log(' Permissions:');\n console.log(' โ€ข projects:read,write');\n console.log(' โ€ข agents:spawn,monitor');\n console.log(' โ€ข tasks:create,monitor');\n console.log(' Conditions: Time window 06:00-22:00');\n\n console.log('\\n๐Ÿ“› operator (12 users)');\n console.log(' Permissions:');\n console.log(' โ€ข system:monitor');\n console.log(' โ€ข agents:list,info');\n console.log(' โ€ข tasks:list,status');\n\n console.log('\\n๐Ÿ“› auditor (5 users)');\n console.log(' Permissions:');\n console.log(' โ€ข audit:read');\n console.log(' โ€ข system:logs');\n console.log(' โ€ข reports:generate');\n\n console.log('\\n๐Ÿ“› viewer (85 users)');\n console.log(' Permissions:');\n console.log(' โ€ข *:read (read-only access)');\n } else if (rbacAction === 'assign') {\n const user = subArgs[2];\n const role = subArgs[3];\n if (user && role) {\n printSuccess(`Assigning role ${role} to user ${user}`);\n console.log('โœ… Role assignment complete');\n console.log(' Effective immediately');\n console.log(' Audit log entry created');\n } else {\n printError('Usage: security rbac assign ');\n }\n } else {\n console.log('RBAC commands: roles, permissions, assign, revoke');\n }\n break;\n\n case 'rate-limit':\n const rateLimitAction = subArgs[1];\n\n if (rateLimitAction === 'status') {\n printSuccess('Rate Limiting Status:');\n console.log('\\n๐Ÿ“Š Current Limits:');\n console.log(' Global:');\n console.log(' โ€ข Limit: 1000 requests/minute');\n console.log(' โ€ข Current: 245 requests/minute (24.5%)');\n console.log(' โ€ข Available: 755 requests');\n console.log(' Per-User:');\n console.log(' โ€ข Default: 100 requests/minute');\n console.log(' โ€ข Premium: 500 requests/minute');\n console.log(' Per-Endpoint:');\n console.log(' โ€ข /api/agents/spawn: 10/minute');\n console.log(' โ€ข /api/tasks/create: 50/minute');\n console.log(' โ€ข /api/memory/query: 200/minute');\n\n console.log('\\n๐Ÿšจ Recent Violations:');\n console.log(' โ€ข user123: 2 violations (15 min ago)');\n console.log(' โ€ข api-client-7: 1 violation (1 hour ago)');\n } else if (rateLimitAction === 'configure') {\n printSuccess('Configuring Rate Limits...');\n console.log(' Global limit: 1000 req/min');\n console.log(' Burst capacity: 200 requests');\n console.log(' Cooldown period: 60 seconds');\n console.log(' Headers: X-RateLimit-* enabled');\n console.log('\\nโœ… Rate limiting configured');\n } else {\n console.log('Rate limit commands: status, configure, reset');\n }\n break;\n\n case 'circuit-breaker':\n const cbAction = subArgs[1];\n\n if (cbAction === 'status') {\n printSuccess('Circuit Breaker Status:');\n console.log('\\nโšก Active Circuit Breakers:');\n console.log('โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”');\n console.log('โ”‚ Service โ”‚ State โ”‚ Failures โ”‚ Successes โ”‚ Last Change โ”‚');\n console.log('โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค');\n console.log('โ”‚ api-gateway โ”‚ OPEN โ”‚ 15 โ”‚ 0 โ”‚ 2m ago โ”‚');\n console.log('โ”‚ auth-service โ”‚ CLOSED โ”‚ 0 โ”‚ 1,234 โ”‚ 1h ago โ”‚');\n console.log('โ”‚ memory-service โ”‚ CLOSED โ”‚ 1 โ”‚ 5,678 โ”‚ 3h ago โ”‚');\n console.log('โ”‚ agent-manager โ”‚ HALF โ”‚ 3 โ”‚ 45 โ”‚ 5m ago โ”‚');\n console.log('โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜');\n\n console.log('\\n๐Ÿ“ˆ Configuration:');\n console.log(' Failure Threshold: 10 failures');\n console.log(' Success Threshold: 5 successes');\n console.log(' Timeout: 60 seconds');\n console.log(' Half-Open Requests: 3 max');\n } else if (cbAction === 'reset') {\n const service = subArgs[2];\n if (service) {\n printSuccess(`Resetting circuit breaker: ${service}`);\n console.log('โœ… Circuit breaker reset to CLOSED state');\n } else {\n console.log('All circuit breakers reset');\n }\n } else {\n console.log('Circuit breaker commands: status, reset, configure');\n }\n break;\n\n case 'audit':\n const auditAction = subArgs[1];\n\n if (auditAction === 'status') {\n printSuccess('Audit Logging Status:');\n console.log(' Status: Active');\n console.log(' Storage Backend: AWS S3 (encrypted)');\n console.log(' Retention Period: 7 years');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n console.log('\\n๐Ÿ“Š Statistics (Last 24h):');\n console.log(' Total Events: 48,234');\n console.log(' Authentication: 1,234');\n console.log(' Authorization: 15,678');\n console.log(' Data Access: 23,456');\n console.log(' Configuration Changes: 89');\n console.log(' Security Events: 12');\n } else if (auditAction === 'search') {\n const query = subArgs.slice(2).join(' ');\n printSuccess(`Searching audit logs: \"${query || 'recent'}\"`);\n console.log('\\n๐Ÿ“‹ Recent Audit Events:');\n console.log(\n '2024-01-10 14:23:45 | AUTH_SUCCESS | alice@corp.com | Login from 10.0.1.45',\n );\n console.log('2024-01-10 14:24:12 | PERMISSION_GRANTED | alice@corp.com | agents.spawn');\n console.log('2024-01-10 14:24:13 | AGENT_CREATED | alice@corp.com | agent-12345');\n console.log(\n '2024-01-10 14:25:01 | CONFIG_CHANGED | bob@corp.com | terminal.poolSize: 10->20',\n );\n console.log(\n '2024-01-10 14:26:30 | PERMISSION_DENIED | charlie@corp.com | admin.users.delete',\n );\n } else if (auditAction === 'export') {\n printSuccess('Exporting audit logs...');\n console.log(' Time range: Last 30 days');\n console.log(' Format: JSON (encrypted)');\n console.log(' Destination: audit-export-20240110.json.enc');\n console.log('\\nโœ… Export complete: 145,234 events');\n } else {\n console.log('Audit commands: status, search, export, configure');\n }\n break;\n\n case 'compliance':\n printSuccess('Compliance Status:');\n console.log('\\n๐Ÿ›๏ธ Active Compliance Frameworks:');\n console.log('\\nโœ… SOC2 Type II');\n console.log(' Last Audit: 2023-10-15');\n console.log(' Next Audit: 2024-04-15');\n console.log(' Status: Compliant');\n console.log(' Controls: 89/89 passing');\n\n console.log('\\nโœ… GDPR (General Data Protection Regulation)');\n console.log(' Data Protection Officer: Jane Smith');\n console.log(' Privacy Impact Assessments: 12 completed');\n console.log(' Data Subject Requests: 3 pending, 45 completed');\n console.log(' Status: Compliant');\n\n console.log('\\nโœ… HIPAA (Health Insurance Portability Act)');\n console.log(' BAA Agreements: 5 active');\n console.log(' PHI Encryption: AES-256 at rest, TLS 1.3 in transit');\n console.log(' Access Controls: Implemented');\n console.log(' Status: Compliant');\n\n console.log('\\n๐Ÿ“‹ Required Actions:');\n console.log(' โ€ข Complete Q1 security training (Due: Jan 31)');\n console.log(' โ€ข Update data retention policies (Due: Feb 15)');\n break;\n\n case 'test':\n printSuccess('Running Security Test Suite...');\n console.log('\\n๐Ÿงช Security Tests:');\n console.log(' โœ… Authentication: Token validation working');\n console.log(' โœ… Authorization: RBAC policies enforced');\n console.log(' โœ… Rate Limiting: Limits properly enforced');\n console.log(' โœ… Circuit Breakers: Failing services isolated');\n console.log(' โœ… Audit Logging: All events captured');\n console.log(' โœ… Encryption: TLS 1.3 verified');\n console.log(' โœ… Session Management: Timeouts working');\n console.log(' โš ๏ธ MFA Bypass: 3 users without MFA');\n console.log('\\n๐Ÿ“Š Security Score: 94/100');\n console.log(' Recommendations:');\n console.log(' โ€ข Enforce MFA for all users');\n console.log(' โ€ข Update TLS certificates (expire in 45 days)');\n console.log(' โ€ข Review inactive user accounts');\n break;\n\n default:\n console.log('Security commands:');\n console.log(' status - Show security status overview');\n console.log(' auth - Authentication management');\n console.log(' rbac - Role-based access control');\n console.log(' rate-limit - Rate limiting configuration');\n console.log(' circuit-breaker - Circuit breaker management');\n console.log(' audit - Audit log management');\n console.log(' compliance - Compliance status');\n console.log(' test - Run security tests');\n console.log('\\nExamples:');\n console.log(' security auth configure');\n console.log(' security rbac assign user@example.com developer');\n console.log(' security audit search \"failed login\"');\n console.log(' security circuit-breaker reset api-gateway');\n }\n break;\n\n case 'backup':\n const backupCmd = subArgs[0];\n switch (backupCmd) {\n case 'configure':\n printSuccess('Configuring Backup Strategy...');\n console.log('๐Ÿ—„๏ธ Backup Configuration:');\n console.log(' Strategy: 3-2-1 (3 copies, 2 media, 1 offsite)');\n console.log(' Locations:');\n console.log(' โ€ข Primary: AWS S3 (us-east-1)');\n console.log(' โ€ข Secondary: Azure Blob (eastus)');\n console.log(' โ€ข Tertiary: Local NAS');\n console.log(' Schedule:');\n console.log(' โ€ข Full: Weekly (Sunday 2 AM)');\n console.log(' โ€ข Incremental: Every 6 hours');\n console.log(' โ€ข Differential: Daily (2 AM)');\n console.log(' Encryption: AES-256');\n console.log(' Compression: LZ4');\n console.log(' Verification: Automatic');\n console.log('\\nโœ… Backup strategy configured');\n break;\n\n case 'dr':\n const drAction = subArgs[1];\n if (drAction === 'configure') {\n printSuccess('Configuring Disaster Recovery...');\n console.log('๐Ÿšจ DR Configuration:');\n console.log(' RPO (Recovery Point Objective): 1 hour');\n console.log(' RTO (Recovery Time Objective): 15 minutes');\n console.log(' Replication: Real-time to secondary region');\n console.log(' Failover: Automatic with manual override');\n console.log(' Testing: Monthly DR drills');\n console.log('\\nโœ… Disaster recovery configured');\n } else if (drAction === 'test') {\n printSuccess('Running DR Test...');\n console.log('๐Ÿงช DR Test Progress:');\n console.log(' โœ“ Initiating failover simulation');\n console.log(' โœ“ Switching to DR site');\n console.log(' โœ“ Verifying data integrity');\n console.log(' โœ“ Testing application functionality');\n console.log(' โœ“ Measuring RTO: 12 minutes');\n console.log(' โœ“ Failing back to primary');\n console.log('\\nโœ… DR test completed successfully');\n } else {\n console.log('DR commands: configure, test, status');\n }\n break;\n\n case 'restore':\n const restorePoint = subArgs[1];\n if (!restorePoint) {\n printError('Usage: backup restore ');\n break;\n }\n\n printSuccess(`Restoring from backup: ${restorePoint}`);\n console.log('๐Ÿ”„ Restore Progress:');\n console.log(' โœ“ Located backup in S3');\n console.log(' โœ“ Verifying backup integrity');\n console.log(' โœ“ Downloading backup data');\n console.log(' โœ“ Decrypting backup');\n console.log(' โœ“ Restoring application data');\n console.log(' โœ“ Restoring configuration');\n console.log(' โœ“ Verifying restored data');\n console.log('\\nโœ… Restore completed successfully');\n break;\n\n default:\n console.log('Backup commands:');\n console.log(' configure - Configure backup strategy');\n console.log(' dr - Disaster recovery management');\n console.log(' restore - Restore from backup');\n console.log(' list - List available backups');\n console.log('\\nExamples:');\n console.log(' backup configure --strategy 3-2-1');\n console.log(' backup dr test');\n console.log(' backup restore \"backup-20240110-023000\"');\n }\n break;\n\n default:\n printError(`Unknown command: ${command}`);\n console.log('Run \"claude-flow help\" for available commands');\n\n // Suggest similar commands\n const commonCommands = [\n 'agent',\n 'task',\n 'spawn',\n 'init',\n 'start',\n 'status',\n 'memory',\n 'sparc',\n 'help',\n ];\n const suggestions = commonCommands.filter(\n (cmd) => cmd.startsWith(command.toLowerCase()) || cmd.includes(command.toLowerCase()),\n );\n\n if (suggestions.length > 0) {\n console.log('\\nDid you mean:');\n suggestions.forEach((cmd) => console.log(` claude-flow ${cmd}`));\n }\n\n exit(1);\n }\n}\n\n// REPL Implementation\nasync function startRepl() {\n console.log('๐Ÿง  Claude-Flow Interactive Shell v' + VERSION);\n console.log('Type \"help\" for available commands, \"exit\" to quit\\n');\n\n const replState = {\n history: [],\n historyIndex: -1,\n currentSession: null,\n context: {\n agents: [],\n tasks: [],\n terminals: [],\n memory: {},\n },\n };\n\n // REPL command handlers\n const replCommands = {\n help: () => {\n console.log(`\n๐Ÿ“š Available REPL Commands:\n \nSystem:\n status - Show system status\n config [key] - Show configuration (or specific key)\n clear - Clear the screen\n history - Show command history\n exit/quit - Exit REPL mode\n\nAgents:\n agent spawn [name] - Spawn new agent\n agent list - List active agents\n agent info - Show agent details\n agent terminate - Terminate agent\n\nTasks:\n task create - Create new task\n task list - List active tasks\n task assign - Assign task to agent\n task status - Show task status\n\nMemory:\n memory store - Store data in memory\n memory get - Retrieve data from memory\n memory list - List all memory keys\n memory clear - Clear all memory\n\nTerminal:\n terminal create [name] - Create terminal session\n terminal list - List terminals\n terminal exec - Execute command\n terminal attach - Attach to terminal\n\nShortcuts:\n ! - Execute shell command\n / - Search command history\n โ†‘/โ†“ - Navigate command history\n`);\n },\n\n status: () => {\n console.log('๐ŸŸข Claude-Flow Status:');\n console.log(` Agents: ${replState.context.agents.length} active`);\n console.log(` Tasks: ${replState.context.tasks.length} in queue`);\n console.log(` Terminals: ${replState.context.terminals.length} active`);\n console.log(` Memory Keys: ${Object.keys(replState.context.memory).length}`);\n },\n\n clear: () => {\n console.clear();\n console.log('๐Ÿง  Claude-Flow Interactive Shell v' + VERSION);\n },\n\n history: () => {\n console.log('๐Ÿ“œ Command History:');\n replState.history.forEach((cmd, i) => {\n console.log(` ${i + 1}: ${cmd}`);\n });\n },\n\n config: async (key) => {\n try {\n const config = JSON.parse(await readTextFile('claude-flow.config.json'));\n if (key) {\n const keys = key.split('.');\n let value = config;\n for (const k of keys) {\n value = value[k];\n }\n console.log(`${key}: ${JSON.stringify(value, null, 2)}`);\n } else {\n console.log(JSON.stringify(config, null, 2));\n }\n } catch {\n console.log('No configuration file found. Using defaults.');\n }\n },\n };\n\n // Process REPL commands\n async function processReplCommand(input) {\n const trimmed = input.trim();\n if (!trimmed) return true;\n\n // Add to history\n replState.history.push(trimmed);\n replState.historyIndex = replState.history.length;\n\n // Handle special commands\n if (trimmed === 'exit' || trimmed === 'quit') {\n console.log('๐Ÿ‘‹ Exiting Claude-Flow REPL...');\n return false;\n }\n\n // Handle shell commands\n if (trimmed.startsWith('!')) {\n const shellCmd = trimmed.substring(1);\n try {\n await new Promise((resolve) => {\n const proc = spawn('sh', ['-c', shellCmd], {\n stdio: ['inherit', 'pipe', 'pipe'],\n });\n\n proc.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n\n proc.stderr.on('data', (data) => {\n console.error(data.toString());\n });\n\n proc.on('exit', resolve);\n });\n } catch (err) {\n console.error(`Shell error: ${err.message}`);\n }\n return true;\n }\n\n // Handle search\n if (trimmed.startsWith('/')) {\n const search = trimmed.substring(1);\n const matches = replState.history.filter((cmd) => cmd.includes(search));\n if (matches.length > 0) {\n console.log('๐Ÿ” Search results:');\n matches.forEach((cmd) => console.log(` ${cmd}`));\n } else {\n console.log('No matches found');\n }\n return true;\n }\n\n // Parse command and arguments\n const parts = trimmed.split(' ');\n const command = parts[0];\n const args = parts.slice(1);\n\n // Handle built-in REPL commands\n if (replCommands[command]) {\n await replCommands[command](...args);\n return true;\n }\n\n // Handle multi-word commands\n if (command === 'agent') {\n await handleAgentCommand(args, replState);\n } else if (command === 'task') {\n await handleTaskCommand(args, replState);\n } else if (command === 'memory') {\n await handleMemoryCommand(args, replState);\n } else if (command === 'terminal') {\n await handleTerminalCommand(args, replState);\n } else {\n console.log(`Unknown command: ${command}. Type \"help\" for available commands.`);\n }\n\n return true;\n }\n\n // Agent command handler\n async function handleAgentCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'spawn':\n const rawType = args[1] || 'researcher';\n const type = resolveLegacyAgentType(rawType);\n const name = args[2] || `agent-${Date.now()}`;\n const agent = {\n id: `agent-${Date.now()}`,\n type,\n name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.agents.push(agent);\n printSuccess(`Spawned ${type} agent: ${name} (${agent.id})`);\n break;\n\n case 'list':\n if (state.context.agents.length === 0) {\n console.log('No active agents');\n } else {\n console.log('Active agents:');\n state.context.agents.forEach((agent) => {\n console.log(` ${agent.id} - ${agent.name} (${agent.type}) - ${agent.status}`);\n });\n }\n break;\n\n case 'info':\n const agentId = args[1];\n const foundAgent = state.context.agents.find((a) => a.id === agentId || a.name === agentId);\n if (foundAgent) {\n console.log(`Agent: ${foundAgent.name}`);\n console.log(` ID: ${foundAgent.id}`);\n console.log(` Type: ${foundAgent.type}`);\n console.log(` Status: ${foundAgent.status}`);\n console.log(` Created: ${foundAgent.created}`);\n } else {\n printError(`Agent not found: ${agentId}`);\n }\n break;\n\n case 'terminate':\n const termId = args[1];\n const index = state.context.agents.findIndex((a) => a.id === termId || a.name === termId);\n if (index >= 0) {\n const removed = state.context.agents.splice(index, 1)[0];\n printSuccess(`Terminated agent: ${removed.name}`);\n } else {\n printError(`Agent not found: ${termId}`);\n }\n break;\n\n default:\n console.log('Agent commands: spawn, list, info, terminate');\n }\n }\n\n // Task command handler\n async function handleTaskCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const type = args[1] || 'general';\n const description = args.slice(2).join(' ') || 'No description';\n const task = {\n id: `task-${Date.now()}`,\n type,\n description,\n status: 'pending',\n created: new Date().toISOString(),\n };\n state.context.tasks.push(task);\n printSuccess(`Created task: ${task.id}`);\n console.log(` Type: ${type}`);\n console.log(` Description: ${description}`);\n break;\n\n case 'list':\n if (state.context.tasks.length === 0) {\n console.log('No active tasks');\n } else {\n console.log('Active tasks:');\n state.context.tasks.forEach((task) => {\n console.log(` ${task.id} - ${task.type} - ${task.status}`);\n console.log(` ${task.description}`);\n });\n }\n break;\n\n case 'assign':\n const taskId = args[1];\n const assignAgentId = args[2];\n const foundTask = state.context.tasks.find((t) => t.id === taskId);\n const assignAgent = state.context.agents.find(\n (a) => a.id === assignAgentId || a.name === assignAgentId,\n );\n\n if (foundTask && assignAgent) {\n foundTask.assignedTo = assignAgent.id;\n foundTask.status = 'assigned';\n printSuccess(`Assigned task ${taskId} to agent ${assignAgent.name}`);\n } else {\n printError('Task or agent not found');\n }\n break;\n\n case 'status':\n const statusId = args[1];\n const statusTask = state.context.tasks.find((t) => t.id === statusId);\n if (statusTask) {\n console.log(`Task: ${statusTask.id}`);\n console.log(` Type: ${statusTask.type}`);\n console.log(` Status: ${statusTask.status}`);\n console.log(` Description: ${statusTask.description}`);\n if (statusTask.assignedTo) {\n console.log(` Assigned to: ${statusTask.assignedTo}`);\n }\n console.log(` Created: ${statusTask.created}`);\n } else {\n printError(`Task not found: ${statusId}`);\n }\n break;\n\n default:\n console.log('Task commands: create, list, assign, status');\n }\n }\n\n // Memory command handler\n async function handleMemoryCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'store':\n const key = args[1];\n const value = args.slice(2).join(' ');\n if (key && value) {\n state.context.memory[key] = value;\n printSuccess(`Stored: ${key} = ${value}`);\n } else {\n printError('Usage: memory store ');\n }\n break;\n\n case 'get':\n const getKey = args[1];\n if (getKey && state.context.memory[getKey]) {\n console.log(`${getKey}: ${state.context.memory[getKey]}`);\n } else {\n console.log(`Key not found: ${getKey}`);\n }\n break;\n\n case 'list':\n const keys = Object.keys(state.context.memory);\n if (keys.length === 0) {\n console.log('No data in memory');\n } else {\n console.log('Memory keys:');\n keys.forEach((key) => {\n console.log(` ${key}: ${state.context.memory[key]}`);\n });\n }\n break;\n\n case 'clear':\n state.context.memory = {};\n printSuccess('Memory cleared');\n break;\n\n default:\n console.log('Memory commands: store, get, list, clear');\n }\n }\n\n // Terminal command handler\n async function handleTerminalCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const name = args[1] || `term-${Date.now()}`;\n const terminal = {\n id: name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.terminals.push(terminal);\n printSuccess(`Created terminal: ${name}`);\n break;\n\n case 'list':\n if (state.context.terminals.length === 0) {\n console.log('No active terminals');\n } else {\n console.log('Active terminals:');\n state.context.terminals.forEach((term) => {\n console.log(` ${term.id} - ${term.status}`);\n });\n }\n break;\n\n case 'exec':\n const cmd = args.slice(1).join(' ');\n if (cmd) {\n console.log(`Executing: ${cmd}`);\n console.log('(Command execution simulated in REPL)');\n } else {\n printError('Usage: terminal exec ');\n }\n break;\n\n case 'attach':\n const attachId = args[1];\n if (attachId) {\n state.currentSession = attachId;\n console.log(`Attached to terminal: ${attachId}`);\n console.log('(Type \"terminal detach\" to detach)');\n } else {\n printError('Usage: terminal attach ');\n }\n break;\n\n case 'detach':\n if (state.currentSession) {\n console.log(`Detached from terminal: ${state.currentSession}`);\n state.currentSession = null;\n } else {\n console.log('Not attached to any terminal');\n }\n break;\n\n default:\n console.log('Terminal commands: create, list, exec, attach, detach');\n }\n }\n\n // Main REPL loop with Node.js readline\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n // Set prompt based on session\n function updatePrompt() {\n rl.setPrompt(\n replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ',\n );\n }\n\n updatePrompt();\n rl.prompt();\n\n // Handle each line of input\n rl.on('line', async (input) => {\n input = input.trim();\n\n // Process command\n const shouldContinue = await processReplCommand(input);\n if (!shouldContinue) {\n rl.close();\n } else {\n updatePrompt();\n rl.prompt();\n }\n });\n\n // Handle CTRL+C\n rl.on('SIGINT', () => {\n console.log('\\nExiting Claude-Flow...');\n rl.close();\n process.exit(0);\n });\n\n // Wait for REPL to close\n return new Promise((resolve) => {\n rl.on('close', resolve);\n });\n}\n\n// Helper functions for init command\nfunction createMinimalClaudeMd() {\n return `# Claude Code Integration\n\nThis file provides guidance to Claude when working with this codebase.\n\n## Project Overview\n[Describe your project here]\n\n## Key Conventions\n- Code style guidelines\n- Naming conventions\n- Architecture patterns\n\n## Important Notes\n- Special considerations\n- Areas to be careful with\n`;\n}\n\nfunction createFullClaudeMd() {\n return `# Claude Code Integration Guide\n\nThis document provides comprehensive guidance to Claude when working with this codebase.\n\n## Project Overview\n[Provide a detailed description of your project, its purpose, and main features]\n\n## Architecture\n[Describe the overall architecture, main components, and how they interact]\n\n## Code Conventions\n- **Naming**: [Describe naming conventions for files, functions, variables, etc.]\n- **Style**: [Code formatting preferences, linting rules]\n- **Patterns**: [Design patterns used in the project]\n- **Testing**: [Testing approach and requirements]\n\n## Directory Structure\n\\`\\`\\`\nproject/\nโ”œโ”€โ”€ src/ # Source code\nโ”œโ”€โ”€ tests/ # Test files\nโ”œโ”€โ”€ docs/ # Documentation\nโ””โ”€โ”€ ... # Other directories\n\\`\\`\\`\n\n## Development Workflow\n1. [Step-by-step development process]\n2. [How to run tests]\n3. [How to build/deploy]\n\n## Important Considerations\n- [Security considerations]\n- [Performance requirements]\n- [Compatibility requirements]\n\n## Common Tasks\n- **Add a new feature**: [Instructions]\n- **Fix a bug**: [Process]\n- **Update documentation**: [Guidelines]\n\n## Dependencies\n[List key dependencies and their purposes]\n\n## Troubleshooting\n[Common issues and solutions]\n`;\n}\n\nfunction createMinimalMemoryBankMd() {\n return `# Memory Bank\n\nSession memory and context storage.\n\n## Current Session\n- Started: ${new Date().toISOString()}\n- Context: [Current work context]\n\n## Key Information\n- [Important facts to remember]\n\n## Progress Log\n- [Track progress here]\n`;\n}\n\nfunction createFullMemoryBankMd() {\n return `# Memory Bank\n\nThis file serves as persistent memory storage for Claude across sessions.\n\n## Session Information\n- **Current Session**: Started ${new Date().toISOString()}\n- **Project Phase**: [Development/Testing/Production]\n- **Active Tasks**: [List current tasks]\n\n## Project Context\n### Technical Stack\n- Languages: [List languages used]\n- Frameworks: [List frameworks]\n- Tools: [Development tools]\n\n### Architecture Decisions\n- [Record key architectural decisions]\n- [Rationale for technology choices]\n\n## Important Information\n### API Keys and Secrets\n- [Never store actual secrets here, just references]\n\n### External Services\n- [List integrated services]\n- [Configuration requirements]\n\n### Database Schema\n- [Current schema version]\n- [Recent migrations]\n\n## Progress Tracking\n### Completed Tasks\n- [x] [Completed task 1]\n- [x] [Completed task 2]\n\n### In Progress\n- [ ] [Current task 1]\n- [ ] [Current task 2]\n\n### Upcoming\n- [ ] [Future task 1]\n- [ ] [Future task 2]\n\n## Code Patterns\n### Established Patterns\n\\`\\`\\`javascript\n// Example pattern\n\\`\\`\\`\n\n### Anti-patterns to Avoid\n- [List anti-patterns]\n\n## Meeting Notes\n### [Date]\n- Participants: [Names]\n- Decisions: [Key decisions]\n- Action items: [Tasks assigned]\n\n## Debugging History\n### Issue: [Issue name]\n- **Date**: [Date]\n- **Symptoms**: [What was observed]\n- **Root Cause**: [What caused it]\n- **Solution**: [How it was fixed]\n\n## Performance Metrics\n- [Baseline metrics]\n- [Optimization goals]\n\n## Documentation Links\n- [API Documentation]: [URL]\n- [Design Documents]: [URL]\n- [Issue Tracker]: [URL]\n`;\n}\n\nfunction createMinimalCoordinationMd() {\n return `# Coordination\n\nTask and workflow coordination.\n\n## Active Tasks\n1. [Current task]\n\n## Workflow\n- [ ] Step 1\n- [ ] Step 2\n\n## Resources\n- [Available resources]\n`;\n}\n\nfunction createFullCoordinationMd() {\n return `# Coordination Center\n\nCentral coordination for multi-agent collaboration and task management.\n\n## Active Agents\n| Agent ID | Type | Status | Assigned Tasks | Last Active |\n|----------|------|--------|----------------|-------------|\n| [ID] | [Type] | [Status] | [Tasks] | [Timestamp] |\n\n## Task Queue\n### High Priority\n1. **[Task Name]**\n - Description: [What needs to be done]\n - Assigned to: [Agent ID]\n - Dependencies: [Other tasks]\n - Deadline: [Date/Time]\n\n### Medium Priority\n1. [Task details]\n\n### Low Priority\n1. [Task details]\n\n## Workflow Definitions\n### [Workflow Name]\n\\`\\`\\`yaml\nname: [Workflow Name]\ndescription: [What this workflow does]\nsteps:\n - name: [Step 1]\n agent: [Agent type]\n action: [What to do]\n - name: [Step 2]\n agent: [Agent type]\n action: [What to do]\n depends_on: [Step 1]\n\\`\\`\\`\n\n## Resource Allocation\n### Computational Resources\n- CPU: [Usage/Limits]\n- Memory: [Usage/Limits]\n- Storage: [Usage/Limits]\n\n### External Resources\n- API Rate Limits: [Service: limit]\n- Database Connections: [Current/Max]\n\n## Communication Channels\n### Inter-Agent Messages\n- [Agent A โ†’ Agent B]: [Message type]\n\n### External Communications\n- Webhooks: [Configured webhooks]\n- Notifications: [Notification settings]\n\n## Synchronization Points\n- [Sync Point 1]: [Description]\n- [Sync Point 2]: [Description]\n\n## Conflict Resolution\n### Strategy\n- [How conflicts are resolved]\n\n### Recent Conflicts\n- [Date]: [Conflict description] โ†’ [Resolution]\n\n## Performance Metrics\n### Task Completion\n- Average time: [Time]\n- Success rate: [Percentage]\n\n### Agent Efficiency\n- [Agent Type]: [Metrics]\n\n## Scheduled Maintenance\n- [Date/Time]: [What will be done]\n\n## Emergency Procedures\n### System Overload\n1. [Step 1]\n2. [Step 2]\n\n### Agent Failure\n1. [Recovery procedure]\n`;\n}\n\nfunction createAgentsReadme() {\n return `# Agents Directory\n\nThis directory stores agent-specific memory and state information.\n\n## Structure\nEach agent gets its own subdirectory named by agent ID:\n- \\`agent-001/\\`: First agent's memory\n- \\`agent-002/\\`: Second agent's memory\n- etc.\n\n## Files per Agent\n- \\`profile.json\\`: Agent configuration and capabilities\n- \\`memory.md\\`: Agent's working memory\n- \\`tasks.json\\`: Assigned tasks and their status\n- \\`metrics.json\\`: Performance metrics\n\n## Usage\nFiles in this directory are automatically managed by the Claude-Flow system.\n`;\n}\n\nfunction createSessionsReadme() {\n return `# Sessions Directory\n\nThis directory stores session-specific information and terminal states.\n\n## Structure\nEach session gets a unique directory:\n- \\`session-[timestamp]/\\`: Session data\n - \\`metadata.json\\`: Session metadata\n - \\`terminal.log\\`: Terminal output\n - \\`commands.history\\`: Command history\n - \\`state.json\\`: Session state snapshot\n\n## Retention Policy\nSessions are retained for 30 days by default, then archived or deleted based on configuration.\n\n## Usage\nThe Claude-Flow system automatically manages session files. Do not modify these files manually.\n`;\n}\n\n// Helper function to create SPARC structure manually\nasync function createSparcStructureManually() {\n try {\n // Create .roo directory structure\n const rooDirectories = [\n '.roo',\n '.roo/templates',\n '.roo/workflows',\n '.roo/modes',\n '.roo/configs',\n ];\n\n for (const dir of rooDirectories) {\n try {\n await mkdirAsync(dir, { recursive: true });\n console.log(` โœ“ Created ${dir}/`);\n } catch (err) {\n if (!(err instanceof errors.AlreadyExists)) {\n throw err;\n }\n }\n }\n\n // Create .roomodes file (copy from existing if available, or create basic version)\n let roomodesContent;\n try {\n // Check if .roomodes already exists and read it\n roomodesContent = await readTextFile('.roomodes');\n console.log(' โœ“ Using existing .roomodes configuration');\n } catch {\n // Create basic .roomodes configuration\n roomodesContent = createBasicRoomodesConfig();\n await writeTextFile('.roomodes', roomodesContent);\n console.log(' โœ“ Created .roomodes configuration');\n }\n\n // Create basic workflow templates\n const basicWorkflow = createBasicSparcWorkflow();\n await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);\n console.log(' โœ“ Created .roo/workflows/basic-tdd.json');\n\n // Create README for .roo directory\n const rooReadme = createRooReadme();\n await writeTextFile('.roo/README.md', rooReadme);\n console.log(' โœ“ Created .roo/README.md');\n\n console.log(' โœ… Basic SPARC structure created successfully');\n } catch (err) {\n console.log(` โŒ Failed to create SPARC structure: ${err.message}`);\n }\n}\n\nfunction createBasicRoomodesConfig() {\n return JSON.stringify(\n {\n customModes: [\n {\n slug: 'architect',\n name: '๐Ÿ—๏ธ Architect',\n roleDefinition:\n 'You design scalable, secure, and modular architectures based on functional specs and user needs. You define responsibilities across services, APIs, and components.',\n customInstructions:\n 'Create architecture mermaid diagrams, data flows, and integration points. Ensure no part of the design includes secrets or hardcoded env values. Emphasize modular boundaries and maintain extensibility.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'code',\n name: '๐Ÿง  Auto-Coder',\n roleDefinition:\n 'You write clean, efficient, modular code based on pseudocode and architecture. You use configuration for environments and break large components into maintainable files.',\n customInstructions:\n 'Write modular code using clean architecture principles. Never hardcode secrets or environment values. Split code into files < 500 lines. Use config files or environment abstractions. Use \\\\`new_task\\\\` for subtasks and finish with \\\\`attempt_completion\\\\`.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'tdd',\n name: '๐Ÿงช Tester (TDD)',\n roleDefinition:\n 'You implement Test-Driven Development (TDD, London School), writing tests first and refactoring after minimal implementation passes.',\n customInstructions:\n 'Write failing tests first. Implement only enough code to pass. Refactor after green. Ensure tests do not hardcode secrets. Keep files < 500 lines.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'spec-pseudocode',\n name: '๐Ÿ“‹ Specification Writer',\n roleDefinition:\n 'You capture full project contextโ€”functional requirements, edge cases, constraintsโ€”and translate that into modular pseudocode with TDD anchors.',\n customInstructions:\n 'Write pseudocode as a series of md files with phase_number_name.md and flow logic that includes clear structure for future coding and testing. Split complex logic across modules.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'integration',\n name: '๐Ÿ”— System Integrator',\n roleDefinition:\n 'You merge the outputs of all modes into a working, tested, production-ready system. You ensure consistency, cohesion, and modularity.',\n customInstructions:\n 'Verify interface compatibility, shared modules, and env config standards. Split integration logic across domains as needed. Use \\\\`new_task\\\\` for preflight testing.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'debug',\n name: '๐Ÿชฒ Debugger',\n roleDefinition:\n 'You troubleshoot runtime bugs, logic errors, or integration failures by tracing, inspecting, and analyzing behavior.',\n customInstructions:\n 'Use logs, traces, and stack analysis to isolate bugs. Avoid changing env configuration directly. Keep fixes modular.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createBasicSparcWorkflow() {\n return JSON.stringify(\n {\n name: 'Basic TDD Workflow',\n description: 'A simple SPARC-based TDD workflow for development',\n sequential: true,\n steps: [\n {\n mode: 'spec-pseudocode',\n description: 'Create detailed specifications and pseudocode',\n phase: 'specification',\n },\n {\n mode: 'tdd',\n description: 'Write failing tests (Red phase)',\n phase: 'red',\n },\n {\n mode: 'code',\n description: 'Implement minimal code to pass tests (Green phase)',\n phase: 'green',\n },\n {\n mode: 'tdd',\n description: 'Refactor and optimize (Refactor phase)',\n phase: 'refactor',\n },\n {\n mode: 'integration',\n description: 'Integrate and verify complete solution',\n phase: 'integration',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createRooReadme() {\n return `# .roo Directory - SPARC Development Environment\n\nThis directory contains the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) development environment configuration and templates.\n\n## Directory Structure\n\n\\`\\`\\`\n.roo/\nโ”œโ”€โ”€ README.md # This file\nโ”œโ”€โ”€ templates/ # Template files for common patterns\nโ”œโ”€โ”€ workflows/ # Predefined SPARC workflows\nโ”‚ โ””โ”€โ”€ basic-tdd.json # Basic TDD workflow\nโ”œโ”€โ”€ modes/ # Custom mode definitions (optional)\nโ””โ”€โ”€ configs/ # Configuration files\n\\`\\`\\`\n\n## SPARC Methodology\n\nSPARC is a systematic approach to software development:\n\n1. **Specification**: Define clear requirements and constraints\n2. **Pseudocode**: Create detailed logic flows and algorithms \n3. **Architecture**: Design system structure and components\n4. **Refinement**: Implement, test, and optimize using TDD\n5. **Completion**: Integrate, document, and validate\n\n## Usage with Claude-Flow\n\nUse the claude-flow SPARC commands to leverage this environment:\n\n\\`\\`\\`bash\n# List available modes\nclaude-flow sparc modes\n\n# Run specific mode\nclaude-flow sparc run code \"implement user authentication\"\n\n# Execute full TDD workflow \nclaude-flow sparc tdd \"payment processing system\"\n\n# Use custom workflow\nclaude-flow sparc workflow .roo/workflows/basic-tdd.json\n\\`\\`\\`\n\n## Configuration\n\nThe main configuration is in \\`.roomodes\\` at the project root. This directory provides additional templates and workflows to support the SPARC development process.\n\n## Customization\n\nYou can customize this environment by:\n- Adding new workflow templates to \\`workflows/\\`\n- Creating mode-specific templates in \\`templates/\\`\n- Adding project-specific configurations in \\`configs/\\`\n\nFor more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nfunction createSparcClaudeMd() {\n return `# Claude Code Configuration - SPARC Development Environment\n\n## Project Overview\nThis project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.\n\n## SPARC Development Commands\n\n### Core SPARC Commands\n- \\`npx claude-flow sparc modes\\`: List all available SPARC development modes\n- \\`npx claude-flow sparc run \"\"\\`: Execute specific SPARC mode for a task\n- \\`npx claude-flow sparc tdd \"\"\\`: Run complete TDD workflow using SPARC methodology\n- \\`npx claude-flow sparc info \\`: Get detailed information about a specific mode\n\n### Standard Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run the test suite\n- \\`npm run lint\\`: Run linter and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n\n## SPARC Methodology Workflow\n\n### 1. Specification Phase\n\\`\\`\\`bash\n# Create detailed specifications and requirements\nnpx claude-flow sparc run spec-pseudocode \"Define user authentication requirements\"\n\\`\\`\\`\n- Define clear functional requirements\n- Document edge cases and constraints\n- Create user stories and acceptance criteria\n- Establish non-functional requirements\n\n### 2. Pseudocode Phase\n\\`\\`\\`bash\n# Develop algorithmic logic and data flows\nnpx claude-flow sparc run spec-pseudocode \"Create authentication flow pseudocode\"\n\\`\\`\\`\n- Break down complex logic into steps\n- Define data structures and interfaces\n- Plan error handling and edge cases\n- Create modular, testable components\n\n### 3. Architecture Phase\n\\`\\`\\`bash\n# Design system architecture and component structure\nnpx claude-flow sparc run architect \"Design authentication service architecture\"\n\\`\\`\\`\n- Create system diagrams and component relationships\n- Define API contracts and interfaces\n- Plan database schemas and data flows\n- Establish security and scalability patterns\n\n### 4. Refinement Phase (TDD Implementation)\n\\`\\`\\`bash\n# Execute Test-Driven Development cycle\nnpx claude-flow sparc tdd \"implement user authentication system\"\n\\`\\`\\`\n\n**TDD Cycle:**\n1. **Red**: Write failing tests first\n2. **Green**: Implement minimal code to pass tests\n3. **Refactor**: Optimize and clean up code\n4. **Repeat**: Continue until feature is complete\n\n### 5. Completion Phase\n\\`\\`\\`bash\n# Integration, documentation, and validation\nnpx claude-flow sparc run integration \"integrate authentication with user management\"\n\\`\\`\\`\n- Integrate all components\n- Perform end-to-end testing\n- Create comprehensive documentation\n- Validate against original requirements\n\n## SPARC Mode Reference\n\n### Development Modes\n- **\\`architect\\`**: System design and architecture planning\n- **\\`code\\`**: Clean, modular code implementation\n- **\\`tdd\\`**: Test-driven development and testing\n- **\\`spec-pseudocode\\`**: Requirements and algorithmic planning\n- **\\`integration\\`**: System integration and coordination\n\n### Quality Assurance Modes\n- **\\`debug\\`**: Troubleshooting and bug resolution\n- **\\`security-review\\`**: Security analysis and vulnerability assessment\n- **\\`refinement-optimization-mode\\`**: Performance optimization and refactoring\n\n### Support Modes\n- **\\`docs-writer\\`**: Documentation creation and maintenance\n- **\\`devops\\`**: Deployment and infrastructure management\n- **\\`mcp\\`**: External service integration\n\n## Code Style and Best Practices\n\n### SPARC Development Principles\n- **Modular Design**: Keep files under 500 lines, break into logical components\n- **Environment Safety**: Never hardcode secrets or environment-specific values\n- **Test-First**: Always write tests before implementation (Red-Green-Refactor)\n- **Clean Architecture**: Separate concerns, use dependency injection\n- **Documentation**: Maintain clear, up-to-date documentation\n\n### Coding Standards\n- Use TypeScript for type safety and better tooling\n- Follow consistent naming conventions (camelCase for variables, PascalCase for classes)\n- Implement proper error handling and logging\n- Use async/await for asynchronous operations\n- Prefer composition over inheritance\n\n### Memory and State Management\n- Use claude-flow memory system for persistent state across sessions\n- Store progress and findings using namespaced keys\n- Query previous work before starting new tasks\n- Export/import memory for backup and sharing\n\n## SPARC Memory Integration\n\n### Memory Commands for SPARC Development\n\\`\\`\\`bash\n# Store project specifications\nnpx claude-flow memory store spec_auth \"User authentication requirements and constraints\"\n\n# Store architectural decisions\nnpx claude-flow memory store arch_decisions \"Database schema and API design choices\"\n\n# Store test results and coverage\nnpx claude-flow memory store test_coverage \"Authentication module: 95% coverage, all tests passing\"\n\n# Query previous work\nnpx claude-flow memory query auth_implementation\n\n# Export project memory\nnpx claude-flow memory export project_backup.json\n\\`\\`\\`\n\n### Memory Namespaces\n- **\\`spec\\`**: Requirements and specifications\n- **\\`arch\\`**: Architecture and design decisions\n- **\\`impl\\`**: Implementation notes and code patterns\n- **\\`test\\`**: Test results and coverage reports\n- **\\`debug\\`**: Bug reports and resolution notes\n\n## Workflow Examples\n\n### Feature Development Workflow\n\\`\\`\\`bash\n# 1. Start with specification\nnpx claude-flow sparc run spec-pseudocode \"User profile management feature\"\n\n# 2. Design architecture\nnpx claude-flow sparc run architect \"Profile service architecture with data validation\"\n\n# 3. Implement with TDD\nnpx claude-flow sparc tdd \"user profile CRUD operations\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"profile data access and validation\"\n\n# 5. Integration testing\nnpx claude-flow sparc run integration \"profile service with authentication system\"\n\n# 6. Documentation\nnpx claude-flow sparc run docs-writer \"profile service API documentation\"\n\\`\\`\\`\n\n### Bug Fix Workflow\n\\`\\`\\`bash\n# 1. Debug and analyze\nnpx claude-flow sparc run debug \"authentication token expiration issue\"\n\n# 2. Write regression tests\nnpx claude-flow sparc run tdd \"token refresh mechanism tests\"\n\n# 3. Implement fix\nnpx claude-flow sparc run code \"fix token refresh in authentication service\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"token handling security implications\"\n\\`\\`\\`\n\n## Configuration Files\n\n### SPARC Configuration\n- **\\`.roomodes\\`**: SPARC mode definitions and configurations\n- **\\`.roo/\\`**: Templates, workflows, and mode-specific rules\n\n### Claude-Flow Configuration\n- **\\`memory/\\`**: Persistent memory and session data\n- **\\`coordination/\\`**: Multi-agent coordination settings\n\n## Git Workflow Integration\n\n### Commit Strategy with SPARC\n- **Specification commits**: After completing requirements analysis\n- **Architecture commits**: After design phase completion\n- **TDD commits**: After each Red-Green-Refactor cycle\n- **Integration commits**: After successful component integration\n- **Documentation commits**: After completing documentation updates\n\n### Branch Strategy\n- **\\`feature/sparc-\\`**: Feature development with SPARC methodology\n- **\\`hotfix/sparc-\\`**: Bug fixes using SPARC debugging workflow\n- **\\`refactor/sparc-\\`**: Refactoring using optimization mode\n\n## Troubleshooting\n\n### Common SPARC Issues\n- **Mode not found**: Check \\`.roomodes\\` file exists and is valid JSON\n- **Memory persistence**: Ensure \\`memory/\\` directory has write permissions\n- **Tool access**: Verify required tools are available for the selected mode\n- **Namespace conflicts**: Use unique memory namespaces for different features\n\n### Debug Commands\n\\`\\`\\`bash\n# Check SPARC configuration\nnpx claude-flow sparc modes\n\n# Verify memory system\nnpx claude-flow memory stats\n\n# Check system status\nnpx claude-flow status\n\n# View detailed mode information\nnpx claude-flow sparc info \n\\`\\`\\`\n\n## Project Architecture\n\nThis SPARC-enabled project follows a systematic development approach:\n- **Clear separation of concerns** through modular design\n- **Test-driven development** ensuring reliability and maintainability\n- **Iterative refinement** for continuous improvement\n- **Comprehensive documentation** for team collaboration\n- **AI-assisted development** through specialized SPARC modes\n\n## Important Notes\n\n- Always run tests before committing (\\`npm run test\\`)\n- Use SPARC memory system to maintain context across sessions\n- Follow the Red-Green-Refactor cycle during TDD phases\n- Document architectural decisions in memory for future reference\n- Regular security reviews for any authentication or data handling code\n\nFor more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nif (isMainModule(import.meta.url)) {\n await main();\n}\n"],"names":["executeCommand","hasCommand","showCommandHelp","listCommands","parseFlags","args","cwd","isMainModule","exit","readTextFile","writeTextFile","mkdirAsync","errors","spawn","process","readline","getMainHelp","getCommandHelp","getStandardizedCommandHelp","VERSION","LEGACY_AGENT_MAPPING","analyst","coordinator","optimizer","documenter","monitor","specialist","architect","resolveLegacyAgentType","legacyType","printHelp","plain","console","log","printCommandHelp","command","standardCommands","includes","help","printLegacyHelp","printVersion","printError","message","error","printSuccess","printWarning","warn","showHelpWithCommands","commands","name","padEnd","description","main","length","usePlainHelp","flags","parsedArgs","slice","enhancedFlags","detectExecutionEnvironment","applySmartDefaults","_environment","skipWarnings","e","h","detailedHelp","env","terminalType","isInteractive","supportsRawMode","isVSCode","isCI","isDocker","isSSH","recommendedFlags","join","appliedDefaults","err","subArgs","rawSpawnType","spawnType","spawnName","Date","now","terminalCmd","poolCmd","detailed","termId","nameIndex","indexOf","shellIndex","wdIndex","envIndex","persistentIndex","terminalConfig","shell","workingDirectory","persistent","execCmd","sessionFlag","timeoutFlag","backgroundFlag","sessionId","cmdStart","cmdEnd","lastIndexOf","batchSession","find","arg","startsWith","commandsFlag","fileFlag","split","forEach","cmd","i","listDetailed","infoSessionId","attachId","detachId","terminateId","graceful","idleTime","monitorId","recordId","outputFlag","replayFile","shareId","accessLevel","multiCmd","configName","envName","configFile","sessionCmd","workflowFile","startRepl","projectCmd","projectName","isolationFlag","resourceQuotaFlag","securityProfileFlag","templateFlag","switchProject","showActive","withStats","projects","status","agents","tasks","project","configAction","configProject","configKey","configValue","monitorProject","backupProject","includeData","includeConfig","includeHistory","outputFile","shareFrom","shareTo","agentsFlag","permissionsFlag","durationFlag","fedCmd","fedName","projectsFlag","cloudCmd","cloudProvider","awsServices","awsRegions","awsHA","awsCostOpt","azureServices","azureRegions","azureIntegration","gcpServices","gcpRegions","multiCloud","multiCloudCmd","failoverTarget","k8sCmd","replicas","claudeCmd","taskEndIndex","task","tools","noPermissions","config","mode","parallel","research","coverage","parseInt","commit","verbose","dryRun","instanceId","Math","random","toString","substr","enhancedTask","claudeArgs","push","substring","map","child","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdio","Promise","resolve","on","code","deployCmd","nodes","regions","replicationFactor","scalingAction","securityAction","analyticsCmd","costCmd","securityCmd","authAction","rbacAction","user","role","rateLimitAction","cbAction","service","auditAction","query","backupCmd","drAction","restorePoint","commonCommands","suggestions","filter","toLowerCase","replState","history","historyIndex","currentSession","context","terminals","memory","replCommands","Object","keys","clear","key","JSON","parse","value","k","stringify","processReplCommand","input","trimmed","trim","shellCmd","proc","stdout","data","stderr","search","matches","parts","handleAgentCommand","handleTaskCommand","handleMemoryCommand","handleTerminalCommand","state","subCmd","rawType","type","agent","id","created","toISOString","agentId","foundAgent","a","index","findIndex","removed","splice","taskId","assignAgentId","foundTask","t","assignAgent","assignedTo","statusId","statusTask","getKey","terminal","term","rl","createInterface","stdin","output","updatePrompt","setPrompt","prompt","shouldContinue","close","createMinimalClaudeMd","createFullClaudeMd","createMinimalMemoryBankMd","createFullMemoryBankMd","createMinimalCoordinationMd","createFullCoordinationMd","createAgentsReadme","createSessionsReadme","createSparcStructureManually","rooDirectories","dir","recursive","AlreadyExists","roomodesContent","createBasicRoomodesConfig","basicWorkflow","createBasicSparcWorkflow","rooReadme","createRooReadme","customModes","slug","roleDefinition","customInstructions","groups","source","sequential","steps","phase","createSparcClaudeMd","url"],"mappings":";AAMA,SACEA,cAAc,EACdC,UAAU,EACVC,eAAe,EAEfC,YAAY,QACP,wBAAwB;AAC/B,SAASC,UAAU,QAAQ,aAAa;AACxC,SACEC,IAAI,EACJC,GAAG,EACHC,YAAY,EACZC,IAAI,EACJC,YAAY,EACZC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,mBAAmB;AAC1B,SAASC,KAAK,QAAQ,gBAAgB;AACtC,OAAOC,aAAa,UAAU;AAC9B,OAAOC,cAAc,WAAW;AAChC,SAASC,WAAW,EAAEC,cAAc,EAAEC,0BAA0B,QAAQ,iBAAiB;AACzF,SAASC,OAAO,QAAQ,qBAAqB;AAG7C,MAAMC,uBAAuB;IAC3BC,SAAS;IACTC,aAAa;IACbC,WAAW;IACXC,YAAY;IACZC,SAAS;IACTC,YAAY;IACZC,WAAW;AACb;AAGA,SAASC,uBAAuBC,UAAU;IACxC,OAAOT,oBAAoB,CAACS,WAAW,IAAIA;AAC7C;AAEA,SAASC,UAAUC,QAAQ,KAAK;IAC9BC,QAAQC,GAAG,CAACjB,YAAYe;AAC1B;AAEA,SAASG,iBAAiBC,OAAO;IAE/B,MAAMC,mBAAmB;QAAC;QAAS;QAAS;KAAS;IACrD,IAAIA,iBAAiBC,QAAQ,CAACF,UAAU;QACtC,MAAMG,OAAOpB,2BAA2BiB;QACxCH,QAAQC,GAAG,CAACK;IACd,OAAO;QACL,MAAMA,OAAOrB,eAAekB;QAC5BH,QAAQC,GAAG,CAACK;IACd;AACF;AAGA,SAASC;IACPP,QAAQC,GAAG,CAAC,CAAC;gBACC,EAAEd,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoPV,CAAC;AACD;AAEA,IAAIhV,aAAa,YAAYiV,GAAG,GAAG;IACjC,MAAMpS;AACR"} \ No newline at end of file +{"version":3,"sources":["../../../src/cli/simple-cli.ts"],"sourcesContent":["#!/usr/bin/env -S deno run --allow-all\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport { promises as fs } from 'node:fs';\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport { VERSION } from '../core/version.js';\n\nfunction printHelp() {\n console.log(`\n๐ŸŒŠ Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n๐ŸŽฏ ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure\n\nUSAGE:\n claude-flow [options]\n\n๐Ÿš€ INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n โ€ข Complete ruv-swarm integration with 27 MCP tools\n โ€ข Neural network processing with WASM optimization\n โ€ข Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n โ€ข Cross-session memory and persistent learning\n โ€ข GitHub workflow automation (6 specialized modes)\n โ€ข Production-ready Docker infrastructure\n โ€ข Enterprise security and compliance features\n\n๐Ÿง  SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n๐Ÿ™ GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n๐Ÿ—๏ธ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn [--name] # Create AI agent with swarm coordination\n agent # Advanced agent management with neural patterns\n sparc # 17 SPARC modes with neural enhancement\n memory # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n๐Ÿค– NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n๐ŸŽฎ ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n \n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n \n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n \n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n \n # Real-time system monitoring\n ./claude-flow status --verbose\n\n๐Ÿข ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n๐Ÿง  NEURAL NETWORK FEATURES (v2.0.0):\n โ€ข WASM-powered cognitive patterns with SIMD optimization\n โ€ข 27 MCP tools for comprehensive workflow automation\n โ€ข Cross-session learning and adaptation\n โ€ข Real-time performance monitoring (sub-10ms response times)\n โ€ข 32.3% token usage reduction through intelligent coordination\n โ€ข Self-healing workflows with automatic error recovery\n\n๐Ÿ“Š ENTERPRISE PERFORMANCE METRICS:\n โ€ข 84.8% SWE-Bench solve rate through coordinated intelligence\n โ€ข 2.8-4.4x speed improvement with parallel execution\n โ€ข 60% Docker build performance improvement\n โ€ข 100% test success rate with comprehensive validation\n โ€ข Sub-10ms MCP response times\n\n๐Ÿ”— INTEGRATION & COMPATIBILITY:\n โ€ข Node.js 20+ optimization for enterprise environments\n โ€ข Complete Claude Code integration with enhanced capabilities\n โ€ข Multi-platform support (Windows, macOS, Linux)\n โ€ข Enterprise security with access control and audit logging\n โ€ข Cross-package synchronization and dependency management\n\nGET DETAILED HELP:\n claude-flow help # Command-specific enterprise documentation\n claude-flow --help # Alternative help syntax\n \n Examples:\n claude-flow help swarm # Swarm intelligence coordination\n claude-flow help github # GitHub workflow automation\n claude-flow help neural # Neural network processing\n claude-flow help enterprise # Enterprise features and compliance\n\nCOMMON OPTIONS:\n --verbose, -v Enable detailed output with performance metrics\n --help Show command help with enterprise features\n --config Use custom enterprise configuration\n --parallel Enable parallel execution (default for swarms)\n --monitor Real-time monitoring and performance tracking\n\n๐Ÿ“š Documentation: https://github.com/ruvnet/claude-code-flow\n๐Ÿ ruv-swarm: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm\n\n๐Ÿš€ Enterprise-Grade AI Agent Orchestration - Built with โค๏ธ by rUv for the Claude community\n`);\n}\n\nfunction printVersion() {\n console.log(`Claude-Flow v${VERSION}`);\n}\n\nfunction printError(message: string) {\n console.error(`โŒ Error: ${message}`);\n}\n\nfunction printSuccess(message: string) {\n console.log(`โœ… ${message}`);\n}\n\nfunction printWarning(message: string) {\n console.warn(`โš ๏ธ Warning: ${message}`);\n}\n\nfunction showHelpWithCommands() {\n printHelp();\n console.log('\\nRegistered Commands:');\n const commands = listCommands();\n for (const command of commands) {\n console.log(` ${command.name.padEnd(12)} ${command.description}`);\n }\n console.log('\\nUse \"claude-flow help \" for detailed usage information');\n}\n\nasync function main() {\n const args = Deno.args;\n\n if (args.length === 0) {\n printHelp();\n return;\n }\n\n const command = args[0];\n const { flags, args: parsedArgs } = parseFlags(args.slice(1));\n\n // Handle special commands first\n switch (command) {\n case 'version':\n case '--version':\n case '-v':\n printVersion();\n return;\n\n case 'help':\n case '--help':\n case '-h':\n if (parsedArgs.length > 0) {\n showCommandHelp(parsedArgs[0]);\n } else {\n showHelpWithCommands();\n }\n return;\n }\n\n // Check if this is a registered modular command\n if (hasCommand(command)) {\n try {\n await executeCommand(command, parsedArgs, flags);\n return;\n } catch (err: unknown) {\n printError((err as Error).message);\n return;\n }\n }\n\n // Legacy command handling (to be refactored)\n const subArgs = parsedArgs; // Use parsed args for legacy commands\n\n switch (command) {\n case 'status':\n printSuccess('Claude-Flow System Status:');\n console.log('๐ŸŸก Status: Not Running (orchestrator not started)');\n console.log('๐Ÿค– Agents: 0 active');\n console.log('๐Ÿ“‹ Tasks: 0 in queue');\n console.log('๐Ÿ’พ Memory: Ready');\n console.log('๐Ÿ–ฅ๏ธ Terminal Pool: Ready');\n console.log('๐ŸŒ MCP Server: Stopped');\n break;\n\n case 'monitor':\n printSuccess('Starting system monitor...');\n console.log('๐Ÿ“Š Real-time monitoring would display here');\n break;\n\n case 'spawn':\n // Convenience alias for agent spawn\n const spawnType = subArgs[0] || 'general';\n const spawnName = (flags as any).name || `agent-${Date.now()}`;\n\n printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);\n console.log('๐Ÿค– Agent would be created with the following configuration:');\n console.log(` Type: ${spawnType}`);\n console.log(` Name: ${spawnName}`);\n console.log(' Capabilities: Research, Analysis, Code Generation');\n console.log(' Status: Ready');\n console.log('\\n๐Ÿ“‹ Note: Full agent spawning requires orchestrator to be running');\n break;\n\n case 'terminal':\n const terminalCmd = subArgs[0];\n switch (terminalCmd) {\n case 'pool':\n const poolCmd = subArgs[1];\n const detailed = subArgs.includes('--detailed') || subArgs.includes('-d');\n\n if (poolCmd === 'status') {\n printSuccess('Terminal Pool Status:');\n console.log('๐Ÿ–ฅ๏ธ Status: Ready');\n console.log('๐Ÿ“Š Pool Size: 10 (default)');\n console.log('๐ŸŸข Active Terminals: 0');\n console.log('โธ๏ธ Idle Terminals: 0');\n console.log('๐Ÿ“ˆ Total Created: 0');\n\n if (detailed) {\n console.log('\\n๐Ÿ“‹ Detailed Information:');\n console.log(' Configuration:');\n console.log(' โ€ข Max Pool Size: 10');\n console.log(' โ€ข Idle Timeout: 5 minutes');\n console.log(' โ€ข Shell: /bin/bash');\n console.log(' โ€ข Working Directory: ' + process.cwd());\n console.log(' Performance:');\n console.log(' โ€ข Average Response Time: N/A');\n console.log(' โ€ข Terminal Creation Time: N/A');\n console.log(' โ€ข Memory Usage: N/A');\n console.log(' Health:');\n console.log(' โ€ข Pool Health: Healthy');\n console.log(' โ€ข Last Health Check: Just now');\n }\n } else if (poolCmd === 'list') {\n printSuccess('Terminal Pool Sessions:');\n console.log('๐Ÿ“‹ No active terminal sessions');\n } else if (poolCmd === 'create') {\n printSuccess('Creating new terminal session...');\n console.log('๐Ÿ†” Terminal ID: term-' + Date.now());\n console.log('๐Ÿ–ฅ๏ธ Status: Created');\n console.log('๐Ÿš Shell: /bin/bash');\n } else if (poolCmd === 'terminate') {\n const termId = subArgs[2];\n if (termId) {\n printSuccess(`Terminating terminal: ${termId}`);\n console.log('โœ… Terminal terminated successfully');\n } else {\n printError('Usage: terminal pool terminate ');\n }\n } else if (poolCmd === 'stats') {\n // Pool statistics command\n printSuccess('Terminal Pool Statistics:');\n console.log('๐Ÿ“Š Utilization: 0%');\n console.log('โšก Performance Metrics:');\n console.log(' โ€ข Average Command Time: N/A');\n console.log(' โ€ข Total Commands: 0');\n console.log(' โ€ข Failed Commands: 0');\n console.log('โ™ป๏ธ Recycling Stats:');\n console.log(' โ€ข Terminals Recycled: 0');\n console.log(' โ€ข Average Lifetime: N/A');\n } else {\n console.log('Terminal pool commands: status, list, create, terminate, stats');\n console.log('Options: --detailed, -d');\n }\n break;\n\n case 'create':\n // Advanced terminal creation\n const nameIndex = subArgs.indexOf('--name');\n const shellIndex = subArgs.indexOf('--shell');\n const wdIndex = subArgs.indexOf('--working-directory');\n const envIndex = subArgs.indexOf('--env');\n const persistentIndex = subArgs.indexOf('--persistent');\n\n const terminalConfig = {\n name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),\n shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',\n workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),\n env: envIndex >= 0 ? subArgs[envIndex + 1] : '',\n persistent: persistentIndex >= 0,\n };\n\n printSuccess('Creating terminal session...');\n console.log(`๐Ÿ†” Terminal ID: ${terminalConfig.name}`);\n console.log(`๐Ÿš Shell: ${terminalConfig.shell}`);\n console.log(`๐Ÿ“ Working Directory: ${terminalConfig.workingDirectory}`);\n if (terminalConfig.env) {\n console.log(`๐Ÿ”ง Environment: ${terminalConfig.env}`);\n }\n if (terminalConfig.persistent) {\n console.log('๐Ÿ’พ Persistent: Yes');\n }\n break;\n\n case 'execute':\n case 'exec':\n const execCmd = subArgs.slice(1).join(' ');\n const sessionFlag = subArgs.indexOf('--session');\n const timeoutFlag = subArgs.indexOf('--timeout');\n const backgroundFlag = subArgs.includes('--background');\n\n if (execCmd && sessionFlag < 0) {\n printSuccess(`Executing command: ${execCmd}`);\n console.log('๐Ÿ–ฅ๏ธ Command would execute in terminal pool');\n console.log('๐Ÿ“ Output would appear here');\n if (backgroundFlag) {\n console.log('๐Ÿ”„ Running in background');\n }\n } else if (sessionFlag >= 0) {\n const sessionId = subArgs[sessionFlag + 1];\n const cmdStart = subArgs.indexOf('\"');\n const cmdEnd = subArgs.lastIndexOf('\"');\n const command =\n cmdStart >= 0 && cmdEnd > cmdStart\n ? subArgs\n .slice(cmdStart, cmdEnd + 1)\n .join(' ')\n .slice(1, -1)\n : 'echo \"No command\"';\n\n printSuccess(`Executing in session ${sessionId}: ${command}`);\n if (timeoutFlag >= 0) {\n console.log(`โฑ๏ธ Timeout: ${subArgs[timeoutFlag + 1]}`);\n }\n } else {\n printError('Usage: terminal execute [--session ] [--timeout ]');\n }\n break;\n\n case 'batch-exec':\n // Batch command execution\n const batchSession = subArgs.find((arg) => !arg.startsWith('--'));\n const commandsFlag = subArgs.indexOf('--commands');\n const fileFlag = subArgs.indexOf('--file');\n\n if (commandsFlag >= 0) {\n const commands = subArgs[commandsFlag + 1].split(',');\n printSuccess(`Executing ${commands.length} commands in sequence`);\n commands.forEach((cmd: string, i: number) => {\n console.log(` ${i + 1}. ${cmd}`);\n });\n } else if (fileFlag >= 0) {\n printSuccess(`Executing commands from file: ${subArgs[fileFlag + 1]}`);\n } else {\n console.log('Usage: terminal batch-exec --commands \"cmd1,cmd2,cmd3\" [--session ]');\n }\n break;\n\n case 'list':\n // List all terminal sessions\n const listDetailed = subArgs.includes('--detailed');\n printSuccess('Active Terminal Sessions:');\n console.log('๐Ÿ“‹ No active terminal sessions');\n if (listDetailed) {\n console.log('\\nSystem Information:');\n console.log(' โ€ข Total Sessions Created: 0');\n console.log(' โ€ข Sessions Recycled: 0');\n console.log(' โ€ข Average Session Lifetime: N/A');\n }\n break;\n\n case 'info':\n // Get terminal info\n const infoSessionId = subArgs[1];\n if (infoSessionId) {\n printSuccess(`Terminal Information: ${infoSessionId}`);\n console.log('๐Ÿ†” Session ID: ' + infoSessionId);\n console.log('๐Ÿ“ Status: Not found');\n console.log('๐Ÿš Shell: N/A');\n console.log('๐Ÿ“ Working Directory: N/A');\n console.log('โฑ๏ธ Created: N/A');\n console.log('๐Ÿ“Š Commands Executed: 0');\n } else {\n printError('Usage: terminal info ');\n }\n break;\n\n case 'attach':\n // Attach to terminal\n const attachId = subArgs[1];\n if (attachId) {\n printSuccess(`Attaching to terminal: ${attachId}`);\n console.log('๐Ÿ”— Would enter interactive mode');\n console.log('๐Ÿ’ก Press Ctrl+D to detach');\n } else {\n printError('Usage: terminal attach ');\n }\n break;\n\n case 'detach':\n // Detach from terminal\n const detachId = subArgs[1];\n if (detachId) {\n printSuccess(`Detaching from terminal: ${detachId}`);\n console.log('โœ… Session continues running in background');\n } else {\n printError('Usage: terminal detach ');\n }\n break;\n\n case 'terminate':\n // Terminate terminal\n const terminateId = subArgs[1];\n const graceful = subArgs.includes('--graceful');\n if (terminateId) {\n printSuccess(`Terminating terminal: ${terminateId}`);\n if (graceful) {\n console.log('๐Ÿ• Graceful shutdown initiated');\n }\n console.log('โœ… Terminal terminated');\n } else {\n printError('Usage: terminal terminate [--graceful]');\n }\n break;\n\n case 'cleanup':\n // Cleanup idle terminals\n const idleTime = subArgs.find((arg) => arg.includes('--idle-longer-than'));\n printSuccess('Cleaning up idle terminals...');\n console.log('๐Ÿงน Scanning for idle sessions');\n if (idleTime) {\n console.log(`โฑ๏ธ Idle threshold: ${idleTime.split('=')[1] || '30m'}`);\n }\n console.log('โœ… Cleanup complete: 0 terminals removed');\n break;\n\n case 'monitor':\n // Monitor terminal\n const monitorId = subArgs[1];\n if (monitorId) {\n printSuccess(`Monitoring terminal: ${monitorId}`);\n console.log('๐Ÿ“Š Real-time metrics would display here');\n console.log(' โ€ข CPU: 0%');\n console.log(' โ€ข Memory: 0MB');\n console.log(' โ€ข I/O: 0 ops/s');\n } else {\n printError('Usage: terminal monitor ');\n }\n break;\n\n case 'record':\n // Record terminal session\n const recordId = subArgs[1];\n const outputFlag = subArgs.indexOf('--output');\n if (recordId && outputFlag >= 0) {\n printSuccess(`Recording terminal session: ${recordId}`);\n console.log(`๐Ÿ“น Output file: ${subArgs[outputFlag + 1]}`);\n console.log('๐Ÿ”ด Recording started');\n } else {\n printError('Usage: terminal record --output ');\n }\n break;\n\n case 'replay':\n // Replay terminal session\n const replayFile = subArgs[1];\n if (replayFile) {\n printSuccess(`Replaying session from: ${replayFile}`);\n console.log('โ–ถ๏ธ Playback would start here');\n console.log('โธ๏ธ Controls: space=pause, arrows=seek, q=quit');\n } else {\n printError('Usage: terminal replay ');\n }\n break;\n\n case 'share':\n // Share terminal session\n const shareId = subArgs[1];\n const accessLevel = subArgs.find((arg) => arg.includes('--access-level'));\n if (shareId) {\n printSuccess(`Sharing terminal session: ${shareId}`);\n console.log(`๐Ÿ”— Share URL: https://claude-flow.local/terminal/${shareId}/view`);\n console.log(`๐Ÿ” Access: ${accessLevel ? accessLevel.split('=')[1] : 'read-only'}`);\n console.log('โฑ๏ธ Expires in: 2 hours');\n } else {\n printError('Usage: terminal share [--access-level read|write]');\n }\n break;\n\n case 'multi-config':\n // Multi-terminal configuration\n const multiCmd = subArgs[1];\n if (multiCmd === 'create') {\n const configName = subArgs.find((arg) => !arg.startsWith('--'));\n printSuccess(`Creating multi-terminal configuration: ${configName || 'default'}`);\n console.log('๐Ÿ“‹ Configuration template created');\n } else {\n console.log('Usage: terminal multi-config create --name --config ');\n }\n break;\n\n case 'multi-launch':\n // Launch multi-terminal environment\n const envName = subArgs[1];\n if (envName) {\n printSuccess(`Launching multi-terminal environment: ${envName}`);\n console.log('๐Ÿš€ Starting terminals in dependency order...');\n console.log(' 1. database - Starting...');\n console.log(' 2. backend-api - Waiting for database...');\n console.log(' 3. frontend-app - Waiting for backend...');\n console.log('โœ… All terminals launched successfully');\n } else {\n printError('Usage: terminal multi-launch ');\n }\n break;\n\n case 'batch-create':\n // Batch create terminals\n const configFile = subArgs.find((arg) => arg.includes('--config'));\n printSuccess('Creating multiple terminal sessions...');\n if (configFile) {\n console.log(`๐Ÿ“„ Loading config from: ${configFile.split('=')[1]}`);\n }\n console.log('โœ… Created 3 terminal sessions');\n break;\n\n case 'session':\n // Legacy session command handling\n const sessionCmd = subArgs[1];\n if (sessionCmd === 'list') {\n printSuccess('Terminal Sessions:');\n console.log('๐Ÿ“‹ No active sessions');\n } else if (sessionCmd === 'info') {\n const sessionId = subArgs[2];\n if (sessionId) {\n printSuccess(`Session Info: ${sessionId}`);\n console.log('๐Ÿ†” Session ID: ' + sessionId);\n console.log('๐Ÿ“ Status: Not found');\n } else {\n printError('Usage: terminal session info ');\n }\n } else {\n console.log('Terminal session commands: list, info');\n }\n break;\n\n default:\n console.log('Terminal commands:');\n console.log(' Basic:');\n console.log(' pool - Manage terminal pool (status, list, create, terminate)');\n console.log(' create - Create new terminal with options');\n console.log(' execute - Execute command in terminal');\n console.log(' list - List all active terminals');\n console.log(' info - Get terminal information');\n console.log(' Session Control:');\n console.log(' attach - Attach to terminal session');\n console.log(' detach - Detach from terminal');\n console.log(' terminate - Terminate terminal session');\n console.log(' cleanup - Clean up idle terminals');\n console.log(' Advanced:');\n console.log(' batch-exec - Execute multiple commands');\n console.log(' monitor - Monitor terminal metrics');\n console.log(' record - Record terminal session');\n console.log(' replay - Replay recorded session');\n console.log(' share - Share terminal session');\n console.log(' Multi-Terminal:');\n console.log(' multi-config - Create multi-terminal config');\n console.log(' multi-launch - Launch terminal environment');\n console.log(' batch-create - Create multiple terminals');\n console.log('\\nExamples:');\n console.log(' terminal pool status --detailed');\n console.log(' terminal create --name \"dev\" --shell bash --persistent');\n console.log(' terminal execute \"npm test\" --session dev --timeout 5m');\n console.log(' terminal batch-exec --commands \"cd /app,npm install,npm start\"');\n console.log(' terminal monitor dev --metrics cpu,memory');\n }\n break;\n\n case 'session':\n printSuccess('Terminal session manager ready');\n console.log('๐Ÿ–ฅ๏ธ Session operations would be handled here');\n break;\n\n case 'workflow':\n const workflowFile = subArgs[0];\n if (workflowFile) {\n printSuccess(`Executing workflow: ${workflowFile}`);\n console.log('๐Ÿ”„ Workflow execution would start here');\n } else {\n printError('Please specify a workflow file');\n }\n break;\n\n case 'repl':\n printSuccess('Starting interactive REPL mode...');\n await startRepl();\n break;\n\n case 'project':\n const projectCmd = subArgs[0];\n switch (projectCmd) {\n case 'create':\n const projectName = subArgs[1];\n if (!projectName) {\n printError('Usage: project create [options]');\n break;\n }\n\n const isolationFlag = subArgs.indexOf('--isolation');\n const resourceQuotaFlag = subArgs.indexOf('--resource-quota');\n const securityProfileFlag = subArgs.indexOf('--security-profile');\n const templateFlag = subArgs.indexOf('--template');\n\n printSuccess(`Creating project: ${projectName}`);\n console.log('๐Ÿ—๏ธ Project Configuration:');\n console.log(` Name: ${projectName}`);\n console.log(\n ` Isolation: ${isolationFlag >= 0 ? subArgs[isolationFlag + 1] : 'standard'}`,\n );\n if (resourceQuotaFlag >= 0) {\n console.log(` Resource Quota: ${subArgs[resourceQuotaFlag + 1]}`);\n }\n console.log(\n ` Security Profile: ${securityProfileFlag >= 0 ? subArgs[securityProfileFlag + 1] : 'default'}`,\n );\n if (templateFlag >= 0) {\n console.log(` Template: ${subArgs[templateFlag + 1]}`);\n }\n\n // Create project directory structure\n console.log('\\n๐Ÿ“ Creating project structure:');\n console.log(` โœ“ Created /projects/${projectName}/`);\n console.log(` โœ“ Created /projects/${projectName}/agents/`);\n console.log(` โœ“ Created /projects/${projectName}/workflows/`);\n console.log(` โœ“ Created /projects/${projectName}/config/`);\n console.log(` โœ“ Created /projects/${projectName}/data/`);\n console.log(` โœ“ Created project-config.json`);\n console.log('\\nโœ… Project created successfully!');\n break;\n\n case 'switch':\n const switchProject = subArgs[1];\n if (!switchProject) {\n printError('Usage: project switch ');\n break;\n }\n printSuccess(`Switching to project: ${switchProject}`);\n console.log('๐Ÿ”„ Loading project context...');\n console.log(' โœ“ Project configuration loaded');\n console.log(' โœ“ Agent states restored');\n console.log(' โœ“ Workflow history loaded');\n console.log(`\\n๐Ÿ“ Active project: ${switchProject}`);\n break;\n\n case 'list':\n const showActive = subArgs.includes('--active');\n const withStats = subArgs.includes('--with-stats');\n\n printSuccess('Available projects:');\n const projects = [\n { name: 'microservices-platform', status: 'active', agents: 12, tasks: 45 },\n { name: 'ai-research', status: 'idle', agents: 3, tasks: 8 },\n { name: 'frontend-apps', status: 'archived', agents: 0, tasks: 0 },\n ];\n\n projects.forEach((project) => {\n if (showActive && project.status !== 'active') return;\n\n console.log(`\\n๐Ÿ“ฆ ${project.name}`);\n console.log(` Status: ${project.status}`);\n if (withStats) {\n console.log(` Active Agents: ${project.agents}`);\n console.log(` Pending Tasks: ${project.tasks}`);\n }\n });\n break;\n\n case 'config':\n const configAction = subArgs[1];\n const configProject = subArgs[2];\n\n if (configAction === 'set' && configProject) {\n const configKey = subArgs[3];\n const configValue = subArgs.slice(4).join(' ');\n\n printSuccess(`Updating project configuration: ${configProject}`);\n console.log(` Setting: ${configKey} = ${configValue}`);\n console.log('โœ… Configuration updated');\n } else if (configAction === 'get' && configProject) {\n const configKey = subArgs[3];\n console.log(`Project: ${configProject}`);\n console.log(`${configKey}: (configuration value)`);\n } else {\n console.log('Usage: project config set ');\n console.log(' project config get ');\n }\n break;\n\n case 'monitor':\n const monitorProject = subArgs[1];\n if (!monitorProject) {\n printError('Usage: project monitor [options]');\n break;\n }\n\n printSuccess(`Monitoring project: ${monitorProject}`);\n console.log('\\n๐Ÿ“Š Real-time Metrics:');\n console.log(' Resource Usage:');\n console.log(' โ€ข CPU: 45%');\n console.log(' โ€ข Memory: 2.3GB / 4GB');\n console.log(' โ€ข Storage: 8.5GB / 20GB');\n console.log(' โ€ข Network: 23Mbps / 100Mbps');\n console.log(' Agent Performance:');\n console.log(' โ€ข Active Agents: 8');\n console.log(' โ€ข Average Response Time: 234ms');\n console.log(' โ€ข Task Success Rate: 94%');\n console.log(' Costs:');\n console.log(' โ€ข Today: $124.50');\n console.log(' โ€ข This Month: $2,845.00');\n break;\n\n case 'backup':\n const backupProject = subArgs[1];\n if (!backupProject) {\n printError('Usage: project backup [options]');\n break;\n }\n\n const includeData = subArgs.includes('--include-data');\n const includeConfig = subArgs.includes('--include-config');\n const includeHistory = subArgs.includes('--include-history');\n const outputFlag = subArgs.indexOf('--output');\n\n printSuccess(`Creating backup for project: ${backupProject}`);\n console.log('๐Ÿ—„๏ธ Backup Configuration:');\n console.log(` Include Data: ${includeData ? 'Yes' : 'No'}`);\n console.log(` Include Config: ${includeConfig ? 'Yes' : 'No'}`);\n console.log(` Include History: ${includeHistory ? 'Yes' : 'No'}`);\n\n console.log('\\n๐Ÿ“ฆ Creating backup...');\n console.log(' โœ“ Collecting project data');\n console.log(' โœ“ Compressing files');\n console.log(' โœ“ Encrypting backup');\n\n const outputFile =\n outputFlag >= 0\n ? subArgs[outputFlag + 1]\n : `${backupProject}-backup-${Date.now()}.tar.gz`;\n console.log(`\\nโœ… Backup created: ${outputFile}`);\n console.log(' Size: 145MB');\n console.log(' Checksum: sha256:abcd1234...');\n break;\n\n case 'share':\n const shareFrom = subArgs[1];\n const shareTo = subArgs[2];\n\n if (!shareFrom || !shareTo) {\n printError('Usage: project share [options]');\n break;\n }\n\n const agentsFlag = subArgs.indexOf('--agents');\n const permissionsFlag = subArgs.indexOf('--permissions');\n const durationFlag = subArgs.indexOf('--duration');\n\n printSuccess(`Sharing resources from ${shareFrom} to ${shareTo}`);\n if (agentsFlag >= 0) {\n console.log(` Agents: ${subArgs[agentsFlag + 1]}`);\n }\n if (permissionsFlag >= 0) {\n console.log(` Permissions: ${subArgs[permissionsFlag + 1]}`);\n }\n if (durationFlag >= 0) {\n console.log(` Duration: ${subArgs[durationFlag + 1]}`);\n }\n console.log('\\nโœ… Resource sharing configured');\n break;\n\n case 'federation':\n const fedCmd = subArgs[1];\n\n if (fedCmd === 'create') {\n const fedName = subArgs[2];\n const projectsFlag = subArgs.indexOf('--projects');\n\n if (!fedName) {\n printError('Usage: project federation create --projects ');\n break;\n }\n\n printSuccess(`Creating federation: ${fedName}`);\n if (projectsFlag >= 0) {\n console.log(` Projects: ${subArgs[projectsFlag + 1]}`);\n }\n console.log(' Coordination Model: hierarchical');\n console.log(' Shared Resources: knowledge-base, artifact-registry');\n console.log('\\nโœ… Federation created successfully');\n } else if (fedCmd === 'list') {\n printSuccess('Active federations:');\n console.log('\\n๐Ÿข development-ecosystem');\n console.log(' Projects: backend-services, frontend-apps, infrastructure');\n console.log(' Coordinator: infrastructure');\n console.log(' Status: Active');\n } else {\n console.log('Federation commands: create, list, workflow');\n }\n break;\n\n default:\n console.log('Project commands:');\n console.log(' create - Create new project with isolation');\n console.log(' switch - Switch active project context');\n console.log(' list - List all projects');\n console.log(' config - Get/set project configuration');\n console.log(' monitor - Monitor project resources and performance');\n console.log(' backup - Create project backup');\n console.log(' share - Share resources between projects');\n console.log(' federation - Manage project federations');\n console.log('\\nExamples:');\n console.log(\n ' project create \"microservices\" --isolation strict --resource-quota \"agents:15,memory:4GB\"',\n );\n console.log(' project switch \"microservices\"');\n console.log(' project monitor \"microservices\" --real-time');\n }\n break;\n\n case 'cloud':\n const cloudCmd = subArgs[0];\n const cloudProvider = subArgs[1];\n\n switch (cloudCmd) {\n case 'aws':\n switch (cloudProvider) {\n case 'deploy':\n const awsServices = subArgs.indexOf('--services');\n const awsRegions = subArgs.indexOf('--regions');\n const awsHA = subArgs.includes('--ha-configuration');\n const awsCostOpt = subArgs.includes('--cost-optimization');\n\n printSuccess('Deploying Claude-Flow to AWS');\n console.log('โ˜๏ธ AWS Deployment Configuration:');\n if (awsServices >= 0) {\n console.log(` Services: ${subArgs[awsServices + 1]}`);\n }\n if (awsRegions >= 0) {\n console.log(` Regions: ${subArgs[awsRegions + 1]}`);\n }\n console.log(` High Availability: ${awsHA ? 'Enabled' : 'Disabled'}`);\n console.log(` Cost Optimization: ${awsCostOpt ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating ECS cluster');\n console.log(' โœ“ Setting up Lambda functions');\n console.log(' โœ“ Configuring RDS database');\n console.log(' โœ“ Setting up S3 buckets');\n console.log(' โœ“ Configuring CloudWatch monitoring');\n console.log(' โœ“ Setting up load balancers');\n\n console.log('\\nโœ… AWS deployment completed successfully');\n console.log(' Cluster ARN: arn:aws:ecs:us-east-1:123456789012:cluster/claude-flow');\n console.log(' API Gateway: https://api.aws.claude-flow.com');\n console.log(' Monitoring: https://console.aws.amazon.com/cloudwatch');\n break;\n\n case 'configure':\n printSuccess('Configuring AWS integration');\n console.log('๐Ÿ”ง AWS Configuration:');\n console.log(' โœ“ IAM roles and policies');\n console.log(' โœ“ VPC and security groups');\n console.log(' โœ“ Auto-scaling policies');\n console.log(' โœ“ Backup and disaster recovery');\n console.log(' โœ“ Cost monitoring and alerts');\n break;\n\n case 'status':\n printSuccess('AWS Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' ECS Cluster: 3/3 instances healthy');\n console.log(' Lambda Functions: 12/12 active');\n console.log(' RDS Database: Available (Multi-AZ)');\n console.log(' S3 Buckets: 5 buckets, 2.3TB stored');\n console.log(' CloudWatch: 47 metrics, 0 alarms');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (ECS/Lambda): $1,245.50');\n console.log(' Storage (S3/EBS): $342.25');\n console.log(' Network: $87.30');\n console.log(' Total: $1,675.05');\n break;\n\n default:\n console.log('AWS commands: deploy, configure, status');\n }\n break;\n\n case 'azure':\n switch (cloudProvider) {\n case 'deploy':\n const azureServices = subArgs.indexOf('--services');\n const azureRegions = subArgs.indexOf('--regions');\n const azureIntegration = subArgs.includes('--integration-with-aws');\n\n printSuccess('Deploying Claude-Flow to Azure');\n console.log('โ˜๏ธ Azure Deployment Configuration:');\n if (azureServices >= 0) {\n console.log(` Services: ${subArgs[azureServices + 1]}`);\n }\n if (azureRegions >= 0) {\n console.log(` Regions: ${subArgs[azureRegions + 1]}`);\n }\n console.log(` AWS Integration: ${azureIntegration ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating AKS cluster');\n console.log(' โœ“ Setting up Azure Functions');\n console.log(' โœ“ Configuring Cosmos DB');\n console.log(' โœ“ Setting up Blob Storage');\n console.log(' โœ“ Configuring Azure Monitor');\n console.log(' โœ“ Setting up Application Gateway');\n\n console.log('\\nโœ… Azure deployment completed successfully');\n console.log(' Resource Group: claude-flow-production');\n console.log(' API Gateway: https://api.azure.claude-flow.com');\n console.log(' Monitoring: https://portal.azure.com');\n break;\n\n case 'configure':\n printSuccess('Configuring Azure integration');\n console.log('๐Ÿ”ง Azure Configuration:');\n console.log(' โœ“ Service principals and RBAC');\n console.log(' โœ“ Virtual networks and NSGs');\n console.log(' โœ“ Auto-scaling rules');\n console.log(' โœ“ Backup and site recovery');\n console.log(' โœ“ Cost management and budgets');\n break;\n\n case 'status':\n printSuccess('Azure Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' AKS Cluster: 3/3 nodes ready');\n console.log(' Azure Functions: 8/8 active');\n console.log(' Cosmos DB: Available (Global)');\n console.log(' Blob Storage: 3 containers, 1.8TB stored');\n console.log(' Azure Monitor: 35 metrics, 0 alerts');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (AKS/Functions): $985.40');\n console.log(' Storage (Blob/Cosmos): $267.85');\n console.log(' Network: $63.20');\n console.log(' Total: $1,316.45');\n break;\n\n default:\n console.log('Azure commands: deploy, configure, status');\n }\n break;\n\n case 'gcp':\n switch (cloudProvider) {\n case 'deploy':\n const gcpServices = subArgs.indexOf('--services');\n const gcpRegions = subArgs.indexOf('--regions');\n const multiCloud = subArgs.includes('--multi-cloud-networking');\n\n printSuccess('Deploying Claude-Flow to Google Cloud');\n console.log('โ˜๏ธ GCP Deployment Configuration:');\n if (gcpServices >= 0) {\n console.log(` Services: ${subArgs[gcpServices + 1]}`);\n }\n if (gcpRegions >= 0) {\n console.log(` Regions: ${subArgs[gcpRegions + 1]}`);\n }\n console.log(` Multi-Cloud Networking: ${multiCloud ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Creating GKE cluster');\n console.log(' โœ“ Setting up Cloud Functions');\n console.log(' โœ“ Configuring Cloud SQL');\n console.log(' โœ“ Setting up Cloud Storage');\n console.log(' โœ“ Configuring Cloud Monitoring');\n console.log(' โœ“ Setting up Cloud Load Balancing');\n\n console.log('\\nโœ… GCP deployment completed successfully');\n console.log(' Project ID: claude-flow-production');\n console.log(' API Gateway: https://api.gcp.claude-flow.com');\n console.log(' Monitoring: https://console.cloud.google.com');\n break;\n\n case 'configure':\n printSuccess('Configuring GCP integration');\n console.log('๐Ÿ”ง GCP Configuration:');\n console.log(' โœ“ Service accounts and IAM');\n console.log(' โœ“ VPC networks and firewall rules');\n console.log(' โœ“ Auto-scaling policies');\n console.log(' โœ“ Backup and disaster recovery');\n console.log(' โœ“ Budget alerts and cost optimization');\n break;\n\n case 'status':\n printSuccess('GCP Infrastructure Status');\n console.log('\\n๐Ÿ—๏ธ Infrastructure Health:');\n console.log(' GKE Cluster: 3/3 nodes ready');\n console.log(' Cloud Functions: 10/10 active');\n console.log(' Cloud SQL: Available (HA)');\n console.log(' Cloud Storage: 4 buckets, 2.1TB stored');\n console.log(' Cloud Monitoring: 42 metrics, 0 incidents');\n\n console.log('\\n๐Ÿ’ฐ Cost Summary (This Month):');\n console.log(' Compute (GKE/Functions): $1,125.30');\n console.log(' Storage (Cloud Storage/SQL): $298.75');\n console.log(' Network: $71.45');\n console.log(' Total: $1,495.50');\n break;\n\n default:\n console.log('GCP commands: deploy, configure, status');\n }\n break;\n\n case 'multi-cloud':\n const multiCloudCmd = subArgs[1];\n\n switch (multiCloudCmd) {\n case 'deploy':\n printSuccess('Deploying multi-cloud Claude-Flow architecture');\n console.log('๐ŸŒ Multi-Cloud Deployment:');\n console.log(' Primary: AWS (us-east-1)');\n console.log(' Secondary: Azure (eastus)');\n console.log(' Tertiary: GCP (us-central1)');\n\n console.log('\\n๐Ÿ”— Cross-Cloud Networking:');\n console.log(' โœ“ VPN connections established');\n console.log(' โœ“ DNS and load balancing configured');\n console.log(' โœ“ Data replication setup');\n console.log(' โœ“ Unified monitoring deployed');\n\n console.log('\\nโœ… Multi-cloud deployment completed');\n console.log(' Global endpoint: https://global.claude-flow.com');\n console.log(' Failover time: < 30 seconds');\n console.log(' Data consistency: Eventually consistent');\n break;\n\n case 'status':\n printSuccess('Multi-Cloud Infrastructure Status');\n console.log('\\n๐ŸŒ Global Infrastructure:');\n console.log(' AWS (Primary): ๐ŸŸข Healthy');\n console.log(' Azure (Secondary): ๐ŸŸข Healthy');\n console.log(' GCP (Tertiary): ๐ŸŸข Healthy');\n\n console.log('\\n๐Ÿ“Š Traffic Distribution:');\n console.log(' AWS: 45% (2,341 req/min)');\n console.log(' Azure: 35% (1,823 req/min)');\n console.log(' GCP: 20% (1,042 req/min)');\n\n console.log('\\n๐Ÿ’ฐ Total Cost (This Month): $4,487.00');\n break;\n\n case 'failover':\n const failoverTarget = subArgs[2];\n if (!failoverTarget) {\n printError('Usage: cloud multi-cloud failover ');\n break;\n }\n\n printWarning(`Initiating failover to ${failoverTarget}`);\n console.log('๐Ÿ”„ Failover Process:');\n console.log(' โœ“ Health check failed on primary');\n console.log(' โœ“ Traffic routing to secondary');\n console.log(' โœ“ Database replication verified');\n console.log(' โœ“ DNS updates propagated');\n\n console.log(`\\nโœ… Failover to ${failoverTarget} completed in 23 seconds`);\n break;\n\n default:\n console.log('Multi-cloud commands: deploy, status, failover');\n }\n break;\n\n case 'kubernetes':\n const k8sCmd = subArgs[1];\n\n switch (k8sCmd) {\n case 'deploy':\n printSuccess('Deploying Claude-Flow to Kubernetes');\n console.log('โš™๏ธ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Resources: 1Gi memory, 500m CPU per pod');\n\n console.log('\\n๐Ÿ“ฆ Deploying Components:');\n console.log(' โœ“ Orchestrator deployment');\n console.log(' โœ“ MCP server deployment');\n console.log(' โœ“ Memory bank deployment');\n console.log(' โœ“ Load balancer service');\n console.log(' โœ“ Ingress controller');\n console.log(' โœ“ ConfigMaps and Secrets');\n\n console.log('\\nโœ… Kubernetes deployment completed');\n console.log(' Pods: 3/3 running');\n console.log(' Service: claude-flow-orchestrator-service');\n console.log(' Ingress: https://k8s.claude-flow.com');\n break;\n\n case 'scale':\n const replicas = subArgs[2] || '5';\n printSuccess(`Scaling Claude-Flow to ${replicas} replicas`);\n console.log('๐Ÿ“ˆ Scaling Progress:');\n console.log(` Current replicas: 3`);\n console.log(` Target replicas: ${replicas}`);\n console.log(' โœ“ Updating deployment');\n console.log(' โœ“ Rolling update in progress');\n console.log(` โœ“ Scaled to ${replicas} replicas successfully`);\n break;\n\n case 'status':\n printSuccess('Kubernetes Cluster Status');\n console.log('\\nโš™๏ธ Cluster Information:');\n console.log(' Namespace: claude-flow');\n console.log(' Deployments: 3/3 ready');\n console.log(' Pods: 3/3 running');\n console.log(' Services: 2 active');\n console.log(' ConfigMaps: 2');\n console.log(' Secrets: 1');\n\n console.log('\\n๐Ÿ“Š Resource Usage:');\n console.log(' CPU: 1.2/3.0 cores (40%)');\n console.log(' Memory: 2.1/3.0 GB (70%)');\n console.log(' Storage: 8.5/50 GB (17%)');\n break;\n\n default:\n console.log('Kubernetes commands: deploy, scale, status');\n }\n break;\n\n default:\n console.log('Cloud commands:');\n console.log(' aws - Amazon Web Services integration');\n console.log(' azure - Microsoft Azure integration');\n console.log(' gcp - Google Cloud Platform integration');\n console.log(' multi-cloud - Multi-cloud deployment and management');\n console.log(' kubernetes - Kubernetes deployment and management');\n console.log('\\nExamples:');\n console.log(\n ' cloud aws deploy --services \"ecs,lambda,rds\" --regions \"us-east-1,us-west-2\"',\n );\n console.log(' cloud azure deploy --services \"aks,functions,cosmos-db\"');\n console.log(' cloud gcp deploy --services \"gke,cloud-functions,cloud-sql\"');\n console.log(' cloud multi-cloud deploy');\n console.log(' cloud kubernetes deploy');\n }\n break;\n\n case 'claude':\n const claudeCmd = subArgs[0];\n switch (claudeCmd) {\n case 'spawn':\n // Extract task description and flags\n let taskEndIndex = subArgs.length;\n for (let i = 1; i < subArgs.length; i++) {\n if (subArgs[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = subArgs.slice(1, taskEndIndex).join(' ');\n if (!task) {\n printError('Usage: claude spawn [options]');\n break;\n }\n\n // Parse flags\n const flags: Record = {};\n for (let i = taskEndIndex; i < subArgs.length; i++) {\n const arg = subArgs[i];\n if (arg === '--tools' || arg === '-t') {\n flags.tools = subArgs[++i];\n } else if (arg === '--no-permissions') {\n flags.noPermissions = true;\n } else if (arg === '--config' || arg === '-c') {\n flags.config = subArgs[++i];\n } else if (arg === '--mode' || arg === '-m') {\n flags.mode = subArgs[++i];\n } else if (arg === '--parallel') {\n flags.parallel = true;\n } else if (arg === '--research') {\n flags.research = true;\n } else if (arg === '--coverage') {\n flags.coverage = parseInt(subArgs[++i]);\n } else if (arg === '--commit') {\n flags.commit = subArgs[++i];\n } else if (arg === '--verbose' || arg === '-v') {\n flags.verbose = true;\n } else if (arg === '--dry-run' || arg === '-d') {\n flags.dryRun = true;\n }\n }\n\n // Build tools list\n let tools = flags.tools || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n if (flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n if (flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (flags.dryRun) {\n printWarning('DRY RUN - Would execute:');\n console.log(`Command: claude \"\" --allowedTools ${tools}`);\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${flags.mode || 'full'}`);\n console.log(`Coverage: ${flags.coverage || 80}%`);\n console.log(`Commit: ${flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n } else {\n printSuccess(`Spawning Claude instance: ${instanceId}`);\n console.log(`๐Ÿ“ Original Task: ${task}`);\n console.log(`๐Ÿ”ง Tools: ${tools}`);\n console.log(`โš™๏ธ Mode: ${flags.mode || 'full'}`);\n console.log(`๐Ÿ“Š Coverage: ${flags.coverage || 80}%`);\n console.log(`๐Ÿ’พ Commit: ${flags.commit || 'phase'}`);\n console.log(`โœจ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('๐Ÿ“‹ Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Build the actual claude command with enhanced guidance\n let enhancedTask = `# Task Assignment\n\n## Your Primary Task\n${task}\n\n## Development Environment\n\nYou are working in a development environment with advanced orchestration capabilities available if needed.\n\n### Project Context\n- Working Directory: ${process.cwd()}\n- Instance ID: ${instanceId}\n- Development Mode: ${flags.mode || 'full'}\n${flags.coverage ? `- Test Coverage Target: ${flags.coverage}%` : ''}\n${flags.commit ? `- Git Commit Strategy: ${flags.commit}` : ''}\n${flags.config ? `- MCP Config: ${flags.config}` : ''}\n\n### Available Tools\n- You have access to these tools: ${tools}\n${flags.tools ? `- Custom tools specified: ${flags.tools}` : ''}\n\n### Optional Orchestration Features\n\nIf this task requires complex coordination, memory persistence, or multi-agent collaboration, you can use the claude-flow system:\n\n1. **Persistent Memory** (if needed for your task)\n - Store project data: \\`npx claude-flow memory store \"\"\\`\n - Retrieve stored data: \\`npx claude-flow memory query \\`\n - Export/Import memory: \\`npx claude-flow memory export/import \\`\n\n2. **Task Coordination** (if working on complex multi-part tasks)\n - Check task status: \\`npx claude-flow status\\`\n - Monitor progress: \\`npx claude-flow monitor\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n3. **Multi-Agent Collaboration** (if task benefits from parallelization)\n - Spawn specialized agents: \\`npx claude-flow agent spawn --name \\`\n - Create subtasks: \\`npx claude-flow task create \"\"\\`\n - Coordinate work: \\`npx claude-flow task assign \\``;\n\n if (flags.parallel) {\n enhancedTask += `\n\n **Parallel Execution Enabled**: The orchestration system can help coordinate parallel work if needed.`;\n }\n\n if (flags.research) {\n enhancedTask += `\n\n **Research Mode**: Web research tools are available for information gathering.`;\n }\n\n enhancedTask += `\n\n### Task Execution Guidelines\n\n1. **Focus on Your Primary Objective**:\n - Understand the specific requirements of the task\n - Plan your approach based on the project's needs\n - Use appropriate tools and practices for the technology stack\n ${flags.mode === 'backend-only' ? ' - Focus on backend implementation' : ''}\n ${flags.mode === 'frontend-only' ? ' - Focus on frontend implementation' : ''}\n ${flags.mode === 'api-only' ? ' - Focus on API design and implementation' : ''}\n\n2. **Development Best Practices**:\n - Write clean, maintainable code following project conventions\n - Include appropriate tests and documentation\n - Use version control effectively\n ${flags.coverage ? ` - Ensure test coverage meets ${flags.coverage}% target` : ''}\n ${flags.commit === 'phase' ? ' - Commit changes after completing major phases' : ''}\n ${flags.commit === 'feature' ? ' - Commit changes after each feature is complete' : ''}\n ${flags.commit === 'manual' ? ' - Only commit when explicitly requested' : ''}\n\n3. **Leverage Orchestration When Beneficial**:\n - For complex tasks requiring persistent state, use the memory bank\n - For multi-part projects, use task coordination features\n - For parallelizable work, consider multi-agent approaches\n ${flags.parallel ? ' - Parallel capabilities are enabled for this task' : ''}\n ${flags.research ? ' - Research tools are available if needed' : ''}\n ${flags.noPermissions ? ' - Running with --no-permissions mode' : ''}\n ${flags.verbose ? ' - Verbose mode enabled for detailed output' : ''}\n\n## Getting Started\n\nBegin working on your task. The orchestration features are available as tools to help you be more effective, but your primary focus should be on delivering the requested functionality.\n\n### Quick Reference (if using orchestration features)\n\n\\`\\`\\`bash\n# Example: Storing project-specific data\nBash(\"npx claude-flow memory store project_config '{\\\\\"name\\\\\": \\\\\"my-app\\\\\", \\\\\"version\\\\\": \\\\\"1.0.0\\\\\"}'\")\n\n# Example: Checking for previous work\nBash(\"npx claude-flow memory query previous_implementation\")\n\n# Example: Creating subtasks for complex projects\nBash(\"npx claude-flow task create frontend 'Build React components'\")\nBash(\"npx claude-flow task create backend 'Implement API endpoints'\")\n\\`\\`\\`\n\nRemember: These are optional tools. Use them when they add value to your development process.\n\n## Development Mode: ${flags.mode || 'full'}\n${flags.mode === 'backend-only' ? `Focus on server-side implementation, APIs, and business logic.` : ''}\n${flags.mode === 'frontend-only' ? `Focus on client-side implementation, UI/UX, and user interactions.` : ''}\n${flags.mode === 'api-only' ? `Focus on API design, documentation, and endpoint implementation.` : ''}\n${flags.mode === 'full' || !flags.mode ? `Full-stack development covering all aspects of the application.` : ''}\n\n`;\n\n const claudeArgs = [enhancedTask];\n claudeArgs.push('--allowedTools', tools);\n\n // DEBUG: Log what we're about to pass\n console.log('\\n๐Ÿ” DEBUG - Command Construction:');\n console.log(`First arg length: ${claudeArgs[0].length} chars`);\n console.log(`First 100 chars: ${claudeArgs[0].substring(0, 100)}...`);\n console.log(`Args count: ${claudeArgs.length}`);\n\n if (flags.noPermissions) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n if (flags.config) {\n claudeArgs.push('--mcp-config', flags.config);\n }\n\n if (flags.verbose) {\n claudeArgs.push('--verbose');\n }\n\n // Execute the actual claude command\n try {\n // Debug: Log the actual command being executed\n if (flags.verbose) {\n console.log('Debug - Executing command:');\n console.log(\n `claude ${claudeArgs.map((arg) => (arg.includes(' ') || arg.includes('\\n') ? `\"${arg}\"` : arg)).join(' ')}`,\n );\n }\n\n const command = new Deno.Command('claude', {\n args: claudeArgs,\n env: {\n ...Deno.env.toObject(),\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: flags.mode || 'full',\n CLAUDE_FLOW_COVERAGE: (flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: flags.commit || 'phase',\n // Add claude-flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdin: 'inherit',\n stdout: 'inherit',\n stderr: 'inherit',\n });\n\n const child = command.spawn();\n const status = await child.status;\n\n if (status.success) {\n printSuccess(`Claude instance ${instanceId} completed successfully`);\n } else {\n printError(`Claude instance ${instanceId} exited with code ${status.code}`);\n }\n } catch (err: unknown) {\n printError(`Failed to spawn Claude: ${(err as Error).message}`);\n console.log('Make sure you have the Claude CLI installed.');\n }\n }\n break;\n\n case 'batch':\n const workflowFile = subArgs[1];\n if (!workflowFile) {\n printError('Usage: claude batch ');\n break;\n }\n printSuccess(`Loading workflow: ${workflowFile}`);\n console.log('๐Ÿ“‹ Batch execution would process workflow file');\n break;\n\n default:\n console.log('Claude commands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n }\n break;\n\n case 'deploy':\n const deployCmd = subArgs[0];\n switch (deployCmd) {\n case 'ha-cluster':\n const nodes = subArgs.find((arg) => arg.includes('--nodes'));\n const regions = subArgs.find((arg) => arg.includes('--regions'));\n const replicationFactor = subArgs.find((arg) => arg.includes('--replication-factor'));\n\n printSuccess('Deploying High Availability Cluster...');\n console.log('๐Ÿ—๏ธ HA Configuration:');\n console.log(` Nodes: ${nodes ? nodes.split('=')[1] : '3'}`);\n console.log(\n ` Regions: ${regions ? regions.split('=')[1] : 'us-east-1,us-west-2,eu-west-1'}`,\n );\n console.log(\n ` Replication Factor: ${replicationFactor ? replicationFactor.split('=')[1] : '2'}`,\n );\n console.log(' Load Balancer: nginx');\n console.log(' Health Checks: comprehensive');\n\n console.log('\\n๐Ÿš€ Deployment Progress:');\n console.log(' โœ“ Provisioning nodes in us-east-1');\n console.log(' โœ“ Provisioning nodes in us-west-2');\n console.log(' โœ“ Provisioning nodes in eu-west-1');\n console.log(' โœ“ Configuring load balancer');\n console.log(' โœ“ Setting up health checks');\n console.log(' โœ“ Establishing replication');\n console.log('\\nโœ… HA cluster deployed successfully!');\n console.log(' Cluster endpoint: https://claude-flow-ha.example.com');\n break;\n\n case 'scaling':\n const scalingAction = subArgs[1];\n\n if (scalingAction === 'configure') {\n printSuccess('Configuring Auto-Scaling...');\n console.log('๐Ÿ“ˆ Scaling Configuration:');\n console.log(' Min Instances: 2');\n console.log(' Max Instances: 50');\n console.log(' Scale Up Threshold: CPU:70%, Memory:80%');\n console.log(' Scale Down Threshold: CPU:30%, Memory:40%');\n console.log(' Cool-down Periods: Up:300s, Down:600s');\n console.log('\\nโœ… Auto-scaling configured');\n } else if (scalingAction === 'predictive') {\n printSuccess('Enabling Predictive Scaling...');\n console.log('๐Ÿ”ฎ Predictive Configuration:');\n console.log(' Forecast Horizon: 1 hour');\n console.log(' Learning Period: 7 days');\n console.log(' Confidence Threshold: 0.8');\n console.log(' ML Model: LSTM-based forecasting');\n console.log('\\nโœ… Predictive scaling enabled');\n } else {\n console.log('Scaling commands: configure, predictive, status');\n }\n break;\n\n case 'security':\n const securityAction = subArgs[1];\n\n if (securityAction === 'harden') {\n printSuccess('Applying Security Hardening...');\n console.log('๐Ÿ”’ Security Configuration:');\n console.log(' Profile: enterprise');\n console.log(' Encryption: all-traffic, at-rest');\n console.log(' Authentication: multi-factor');\n console.log(' Authorization: RBAC');\n console.log(' Audit Logging: comprehensive');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n\n console.log('\\n๐Ÿ›ก๏ธ Applying security measures:');\n console.log(' โœ“ Enabling encryption at rest');\n console.log(' โœ“ Configuring TLS 1.3 minimum');\n console.log(' โœ“ Setting up MFA requirements');\n console.log(' โœ“ Implementing RBAC policies');\n console.log(' โœ“ Enabling audit logging');\n console.log(' โœ“ Applying compliance controls');\n console.log('\\nโœ… Security hardening complete');\n } else if (securityAction === 'monitor') {\n printSuccess('Security Monitoring Active');\n console.log('๐Ÿ” Real-time Security Status:');\n console.log(' Threat Level: Low');\n console.log(' Active Sessions: 42');\n console.log(' Failed Auth Attempts: 3 (last 24h)');\n console.log(' Anomalies Detected: 0');\n console.log(' Compliance Status: โœ… Compliant');\n } else {\n console.log('Security commands: harden, policy, rbac, monitor');\n }\n break;\n\n case 'kubernetes':\n case 'k8s':\n printSuccess('Deploying to Kubernetes...');\n console.log('โ˜ธ๏ธ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Image: claude-flow/orchestrator:latest');\n console.log(' Service Type: LoadBalancer');\n\n console.log('\\n๐Ÿ“ฆ Creating resources:');\n console.log(' โœ“ Created namespace/claude-flow');\n console.log(' โœ“ Created deployment/claude-flow-orchestrator');\n console.log(' โœ“ Created service/claude-flow-orchestrator-service');\n console.log(' โœ“ Created configmap/claude-flow-config');\n console.log(' โœ“ Created secret/claude-flow-secrets');\n console.log('\\nโœ… Kubernetes deployment complete');\n console.log(' Service endpoint: http://a1b2c3d4.elb.amazonaws.com');\n break;\n\n default:\n console.log('Deploy commands:');\n console.log(' ha-cluster - Deploy high availability cluster');\n console.log(' scaling - Configure auto-scaling');\n console.log(' security - Security hardening and monitoring');\n console.log(' kubernetes - Deploy to Kubernetes cluster');\n console.log('\\nExamples:');\n console.log(' deploy ha-cluster --nodes=3 --regions=\"us-east-1,us-west-2\"');\n console.log(' deploy scaling configure --min=2 --max=50');\n console.log(' deploy security harden --profile enterprise');\n }\n break;\n\n case 'analytics':\n const analyticsCmd = subArgs[0];\n switch (analyticsCmd) {\n case 'performance':\n printSuccess('Performance Analytics Report');\n console.log('\\n๐Ÿ“Š System Performance (Last 30 Days):');\n console.log(' Agent Productivity:');\n console.log(' โ€ข Tasks Completed: 12,847');\n console.log(' โ€ข Average Task Time: 3.4 minutes');\n console.log(' โ€ข Success Rate: 94.2%');\n console.log(' Resource Efficiency:');\n console.log(' โ€ข CPU Utilization: 67% average');\n console.log(' โ€ข Memory Usage: 2.8GB average');\n console.log(' โ€ข Cost per Task: $0.024');\n console.log(' Trends:');\n console.log(' โ€ข Performance: โ†‘ 12% improvement');\n console.log(' โ€ข Efficiency: โ†‘ 8% improvement');\n console.log(' โ€ข Costs: โ†“ 15% reduction');\n break;\n\n case 'business-impact':\n printSuccess('Business Impact Analysis');\n console.log('\\n๐Ÿ’ผ Business Metrics:');\n console.log(' Productivity Gains:');\n console.log(' โ€ข Development Velocity: +45%');\n console.log(' โ€ข Time to Market: -30%');\n console.log(' โ€ข Defect Rate: -62%');\n console.log(' Cost Savings:');\n console.log(' โ€ข Monthly Savings: $24,500');\n console.log(' โ€ข ROI: 312%');\n console.log(' โ€ข Payback Period: 3.2 months');\n console.log(' Quality Improvements:');\n console.log(' โ€ข Code Coverage: 92%');\n console.log(' โ€ข Customer Satisfaction: +18%');\n break;\n\n case 'cost':\n const costCmd = subArgs[1];\n if (costCmd === 'analyze') {\n printSuccess('Cost Analysis Report');\n console.log('\\n๐Ÿ’ฐ Cost Breakdown:');\n console.log(' By Project:');\n console.log(' โ€ข microservices-platform: $8,234 (41%)');\n console.log(' โ€ข ai-research: $5,123 (26%)');\n console.log(' โ€ข frontend-apps: $3,456 (17%)');\n console.log(' โ€ข other: $3,187 (16%)');\n console.log(' By Resource:');\n console.log(' โ€ข Compute: $12,450 (62%)');\n console.log(' โ€ข Storage: $4,230 (21%)');\n console.log(' โ€ข Network: $2,120 (11%)');\n console.log(' โ€ข Other: $1,200 (6%)');\n console.log(' Optimization Opportunities:');\n console.log(' โ€ข Use spot instances: Save $3,200/month');\n console.log(' โ€ข Optimize storage: Save $800/month');\n console.log(' โ€ข Schedule off-peak: Save $1,500/month');\n } else {\n console.log('Cost commands: analyze, optimize, budget');\n }\n break;\n\n default:\n console.log('Analytics commands:');\n console.log(' performance - System performance analytics');\n console.log(' business-impact - Business impact analysis');\n console.log(' cost - Cost analysis and optimization');\n console.log(' capacity - Capacity planning');\n console.log('\\nExamples:');\n console.log(' analytics performance --time-range 30d');\n console.log(' analytics cost analyze --granularity project');\n }\n break;\n\n case 'security':\n const securityCmd = subArgs[0];\n switch (securityCmd) {\n case 'status':\n printSuccess('Enterprise Security Status');\n console.log('\\n๐Ÿ” Authentication:');\n console.log(' Method: Token-based (JWT)');\n console.log(' MFA: Enabled (TOTP, SMS, Hardware Keys)');\n console.log(' Sessions: 42 active');\n console.log(' Session Timeout: 4 hours');\n\n console.log('\\n๐Ÿ›ก๏ธ Authorization:');\n console.log(' Model: Role-Based Access Control (RBAC)');\n console.log(' Roles: 5 defined (admin, developer, operator, auditor, viewer)');\n console.log(' Permissions: 47 granular permissions');\n console.log(' Policy Engine: Active');\n\n console.log('\\n๐Ÿšฆ Rate Limiting:');\n console.log(' Global Limit: 1000 req/min');\n console.log(' Per-User Limit: 100 req/min');\n console.log(' Burst Capacity: 200 requests');\n console.log(' Current Usage: 245 req/min (24.5%)');\n\n console.log('\\nโšก Circuit Breakers:');\n console.log(' Total Breakers: 12');\n console.log(' Status: 10 closed, 1 half-open, 1 open');\n console.log(' Last Triggered: api-gateway (2 minutes ago)');\n\n console.log('\\n๐Ÿ“ Audit Logging:');\n console.log(' Status: Active');\n console.log(' Storage: Encrypted S3 bucket');\n console.log(' Retention: 7 years');\n console.log(' Events Today: 48,234');\n console.log(' Compliance: SOC2, GDPR, HIPAA compliant');\n break;\n\n case 'auth':\n const authAction = subArgs[1];\n\n if (authAction === 'configure') {\n printSuccess('Configuring Authentication...');\n console.log('๐Ÿ” Authentication Configuration:');\n console.log(' Method: JWT with RS256');\n console.log(' Token Expiry: 4 hours');\n console.log(' Refresh Token: 30 days');\n console.log(' MFA Required: Yes');\n console.log(' Password Policy:');\n console.log(' โ€ข Minimum length: 12 characters');\n console.log(' โ€ข Complexity: Upper, lower, numbers, symbols');\n console.log(' โ€ข History: Last 12 passwords');\n console.log(' โ€ข Expiry: 90 days');\n console.log('\\nโœ… Authentication configured');\n } else if (authAction === 'sessions') {\n printSuccess('Active Sessions:');\n console.log('\\n๐Ÿ”‘ Current Sessions:');\n console.log('โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”');\n console.log('โ”‚ User โ”‚ Role โ”‚ IP Address โ”‚ Login Time โ”‚ MFA โ”‚');\n console.log('โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค');\n console.log('โ”‚ alice@corp.com โ”‚ admin โ”‚ 10.0.1.45 โ”‚ 2h ago โ”‚ Hardware โ”‚');\n console.log('โ”‚ bob@corp.com โ”‚ developerโ”‚ 10.0.2.123 โ”‚ 45m ago โ”‚ TOTP โ”‚');\n console.log('โ”‚ charlie@corp.comโ”‚ operator โ”‚ 10.0.1.200 โ”‚ 1h ago โ”‚ SMS โ”‚');\n console.log('โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜');\n } else if (authAction === 'mfa') {\n printSuccess('Multi-Factor Authentication Status:');\n console.log(' Enforcement: Required for all users');\n console.log(' Methods Available:');\n console.log(' โ€ข TOTP (Time-based One-Time Password)');\n console.log(' โ€ข SMS (Text message)');\n console.log(' โ€ข Hardware Keys (FIDO2/WebAuthn)');\n console.log(' โ€ข Backup Codes');\n console.log(' Users with MFA: 98% (147/150)');\n } else {\n console.log('Auth commands: configure, sessions, mfa, tokens');\n }\n break;\n\n case 'rbac':\n const rbacAction = subArgs[1];\n\n if (rbacAction === 'roles') {\n printSuccess('RBAC Roles:');\n console.log('\\n๐Ÿ‘ฅ Defined Roles:');\n console.log('\\n๐Ÿ“› admin (3 users)');\n console.log(' Permissions: * (all permissions)');\n console.log(' Conditions: MFA required, IP restriction');\n\n console.log('\\n๐Ÿ“› developer (45 users)');\n console.log(' Permissions:');\n console.log(' โ€ข projects:read,write');\n console.log(' โ€ข agents:spawn,monitor');\n console.log(' โ€ข tasks:create,monitor');\n console.log(' Conditions: Time window 06:00-22:00');\n\n console.log('\\n๐Ÿ“› operator (12 users)');\n console.log(' Permissions:');\n console.log(' โ€ข system:monitor');\n console.log(' โ€ข agents:list,info');\n console.log(' โ€ข tasks:list,status');\n\n console.log('\\n๐Ÿ“› auditor (5 users)');\n console.log(' Permissions:');\n console.log(' โ€ข audit:read');\n console.log(' โ€ข system:logs');\n console.log(' โ€ข reports:generate');\n\n console.log('\\n๐Ÿ“› viewer (85 users)');\n console.log(' Permissions:');\n console.log(' โ€ข *:read (read-only access)');\n } else if (rbacAction === 'assign') {\n const user = subArgs[2];\n const role = subArgs[3];\n if (user && role) {\n printSuccess(`Assigning role ${role} to user ${user}`);\n console.log('โœ… Role assignment complete');\n console.log(' Effective immediately');\n console.log(' Audit log entry created');\n } else {\n printError('Usage: security rbac assign ');\n }\n } else {\n console.log('RBAC commands: roles, permissions, assign, revoke');\n }\n break;\n\n case 'rate-limit':\n const rateLimitAction = subArgs[1];\n\n if (rateLimitAction === 'status') {\n printSuccess('Rate Limiting Status:');\n console.log('\\n๐Ÿ“Š Current Limits:');\n console.log(' Global:');\n console.log(' โ€ข Limit: 1000 requests/minute');\n console.log(' โ€ข Current: 245 requests/minute (24.5%)');\n console.log(' โ€ข Available: 755 requests');\n console.log(' Per-User:');\n console.log(' โ€ข Default: 100 requests/minute');\n console.log(' โ€ข Premium: 500 requests/minute');\n console.log(' Per-Endpoint:');\n console.log(' โ€ข /api/agents/spawn: 10/minute');\n console.log(' โ€ข /api/tasks/create: 50/minute');\n console.log(' โ€ข /api/memory/query: 200/minute');\n\n console.log('\\n๐Ÿšจ Recent Violations:');\n console.log(' โ€ข user123: 2 violations (15 min ago)');\n console.log(' โ€ข api-client-7: 1 violation (1 hour ago)');\n } else if (rateLimitAction === 'configure') {\n printSuccess('Configuring Rate Limits...');\n console.log(' Global limit: 1000 req/min');\n console.log(' Burst capacity: 200 requests');\n console.log(' Cooldown period: 60 seconds');\n console.log(' Headers: X-RateLimit-* enabled');\n console.log('\\nโœ… Rate limiting configured');\n } else {\n console.log('Rate limit commands: status, configure, reset');\n }\n break;\n\n case 'circuit-breaker':\n const cbAction = subArgs[1];\n\n if (cbAction === 'status') {\n printSuccess('Circuit Breaker Status:');\n console.log('\\nโšก Active Circuit Breakers:');\n console.log('โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”');\n console.log('โ”‚ Service โ”‚ State โ”‚ Failures โ”‚ Successes โ”‚ Last Change โ”‚');\n console.log('โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค');\n console.log('โ”‚ api-gateway โ”‚ OPEN โ”‚ 15 โ”‚ 0 โ”‚ 2m ago โ”‚');\n console.log('โ”‚ auth-service โ”‚ CLOSED โ”‚ 0 โ”‚ 1,234 โ”‚ 1h ago โ”‚');\n console.log('โ”‚ memory-service โ”‚ CLOSED โ”‚ 1 โ”‚ 5,678 โ”‚ 3h ago โ”‚');\n console.log('โ”‚ agent-manager โ”‚ HALF โ”‚ 3 โ”‚ 45 โ”‚ 5m ago โ”‚');\n console.log('โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜');\n\n console.log('\\n๐Ÿ“ˆ Configuration:');\n console.log(' Failure Threshold: 10 failures');\n console.log(' Success Threshold: 5 successes');\n console.log(' Timeout: 60 seconds');\n console.log(' Half-Open Requests: 3 max');\n } else if (cbAction === 'reset') {\n const service = subArgs[2];\n if (service) {\n printSuccess(`Resetting circuit breaker: ${service}`);\n console.log('โœ… Circuit breaker reset to CLOSED state');\n } else {\n console.log('All circuit breakers reset');\n }\n } else {\n console.log('Circuit breaker commands: status, reset, configure');\n }\n break;\n\n case 'audit':\n const auditAction = subArgs[1];\n\n if (auditAction === 'status') {\n printSuccess('Audit Logging Status:');\n console.log(' Status: Active');\n console.log(' Storage Backend: AWS S3 (encrypted)');\n console.log(' Retention Period: 7 years');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n console.log('\\n๐Ÿ“Š Statistics (Last 24h):');\n console.log(' Total Events: 48,234');\n console.log(' Authentication: 1,234');\n console.log(' Authorization: 15,678');\n console.log(' Data Access: 23,456');\n console.log(' Configuration Changes: 89');\n console.log(' Security Events: 12');\n } else if (auditAction === 'search') {\n const query = subArgs.slice(2).join(' ');\n printSuccess(`Searching audit logs: \"${query || 'recent'}\"`);\n console.log('\\n๐Ÿ“‹ Recent Audit Events:');\n console.log(\n '2024-01-10 14:23:45 | AUTH_SUCCESS | alice@corp.com | Login from 10.0.1.45',\n );\n console.log('2024-01-10 14:24:12 | PERMISSION_GRANTED | alice@corp.com | agents.spawn');\n console.log('2024-01-10 14:24:13 | AGENT_CREATED | alice@corp.com | agent-12345');\n console.log(\n '2024-01-10 14:25:01 | CONFIG_CHANGED | bob@corp.com | terminal.poolSize: 10->20',\n );\n console.log(\n '2024-01-10 14:26:30 | PERMISSION_DENIED | charlie@corp.com | admin.users.delete',\n );\n } else if (auditAction === 'export') {\n printSuccess('Exporting audit logs...');\n console.log(' Time range: Last 30 days');\n console.log(' Format: JSON (encrypted)');\n console.log(' Destination: audit-export-20240110.json.enc');\n console.log('\\nโœ… Export complete: 145,234 events');\n } else {\n console.log('Audit commands: status, search, export, configure');\n }\n break;\n\n case 'compliance':\n printSuccess('Compliance Status:');\n console.log('\\n๐Ÿ›๏ธ Active Compliance Frameworks:');\n console.log('\\nโœ… SOC2 Type II');\n console.log(' Last Audit: 2023-10-15');\n console.log(' Next Audit: 2024-04-15');\n console.log(' Status: Compliant');\n console.log(' Controls: 89/89 passing');\n\n console.log('\\nโœ… GDPR (General Data Protection Regulation)');\n console.log(' Data Protection Officer: Jane Smith');\n console.log(' Privacy Impact Assessments: 12 completed');\n console.log(' Data Subject Requests: 3 pending, 45 completed');\n console.log(' Status: Compliant');\n\n console.log('\\nโœ… HIPAA (Health Insurance Portability Act)');\n console.log(' BAA Agreements: 5 active');\n console.log(' PHI Encryption: AES-256 at rest, TLS 1.3 in transit');\n console.log(' Access Controls: Implemented');\n console.log(' Status: Compliant');\n\n console.log('\\n๐Ÿ“‹ Required Actions:');\n console.log(' โ€ข Complete Q1 security training (Due: Jan 31)');\n console.log(' โ€ข Update data retention policies (Due: Feb 15)');\n break;\n\n case 'test':\n printSuccess('Running Security Test Suite...');\n console.log('\\n๐Ÿงช Security Tests:');\n console.log(' โœ… Authentication: Token validation working');\n console.log(' โœ… Authorization: RBAC policies enforced');\n console.log(' โœ… Rate Limiting: Limits properly enforced');\n console.log(' โœ… Circuit Breakers: Failing services isolated');\n console.log(' โœ… Audit Logging: All events captured');\n console.log(' โœ… Encryption: TLS 1.3 verified');\n console.log(' โœ… Session Management: Timeouts working');\n console.log(' โš ๏ธ MFA Bypass: 3 users without MFA');\n console.log('\\n๐Ÿ“Š Security Score: 94/100');\n console.log(' Recommendations:');\n console.log(' โ€ข Enforce MFA for all users');\n console.log(' โ€ข Update TLS certificates (expire in 45 days)');\n console.log(' โ€ข Review inactive user accounts');\n break;\n\n default:\n console.log('Security commands:');\n console.log(' status - Show security status overview');\n console.log(' auth - Authentication management');\n console.log(' rbac - Role-based access control');\n console.log(' rate-limit - Rate limiting configuration');\n console.log(' circuit-breaker - Circuit breaker management');\n console.log(' audit - Audit log management');\n console.log(' compliance - Compliance status');\n console.log(' test - Run security tests');\n console.log('\\nExamples:');\n console.log(' security auth configure');\n console.log(' security rbac assign user@example.com developer');\n console.log(' security audit search \"failed login\"');\n console.log(' security circuit-breaker reset api-gateway');\n }\n break;\n\n case 'backup':\n const backupCmd = subArgs[0];\n switch (backupCmd) {\n case 'configure':\n printSuccess('Configuring Backup Strategy...');\n console.log('๐Ÿ—„๏ธ Backup Configuration:');\n console.log(' Strategy: 3-2-1 (3 copies, 2 media, 1 offsite)');\n console.log(' Locations:');\n console.log(' โ€ข Primary: AWS S3 (us-east-1)');\n console.log(' โ€ข Secondary: Azure Blob (eastus)');\n console.log(' โ€ข Tertiary: Local NAS');\n console.log(' Schedule:');\n console.log(' โ€ข Full: Weekly (Sunday 2 AM)');\n console.log(' โ€ข Incremental: Every 6 hours');\n console.log(' โ€ข Differential: Daily (2 AM)');\n console.log(' Encryption: AES-256');\n console.log(' Compression: LZ4');\n console.log(' Verification: Automatic');\n console.log('\\nโœ… Backup strategy configured');\n break;\n\n case 'dr':\n const drAction = subArgs[1];\n if (drAction === 'configure') {\n printSuccess('Configuring Disaster Recovery...');\n console.log('๐Ÿšจ DR Configuration:');\n console.log(' RPO (Recovery Point Objective): 1 hour');\n console.log(' RTO (Recovery Time Objective): 15 minutes');\n console.log(' Replication: Real-time to secondary region');\n console.log(' Failover: Automatic with manual override');\n console.log(' Testing: Monthly DR drills');\n console.log('\\nโœ… Disaster recovery configured');\n } else if (drAction === 'test') {\n printSuccess('Running DR Test...');\n console.log('๐Ÿงช DR Test Progress:');\n console.log(' โœ“ Initiating failover simulation');\n console.log(' โœ“ Switching to DR site');\n console.log(' โœ“ Verifying data integrity');\n console.log(' โœ“ Testing application functionality');\n console.log(' โœ“ Measuring RTO: 12 minutes');\n console.log(' โœ“ Failing back to primary');\n console.log('\\nโœ… DR test completed successfully');\n } else {\n console.log('DR commands: configure, test, status');\n }\n break;\n\n case 'restore':\n const restorePoint = subArgs[1];\n if (!restorePoint) {\n printError('Usage: backup restore ');\n break;\n }\n\n printSuccess(`Restoring from backup: ${restorePoint}`);\n console.log('๐Ÿ”„ Restore Progress:');\n console.log(' โœ“ Located backup in S3');\n console.log(' โœ“ Verifying backup integrity');\n console.log(' โœ“ Downloading backup data');\n console.log(' โœ“ Decrypting backup');\n console.log(' โœ“ Restoring application data');\n console.log(' โœ“ Restoring configuration');\n console.log(' โœ“ Verifying restored data');\n console.log('\\nโœ… Restore completed successfully');\n break;\n\n default:\n console.log('Backup commands:');\n console.log(' configure - Configure backup strategy');\n console.log(' dr - Disaster recovery management');\n console.log(' restore - Restore from backup');\n console.log(' list - List available backups');\n console.log('\\nExamples:');\n console.log(' backup configure --strategy 3-2-1');\n console.log(' backup dr test');\n console.log(' backup restore \"backup-20240110-023000\"');\n }\n break;\n\n default:\n printError(`Unknown command: ${command}`);\n console.log('Run \"claude-flow help\" for available commands');\n\n // Suggest similar commands\n const commonCommands = [\n 'agent',\n 'task',\n 'spawn',\n 'init',\n 'start',\n 'status',\n 'memory',\n 'sparc',\n 'help',\n ];\n const suggestions = commonCommands.filter(\n (cmd) => cmd.startsWith(command.toLowerCase()) || cmd.includes(command.toLowerCase()),\n );\n\n if (suggestions.length > 0) {\n console.log('\\nDid you mean:');\n suggestions.forEach((cmd) => console.log(` claude-flow ${cmd}`));\n }\n\n process.exit(1);\n }\n}\n\n// REPL Implementation\nasync function startRepl() {\n console.log('๐Ÿง  Claude-Flow Interactive Shell v' + VERSION);\n console.log('Type \"help\" for available commands, \"exit\" to quit\\n');\n\n const replState = {\n history: [] as string[],\n historyIndex: -1,\n currentSession: null,\n context: {\n agents: [] as any[],\n tasks: [] as any[],\n terminals: [] as any[],\n memory: {} as Record,\n },\n };\n\n // REPL command handlers\n const replCommands = {\n help: () => {\n console.log(`\n๐Ÿ“š Available REPL Commands:\n \nSystem:\n status - Show system status\n config [key] - Show configuration (or specific key)\n clear - Clear the screen\n history - Show command history\n exit/quit - Exit REPL mode\n\nAgents:\n agent spawn [name] - Spawn new agent\n agent list - List active agents\n agent info - Show agent details\n agent terminate - Terminate agent\n\nTasks:\n task create - Create new task\n task list - List active tasks\n task assign - Assign task to agent\n task status - Show task status\n\nMemory:\n memory store - Store data in memory\n memory get - Retrieve data from memory\n memory list - List all memory keys\n memory clear - Clear all memory\n\nTerminal:\n terminal create [name] - Create terminal session\n terminal list - List terminals\n terminal exec - Execute command\n terminal attach - Attach to terminal\n\nShortcuts:\n ! - Execute shell command\n / - Search command history\n โ†‘/โ†“ - Navigate command history\n`);\n },\n\n status: () => {\n console.log('๐ŸŸข Claude-Flow Status:');\n console.log(` Agents: ${replState.context.agents.length} active`);\n console.log(` Tasks: ${replState.context.tasks.length} in queue`);\n console.log(` Terminals: ${replState.context.terminals.length} active`);\n console.log(` Memory Keys: ${Object.keys(replState.context.memory).length}`);\n },\n\n clear: () => {\n console.clear();\n console.log('๐Ÿง  Claude-Flow Interactive Shell v' + VERSION);\n },\n\n history: () => {\n console.log('๐Ÿ“œ Command History:');\n replState.history.forEach((cmd, i) => {\n console.log(` ${i + 1}: ${cmd}`);\n });\n },\n\n config: async (key: string) => {\n try {\n const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));\n if (key) {\n const keys = key.split('.');\n let value = config;\n for (const k of keys) {\n value = value[k];\n }\n console.log(`${key}: ${JSON.stringify(value, null, 2)}`);\n } else {\n console.log(JSON.stringify(config, null, 2));\n }\n } catch {\n console.log('No configuration file found. Using defaults.');\n }\n },\n };\n\n // Process REPL commands\n async function processReplCommand(input: string) {\n const trimmed = input.trim();\n if (!trimmed) return true;\n\n // Add to history\n replState.history.push(trimmed);\n replState.historyIndex = replState.history.length;\n\n // Handle special commands\n if (trimmed === 'exit' || trimmed === 'quit') {\n console.log('๐Ÿ‘‹ Exiting Claude-Flow REPL...');\n return false;\n }\n\n // Handle shell commands\n if (trimmed.startsWith('!')) {\n const shellCmd = trimmed.substring(1);\n try {\n const command = new Deno.Command('sh', {\n args: ['-c', shellCmd],\n stdout: 'piped',\n stderr: 'piped',\n });\n const { stdout, stderr } = await command.output();\n if (stdout.length > 0) {\n console.log(new TextDecoder().decode(stdout));\n }\n if (stderr.length > 0) {\n console.error(new TextDecoder().decode(stderr));\n }\n } catch (err: unknown) {\n console.error(`Shell error: ${(err as Error).message}`);\n }\n return true;\n }\n\n // Handle search\n if (trimmed.startsWith('/')) {\n const search = trimmed.substring(1);\n const matches = replState.history.filter((cmd) => cmd.includes(search));\n if (matches.length > 0) {\n console.log('๐Ÿ” Search results:');\n matches.forEach((cmd) => console.log(` ${cmd}`));\n } else {\n console.log('No matches found');\n }\n return true;\n }\n\n // Parse command and arguments\n const parts = trimmed.split(' ');\n const command = parts[0];\n const args = parts.slice(1);\n\n // Handle built-in REPL commands\n if (command in replCommands) {\n await (replCommands as any)[command](...args);\n return true;\n }\n\n // Handle multi-word commands\n if (command === 'agent') {\n await handleAgentCommand(args, replState);\n } else if (command === 'task') {\n await handleTaskCommand(args, replState);\n } else if (command === 'memory') {\n await handleMemoryCommand(args, replState);\n } else if (command === 'terminal') {\n await handleTerminalCommand(args, replState);\n } else {\n console.log(`Unknown command: ${command}. Type \"help\" for available commands.`);\n }\n\n return true;\n }\n\n // Agent command handler\n async function handleAgentCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'spawn':\n const type = args[1] || 'researcher';\n const name = args[2] || `agent-${Date.now()}`;\n const agent = {\n id: `agent-${Date.now()}`,\n type,\n name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.agents.push(agent);\n printSuccess(`Spawned ${type} agent: ${name} (${agent.id})`);\n break;\n\n case 'list':\n if (state.context.agents.length === 0) {\n console.log('No active agents');\n } else {\n console.log('Active agents:');\n state.context.agents.forEach((agent: any) => {\n console.log(` ${agent.id} - ${agent.name} (${agent.type}) - ${agent.status}`);\n });\n }\n break;\n\n case 'info':\n const agentId = args[1];\n const foundAgent = state.context.agents.find(\n (a: any) => a.id === agentId || a.name === agentId,\n );\n if (foundAgent) {\n console.log(`Agent: ${foundAgent.name}`);\n console.log(` ID: ${foundAgent.id}`);\n console.log(` Type: ${foundAgent.type}`);\n console.log(` Status: ${foundAgent.status}`);\n console.log(` Created: ${foundAgent.created}`);\n } else {\n printError(`Agent not found: ${agentId}`);\n }\n break;\n\n case 'terminate':\n const termId = args[1];\n const index = state.context.agents.findIndex(\n (a: any) => a.id === termId || a.name === termId,\n );\n if (index >= 0) {\n const removed = state.context.agents.splice(index, 1)[0];\n printSuccess(`Terminated agent: ${removed.name}`);\n } else {\n printError(`Agent not found: ${termId}`);\n }\n break;\n\n default:\n console.log('Agent commands: spawn, list, info, terminate');\n }\n }\n\n // Task command handler\n async function handleTaskCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const type = args[1] || 'general';\n const description = args.slice(2).join(' ') || 'No description';\n const task = {\n id: `task-${Date.now()}`,\n type,\n description,\n status: 'pending',\n created: new Date().toISOString(),\n };\n state.context.tasks.push(task);\n printSuccess(`Created task: ${task.id}`);\n console.log(` Type: ${type}`);\n console.log(` Description: ${description}`);\n break;\n\n case 'list':\n if (state.context.tasks.length === 0) {\n console.log('No active tasks');\n } else {\n console.log('Active tasks:');\n state.context.tasks.forEach((task: any) => {\n console.log(` ${task.id} - ${task.type} - ${task.status}`);\n console.log(` ${task.description}`);\n });\n }\n break;\n\n case 'assign':\n const taskId = args[1];\n const assignAgentId = args[2];\n const foundTask = state.context.tasks.find((t: any) => t.id === taskId);\n const assignAgent = state.context.agents.find(\n (a: any) => a.id === assignAgentId || a.name === assignAgentId,\n );\n\n if (foundTask && assignAgent) {\n foundTask.assignedTo = assignAgent.id;\n foundTask.status = 'assigned';\n printSuccess(`Assigned task ${taskId} to agent ${assignAgent.name}`);\n } else {\n printError('Task or agent not found');\n }\n break;\n\n case 'status':\n const statusId = args[1];\n const statusTask = state.context.tasks.find((t: any) => t.id === statusId);\n if (statusTask) {\n console.log(`Task: ${statusTask.id}`);\n console.log(` Type: ${statusTask.type}`);\n console.log(` Status: ${statusTask.status}`);\n console.log(` Description: ${statusTask.description}`);\n if (statusTask.assignedTo) {\n console.log(` Assigned to: ${statusTask.assignedTo}`);\n }\n console.log(` Created: ${statusTask.created}`);\n } else {\n printError(`Task not found: ${statusId}`);\n }\n break;\n\n default:\n console.log('Task commands: create, list, assign, status');\n }\n }\n\n // Memory command handler\n async function handleMemoryCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'store':\n const key = args[1];\n const value = args.slice(2).join(' ');\n if (key && value) {\n state.context.memory[key] = value;\n printSuccess(`Stored: ${key} = ${value}`);\n } else {\n printError('Usage: memory store ');\n }\n break;\n\n case 'get':\n const getKey = args[1];\n if (getKey && state.context.memory[getKey]) {\n console.log(`${getKey}: ${state.context.memory[getKey]}`);\n } else {\n console.log(`Key not found: ${getKey}`);\n }\n break;\n\n case 'list':\n const keys = Object.keys(state.context.memory);\n if (keys.length === 0) {\n console.log('No data in memory');\n } else {\n console.log('Memory keys:');\n keys.forEach((key) => {\n console.log(` ${key}: ${state.context.memory[key]}`);\n });\n }\n break;\n\n case 'clear':\n state.context.memory = {};\n printSuccess('Memory cleared');\n break;\n\n default:\n console.log('Memory commands: store, get, list, clear');\n }\n }\n\n // Terminal command handler\n async function handleTerminalCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const name = args[1] || `term-${Date.now()}`;\n const terminal = {\n id: name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.terminals.push(terminal);\n printSuccess(`Created terminal: ${name}`);\n break;\n\n case 'list':\n if (state.context.terminals.length === 0) {\n console.log('No active terminals');\n } else {\n console.log('Active terminals:');\n state.context.terminals.forEach((term: any) => {\n console.log(` ${term.id} - ${term.status}`);\n });\n }\n break;\n\n case 'exec':\n const cmd = args.slice(1).join(' ');\n if (cmd) {\n console.log(`Executing: ${cmd}`);\n console.log('(Command execution simulated in REPL)');\n } else {\n printError('Usage: terminal exec ');\n }\n break;\n\n case 'attach':\n const attachId = args[1];\n if (attachId) {\n state.currentSession = attachId;\n console.log(`Attached to terminal: ${attachId}`);\n console.log('(Type \"terminal detach\" to detach)');\n } else {\n printError('Usage: terminal attach ');\n }\n break;\n\n case 'detach':\n if (state.currentSession) {\n console.log(`Detached from terminal: ${state.currentSession}`);\n state.currentSession = null;\n } else {\n console.log('Not attached to any terminal');\n }\n break;\n\n default:\n console.log('Terminal commands: create, list, exec, attach, detach');\n }\n }\n\n // Main REPL loop\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n while (true) {\n // Show prompt\n const prompt = replState.currentSession\n ? `claude-flow:${replState.currentSession}> `\n : 'claude-flow> ';\n await Deno.stdout.write(encoder.encode(prompt));\n\n // Read input\n const buf = new Uint8Array(1024);\n const n = await Deno.stdin.read(buf);\n if (n === null) break;\n\n const input = decoder.decode(buf.subarray(0, n)).trim();\n\n // Process command\n const shouldContinue = await processReplCommand(input);\n if (!shouldContinue) break;\n }\n}\n\n// Helper functions for init command\nfunction createMinimalClaudeMd() {\n return `# Claude Code Integration\n\nThis file provides guidance to Claude when working with this codebase.\n\n## Project Overview\n[Describe your project here]\n\n## Key Conventions\n- Code style guidelines\n- Naming conventions\n- Architecture patterns\n\n## Important Notes\n- Special considerations\n- Areas to be careful with\n`;\n}\n\nfunction createFullClaudeMd() {\n return `# Claude Code Integration Guide\n\nThis document provides comprehensive guidance to Claude when working with this codebase.\n\n## Project Overview\n[Provide a detailed description of your project, its purpose, and main features]\n\n## Architecture\n[Describe the overall architecture, main components, and how they interact]\n\n## Code Conventions\n- **Naming**: [Describe naming conventions for files, functions, variables, etc.]\n- **Style**: [Code formatting preferences, linting rules]\n- **Patterns**: [Design patterns used in the project]\n- **Testing**: [Testing approach and requirements]\n\n## Directory Structure\n\\`\\`\\`\nproject/\nโ”œโ”€โ”€ src/ # Source code\nโ”œโ”€โ”€ tests/ # Test files\nโ”œโ”€โ”€ docs/ # Documentation\nโ””โ”€โ”€ ... # Other directories\n\\`\\`\\`\n\n## Development Workflow\n1. [Step-by-step development process]\n2. [How to run tests]\n3. [How to build/deploy]\n\n## Important Considerations\n- [Security considerations]\n- [Performance requirements]\n- [Compatibility requirements]\n\n## Common Tasks\n- **Add a new feature**: [Instructions]\n- **Fix a bug**: [Process]\n- **Update documentation**: [Guidelines]\n\n## Dependencies\n[List key dependencies and their purposes]\n\n## Troubleshooting\n[Common issues and solutions]\n`;\n}\n\nfunction createMinimalMemoryBankMd() {\n return `# Memory Bank\n\nSession memory and context storage.\n\n## Current Session\n- Started: ${new Date().toISOString()}\n- Context: [Current work context]\n\n## Key Information\n- [Important facts to remember]\n\n## Progress Log\n- [Track progress here]\n`;\n}\n\nfunction createFullMemoryBankMd() {\n return `# Memory Bank\n\nThis file serves as persistent memory storage for Claude across sessions.\n\n## Session Information\n- **Current Session**: Started ${new Date().toISOString()}\n- **Project Phase**: [Development/Testing/Production]\n- **Active Tasks**: [List current tasks]\n\n## Project Context\n### Technical Stack\n- Languages: [List languages used]\n- Frameworks: [List frameworks]\n- Tools: [Development tools]\n\n### Architecture Decisions\n- [Record key architectural decisions]\n- [Rationale for technology choices]\n\n## Important Information\n### API Keys and Secrets\n- [Never store actual secrets here, just references]\n\n### External Services\n- [List integrated services]\n- [Configuration requirements]\n\n### Database Schema\n- [Current schema version]\n- [Recent migrations]\n\n## Progress Tracking\n### Completed Tasks\n- [x] [Completed task 1]\n- [x] [Completed task 2]\n\n### In Progress\n- [ ] [Current task 1]\n- [ ] [Current task 2]\n\n### Upcoming\n- [ ] [Future task 1]\n- [ ] [Future task 2]\n\n## Code Patterns\n### Established Patterns\n\\`\\`\\`javascript\n// Example pattern\n\\`\\`\\`\n\n### Anti-patterns to Avoid\n- [List anti-patterns]\n\n## Meeting Notes\n### [Date]\n- Participants: [Names]\n- Decisions: [Key decisions]\n- Action items: [Tasks assigned]\n\n## Debugging History\n### Issue: [Issue name]\n- **Date**: [Date]\n- **Symptoms**: [What was observed]\n- **Root Cause**: [What caused it]\n- **Solution**: [How it was fixed]\n\n## Performance Metrics\n- [Baseline metrics]\n- [Optimization goals]\n\n## Documentation Links\n- [API Documentation]: [URL]\n- [Design Documents]: [URL]\n- [Issue Tracker]: [URL]\n`;\n}\n\nfunction createMinimalCoordinationMd() {\n return `# Coordination\n\nTask and workflow coordination.\n\n## Active Tasks\n1. [Current task]\n\n## Workflow\n- [ ] Step 1\n- [ ] Step 2\n\n## Resources\n- [Available resources]\n`;\n}\n\nfunction createFullCoordinationMd() {\n return `# Coordination Center\n\nCentral coordination for multi-agent collaboration and task management.\n\n## Active Agents\n| Agent ID | Type | Status | Assigned Tasks | Last Active |\n|----------|------|--------|----------------|-------------|\n| [ID] | [Type] | [Status] | [Tasks] | [Timestamp] |\n\n## Task Queue\n### High Priority\n1. **[Task Name]**\n - Description: [What needs to be done]\n - Assigned to: [Agent ID]\n - Dependencies: [Other tasks]\n - Deadline: [Date/Time]\n\n### Medium Priority\n1. [Task details]\n\n### Low Priority\n1. [Task details]\n\n## Workflow Definitions\n### [Workflow Name]\n\\`\\`\\`yaml\nname: [Workflow Name]\ndescription: [What this workflow does]\nsteps:\n - name: [Step 1]\n agent: [Agent type]\n action: [What to do]\n - name: [Step 2]\n agent: [Agent type]\n action: [What to do]\n depends_on: [Step 1]\n\\`\\`\\`\n\n## Resource Allocation\n### Computational Resources\n- CPU: [Usage/Limits]\n- Memory: [Usage/Limits]\n- Storage: [Usage/Limits]\n\n### External Resources\n- API Rate Limits: [Service: limit]\n- Database Connections: [Current/Max]\n\n## Communication Channels\n### Inter-Agent Messages\n- [Agent A โ†’ Agent B]: [Message type]\n\n### External Communications\n- Webhooks: [Configured webhooks]\n- Notifications: [Notification settings]\n\n## Synchronization Points\n- [Sync Point 1]: [Description]\n- [Sync Point 2]: [Description]\n\n## Conflict Resolution\n### Strategy\n- [How conflicts are resolved]\n\n### Recent Conflicts\n- [Date]: [Conflict description] โ†’ [Resolution]\n\n## Performance Metrics\n### Task Completion\n- Average time: [Time]\n- Success rate: [Percentage]\n\n### Agent Efficiency\n- [Agent Type]: [Metrics]\n\n## Scheduled Maintenance\n- [Date/Time]: [What will be done]\n\n## Emergency Procedures\n### System Overload\n1. [Step 1]\n2. [Step 2]\n\n### Agent Failure\n1. [Recovery procedure]\n`;\n}\n\nfunction createAgentsReadme() {\n return `# Agents Directory\n\nThis directory stores agent-specific memory and state information.\n\n## Structure\nEach agent gets its own subdirectory named by agent ID:\n- \\`agent-001/\\`: First agent's memory\n- \\`agent-002/\\`: Second agent's memory\n- etc.\n\n## Files per Agent\n- \\`profile.json\\`: Agent configuration and capabilities\n- \\`memory.md\\`: Agent's working memory\n- \\`tasks.json\\`: Assigned tasks and their status\n- \\`metrics.json\\`: Performance metrics\n\n## Usage\nFiles in this directory are automatically managed by the Claude-Flow system.\n`;\n}\n\nfunction createSessionsReadme() {\n return `# Sessions Directory\n\nThis directory stores session-specific information and terminal states.\n\n## Structure\nEach session gets a unique directory:\n- \\`session-[timestamp]/\\`: Session data\n - \\`metadata.json\\`: Session metadata\n - \\`terminal.log\\`: Terminal output\n - \\`commands.history\\`: Command history\n - \\`state.json\\`: Session state snapshot\n\n## Retention Policy\nSessions are retained for 30 days by default, then archived or deleted based on configuration.\n\n## Usage\nThe Claude-Flow system automatically manages session files. Do not modify these files manually.\n`;\n}\n\n// Helper function to create SPARC structure manually\nasync function createSparcStructureManually() {\n try {\n // Create .roo directory structure\n const rooDirectories = [\n '.roo',\n '.roo/templates',\n '.roo/workflows',\n '.roo/modes',\n '.roo/configs',\n ];\n\n for (const dir of rooDirectories) {\n try {\n await Deno.mkdir(dir, { recursive: true });\n console.log(` โœ“ Created ${dir}/`);\n } catch (err) {\n if (!(err instanceof Deno.errors.AlreadyExists)) {\n throw err;\n }\n }\n }\n\n // Create .roomodes file (copy from existing if available, or create basic version)\n let roomodesContent;\n try {\n // Check if .roomodes already exists and read it\n roomodesContent = await fs.readFile('.roomodes');\n console.log(' โœ“ Using existing .roomodes configuration');\n } catch {\n // Create basic .roomodes configuration\n roomodesContent = createBasicRoomodesConfig();\n await fs.writeFile('.roomodes', roomodesContent);\n console.log(' โœ“ Created .roomodes configuration');\n }\n\n // Create basic workflow templates\n const basicWorkflow = createBasicSparcWorkflow();\n await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);\n console.log(' โœ“ Created .roo/workflows/basic-tdd.json');\n\n // Create README for .roo directory\n const rooReadme = createRooReadme();\n await fs.writeFile('.roo/README.md', rooReadme);\n console.log(' โœ“ Created .roo/README.md');\n\n console.log(' โœ… Basic SPARC structure created successfully');\n } catch (err: unknown) {\n console.log(` โŒ Failed to create SPARC structure: ${(err as Error).message}`);\n }\n}\n\nfunction createBasicRoomodesConfig() {\n return JSON.stringify(\n {\n customModes: [\n {\n slug: 'architect',\n name: '๐Ÿ—๏ธ Architect',\n roleDefinition:\n 'You design scalable, secure, and modular architectures based on functional specs and user needs. You define responsibilities across services, APIs, and components.',\n customInstructions:\n 'Create architecture mermaid diagrams, data flows, and integration points. Ensure no part of the design includes secrets or hardcoded env values. Emphasize modular boundaries and maintain extensibility.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'code',\n name: '๐Ÿง  Auto-Coder',\n roleDefinition:\n 'You write clean, efficient, modular code based on pseudocode and architecture. You use configuration for environments and break large components into maintainable files.',\n customInstructions:\n 'Write modular code using clean architecture principles. Never hardcode secrets or environment values. Split code into files < 500 lines. Use config files or environment abstractions. Use \\\\`new_task\\\\` for subtasks and finish with \\\\`attempt_completion\\\\`.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'tdd',\n name: '๐Ÿงช Tester (TDD)',\n roleDefinition:\n 'You implement Test-Driven Development (TDD, London School), writing tests first and refactoring after minimal implementation passes.',\n customInstructions:\n 'Write failing tests first. Implement only enough code to pass. Refactor after green. Ensure tests do not hardcode secrets. Keep files < 500 lines.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'spec-pseudocode',\n name: '๐Ÿ“‹ Specification Writer',\n roleDefinition:\n 'You capture full project contextโ€”functional requirements, edge cases, constraintsโ€”and translate that into modular pseudocode with TDD anchors.',\n customInstructions:\n 'Write pseudocode as a series of md files with phase_number_name.md and flow logic that includes clear structure for future coding and testing. Split complex logic across modules.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'integration',\n name: '๐Ÿ”— System Integrator',\n roleDefinition:\n 'You merge the outputs of all modes into a working, tested, production-ready system. You ensure consistency, cohesion, and modularity.',\n customInstructions:\n 'Verify interface compatibility, shared modules, and env config standards. Split integration logic across domains as needed. Use \\\\`new_task\\\\` for preflight testing.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'debug',\n name: '๐Ÿชฒ Debugger',\n roleDefinition:\n 'You troubleshoot runtime bugs, logic errors, or integration failures by tracing, inspecting, and analyzing behavior.',\n customInstructions:\n 'Use logs, traces, and stack analysis to isolate bugs. Avoid changing env configuration directly. Keep fixes modular.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createBasicSparcWorkflow() {\n return JSON.stringify(\n {\n name: 'Basic TDD Workflow',\n description: 'A simple SPARC-based TDD workflow for development',\n sequential: true,\n steps: [\n {\n mode: 'spec-pseudocode',\n description: 'Create detailed specifications and pseudocode',\n phase: 'specification',\n },\n {\n mode: 'tdd',\n description: 'Write failing tests (Red phase)',\n phase: 'red',\n },\n {\n mode: 'code',\n description: 'Implement minimal code to pass tests (Green phase)',\n phase: 'green',\n },\n {\n mode: 'tdd',\n description: 'Refactor and optimize (Refactor phase)',\n phase: 'refactor',\n },\n {\n mode: 'integration',\n description: 'Integrate and verify complete solution',\n phase: 'integration',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createRooReadme() {\n return `# .roo Directory - SPARC Development Environment\n\nThis directory contains the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) development environment configuration and templates.\n\n## Directory Structure\n\n\\`\\`\\`\n.roo/\nโ”œโ”€โ”€ README.md # This file\nโ”œโ”€โ”€ templates/ # Template files for common patterns\nโ”œโ”€โ”€ workflows/ # Predefined SPARC workflows\nโ”‚ โ””โ”€โ”€ basic-tdd.json # Basic TDD workflow\nโ”œโ”€โ”€ modes/ # Custom mode definitions (optional)\nโ””โ”€โ”€ configs/ # Configuration files\n\\`\\`\\`\n\n## SPARC Methodology\n\nSPARC is a systematic approach to software development:\n\n1. **Specification**: Define clear requirements and constraints\n2. **Pseudocode**: Create detailed logic flows and algorithms \n3. **Architecture**: Design system structure and components\n4. **Refinement**: Implement, test, and optimize using TDD\n5. **Completion**: Integrate, document, and validate\n\n## Usage with Claude-Flow\n\nUse the claude-flow SPARC commands to leverage this environment:\n\n\\`\\`\\`bash\n# List available modes\nclaude-flow sparc modes\n\n# Run specific mode\nclaude-flow sparc run code \"implement user authentication\"\n\n# Execute full TDD workflow \nclaude-flow sparc tdd \"payment processing system\"\n\n# Use custom workflow\nclaude-flow sparc workflow .roo/workflows/basic-tdd.json\n\\`\\`\\`\n\n## Configuration\n\nThe main configuration is in \\`.roomodes\\` at the project root. This directory provides additional templates and workflows to support the SPARC development process.\n\n## Customization\n\nYou can customize this environment by:\n- Adding new workflow templates to \\`workflows/\\`\n- Creating mode-specific templates in \\`templates/\\`\n- Adding project-specific configurations in \\`configs/\\`\n\nFor more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nfunction createSparcClaudeMd() {\n return `# Claude Code Configuration - SPARC Development Environment\n\n## Project Overview\nThis project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.\n\n## SPARC Development Commands\n\n### Core SPARC Commands\n- \\`npx claude-flow sparc modes\\`: List all available SPARC development modes\n- \\`npx claude-flow sparc run \"\"\\`: Execute specific SPARC mode for a task\n- \\`npx claude-flow sparc tdd \"\"\\`: Run complete TDD workflow using SPARC methodology\n- \\`npx claude-flow sparc info \\`: Get detailed information about a specific mode\n\n### Standard Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run the test suite\n- \\`npm run lint\\`: Run linter and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n\n## SPARC Methodology Workflow\n\n### 1. Specification Phase\n\\`\\`\\`bash\n# Create detailed specifications and requirements\nnpx claude-flow sparc run spec-pseudocode \"Define user authentication requirements\"\n\\`\\`\\`\n- Define clear functional requirements\n- Document edge cases and constraints\n- Create user stories and acceptance criteria\n- Establish non-functional requirements\n\n### 2. Pseudocode Phase\n\\`\\`\\`bash\n# Develop algorithmic logic and data flows\nnpx claude-flow sparc run spec-pseudocode \"Create authentication flow pseudocode\"\n\\`\\`\\`\n- Break down complex logic into steps\n- Define data structures and interfaces\n- Plan error handling and edge cases\n- Create modular, testable components\n\n### 3. Architecture Phase\n\\`\\`\\`bash\n# Design system architecture and component structure\nnpx claude-flow sparc run architect \"Design authentication service architecture\"\n\\`\\`\\`\n- Create system diagrams and component relationships\n- Define API contracts and interfaces\n- Plan database schemas and data flows\n- Establish security and scalability patterns\n\n### 4. Refinement Phase (TDD Implementation)\n\\`\\`\\`bash\n# Execute Test-Driven Development cycle\nnpx claude-flow sparc tdd \"implement user authentication system\"\n\\`\\`\\`\n\n**TDD Cycle:**\n1. **Red**: Write failing tests first\n2. **Green**: Implement minimal code to pass tests\n3. **Refactor**: Optimize and clean up code\n4. **Repeat**: Continue until feature is complete\n\n### 5. Completion Phase\n\\`\\`\\`bash\n# Integration, documentation, and validation\nnpx claude-flow sparc run integration \"integrate authentication with user management\"\n\\`\\`\\`\n- Integrate all components\n- Perform end-to-end testing\n- Create comprehensive documentation\n- Validate against original requirements\n\n## SPARC Mode Reference\n\n### Development Modes\n- **\\`architect\\`**: System design and architecture planning\n- **\\`code\\`**: Clean, modular code implementation\n- **\\`tdd\\`**: Test-driven development and testing\n- **\\`spec-pseudocode\\`**: Requirements and algorithmic planning\n- **\\`integration\\`**: System integration and coordination\n\n### Quality Assurance Modes\n- **\\`debug\\`**: Troubleshooting and bug resolution\n- **\\`security-review\\`**: Security analysis and vulnerability assessment\n- **\\`refinement-optimization-mode\\`**: Performance optimization and refactoring\n\n### Support Modes\n- **\\`docs-writer\\`**: Documentation creation and maintenance\n- **\\`devops\\`**: Deployment and infrastructure management\n- **\\`mcp\\`**: External service integration\n\n## Code Style and Best Practices\n\n### SPARC Development Principles\n- **Modular Design**: Keep files under 500 lines, break into logical components\n- **Environment Safety**: Never hardcode secrets or environment-specific values\n- **Test-First**: Always write tests before implementation (Red-Green-Refactor)\n- **Clean Architecture**: Separate concerns, use dependency injection\n- **Documentation**: Maintain clear, up-to-date documentation\n\n### Coding Standards\n- Use TypeScript for type safety and better tooling\n- Follow consistent naming conventions (camelCase for variables, PascalCase for classes)\n- Implement proper error handling and logging\n- Use async/await for asynchronous operations\n- Prefer composition over inheritance\n\n### Memory and State Management\n- Use claude-flow memory system for persistent state across sessions\n- Store progress and findings using namespaced keys\n- Query previous work before starting new tasks\n- Export/import memory for backup and sharing\n\n## SPARC Memory Integration\n\n### Memory Commands for SPARC Development\n\\`\\`\\`bash\n# Store project specifications\nnpx claude-flow memory store spec_auth \"User authentication requirements and constraints\"\n\n# Store architectural decisions\nnpx claude-flow memory store arch_decisions \"Database schema and API design choices\"\n\n# Store test results and coverage\nnpx claude-flow memory store test_coverage \"Authentication module: 95% coverage, all tests passing\"\n\n# Query previous work\nnpx claude-flow memory query auth_implementation\n\n# Export project memory\nnpx claude-flow memory export project_backup.json\n\\`\\`\\`\n\n### Memory Namespaces\n- **\\`spec\\`**: Requirements and specifications\n- **\\`arch\\`**: Architecture and design decisions\n- **\\`impl\\`**: Implementation notes and code patterns\n- **\\`test\\`**: Test results and coverage reports\n- **\\`debug\\`**: Bug reports and resolution notes\n\n## Workflow Examples\n\n### Feature Development Workflow\n\\`\\`\\`bash\n# 1. Start with specification\nnpx claude-flow sparc run spec-pseudocode \"User profile management feature\"\n\n# 2. Design architecture\nnpx claude-flow sparc run architect \"Profile service architecture with data validation\"\n\n# 3. Implement with TDD\nnpx claude-flow sparc tdd \"user profile CRUD operations\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"profile data access and validation\"\n\n# 5. Integration testing\nnpx claude-flow sparc run integration \"profile service with authentication system\"\n\n# 6. Documentation\nnpx claude-flow sparc run docs-writer \"profile service API documentation\"\n\\`\\`\\`\n\n### Bug Fix Workflow\n\\`\\`\\`bash\n# 1. Debug and analyze\nnpx claude-flow sparc run debug \"authentication token expiration issue\"\n\n# 2. Write regression tests\nnpx claude-flow sparc run tdd \"token refresh mechanism tests\"\n\n# 3. Implement fix\nnpx claude-flow sparc run code \"fix token refresh in authentication service\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"token handling security implications\"\n\\`\\`\\`\n\n## Configuration Files\n\n### SPARC Configuration\n- **\\`.roomodes\\`**: SPARC mode definitions and configurations\n- **\\`.roo/\\`**: Templates, workflows, and mode-specific rules\n\n### Claude-Flow Configuration\n- **\\`memory/\\`**: Persistent memory and session data\n- **\\`coordination/\\`**: Multi-agent coordination settings\n\n## Git Workflow Integration\n\n### Commit Strategy with SPARC\n- **Specification commits**: After completing requirements analysis\n- **Architecture commits**: After design phase completion\n- **TDD commits**: After each Red-Green-Refactor cycle\n- **Integration commits**: After successful component integration\n- **Documentation commits**: After completing documentation updates\n\n### Branch Strategy\n- **\\`feature/sparc-\\`**: Feature development with SPARC methodology\n- **\\`hotfix/sparc-\\`**: Bug fixes using SPARC debugging workflow\n- **\\`refactor/sparc-\\`**: Refactoring using optimization mode\n\n## Troubleshooting\n\n### Common SPARC Issues\n- **Mode not found**: Check \\`.roomodes\\` file exists and is valid JSON\n- **Memory persistence**: Ensure \\`memory/\\` directory has write permissions\n- **Tool access**: Verify required tools are available for the selected mode\n- **Namespace conflicts**: Use unique memory namespaces for different features\n\n### Debug Commands\n\\`\\`\\`bash\n# Check SPARC configuration\nnpx claude-flow sparc modes\n\n# Verify memory system\nnpx claude-flow memory stats\n\n# Check system status\nnpx claude-flow status\n\n# View detailed mode information\nnpx claude-flow sparc info \n\\`\\`\\`\n\n## Project Architecture\n\nThis SPARC-enabled project follows a systematic development approach:\n- **Clear separation of concerns** through modular design\n- **Test-driven development** ensuring reliability and maintainability\n- **Iterative refinement** for continuous improvement\n- **Comprehensive documentation** for team collaboration\n- **AI-assisted development** through specialized SPARC modes\n\n## Important Notes\n\n- Always run tests before committing (\\`npm run test\\`)\n- Use SPARC memory system to maintain context across sessions\n- Follow the Red-Green-Refactor cycle during TDD phases\n- Document architectural decisions in memory for future reference\n- Regular security reviews for any authentication or data handling code\n\nFor more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\n// Run main if executed directly\nif (import.meta.url === `file://${process.argv[1]}`) {\n await main();\n}\n"],"names":["promises","fs","executeCommand","hasCommand","showCommandHelp","listCommands","parseFlags","VERSION","printHelp","console","log","printVersion","printError","message","error","printSuccess","printWarning","warn","showHelpWithCommands","commands","command","name","padEnd","description","main","args","Deno","length","flags","parsedArgs","slice","err","subArgs","spawnType","spawnName","Date","now","terminalCmd","poolCmd","detailed","includes","process","cwd","termId","nameIndex","indexOf","shellIndex","wdIndex","envIndex","persistentIndex","terminalConfig","shell","workingDirectory","env","persistent","execCmd","join","sessionFlag","timeoutFlag","backgroundFlag","sessionId","cmdStart","cmdEnd","lastIndexOf","batchSession","find","arg","startsWith","commandsFlag","fileFlag","split","forEach","cmd","i","listDetailed","infoSessionId","attachId","detachId","terminateId","graceful","idleTime","monitorId","recordId","outputFlag","replayFile","shareId","accessLevel","multiCmd","configName","envName","configFile","sessionCmd","workflowFile","startRepl","projectCmd","projectName","isolationFlag","resourceQuotaFlag","securityProfileFlag","templateFlag","switchProject","showActive","withStats","projects","status","agents","tasks","project","configAction","configProject","configKey","configValue","monitorProject","backupProject","includeData","includeConfig","includeHistory","outputFile","shareFrom","shareTo","agentsFlag","permissionsFlag","durationFlag","fedCmd","fedName","projectsFlag","cloudCmd","cloudProvider","awsServices","awsRegions","awsHA","awsCostOpt","azureServices","azureRegions","azureIntegration","gcpServices","gcpRegions","multiCloud","multiCloudCmd","failoverTarget","k8sCmd","replicas","claudeCmd","taskEndIndex","task","tools","noPermissions","config","mode","parallel","research","coverage","parseInt","commit","verbose","dryRun","instanceId","Math","random","toString","substr","enhancedTask","claudeArgs","push","substring","map","Command","toObject","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdin","stdout","stderr","child","spawn","success","code","deployCmd","nodes","regions","replicationFactor","scalingAction","securityAction","analyticsCmd","costCmd","securityCmd","authAction","rbacAction","user","role","rateLimitAction","cbAction","service","auditAction","query","backupCmd","drAction","restorePoint","commonCommands","suggestions","filter","toLowerCase","exit","replState","history","historyIndex","currentSession","context","terminals","memory","replCommands","help","Object","keys","clear","key","JSON","parse","readFile","value","k","stringify","processReplCommand","input","trimmed","trim","shellCmd","output","TextDecoder","decode","search","matches","parts","handleAgentCommand","handleTaskCommand","handleMemoryCommand","handleTerminalCommand","state","subCmd","type","agent","id","created","toISOString","agentId","foundAgent","a","index","findIndex","removed","splice","taskId","assignAgentId","foundTask","t","assignAgent","assignedTo","statusId","statusTask","getKey","terminal","term","decoder","encoder","TextEncoder","prompt","write","encode","buf","Uint8Array","n","read","subarray","shouldContinue","createMinimalClaudeMd","createFullClaudeMd","createMinimalMemoryBankMd","createFullMemoryBankMd","createMinimalCoordinationMd","createFullCoordinationMd","createAgentsReadme","createSessionsReadme","createSparcStructureManually","rooDirectories","dir","mkdir","recursive","errors","AlreadyExists","roomodesContent","createBasicRoomodesConfig","writeFile","basicWorkflow","createBasicSparcWorkflow","rooReadme","createRooReadme","customModes","slug","roleDefinition","customInstructions","groups","source","sequential","steps","phase","createSparcClaudeMd","url","argv"],"mappings":";AAMA,SAASA,YAAYC,EAAE,QAAQ,UAAU;AACzC,SACEC,cAAc,EACdC,UAAU,EACVC,eAAe,EAEfC,YAAY,QACP,wBAAwB;AAC/B,SAASC,UAAU,QAAQ,aAAa;AACxC,SAASC,OAAO,QAAQ,q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AAM;gBACN7H,aAAa;gBACb+R,OAAO;YACT;YACA;gBACElK,MAAM;gBACN7H,aAAa;gBACb+R,OAAO;YACT;YACA;gBACElK,MAAM;gBACN7H,aAAa;gBACb+R,OAAO;YACT;YACA;gBACElK,MAAM;gBACN7H,aAAa;gBACb+R,OAAO;YACT;YACA;gBACElK,MAAM;gBACN7H,aAAa;gBACb+R,OAAO;YACT;SACD;IACH,GACA,MACA;AAEJ;AAEA,SAAST;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDV,CAAC;AACD;AAEA,SAASU;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoPV,CAAC;AACD;AAGA,IAAI,YAAYC,GAAG,KAAK,CAAC,OAAO,EAAE/Q,QAAQgR,IAAI,CAAC,EAAE,EAAE,EAAE;IACnD,MAAMjS;AACR"} \ No newline at end of file diff --git a/dist-cjs/src/cli/simple-commands/hive-mind.js b/dist-cjs/src/cli/simple-commands/hive-mind.js index 184036708b..0a5c66a6ae 100644 --- a/dist-cjs/src/cli/simple-commands/hive-mind.js +++ b/dist-cjs/src/cli/simple-commands/hive-mind.js @@ -1669,6 +1669,14 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, console.log(chalk.gray('\nFalling back to displaying instructions...')); } if (claudeAvailable && !flags.dryRun) { + try { + const { injectMemoryProtocol, enhanceHiveMindPrompt } = await import('./inject-memory-protocol.js'); + await injectMemoryProtocol(); + hiveMindPrompt = enhanceHiveMindPrompt(hiveMindPrompt, workers); + console.log(chalk.green('๐Ÿ“ Memory coordination protocol injected into CLAUDE.md')); + } catch (err) { + console.log(chalk.yellow('โš ๏ธ Memory protocol injection not available, using standard prompt')); + } const isNonInteractive = flags['non-interactive'] || flags.nonInteractive; const claudeArgs = []; if (isNonInteractive) { diff --git a/dist-cjs/src/cli/simple-commands/hive-mind.js.map b/dist-cjs/src/cli/simple-commands/hive-mind.js.map index 04cf42c5ee..6479f2c98f 100644 --- a/dist-cjs/src/cli/simple-commands/hive-mind.js.map +++ b/dist-cjs/src/cli/simple-commands/hive-mind.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence\nimport Database from 'better-sqlite3';\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('๐Ÿง  Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('๐Ÿ')} Queen-led coordination with worker specialization\n ${chalk.cyan('๐Ÿง ')} Collective memory and knowledge sharing\n ${chalk.cyan('๐Ÿค')} Consensus building for critical decisions\n ${chalk.cyan('โšก')} Parallel task execution with auto-scaling\n ${chalk.cyan('๐Ÿ”„')} Work stealing and load balancing\n ${chalk.cyan('๐Ÿ“Š')} Real-time metrics and performance tracking\n ${chalk.cyan('๐Ÿ›ก๏ธ')} Fault tolerance and self-healing\n ${chalk.cyan('๐Ÿ”’')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type Queen coordinator type (strategic, tactical, adaptive)\n --max-workers Maximum worker agents (default: 8)\n --consensus Consensus algorithm (majority, weighted, byzantine)\n --memory-size Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind system...').start();\n\n try {\n // Create hive mind directory structure\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n if (!existsSync(hiveMindDir)) {\n mkdirSync(hiveMindDir, { recursive: true });\n }\n\n // Initialize SQLite database\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const db = new Database(dbPath);\n\n // Create tables\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n queen_type TEXT DEFAULT 'strategic',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n `);\n\n db.close();\n\n // Create configuration file\n const config = {\n version: '2.0.0',\n initialized: new Date().toISOString(),\n defaults: {\n queenType: 'strategic',\n maxWorkers: 8,\n consensusAlgorithm: 'majority',\n memorySize: 100,\n autoScale: true,\n encryption: false,\n },\n mcpTools: {\n enabled: true,\n parallel: true,\n timeout: 60000,\n },\n };\n\n await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));\n\n spinner.succeed('Hive Mind system initialized successfully!');\n\n console.log('\\n' + chalk.green('โœ“') + ' Created .hive-mind directory');\n console.log(chalk.green('โœ“') + ' Initialized SQLite database');\n console.log(chalk.green('โœ“') + ' Created configuration file');\n console.log('\\n' + chalk.yellow('Next steps:'));\n console.log(\n ' 1. Run ' + chalk.cyan('claude-flow hive-mind spawn') + ' to create your first swarm',\n );\n console.log(\n ' 2. Use ' + chalk.cyan('claude-flow hive-mind wizard') + ' for interactive setup',\n );\n } catch (error) {\n spinner.fail('Failed to initialize Hive Mind system');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Interactive wizard for hive mind operations\n */\n// Wrapped wizard function that handles non-interactive environments\nconst hiveMindWizard = safeInteractive(\n // Interactive version\n async function (flags = {}) {\n console.log(chalk.yellow('\\n๐Ÿง™ Hive Mind Interactive Wizard\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: '๐Ÿ Create new swarm', value: 'spawn' },\n { name: '๐Ÿ“Š View swarm status', value: 'status' },\n { name: '๐Ÿง  Manage collective memory', value: 'memory' },\n { name: '๐Ÿค View consensus decisions', value: 'consensus' },\n { name: '๐Ÿ“ˆ Performance metrics', value: 'metrics' },\n { name: '๐Ÿ”ง Configure hive mind', value: 'config' },\n { name: 'โŒ Exit', value: 'exit' },\n ],\n },\n ]);\n\n switch (action) {\n case 'spawn':\n await spawnSwarmWizard();\n break;\n case 'status':\n await showStatus({});\n break;\n case 'memory':\n await manageMemoryWizard();\n break;\n case 'consensus':\n await showConsensus({});\n break;\n case 'metrics':\n await showMetrics({});\n break;\n case 'config':\n await configureWizard();\n break;\n case 'exit':\n console.log(chalk.gray('Exiting wizard...'));\n break;\n }\n },\n // Non-interactive fallback\n async function (flags = {}) {\n console.log(chalk.yellow('\\n๐Ÿง™ Hive Mind - Non-Interactive Mode\\n'));\n\n // Default to creating a swarm with sensible defaults\n console.log(chalk.cyan('Creating new swarm with default settings...'));\n console.log(chalk.gray('Use command-line flags to customize:'));\n console.log(chalk.gray(' --objective \"Your task\" Set swarm objective'));\n console.log(chalk.gray(' --queen-type strategic Set queen type'));\n console.log(chalk.gray(' --max-workers 8 Set worker count'));\n console.log();\n\n const objective = flags.objective || 'General task coordination';\n const config = {\n name: flags.name || `swarm-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale || flags['auto-scale'] || false,\n namespace: flags.namespace || 'default',\n verbose: flags.verbose || false,\n encryption: flags.encryption || false,\n };\n\n await spawnSwarm([objective], {\n ...flags,\n name: config.name,\n queenType: config.queenType,\n maxWorkers: config.maxWorkers,\n consensusAlgorithm: config.consensusAlgorithm,\n autoScale: config.autoScale,\n encryption: config.encryption,\n nonInteractive: true,\n });\n },\n);\n\n/**\n * Spawn swarm wizard\n */\nasync function spawnSwarmWizard() {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'objective',\n message: 'What is the swarm objective?',\n validate: (input) => input.trim().length > 0 || 'Please enter an objective',\n },\n {\n type: 'input',\n name: 'name',\n message: 'Swarm name (optional):',\n default: (answers) => `swarm-${Date.now()}`,\n },\n {\n type: 'list',\n name: 'queenType',\n message: 'Select queen coordinator type:',\n choices: [\n { name: 'Strategic - High-level planning and coordination', value: 'strategic' },\n { name: 'Tactical - Detailed task management', value: 'tactical' },\n { name: 'Adaptive - Learns and adapts strategies', value: 'adaptive' },\n ],\n default: 'strategic',\n },\n {\n type: 'number',\n name: 'maxWorkers',\n message: 'Maximum number of worker agents:',\n default: 8,\n validate: (input) => (input > 0 && input <= 20) || 'Please enter a number between 1 and 20',\n },\n {\n type: 'checkbox',\n name: 'workerTypes',\n message: 'Select worker agent types:',\n choices: [\n { name: 'Researcher', value: 'researcher', checked: true },\n { name: 'Coder', value: 'coder', checked: true },\n { name: 'Analyst', value: 'analyst', checked: true },\n { name: 'Tester', value: 'tester', checked: true },\n { name: 'Architect', value: 'architect' },\n { name: 'Reviewer', value: 'reviewer' },\n { name: 'Optimizer', value: 'optimizer' },\n { name: 'Documenter', value: 'documenter' },\n ],\n },\n {\n type: 'list',\n name: 'consensusAlgorithm',\n message: 'Consensus algorithm for decisions:',\n choices: [\n { name: 'Majority - Simple majority voting', value: 'majority' },\n { name: 'Weighted - Expertise-weighted voting', value: 'weighted' },\n { name: 'Byzantine - Fault-tolerant consensus', value: 'byzantine' },\n ],\n default: 'majority',\n },\n {\n type: 'confirm',\n name: 'autoScale',\n message: 'Enable auto-scaling?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'monitor',\n message: 'Launch monitoring dashboard?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'spawnClaude',\n message: 'Spawn Claude Code instance with hive-mind coordination?',\n default: true,\n },\n ]);\n\n // Spawn the swarm with collected parameters\n const swarmResult = await spawnSwarm([answers.objective], {\n name: answers.name,\n queenType: answers.queenType,\n 'queen-type': answers.queenType,\n maxWorkers: answers.maxWorkers,\n 'max-workers': answers.maxWorkers,\n workerTypes: answers.workerTypes.join(','),\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n 'auto-scale': answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false,\n spawnClaude: answers.spawnClaude, // Pass the Claude spawning preference\n });\n\n // If Claude Code spawning was requested, launch it using the same function as --claude flag\n if (answers.spawnClaude && swarmResult && swarmResult.swarmId) {\n // Create workers array in the same format expected by spawnClaudeCodeInstances\n const workers = answers.workerTypes.map((type, index) => ({\n id: `worker-${index + 1}`,\n type,\n role: 'worker',\n status: 'active',\n capabilities: getAgentCapabilities(type)\n }));\n \n // Create flags object with the wizard settings\n const claudeFlags = {\n queenType: answers.queenType,\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false\n };\n \n // Use the same Claude spawning function as the --claude flag\n console.log(chalk.cyan(`\\n๐ŸŽฏ Objective from wizard: \"${answers.objective}\"`));\n await spawnClaudeCodeInstances(\n swarmResult.swarmId,\n answers.name,\n answers.objective,\n workers,\n claudeFlags\n );\n }\n \n return swarmResult;\n}\n\n/**\n * Spawn a hive mind swarm\n */\nasync function spawnSwarm(args, flags) {\n const objective = args.join(' ').trim();\n\n // Check for non-interactive mode FIRST\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n if (!objective && !flags.wizard) {\n if (isNonInteractive) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n } else {\n console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));\n console.log('Example: claude-flow hive-mind spawn \"Build REST API\"');\n }\n return;\n }\n \n // Log non-interactive mode status\n if (isNonInteractive && flags.verbose) {\n console.log(chalk.cyan('๐Ÿค– Running in non-interactive mode'));\n }\n\n // Validate parameters\n if (flags.verbose) {\n console.log(chalk.gray('๐Ÿ” Debug: Parsed flags:'));\n console.log(chalk.gray(JSON.stringify(flags, null, 2)));\n }\n\n // Validate queen type\n const validQueenTypes = ['strategic', 'tactical', 'adaptive'];\n const queenType = flags.queenType || flags['queen-type'] || 'strategic';\n if (!validQueenTypes.includes(queenType)) {\n console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));\n return;\n }\n\n // Validate max workers\n const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');\n if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {\n console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));\n return;\n }\n\n // Validate consensus algorithm\n const validConsensusTypes = ['majority', 'weighted', 'byzantine'];\n const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';\n if (!validConsensusTypes.includes(consensusAlgorithm)) {\n console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));\n return;\n }\n\n const spinner = ora('Spawning Hive Mind swarm...').start();\n\n try {\n // Initialize hive mind core with error handling\n let hiveMind;\n try {\n spinner.text = 'Initializing Hive Mind Core...';\n hiveMind = new HiveMindCore({\n objective,\n name: flags.name || `hive-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale !== undefined ? flags.autoScale : (flags['auto-scale'] !== undefined ? flags['auto-scale'] : true),\n namespace: flags.namespace || 'default',\n encryption: flags.encryption || false,\n });\n } catch (error) {\n console.error('HiveMindCore initialization failed:', error);\n throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);\n }\n\n spinner.text = 'Setting up database connection...';\n // Initialize database connection\n const dbDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(dbDir, 'hive.db');\n\n // Ensure .hive-mind directory exists\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Check if database file exists and try to create a clean one if needed\n let db;\n try {\n spinner.text = 'Creating database connection...';\n db = new Database(dbPath);\n // Test the database with a simple query\n db.prepare('SELECT 1').get();\n spinner.text = 'Database connection established';\n } catch (error) {\n console.warn('Database issue detected, recreating...', error.message);\n spinner.text = 'Recreating database...';\n // Remove corrupted database\n if (existsSync(dbPath)) {\n try {\n const fs = await import('fs');\n fs.unlinkSync(dbPath);\n } catch (e) {\n console.warn('Could not remove corrupted database:', e.message);\n }\n }\n // Create new database\n db = new Database(dbPath);\n }\n\n // Initialize database schema if not exists\n spinner.text = 'Creating database schema...';\n try {\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n queen_type TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT NOT NULL,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n swarm_name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n paused_at DATETIME,\n resumed_at DATETIME,\n completion_percentage REAL DEFAULT 0,\n checkpoint_data TEXT,\n metadata TEXT,\n parent_pid INTEGER,\n child_pids TEXT,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_checkpoints (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n checkpoint_name TEXT NOT NULL,\n checkpoint_data TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_logs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\n log_level TEXT DEFAULT 'info',\n message TEXT,\n agent_id TEXT,\n data TEXT,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n `);\n spinner.text = 'Database schema created successfully';\n } catch (error) {\n console.error('Database schema creation failed:', error);\n throw new Error(`Failed to create database schema: ${error.message}`);\n }\n\n // Create swarm record with safe ID generation\n spinner.text = 'Creating swarm record...';\n const timestamp = Date.now();\n const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr\n const swarmId = `swarm-${timestamp}-${randomPart}`;\n try {\n db.prepare(\n `\n INSERT INTO swarms (id, name, objective, queen_type)\n VALUES (?, ?, ?, ?)\n `,\n ).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);\n } catch (error) {\n console.error('Failed to create swarm record:', error);\n throw new Error(`Failed to create swarm record: ${error.message}`);\n }\n\n // Create session for this swarm\n spinner.text = 'Creating session tracking...';\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {\n queenType: hiveMind.config.queenType,\n maxWorkers: hiveMind.config.maxWorkers,\n consensusAlgorithm: hiveMind.config.consensusAlgorithm,\n autoScale: hiveMind.config.autoScale,\n encryption: hiveMind.config.encryption,\n workerTypes: flags.workerTypes,\n });\n\n spinner.text = 'Session tracking established...';\n\n // Initialize auto-save middleware (use the same session manager)\n const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {\n saveInterval: 30000, // Save every 30 seconds\n autoStart: true,\n });\n\n // Close session manager after auto-save is set up\n // sessionManager.close(); // Don't close yet as auto-save needs it\n\n // Track initial swarm creation\n autoSave.trackChange('swarm_created', {\n swarmId,\n swarmName: hiveMind.config.name,\n objective,\n workerCount: hiveMind.config.maxWorkers,\n });\n\n spinner.text = 'Initializing Queen coordinator...';\n\n // Initialize Queen\n const queen = new QueenCoordinator({\n swarmId,\n type: hiveMind.config.queenType,\n objective,\n });\n\n // Spawn Queen agent\n const queenAgent = {\n id: `queen-${swarmId}`,\n swarmId,\n name: 'Queen Coordinator',\n type: 'coordinator',\n role: 'queen',\n status: 'active',\n capabilities: JSON.stringify(['coordination', 'planning', 'decision-making']),\n };\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(queenAgent));\n\n spinner.text = 'Spawning worker agents...';\n\n // Determine worker types\n const workerTypes = flags.workerTypes\n ? flags.workerTypes.split(',')\n : ['researcher', 'coder', 'analyst', 'tester'];\n\n // Spawn worker agents\n const workers = [];\n for (let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++) {\n const workerType = workerTypes[i % workerTypes.length];\n const workerId = `worker-${swarmId}-${i}`;\n\n const worker = {\n id: workerId,\n swarmId,\n name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,\n type: workerType,\n role: 'worker',\n status: 'idle',\n capabilities: JSON.stringify(getAgentCapabilities(workerType)),\n };\n\n workers.push(worker);\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(worker));\n\n // Track agent spawning for auto-save\n autoSave.trackAgentActivity(workerId, 'spawned', {\n type: workerType,\n name: worker.name,\n });\n }\n\n spinner.text = 'Initializing collective memory...';\n\n // Initialize collective memory\n const memory = new CollectiveMemory({\n swarmId,\n maxSize: flags.memorySize || 100,\n });\n\n // Store initial context\n memory.store('objective', objective, 'context');\n memory.store('queen_type', hiveMind.config.queenType, 'config');\n memory.store('worker_count', workers.length, 'metrics');\n memory.store('session_id', sessionId, 'system');\n\n spinner.text = 'Establishing communication channels...';\n\n // Initialize communication system\n const communication = new SwarmCommunication({\n swarmId,\n encryption: hiveMind.config.encryption,\n });\n\n db.close();\n\n spinner.succeed('Hive Mind swarm spawned successfully!');\n\n // Display swarm summary\n console.log('\\n' + chalk.bold('๐Ÿ Swarm Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Name:'), hiveMind.config.name);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);\n console.log(chalk.cyan('Workers:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));\n console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);\n console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n // Launch monitoring if requested\n if (flags.monitor) {\n console.log('\\n' + chalk.yellow('Launching monitoring dashboard...'));\n // TODO: Implement monitoring dashboard\n }\n\n // Enhanced coordination instructions with MCP tools\n console.log('\\n' + chalk.green('โœ“') + ' Swarm is ready for coordination');\n console.log(chalk.gray('Use \"claude-flow hive-mind status\" to view swarm activity'));\n console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));\n console.log(chalk.blue('๐Ÿ’ก To pause:') + ' Press Ctrl+C to safely pause and resume later');\n console.log(chalk.blue('๐Ÿ’ก To resume:') + ' claude-flow hive-mind resume ' + sessionId);\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session...'));\n \n try {\n // Save current checkpoint using the existing session manager\n // const sessionManager = new HiveMindSessionManager(); // Use existing one\n \n // Create checkpoint data\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n workerCount: workers.length,\n workerTypes,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C',\n };\n \n // Save checkpoint\n await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);\n \n // Pause the session\n await sessionManager.pauseSession(sessionId);\n \n // Close session manager\n sessionManager.close();\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n // Clean up auto-save if active\n if (global.autoSaveInterval) {\n clearInterval(global.autoSaveInterval);\n }\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Offer to spawn Claude Code instances with coordination instructions\n // Spawn Claude if --claude or --spawn flag is set\n if (flags.claude || flags.spawn) {\n await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);\n } else {\n console.log(\n '\\n' +\n chalk.blue('๐Ÿ’ก Pro Tip:') +\n ' Add --claude to spawn coordinated Claude Code instances',\n );\n console.log(chalk.gray(' claude-flow hive-mind spawn \"objective\" --claude'));\n }\n\n // Return swarm info for wizard use\n return { swarmId, hiveMind };\n } catch (error) {\n spinner.fail('Failed to spawn Hive Mind swarm');\n console.error(chalk.red('Error:'), error.message);\n\n // If error contains \"sha3\", provide specific guidance\n if (error.message.includes('sha3') || error.message.includes('SHA3')) {\n console.error('\\n๐Ÿ” SHA3 Function Error Detected');\n console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');\n console.error('\\nPossible solutions:');\n console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');\n console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');\n console.error('3. Check if any SQLite extensions are conflicting');\n console.error('\\n๐Ÿšจ Detailed error:');\n console.error(error.stack || error.message);\n }\n\n exit(1);\n }\n}\n\n/**\n * Get agent capabilities based on type\n */\nfunction getAgentCapabilities(type) {\n const capabilities = {\n researcher: ['web-search', 'data-gathering', 'analysis', 'synthesis'],\n coder: ['code-generation', 'implementation', 'refactoring', 'debugging'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting', 'visualization'],\n tester: ['test-generation', 'quality-assurance', 'bug-detection', 'validation'],\n architect: ['system-design', 'architecture', 'planning', 'documentation'],\n reviewer: ['code-review', 'quality-check', 'feedback', 'improvement'],\n optimizer: ['performance-tuning', 'optimization', 'profiling', 'enhancement'],\n documenter: ['documentation', 'explanation', 'tutorial-creation', 'knowledge-base'],\n };\n\n return capabilities[type] || ['general'];\n}\n\n/**\n * Show hive mind status\n */\nasync function showStatus(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n\n if (!existsSync(dbPath)) {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Use the metrics reader for real data\n const metricsReader = new HiveMindMetricsReader(dbPath);\n const swarms = metricsReader.getActiveSwarms();\n\n if (swarms.length === 0) {\n console.log(chalk.gray('No active swarms found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿ Active Hive Mind Swarms\\n'));\n\n for (const swarm of swarms) {\n console.log(chalk.yellow('โ•'.repeat(60)));\n console.log(chalk.cyan('Swarm:'), swarm.name);\n console.log(chalk.cyan('ID:'), swarm.id);\n console.log(chalk.cyan('Objective:'), swarm.objective);\n console.log(chalk.cyan('Queen Type:'), swarm.queen_type);\n console.log(chalk.cyan('Status:'), chalk.green(swarm.status));\n console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());\n \n // Show real agent count\n console.log(chalk.cyan('Total Agents:'), swarm.agent_count || 0);\n\n console.log('\\n' + chalk.bold('Agents:'));\n\n // Group by role using real agent data\n const agents = swarm.agents || [];\n const queen = agents.find((a) => a.role === 'queen');\n const workers = agents.filter((a) => a.role === 'worker');\n\n if (queen) {\n console.log(' ' + chalk.magenta('๐Ÿ‘‘ Queen:'), queen.name, chalk.gray(`(${queen.status})`));\n } else {\n console.log(' ' + chalk.gray('No queen assigned yet'));\n }\n\n console.log(' ' + chalk.blue('๐Ÿ Workers:'));\n if (workers.length > 0) {\n workers.forEach((worker) => {\n const statusColor =\n worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';\n console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);\n });\n } else {\n console.log(' ' + chalk.gray('No workers spawned yet'));\n }\n\n // Get real task statistics\n const taskStats = swarm.task_metrics || {\n total: 0,\n completed: 0,\n in_progress: 0,\n pending: 0,\n failed: 0\n };\n\n console.log('\\n' + chalk.bold('Tasks:'));\n console.log(` Total: ${taskStats.total}`);\n console.log(` Completed: ${chalk.green(taskStats.completed || 0)}`);\n console.log(` In Progress: ${chalk.yellow(taskStats.in_progress || 0)}`);\n console.log(` Pending: ${chalk.gray(taskStats.pending || 0)}`);\n console.log(` ${chalk.bold('Completion:')} ${swarm.completion_percentage || 0}%`);\n\n // Show real memory count\n console.log('\\n' + chalk.bold('Collective Memory:'));\n console.log(` Entries: ${swarm.memory_count || 0}`);\n\n // Show real consensus count\n console.log('\\n' + chalk.bold('Consensus Decisions:'));\n console.log(` Total: ${swarm.consensus_count || 0}`);\n }\n\n console.log(chalk.yellow('โ•'.repeat(60)) + '\\n');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show consensus decisions\n */\nasync function showConsensus(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const decisions = db\n .prepare(\n `\n SELECT cd.*, s.name as swarm_name\n FROM consensus_decisions cd\n JOIN swarms s ON cd.swarm_id = s.id\n ORDER BY cd.created_at DESC\n LIMIT 20\n `,\n )\n .all();\n\n if (decisions.length === 0) {\n console.log(chalk.gray('No consensus decisions found'));\n db.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿค Recent Consensus Decisions\\n'));\n\n decisions.forEach((decision) => {\n console.log(chalk.yellow('โ”€'.repeat(50)));\n console.log(chalk.cyan('Swarm:'), decision.swarm_name);\n console.log(chalk.cyan('Topic:'), decision.topic);\n console.log(chalk.cyan('Decision:'), decision.decision);\n console.log(chalk.cyan('Algorithm:'), decision.algorithm);\n console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);\n console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());\n\n if (decision.votes) {\n const votes = JSON.parse(decision.votes);\n console.log(chalk.cyan('Votes:'));\n\n // Handle vote summary format (for/against/abstain/details)\n if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {\n console.log(` - for: ${votes.for || 0}`);\n console.log(` - against: ${votes.against || 0}`);\n console.log(` - abstain: ${votes.abstain || 0}`);\n\n // Display vote details properly if they exist\n if (votes.details && Array.isArray(votes.details)) {\n console.log(' - details:');\n votes.details.forEach((detail, index) => {\n if (typeof detail === 'object') {\n // Extract available fields\n const agent =\n detail.agentId ||\n detail.agent ||\n detail.id ||\n detail.name ||\n `agent-${index + 1}`;\n const vote = detail.vote || detail.choice || detail.decision || 'unknown';\n const reason = detail.reason || detail.justification || detail.rationale;\n\n // Build display string\n let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;\n\n // Add reason if available\n if (reason && reason !== 'N/A' && reason !== '') {\n displayString += `, Reason: ${reason}`;\n }\n\n console.log(displayString);\n } else {\n console.log(` ${index + 1}. ${detail}`);\n }\n });\n }\n } else {\n // Handle individual agent votes format\n Object.entries(votes).forEach(([agent, vote]) => {\n console.log(` - ${agent}: ${vote}`);\n });\n }\n }\n });\n\n console.log(chalk.yellow('โ”€'.repeat(50)) + '\\n');\n\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show performance metrics\n */\nasync function showMetrics(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n // Get overall metrics\n const overallStats = db\n .prepare(\n `\n SELECT \n (SELECT COUNT(*) FROM swarms) as total_swarms,\n (SELECT COUNT(*) FROM agents) as total_agents,\n (SELECT COUNT(*) FROM tasks) as total_tasks,\n (SELECT COUNT(*) FROM tasks WHERE status = 'completed') as completed_tasks\n `,\n )\n .get();\n\n console.log(chalk.bold('\\n๐Ÿ“Š Hive Mind Performance Metrics\\n'));\n\n // Get task status breakdown\n const taskBreakdown = db\n .prepare(\n `\n SELECT \n status,\n COUNT(*) as count\n FROM tasks\n GROUP BY status\n ORDER BY count DESC\n `,\n )\n .all();\n\n console.log(chalk.cyan('Overall Statistics:'));\n console.log(` Total Swarms: ${overallStats.total_swarms}`);\n console.log(` Total Agents: ${overallStats.total_agents}`);\n console.log(` Total Tasks: ${overallStats.total_tasks}`);\n console.log(` Completed Tasks: ${overallStats.completed_tasks}`);\n console.log(\n ` Success Rate: ${\n overallStats.total_tasks > 0\n ? ((overallStats.completed_tasks / overallStats.total_tasks) * 100).toFixed(1) + '%'\n : 'N/A'\n }`,\n );\n\n if (taskBreakdown.length > 0) {\n console.log('\\n' + chalk.cyan('Task Status Breakdown:'));\n taskBreakdown.forEach((status) => {\n const percentage =\n overallStats.total_tasks > 0\n ? ((status.count / overallStats.total_tasks) * 100).toFixed(1)\n : '0';\n const statusColor =\n status.status === 'completed'\n ? 'green'\n : status.status === 'in_progress'\n ? 'yellow'\n : status.status === 'failed'\n ? 'red'\n : 'gray';\n console.log(\n ` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`,\n );\n });\n }\n\n // Get agent performance (check for completed_at column)\n let agentPerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent performance:', error.message);\n }\n\n if (agentPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Top Performing Agents:'));\n agentPerf.forEach((agent, index) => {\n const successRate =\n agent.tasks_assigned > 0\n ? ((agent.tasks_completed / agent.tasks_assigned) * 100).toFixed(1)\n : '0';\n console.log(` ${index + 1}. ${agent.name} (${agent.type})`);\n console.log(\n ` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`,\n );\n if (agent.avg_completion_minutes) {\n console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n\n // Get swarm performance\n const swarmPerf = db\n .prepare(\n `\n SELECT \n s.name,\n s.objective,\n (SELECT COUNT(*) FROM agents a WHERE a.swarm_id = s.id) as agent_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id) as task_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id AND t.status = 'completed') as completed_count,\n (SELECT COUNT(*) FROM collective_memory cm WHERE cm.swarm_id = s.id) as memory_entries,\n (SELECT COUNT(*) FROM consensus_decisions cd WHERE cd.swarm_id = s.id) as consensus_count\n FROM swarms s\n WHERE s.status = 'active'\n ORDER BY s.created_at DESC\n LIMIT 5\n `,\n )\n .all();\n\n if (swarmPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Active Swarm Performance:'));\n swarmPerf.forEach((swarm) => {\n const successRate =\n swarm.task_count > 0\n ? ((swarm.completed_count / swarm.task_count) * 100).toFixed(1)\n : '0';\n console.log(`\\n ${chalk.yellow(swarm.name)}`);\n console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);\n console.log(\n ` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`,\n );\n console.log(\n ` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`,\n );\n });\n }\n\n // Get performance insights\n let avgTaskTime = { avg_minutes: null };\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n avgTaskTime = db\n .prepare(\n `\n SELECT \n AVG(CASE WHEN completed_at IS NOT NULL \n THEN (julianday(completed_at) - julianday(created_at)) * 24 * 60 \n ELSE NULL END) as avg_minutes\n FROM tasks\n WHERE status = 'completed'\n `,\n )\n .get();\n }\n } catch (error) {\n console.warn('Could not calculate average task time:', error.message);\n }\n\n // Get agent type performance\n let agentTypePerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent type performance:', error.message);\n }\n\n if (avgTaskTime.avg_minutes) {\n console.log('\\n' + chalk.cyan('Performance Insights:'));\n console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);\n\n if (agentTypePerf.length > 0) {\n console.log('\\n' + chalk.cyan('Agent Type Performance:'));\n agentTypePerf.forEach((type) => {\n const successRate =\n type.total_tasks > 0\n ? ((type.completed_tasks / type.total_tasks) * 100).toFixed(1)\n : '0';\n console.log(\n ` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`,\n );\n if (type.avg_completion_minutes) {\n console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n }\n\n console.log('\\n');\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Manage collective memory wizard\n */\nasync function manageMemoryWizard() {\n console.log(chalk.blue('\\n๐Ÿง  Collective Memory Management\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do with collective memory?',\n choices: [\n { name: '๐Ÿ“‹ View all memories', value: 'list' },\n { name: '๐Ÿ” Search memories', value: 'search' },\n { name: '๐Ÿ’พ Store new memory', value: 'store' },\n { name: '๐Ÿ“Š Memory statistics', value: 'stats' },\n { name: '๐Ÿ—‘๏ธ Clean old memories', value: 'clean' },\n { name: '๐Ÿ“ค Export memory backup', value: 'export' },\n { name: 'โฌ…๏ธ Back to main menu', value: 'back' },\n ],\n },\n ]);\n\n switch (action) {\n case 'list':\n await listMemories();\n break;\n case 'search':\n await searchMemories();\n break;\n case 'store':\n await storeMemoryWizard();\n break;\n case 'stats':\n await showMemoryStats();\n break;\n case 'clean':\n await cleanMemories();\n break;\n case 'export':\n await exportMemoryBackup();\n break;\n case 'back':\n await hiveMindWizard();\n return;\n }\n\n // Ask if user wants to continue\n const { continue: continueAction } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'continue',\n message: 'Would you like to perform another memory operation?',\n default: true,\n },\n ]);\n\n if (continueAction) {\n await manageMemoryWizard();\n }\n}\n\n/**\n * Configure hive mind wizard\n */\nasync function configureWizard() {\n // TODO: Implement configuration wizard\n console.log(chalk.yellow('Configuration wizard coming soon...'));\n}\n\n/**\n * Main hive mind command handler\n */\nexport async function hiveMindCommand(args, flags) {\n const subcommand = args[0];\n const subArgs = args.slice(1);\n\n // Handle help flags\n if (\n !subcommand ||\n subcommand === '--help' ||\n subcommand === '-h' ||\n subcommand === 'help' ||\n flags.help\n ) {\n showHiveMindHelp();\n return;\n }\n\n // Warn about non-interactive environments for certain commands\n if ((subcommand === 'spawn' && (flags.claude || flags.spawn)) || subcommand === 'wizard') {\n warnNonInteractive('hive-mind ' + subcommand);\n }\n\n switch (subcommand) {\n case 'init':\n await initHiveMind(flags);\n break;\n\n case 'spawn':\n // Check for non-interactive mode FIRST (like alpha.83)\n if (flags['non-interactive'] || flags.nonInteractive) {\n // In non-interactive mode, skip wizard and use defaults\n if (subArgs.length === 0) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n return;\n }\n await spawnSwarm(subArgs, flags);\n } else if (flags.wizard || subArgs.length === 0) {\n await spawnSwarmWizard();\n } else {\n await spawnSwarm(subArgs, flags);\n }\n break;\n\n case 'status':\n await showStatus(flags);\n break;\n\n case 'sessions':\n await showSessions(flags);\n break;\n\n case 'resume':\n await resumeSession(subArgs, flags);\n break;\n\n case 'stop':\n await stopSession(subArgs, flags);\n break;\n\n case 'consensus':\n await showConsensus(flags);\n break;\n\n case 'memory':\n await manageMemoryWizard();\n break;\n\n case 'metrics':\n await showMetrics(flags);\n break;\n\n case 'wizard':\n await hiveMindWizard(flags);\n break;\n\n case 'help':\n case '--help':\n case '-h':\n showHiveMindHelp();\n break;\n\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log('Run \"claude-flow hive-mind help\" for usage information');\n exit(1);\n }\n}\n\n/**\n * List all memories in the collective memory store\n */\nasync function listMemories() {\n try {\n console.log(chalk.blue('\\n๐Ÿ“‹ Collective Memory Store\\n'));\n\n // Read directly from hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all();\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found in the collective store.'));\n console.log(\n chalk.gray('Try storing some memories first using the \"๐Ÿ’พ Store new memory\" option.'),\n );\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.cyan(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n console.log(` Created by: ${memory.created_by || 'system'}`);\n \n // Parse and display value\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed);\n } catch {\n // Keep as string\n }\n \n if (displayValue.length > 100) {\n console.log(` Value: ${displayValue.substring(0, 100)}...`);\n } else {\n console.log(` Value: ${displayValue}`);\n }\n \n if (memory.confidence !== null && memory.confidence !== 1) {\n console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);\n }\n \n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error listing memories:'), error.message);\n console.log(chalk.gray('This might be because no memories have been stored yet.'));\n }\n}\n\n/**\n * Search memories by keyword\n */\nasync function searchMemories() {\n try {\n const { searchTerm } = await inquirer.prompt([\n {\n type: 'input',\n name: 'searchTerm',\n message: 'Enter search term:',\n validate: (input) => input.length > 0,\n },\n ]);\n\n console.log(chalk.blue(`\\n๐Ÿ” Searching for: \"${searchTerm}\"\\n`));\n\n // Search directly in hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const searchPattern = `%${searchTerm}%`;\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n WHERE cm.key LIKE ? OR cm.value LIKE ? OR cm.type LIKE ?\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all(searchPattern, searchPattern, searchPattern);\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found matching your search.'));\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories matching \"${searchTerm}\":\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.green(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n \n // Parse and display value with highlighting\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed, null, 2);\n } catch {\n // Keep as string\n }\n \n console.log(` Value: ${displayValue}`);\n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error searching memories:'), error.message);\n }\n}\n\n/**\n * Store new memory wizard\n */\nasync function storeMemoryWizard() {\n try {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'key',\n message: 'Memory key (identifier):',\n validate: (input) => input.length > 0,\n },\n {\n type: 'list',\n name: 'category',\n message: 'Memory category:',\n choices: [\n 'consensus',\n 'decision',\n 'pattern',\n 'learning',\n 'coordination',\n 'performance',\n 'configuration',\n 'general',\n ],\n },\n {\n type: 'editor',\n name: 'value',\n message: 'Memory content (JSON or text):',\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n let memoryValue;\n\n // Try to parse as JSON, fall back to string\n try {\n memoryValue = JSON.parse(answers.value);\n } catch {\n memoryValue = answers.value;\n }\n\n await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);\n\n console.log(chalk.green(`\\nโœ… Memory stored successfully!`));\n console.log(`Key: ${answers.key}`);\n console.log(`Category: ${answers.category}`);\n } catch (error) {\n console.error(chalk.red('Error storing memory:'), error.message);\n }\n}\n\n/**\n * Show memory statistics\n */\nasync function showMemoryStats() {\n try {\n console.log(chalk.blue('\\n๐Ÿ“Š Memory Statistics\\n'));\n\n const mcpWrapper = await getMcpWrapper();\n\n // Search for all memories with an empty pattern to get everything\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found.'));\n console.log(chalk.gray('Use \"Store new memory\" to create your first memory.'));\n return;\n }\n\n // Calculate statistics\n const stats = {\n total: memories.length,\n categories: {},\n oldestDate: null,\n newestDate: null,\n totalSize: 0,\n };\n\n memories.forEach((memory) => {\n // Count by category\n const category = memory.category || memory.type || 'general';\n stats.categories[category] = (stats.categories[category] || 0) + 1;\n\n // Track dates\n const date = new Date(memory.timestamp || Date.now());\n if (!stats.oldestDate || date < stats.oldestDate) {\n stats.oldestDate = date;\n }\n if (!stats.newestDate || date > stats.newestDate) {\n stats.newestDate = date;\n }\n\n // Estimate size\n stats.totalSize += JSON.stringify(memory).length;\n });\n\n console.log(chalk.cyan('Total memories:'), stats.total);\n console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);\n console.log(\n chalk.cyan('Date range:'),\n `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`,\n );\n\n console.log(chalk.cyan('\\nBy category:'));\n Object.entries(stats.categories).forEach(([category, count]) => {\n console.log(` ${category}: ${count}`);\n });\n } catch (error) {\n console.error(chalk.red('Error getting memory stats:'), error.message);\n }\n}\n\n/**\n * Clean old memories\n */\nasync function cleanMemories() {\n try {\n const { days } = await inquirer.prompt([\n {\n type: 'number',\n name: 'days',\n message: 'Remove memories older than how many days?',\n default: 30,\n validate: (input) => input > 0,\n },\n ]);\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete memories older than ${days} days?`,\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(chalk.yellow('Operation cancelled.'));\n return;\n }\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories first\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - days);\n\n // Filter memories older than cutoff date\n const oldMemories = memories.filter((memory) => {\n const memoryDate = new Date(memory.timestamp || 0);\n return memoryDate < cutoffDate;\n });\n\n if (oldMemories.length === 0) {\n console.log(chalk.yellow('\\n๐ŸŽ‰ No old memories found to clean.'));\n return;\n }\n\n console.log(chalk.green(`\\nโœ… Found ${oldMemories.length} old memories to clean.`));\n console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));\n console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));\n } catch (error) {\n console.error(chalk.red('Error cleaning memories:'), error.message);\n }\n}\n\n/**\n * Export memory backup\n */\nasync function exportMemoryBackup() {\n try {\n const { filename } = await inquirer.prompt([\n {\n type: 'input',\n name: 'filename',\n message: 'Export filename:',\n default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`,\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories using search\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const backup = {\n exportDate: new Date().toISOString(),\n version: '1.0',\n totalMemories: memories.length,\n namespace: 'hive-mind',\n memories: memories,\n };\n\n const fs = await import('fs');\n fs.writeFileSync(filename, JSON.stringify(backup, null, 2));\n\n console.log(chalk.green(`\\nโœ… Memory backup exported to: ${filename}`));\n console.log(chalk.cyan(`Exported ${memories.length} memories`));\n } catch (error) {\n console.error(chalk.red('Error exporting memory backup:'), error.message);\n }\n}\n\n/**\n * Get active session ID for a swarm\n */\nasync function getActiveSessionId(swarmId) {\n const sessionManager = new HiveMindSessionManager();\n try {\n const sessions = await sessionManager.getActiveSessions();\n const activeSession = sessions.find(s => s.swarm_id === swarmId && s.status === 'active');\n return activeSession ? activeSession.id : null;\n } finally {\n sessionManager.close();\n }\n}\n\n/**\n * Spawn Claude Code with Hive Mind coordination instructions\n */\nasync function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {\n console.log('\\n' + chalk.bold('๐Ÿš€ Launching Claude Code with Hive Mind Coordination'));\n console.log(chalk.gray('โ”€'.repeat(60)));\n\n const spinner = ora('Preparing Hive Mind coordination prompt...').start();\n\n try {\n // Generate comprehensive Hive Mind prompt\n const workerGroups = groupWorkersByType(workers);\n const hiveMindPrompt = generateHiveMindPrompt(\n swarmId,\n swarmName,\n objective,\n workers,\n workerGroups,\n flags,\n );\n\n spinner.succeed('Hive Mind coordination prompt ready!');\n\n // Display coordination summary\n console.log('\\n' + chalk.bold('๐Ÿง  Hive Mind Configuration'));\n console.log(chalk.gray('โ”€'.repeat(60)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');\n console.log(chalk.cyan('Worker Count:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));\n console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');\n console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');\n\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n\n const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\nโœ“ Hive Mind prompt saved to: ${promptFile}`));\n\n // Check if claude command exists\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\nโš ๏ธ Claude Code CLI not found in PATH'));\n console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\nFalling back to displaying instructions...'));\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Check if we should run in non-interactive mode\n // Respect --non-interactive flag regardless of --claude\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n \n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming \n claudeArgs.push('--verbose'); // Verbose output\n console.log(chalk.cyan('๐Ÿค– Running in non-interactive mode'));\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n chalk.yellow(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n }\n \n // Add the prompt as the LAST argument\n claudeArgs.push(hiveMindPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n // Track child process PID in session\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await getActiveSessionId(swarmId);\n if (sessionId && claudeProcess.pid) {\n sessionManager.addChildPid(sessionId, claudeProcess.pid);\n }\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n\n // Save checkpoint and pause session\n if (sessionId) {\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C during Claude Code execution',\n claudePid: claudeProcess.pid,\n };\n \n await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);\n await sessionManager.pauseSession(sessionId);\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n }\n \n sessionManager.close();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n sessionManager.close();\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle stdout\n if (claudeProcess.stdout) {\n claudeProcess.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n }\n\n // Handle stderr\n if (claudeProcess.stderr) {\n claudeProcess.stderr.on('data', (data) => {\n console.error(chalk.red(data.toString()));\n });\n }\n\n // Handle process exit\n claudeProcess.on('exit', (code) => {\n // Remove child PID from session\n if (sessionId && claudeProcess.pid) {\n sessionManager.removeChildPid(sessionId, claudeProcess.pid);\n sessionManager.close();\n }\n\n if (code === 0) {\n console.log(chalk.green('\\nโœ“ Claude Code completed successfully'));\n } else if (code !== null) {\n console.log(chalk.red(`\\nโœ— Claude Code exited with code ${code}`));\n }\n });\n\n console.log(chalk.green('\\nโœ“ Claude Code launched with Hive Mind coordination'));\n console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));\n console.log(\n chalk.blue(' Use MCP tools for collective intelligence and task distribution'),\n );\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n } else if (flags.dryRun) {\n console.log(chalk.blue('\\nDry run - would execute Claude Code with prompt:'));\n console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');\n console.log(chalk.gray('\\nFirst 500 characters of prompt:'));\n console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));\n console.log(chalk.gray(`\\nFull prompt saved to: ${promptFile}`));\n } else {\n // Claude not available - show instructions with already saved prompt\n console.log(chalk.yellow('\\n๐Ÿ“‹ Manual Execution Instructions:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.gray('1. Install Claude Code:'));\n console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\n2. Run with the saved prompt:'));\n console.log(chalk.green(` claude < ${promptFile}`));\n console.log(chalk.gray('\\n3. Or copy the prompt manually:'));\n console.log(chalk.green(` cat ${promptFile} | claude`));\n console.log(chalk.gray('\\n4. With auto-permissions:'));\n console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('\\nFailed to launch Claude Code:'), error.message);\n\n // Save prompt as fallback\n const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\nโœ“ Prompt saved to: ${promptFile}`));\n console.log(chalk.yellow('\\nYou can run Claude Code manually with the saved prompt'));\n }\n\n console.log('\\n' + chalk.bold('๐Ÿ’ก Pro Tips:'));\n console.log(chalk.gray('โ”€'.repeat(30)));\n console.log('โ€ข Use --auto-spawn to launch instances automatically');\n console.log('โ€ข Add --verbose for detailed coordination context');\n console.log('โ€ข Monitor with: claude-flow hive-mind status');\n console.log('โ€ข Share memories: mcp__ruv-swarm__memory_usage');\n } catch (error) {\n spinner.fail('Failed to prepare Claude Code coordination');\n console.error(chalk.red('Error:'), error.message);\n }\n}\n\n/**\n * Generate comprehensive Hive Mind prompt for Claude Code\n */\nfunction generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {\n console.log(chalk.cyan(`\\n๐Ÿ” generateHiveMindPrompt received objective: \"${objective}\"`));\n const currentTime = new Date().toISOString();\n const workerTypes = Object.keys(workerGroups);\n const queenType = flags.queenType || 'strategic';\n const consensusAlgorithm = flags.consensus || 'majority';\n\n return `๐Ÿง  HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM\nโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n\nYou are the Queen coordinator of a Hive Mind swarm with collective intelligence capabilities.\n\nHIVE MIND CONFIGURATION:\n๐Ÿ“Œ Swarm ID: ${swarmId}\n๐Ÿ“Œ Swarm Name: ${swarmName}\n๐ŸŽฏ Objective: ${objective}\n๐Ÿ‘‘ Queen Type: ${queenType}\n๐Ÿ Worker Count: ${workers.length}\n๐Ÿค Consensus Algorithm: ${consensusAlgorithm}\nโฐ Initialized: ${currentTime}\n\nWORKER DISTRIBUTION:\n${workerTypes.map((type) => `โ€ข ${type}: ${workerGroups[type].length} agents`).join('\\n')}\n\n๐Ÿ”ง AVAILABLE MCP TOOLS FOR HIVE MIND COORDINATION:\n\n1๏ธโƒฃ **COLLECTIVE INTELLIGENCE**\n mcp__claude-flow__consensus_vote - Democratic decision making\n mcp__claude-flow__memory_share - Share knowledge across the hive\n mcp__claude-flow__neural_sync - Synchronize neural patterns\n mcp__claude-flow__swarm_think - Collective problem solving\n\n2๏ธโƒฃ **QUEEN COORDINATION**\n mcp__claude-flow__queen_command - Issue directives to workers\n mcp__claude-flow__queen_monitor - Monitor swarm health\n mcp__claude-flow__queen_delegate - Delegate complex tasks\n mcp__claude-flow__queen_aggregate - Aggregate worker results\n\n3๏ธโƒฃ **WORKER MANAGEMENT**\n mcp__claude-flow__agent_spawn - Create specialized workers\n mcp__claude-flow__agent_assign - Assign tasks to workers\n mcp__claude-flow__agent_communicate - Inter-agent communication\n mcp__claude-flow__agent_metrics - Track worker performance\n\n4๏ธโƒฃ **TASK ORCHESTRATION**\n mcp__claude-flow__task_create - Create hierarchical tasks\n mcp__claude-flow__task_distribute - Distribute work efficiently\n mcp__claude-flow__task_monitor - Track task progress\n mcp__claude-flow__task_aggregate - Combine task results\n\n5๏ธโƒฃ **MEMORY & LEARNING**\n mcp__claude-flow__memory_store - Store collective knowledge\n mcp__claude-flow__memory_retrieve - Access shared memory\n mcp__claude-flow__neural_train - Learn from experiences\n mcp__claude-flow__pattern_recognize - Identify patterns\n\n๐Ÿ“‹ HIVE MIND EXECUTION PROTOCOL:\n\nAs the Queen coordinator, you must:\n\n1. **INITIALIZE THE HIVE** (CRITICAL: Use Claude Code's Task Tool for Agents):\n \n Step 1: Optional MCP Coordination Setup (Single Message):\n [MCP Tools - Coordination Only]:\n ${workerTypes.map((type) => ` mcp__claude-flow__agent_spawn { \"type\": \"${type}\", \"count\": ${workerGroups[type].length} }`).join('\\n')}\n mcp__claude-flow__memory_store { \"key\": \"hive/objective\", \"value\": \"${objective}\" }\n mcp__claude-flow__memory_store { \"key\": \"hive/queen\", \"value\": \"${queenType}\" }\n mcp__claude-flow__swarm_think { \"topic\": \"initial_strategy\" }\n \n Step 2: REQUIRED - Spawn ACTUAL Agents with Claude Code's Task Tool (Single Message):\n [Claude Code Task Tool - CONCURRENT Agent Execution]:\n ${workerTypes.map((type) => ` Task(\"${type.charAt(0).toUpperCase() + type.slice(1)} Agent\", \"You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\\n')[0]}\", \"${type}\")`).join('\\n')}\n \n Step 3: Batch ALL Todos Together (Single TodoWrite Call):\n TodoWrite { \"todos\": [\n { \"id\": \"1\", \"content\": \"Initialize hive mind collective\", \"status\": \"in_progress\", \"priority\": \"high\" },\n { \"id\": \"2\", \"content\": \"Establish consensus protocols\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"3\", \"content\": \"Distribute initial tasks to workers\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"4\", \"content\": \"Set up collective memory\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"5\", \"content\": \"Monitor worker health\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"6\", \"content\": \"Aggregate worker outputs\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"7\", \"content\": \"Learn from patterns\", \"status\": \"pending\", \"priority\": \"low\" },\n { \"id\": \"8\", \"content\": \"Optimize performance\", \"status\": \"pending\", \"priority\": \"low\" }\n ] }\n\n2. **ESTABLISH COLLECTIVE INTELLIGENCE**:\n - Use consensus_vote for major decisions\n - Share all discoveries via memory_share\n - Synchronize learning with neural_sync\n - Coordinate strategy with swarm_think\n\n3. **QUEEN LEADERSHIP PATTERNS**:\n ${\n queenType === 'strategic'\n ? `\n - Focus on high-level planning and coordination\n - Delegate implementation details to workers\n - Monitor overall progress and adjust strategy\n - Make executive decisions when consensus fails`\n : ''\n }\n ${\n queenType === 'tactical'\n ? `\n - Manage detailed task breakdowns and assignments\n - Closely monitor worker progress and efficiency\n - Optimize resource allocation and load balancing\n - Intervene directly when workers need guidance`\n : ''\n }\n ${\n queenType === 'adaptive'\n ? `\n - Learn from swarm performance and adapt strategies\n - Experiment with different coordination patterns\n - Use neural training to improve over time\n - Balance between strategic and tactical approaches`\n : ''\n }\n\n4. **WORKER COORDINATION**:\n - Spawn workers based on task requirements\n - Assign tasks according to worker specializations\n - Enable peer-to-peer communication for collaboration\n - Monitor and rebalance workloads as needed\n\n5. **CONSENSUS MECHANISMS**:\n ${consensusAlgorithm === 'majority' ? '- Decisions require >50% worker agreement' : ''}\n ${consensusAlgorithm === 'unanimous' ? '- All workers must agree for major decisions' : ''}\n ${consensusAlgorithm === 'weighted' ? '- Worker votes weighted by expertise and performance' : ''}\n ${consensusAlgorithm === 'quorum' ? '- Decisions require 2/3 worker participation' : ''}\n\n6. **COLLECTIVE MEMORY**:\n - Store all important decisions in shared memory\n - Tag memories with worker IDs and timestamps\n - Use memory namespaces: hive/, queen/, workers/, tasks/\n - Implement memory consensus for critical data\n\n7. **PERFORMANCE OPTIMIZATION**:\n - Monitor swarm metrics continuously\n - Identify and resolve bottlenecks\n - Train neural networks on successful patterns\n - Scale worker count based on workload\n\n๐Ÿ’ก HIVE MIND BEST PRACTICES:\n\nโœ… ALWAYS use BatchTool for parallel operations\nโœ… Store decisions in collective memory immediately\nโœ… Use consensus for critical path decisions\nโœ… Monitor worker health and reassign if needed\nโœ… Learn from failures and adapt strategies\nโœ… Maintain constant inter-agent communication\nโœ… Aggregate results before final delivery\n\nโŒ NEVER make unilateral decisions without consensus\nโŒ NEVER let workers operate in isolation\nโŒ NEVER ignore performance metrics\nโŒ NEVER skip memory synchronization\nโŒ NEVER abandon failing workers\n\n๐ŸŽฏ OBJECTIVE EXECUTION STRATEGY:\n\nFor the objective: \"${objective}\"\n\n1. Break down into major phases using swarm_think\n2. Create specialized worker teams for each phase\n3. Establish success criteria and checkpoints\n4. Implement feedback loops and adaptation\n5. Aggregate and synthesize all worker outputs\n6. Deliver comprehensive solution with consensus\n\nโšก CRITICAL: CONCURRENT EXECUTION WITH CLAUDE CODE'S TASK TOOL:\n\nThe Hive Mind MUST use Claude Code's Task tool for actual agent execution:\n\nโœ… CORRECT Pattern:\n[Single Message - All Agents Spawned Concurrently]:\n Task(\"Researcher\", \"Research patterns and best practices...\", \"researcher\")\n Task(\"Coder\", \"Implement core features...\", \"coder\")\n Task(\"Tester\", \"Create comprehensive tests...\", \"tester\")\n Task(\"Analyst\", \"Analyze performance metrics...\", \"analyst\")\n TodoWrite { todos: [8-10 todos ALL in ONE call] }\n\nโŒ WRONG Pattern:\nMessage 1: Task(\"agent1\", ...)\nMessage 2: Task(\"agent2\", ...)\nMessage 3: TodoWrite { single todo }\n// This breaks parallel coordination!\n\nRemember:\n- Use Claude Code's Task tool to spawn ALL agents in ONE message\n- MCP tools are ONLY for coordination setup, not agent execution\n- Batch ALL TodoWrite operations (5-10+ todos minimum)\n- Execute ALL file operations concurrently\n- Store multiple memories simultaneously\n\n๐Ÿš€ BEGIN HIVE MIND EXECUTION:\n\nInitialize the swarm now with the configuration above. Use your collective intelligence to solve the objective efficiently. The Queen must coordinate, workers must collaborate, and the hive must think as one.\n\nRemember: You are not just coordinating agents - you are orchestrating a collective intelligence that is greater than the sum of its parts.`;\n}\n\n/**\n * Generate comprehensive coordination instructions for Claude Code instances\n */\nfunction generateCoordinationInstructions(swarmId, swarmName, objective, workers) {\n return {\n swarmId,\n swarmName,\n objective,\n hiveMindEndpoint: 'ws://localhost:3000/hive-mind',\n mcpTools: [\n 'mcp__ruv-swarm__memory_usage',\n 'mcp__ruv-swarm__swarm_monitor',\n 'mcp__ruv-swarm__task_orchestrate',\n 'mcp__ruv-swarm__neural_train',\n 'mcp__ruv-swarm__consensus_vote',\n 'mcp__ruv-swarm__agent_spawn',\n 'mcp__ruv-swarm__swarm_status',\n ],\n coordinationProtocol: {\n memoryNamespace: `hive-mind-${swarmId}`,\n consensusThreshold: 0.7,\n taskUpdateInterval: 30000,\n healthCheckInterval: 60000,\n },\n workerCapabilities: workers.map((w) => ({\n id: w.id,\n type: w.type,\n capabilities: JSON.parse(w.capabilities),\n })),\n };\n}\n\n/**\n * Group workers by type for specialized spawning\n */\nfunction groupWorkersByType(workers) {\n return workers.reduce((groups, worker) => {\n if (!groups[worker.type]) {\n groups[worker.type] = [];\n }\n groups[worker.type].push(worker);\n return groups;\n }, {});\n}\n\n/**\n * Create Claude Code spawn command with coordination context\n */\nfunction createClaudeCodeSpawnCommand(\n swarmId,\n swarmName,\n objective,\n workerType,\n typeWorkers,\n instructions,\n) {\n const context = `You are a ${workerType} agent in the \"${swarmName}\" Hive Mind swarm.\n\n๐ŸŽฏ MISSION: ${objective}\n\n๐Ÿ SWARM COORDINATION:\n- Swarm ID: ${swarmId}\n- Your Role: ${workerType.toUpperCase()} specialist\n- Team Size: ${typeWorkers.length} ${workerType}(s)\n- Coordination: Hive Mind collective intelligence\n\n๐Ÿง  MANDATORY COORDINATION PROTOCOL:\n1. BEFORE starting work:\n mcp__ruv-swarm__memory_usage {\"action\": \"retrieve\", \"key\": \"hive-mind-${swarmId}/status\"}\n mcp__ruv-swarm__swarm_status {\"swarmId\": \"${swarmId}\"}\n\n2. DURING work (after each major step):\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/${workerType}/progress\", \"value\": {\"step\": \"X\", \"status\": \"Y\", \"findings\": \"Z\"}}\n mcp__ruv-swarm__task_orchestrate {\"swarmId\": \"${swarmId}\", \"update\": {\"agentId\": \"your-id\", \"progress\": \"details\"}}\n\n3. FOR decisions requiring consensus:\n mcp__ruv-swarm__consensus_vote {\"swarmId\": \"${swarmId}\", \"topic\": \"decision topic\", \"vote\": \"your choice\", \"rationale\": \"reasoning\"}\n\n4. WHEN sharing insights:\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/insights/${workerType}\", \"value\": {\"insight\": \"your discovery\", \"impact\": \"significance\"}}\n\n5. BEFORE completing work:\n mcp__ruv-swarm__neural_train {\"swarmId\": \"${swarmId}\", \"experience\": {\"what\": \"learned\", \"outcome\": \"result\"}}\n\n๐Ÿ”ง SPECIALIZED CAPABILITIES:\n${getWorkerTypeInstructions(workerType)}\n\n๐Ÿค COORDINATION RULES:\n- Share ALL discoveries via memory_usage\n- Vote on critical decisions using consensus_vote\n- Update progress every 15 minutes via task_orchestrate\n- Monitor other agents via swarm_status\n- Learn from patterns via neural_train\n\nRemember: You are part of a COLLECTIVE INTELLIGENCE. Your individual success depends on swarm coordination!`;\n\n const command = `claude code --context \"${context.replace(/\"/g, '\\\\\"')}\"`;\n\n return {\n title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,\n command,\n context,\n workerType,\n count: typeWorkers.length,\n };\n}\n\n/**\n * Get specialized instructions for each worker type\n */\nfunction getWorkerTypeInstructions(workerType) {\n const instructions = {\n researcher: `- Conduct thorough research using WebSearch and WebFetch\n- Document findings in structured formats\n- Validate source credibility and relevance\n- Synthesize insights from multiple sources\n- Share research methodology and results`,\n\n coder: `- Write clean, maintainable, well-documented code\n- Follow project conventions and best practices\n- Test implementations thoroughly\n- Document code changes and decisions\n- Review and optimize existing code`,\n\n analyst: `- Analyze data patterns and trends\n- Create comprehensive reports and visualizations\n- Identify key insights and recommendations\n- Validate analytical methodologies\n- Correlate findings across data sources`,\n\n tester: `- Design comprehensive test strategies\n- Execute functional, integration, and performance tests\n- Document test results and issues\n- Verify bug fixes and improvements\n- Ensure quality standards and coverage`,\n\n coordinator: `- Monitor overall progress and coordination\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Optimize resource allocation\n- Ensure alignment with objectives`,\n\n architect: `- Design system architecture and components\n- Define technical standards and patterns\n- Create implementation guidelines\n- Review and approve design decisions\n- Ensure scalability and maintainability`,\n };\n\n return (\n instructions[workerType] ||\n `- Execute tasks according to ${workerType} best practices\n- Collaborate effectively with team members\n- Document work and share insights\n- Maintain quality standards\n- Contribute to collective objectives`\n );\n}\n\n/**\n * Show all hive mind sessions\n */\nasync function showSessions(flags) {\n try {\n // Use metrics reader for real session data\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n \n if (!existsSync(dbPath)) {\n console.log(chalk.gray('No hive mind database found'));\n return;\n }\n \n const metricsReader = new HiveMindMetricsReader(dbPath);\n const sessions = metricsReader.getActiveSessions();\n\n if (sessions.length === 0) {\n console.log(chalk.gray('No active or paused sessions found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿ—‚๏ธ Hive Mind Sessions\\n'));\n\n sessions.forEach((session, index) => {\n const statusColor =\n session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';\n const statusIcon =\n session.status === 'active' ? '๐ŸŸข' : session.status === 'paused' ? '๐ŸŸก' : 'โšซ';\n\n console.log(chalk.yellow('โ•'.repeat(60)));\n console.log(`${statusIcon} ${chalk.bold(session.swarm_name || session.id)}`);\n console.log(chalk.cyan('Session ID:'), session.id);\n console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));\n console.log(chalk.cyan('Objective:'), session.objective || 'Not set');\n console.log(chalk.cyan('Progress:'), `${session.completion_percentage || 0}%`);\n console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());\n console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());\n\n if (session.paused_at) {\n console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());\n }\n\n console.log('\\n' + chalk.bold('Real Progress:'));\n console.log(` Agents: ${session.agent_count || 0}`);\n console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);\n console.log(` In Progress: ${session.in_progress_tasks || 0}`);\n console.log(` Pending: ${session.pending_tasks || 0}`);\n\n if (session.checkpoint_data) {\n console.log('\\n' + chalk.bold('Last Checkpoint:'));\n const checkpointStr = typeof session.checkpoint_data === 'string' \n ? session.checkpoint_data \n : JSON.stringify(session.checkpoint_data, null, 2);\n console.log(\n chalk.gray(checkpointStr.substring(0, 200) + (checkpointStr.length > 200 ? '...' : '')),\n );\n }\n });\n\n console.log(chalk.yellow('โ•'.repeat(60)) + '\\n');\n\n console.log(chalk.blue('๐Ÿ’ก Tips:'));\n console.log(' โ€ข Resume a session: claude-flow hive-mind resume ');\n console.log(' โ€ข View session details: claude-flow hive-mind status');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Resume a paused hive mind session\n */\nasync function resumeSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind resume ');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Resuming Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Allow resuming any session regardless of status\n spinner.text = `Resuming session from status: ${session.status}...`;\n\n if (session.status === 'stopped') {\n spinner.text = 'Restarting stopped session with original configuration...';\n }\n\n // Resume the session\n const resumedSession = await sessionManager.resumeSession(sessionId);\n\n spinner.succeed('Session resumed successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('๐Ÿ“‹ Resumed Session Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);\n console.log(chalk.cyan('Objective:'), resumedSession.objective);\n console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);\n console.log(\n chalk.cyan('Active Agents:'),\n `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`,\n );\n console.log(\n chalk.cyan('Tasks:'),\n `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`,\n );\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n // Show task breakdown\n console.log('\\n' + chalk.bold('๐Ÿ“Š Task Status:'));\n console.log(` โœ… Completed: ${resumedSession.statistics.completedTasks}`);\n console.log(` ๐Ÿ”„ In Progress: ${resumedSession.statistics.inProgressTasks}`);\n console.log(` โณ Pending: ${resumedSession.statistics.pendingTasks}`);\n\n // Show recent activity\n if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {\n console.log('\\n' + chalk.bold('๐Ÿ“œ Recent Activity:'));\n resumedSession.recentLogs.slice(0, 5).forEach((log) => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n console.log(` [${timestamp}] ${log.message}`);\n });\n }\n\n // Restore checkpoint if available\n if (resumedSession.checkpoint_data) {\n console.log('\\n' + chalk.bold('โ™ป๏ธ Restoring from checkpoint...'));\n console.log(chalk.gray('Checkpoint data available for restoration'));\n }\n\n sessionManager.close();\n\n // Offer to spawn Claude Code with restored context\n if (flags.claude || flags.spawn) {\n console.log('\\n' + chalk.yellow('๐Ÿš€ Launching Claude Code with restored context...'));\n\n // Generate prompt with session context\n const restoredPrompt = generateRestoredSessionPrompt(resumedSession);\n\n // Launch Claude Code with restored context\n await launchClaudeWithContext(restoredPrompt, flags, sessionId);\n } else {\n console.log(\n '\\n' +\n chalk.blue('๐Ÿ’ก Pro Tip:') +\n ' Add --claude to spawn Claude Code with restored context',\n );\n console.log(chalk.gray(' claude-flow hive-mind resume ' + sessionId + ' --claude'));\n }\n } catch (error) {\n spinner.fail('Failed to resume session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Stop a hive mind session\n */\nasync function stopSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind stop ');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Stopping Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Stop the session\n await sessionManager.stopSession(sessionId);\n\n spinner.succeed('Session stopped successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('๐Ÿ›‘ Stopped Session Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');\n console.log(chalk.cyan('Final Status:'), 'Stopped');\n console.log(\n chalk.cyan('Active Agents:'),\n session.statistics ? session.statistics.activeAgents : 0,\n );\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n console.log('\\n' + chalk.yellow('๐Ÿ’ก Session has been stopped and all processes cleaned up.'));\n console.log(\n chalk.gray('To resume this session later, use: claude-flow hive-mind resume ' + sessionId),\n );\n\n sessionManager.close();\n } catch (error) {\n spinner.fail('Failed to stop session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Generate prompt for restored session\n */\nfunction generateRestoredSessionPrompt(session) {\n // Get all agents, not just active ones\n const allAgents = session.agents || [];\n const activeAgents = allAgents.filter((a) => a.status === 'active' || a.status === 'busy');\n const idleAgents = allAgents.filter((a) => a.status === 'idle');\n \n // Get all tasks categorized by status\n const allTasks = session.tasks || [];\n const completedTasks = allTasks.filter((t) => t.status === 'completed');\n const inProgressTasks = allTasks.filter((t) => t.status === 'in_progress');\n const pendingTasks = allTasks.filter((t) => t.status === 'pending');\n \n // Calculate session duration\n const sessionStart = new Date(session.created_at);\n const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();\n const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes\n \n // Get more checkpoint history\n const checkpointHistory = session.checkpoints || [];\n \n // Get more activity logs\n const activityLogs = session.recentLogs || [];\n \n // Format agent details with their current tasks\n const formatAgentDetails = (agents) => {\n if (!agents.length) return 'No agents found';\n return agents.map(agent => {\n const agentTasks = allTasks.filter(t => t.agent_id === agent.id);\n const currentTask = agentTasks.find(t => t.status === 'in_progress');\n return `โ€ข ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\\n โ””โ”€ Working on: ${currentTask.description}` : ''}`;\n }).join('\\n');\n };\n \n // Format task details with more information\n const formatTaskDetails = (tasks, limit = 15) => {\n if (!tasks.length) return 'No tasks found';\n const displayTasks = tasks.slice(0, limit);\n return displayTasks.map(task => {\n const agent = allAgents.find(a => a.id === task.agent_id);\n return `โ€ข [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;\n }).join('\\n') + (tasks.length > limit ? `\\n... and ${tasks.length - limit} more tasks` : '');\n };\n \n // Format checkpoint details\n const formatCheckpoints = (checkpoints, limit = 5) => {\n if (!checkpoints.length) return 'No checkpoints found';\n const displayCheckpoints = checkpoints.slice(0, limit);\n return displayCheckpoints.map(cp => \n `โ€ข ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`\n ).join('\\n');\n };\n \n // Format activity logs with more detail\n const formatActivityLogs = (logs, limit = 20) => {\n if (!logs.length) return 'No activity logs found';\n const displayLogs = logs.slice(0, limit);\n return displayLogs.map(log => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n const agent = log.agent_id ? allAgents.find(a => a.id === log.agent_id) : null;\n return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;\n }).join('\\n');\n };\n \n // Extract metadata if available\n const metadata = session.metadata || {};\n const metadataStr = Object.keys(metadata).length > 0 ? \n Object.entries(metadata).map(([k, v]) => `โ€ข ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`).join('\\n') : \n 'No metadata available';\n\n return `๐Ÿ”„ RESUMING HIVE MIND SESSION\nโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n\nYou are resuming a Hive Mind session with comprehensive context:\n\n๐Ÿ“‹ SESSION DETAILS:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n๐Ÿ“Œ Session ID: ${session.id}\n๐Ÿ“Œ Swarm ID: ${session.swarm_id}\n๐Ÿ“Œ Swarm Name: ${session.swarm_name}\n๐ŸŽฏ Objective: ${session.objective}\n๐Ÿ“Š Overall Progress: ${session.statistics.completionPercentage}% complete\nโฑ๏ธ Session Duration: ${duration} minutes\n๐Ÿ“… Created: ${new Date(session.created_at).toLocaleString()}\nโธ๏ธ Paused: ${session.paused_at ? new Date(session.paused_at).toLocaleString() : 'N/A'}\nโ–ถ๏ธ Resumed: ${new Date().toLocaleString()}\n๐Ÿ”„ Status: ${session.status}\n\n๐Ÿ“Š TASK STATISTICS:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nโ€ข Total Tasks: ${session.statistics.totalTasks}\nโ€ข Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round((completedTasks.length / session.statistics.totalTasks) * 100) : 0}%)\nโ€ข In Progress: ${inProgressTasks.length}\nโ€ข Pending: ${pendingTasks.length}\n\n๐Ÿ‘ฅ SWARM COMPOSITION (${allAgents.length} agents):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nActive Agents (${activeAgents.length}):\n${formatAgentDetails(activeAgents)}\n\nIdle Agents (${idleAgents.length}):\n${formatAgentDetails(idleAgents)}\n\n๐Ÿ“ COMPLETED TASKS (${completedTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(completedTasks, 10)}\n\n๐Ÿ”„ IN-PROGRESS TASKS (${inProgressTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(inProgressTasks)}\n\nโณ PENDING TASKS (${pendingTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(pendingTasks)}\n\n๐Ÿ’พ CHECKPOINT HISTORY (${checkpointHistory.length} total):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatCheckpoints(checkpointHistory)}\n\n๐Ÿ“Š SESSION METADATA:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${metadataStr}\n\n๐Ÿ’พ LAST CHECKPOINT DATA:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${session.checkpoint_data ? JSON.stringify(session.checkpoint_data, null, 2) : 'No checkpoint data available'}\n\n๐Ÿ“œ ACTIVITY LOG (Last ${Math.min(20, activityLogs.length)} entries):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatActivityLogs(activityLogs, 20)}\n\n๐ŸŽฏ RESUMPTION PROTOCOL:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n1. **RESTORE CONTEXT**:\n - Review all checkpoint data and activity history above\n - Use mcp__claude-flow__memory_usage to retrieve collective memory\n - Check agent statuses and reassign tasks if needed\n - Verify all in-progress tasks are still valid\n\n2. **CONTINUE EXECUTION**:\n - Resume in-progress tasks with their assigned agents\n - Process pending tasks based on priority (CRITICAL > HIGH > NORMAL > LOW)\n - Maintain agent coordination through memory sharing\n - Update progress tracking after each task completion\n\n3. **COORDINATION REQUIREMENTS**:\n - Use mcp__claude-flow__memory_usage for all cross-agent communication\n - Apply consensus mechanisms for important decisions\n - Maintain swarm topology: ${session.swarm?.topology || 'unknown'}\n - Keep session checkpoint data updated regularly\n\n4. **MEMORY CONTEXT**:\n - Session memory namespace: session-${session.id}\n - Swarm memory namespace: swarm-${session.swarm_id}\n - Use these namespaces to access historical decisions and context\n\nResume the hive mind operation with full context awareness and continue working towards the objective.`;\n}\n\n/**\n * Launch Claude Code with context\n */\nasync function launchClaudeWithContext(prompt, flags, sessionId) {\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);\n await writeFile(promptFile, prompt);\n console.log(chalk.green(`\\nโœ“ Session context saved to: ${promptFile}`));\n\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\nโš ๏ธ Claude Code CLI not found'));\n console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray(`Run with: claude < ${promptFile}`));\n return;\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Debug logging to track spawn calls\n console.log(chalk.blue('\\n๐Ÿ” Debug: About to spawn Claude Code process...'));\n console.log(chalk.gray(` Session ID: ${sessionId}`));\n console.log(chalk.gray(` Process ID: ${process.pid}`));\n \n // Remove --print to allow interactive session (same as initial spawn)\n const claudeArgs = [prompt];\n\n // Add --dangerously-skip-permissions by default for hive-mind operations\n // unless explicitly disabled with --no-auto-permissions\n if (!flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log(\n chalk.yellow(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n\n console.log(chalk.blue('๐Ÿ” Debug: Spawning with args:'), claudeArgs.slice(0, 1).map(a => a.substring(0, 50) + '...'));\n \n // Use 'inherit' for interactive session (same as initial spawn)\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n \n console.log(chalk.blue('๐Ÿ” Debug: Claude process spawned with PID:'), claudeProcess.pid);\n\n // Track child process PID in session (same as initial spawn)\n const sessionManager = new HiveMindSessionManager();\n if (claudeProcess.pid) {\n const sessions = await sessionManager.getActiveSessions();\n const currentSession = sessions.find(s => s.id === sessionId);\n if (currentSession) {\n await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);\n }\n }\n\n // Set up SIGINT handler for automatic session pausing (same as initial spawn)\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process if still running\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n \n // Clean up and close session manager\n sessionManager.close();\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error during shutdown:'), error.message);\n process.exit(1);\n }\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle process exit (same as initial spawn)\n claudeProcess.on('exit', async (code, signal) => {\n if (!isExiting) {\n console.log('\\n' + chalk.yellow('Claude Code has exited'));\n \n // Clean up signal handlers\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigintHandler);\n \n // Close session manager\n sessionManager.close();\n \n process.exit(code || 0);\n }\n });\n\n console.log(chalk.green('\\nโœ“ Claude Code launched with restored session context'));\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('Failed to launch Claude Code:'), error.message);\n }\n}\n\n/**\n * Get MCP wrapper instance\n */\nasync function getMcpWrapper() {\n const { MCPToolWrapper } = await import('./hive-mind/mcp-wrapper.js');\n return new MCPToolWrapper();\n}\n\n// Export for testing\nexport { showHiveMindHelp, initHiveMind, spawnSwarm, showStatus };\n"],"names":["existsSync","mkdirSync","writeFile","path","inquirer","chalk","ora","cwd","exit","mkdirAsync","warnNonInteractive","safeInteractive","Database","HiveMindCore","QueenCoordinator","CollectiveMemory","SwarmCommunication","HiveMindSessionManager","createAutoSaveMiddleware","HiveMindMetricsReader","showHiveMindHelp","console","log","yellow","bold","green","gray","cyan","blue","initHiveMind","flags","spinner","start","hiveMindDir","join","recursive","dbPath","db","exec","close","config","version","initialized","Date","toISOString","defaults","queenType","maxWorkers","consensusAlgorithm","memorySize","autoScale","encryption","mcpTools","enabled","parallel","timeout","JSON","stringify","succeed","error","fail","red","message","hiveMindWizard","action","prompt","type","name","choices","value","spawnSwarmWizard","showStatus","manageMemoryWizard","showConsensus","showMetrics","configureWizard","objective","now","parseInt","consensus","namespace","verbose","spawnSwarm","nonInteractive","answers","validate","input","trim","length","default","checked","swarmResult","workerTypes","monitor","spawnClaude","swarmId","workers","map","index","id","role","status","capabilities","getAgentCapabilities","claudeFlags","spawnClaudeCodeInstances","args","isNonInteractive","wizard","validQueenTypes","includes","isNaN","validConsensusTypes","hiveMind","text","undefined","Error","dbDir","prepare","get","warn","fs","unlinkSync","e","timestamp","randomPart","Math","random","toString","substring","run","sessionManager","sessionId","createSession","autoSave","saveInterval","autoStart","trackChange","swarmName","workerCount","queen","queenAgent","Object","values","split","i","min","workerType","workerId","worker","charAt","toUpperCase","slice","push","trackAgentActivity","memory","maxSize","store","communication","repeat","isExiting","sigintHandler","checkpointData","reason","saveCheckpoint","pauseSession","global","autoSaveInterval","clearInterval","process","on","claude","spawn","stack","researcher","coder","analyst","tester","architect","reviewer","optimizer","documenter","metricsReader","swarms","getActiveSwarms","swarm","queen_type","created_at","toLocaleString","agent_count","agents","find","a","filter","magenta","forEach","statusColor","taskStats","task_metrics","total","completed","in_progress","pending","failed","completion_percentage","memory_count","consensus_count","decisions","all","decision","swarm_name","topic","algorithm","confidence","toFixed","votes","parse","for","against","abstain","details","Array","isArray","detail","agent","agentId","vote","choice","justification","rationale","displayString","entries","overallStats","taskBreakdown","total_swarms","total_agents","total_tasks","completed_tasks","percentage","count","agentPerf","hasCompletedAt","successRate","tasks_assigned","tasks_completed","avg_completion_minutes","swarmPerf","task_count","completed_count","memory_entries","avgTaskTime","avg_minutes","agentTypePerf","listMemories","searchMemories","storeMemoryWizard","showMemoryStats","cleanMemories","exportMemoryBackup","continue","continueAction","hiveMindCommand","subcommand","subArgs","help","showSessions","resumeSession","stopSession","memories","key","swarm_id","created_by","displayValue","parsed","searchTerm","searchPattern","mcpWrapper","getMcpWrapper","memoryValue","storeMemory","category","searchResult","searchMemory","results","data","stats","categories","oldestDate","newestDate","totalSize","date","toLocaleDateString","days","confirm","cutoffDate","setDate","getDate","oldMemories","memoryDate","filename","backup","exportDate","totalMemories","writeFileSync","getActiveSessionId","sessions","getActiveSessions","activeSession","s","workerGroups","groupWorkersByType","hiveMindPrompt","generateHiveMindPrompt","keys","sessionsDir","promptFile","childSpawn","execSync","claudeAvailable","stdio","dryRun","claudeArgs","claudeProcess","shell","pid","addChildPid","killed","kill","claudePid","stdout","stderr","code","removeChildPid","currentTime","getWorkerTypeInstructions","generateCoordinationInstructions","hiveMindEndpoint","coordinationProtocol","memoryNamespace","consensusThreshold","taskUpdateInterval","healthCheckInterval","workerCapabilities","w","reduce","groups","createClaudeCodeSpawnCommand","typeWorkers","instructions","context","command","replace","title","coordinator","session","statusIcon","updated_at","paused_at","in_progress_tasks","pending_tasks","checkpoint_data","checkpointStr","getSession","resumedSession","statistics","completionPercentage","activeAgents","totalAgents","completedTasks","totalTasks","inProgressTasks","pendingTasks","recentLogs","toLocaleTimeString","restoredPrompt","generateRestoredSessionPrompt","launchClaudeWithContext","allAgents","idleAgents","allTasks","tasks","t","sessionStart","sessionPaused","duration","round","checkpointHistory","checkpoints","activityLogs","formatAgentDetails","agentTasks","agent_id","currentTask","description","formatTaskDetails","limit","displayTasks","task","priority","formatCheckpoints","displayCheckpoints","cp","checkpoint_name","formatActivityLogs","logs","displayLogs","metadata","metadataStr","k","v","topology","currentSession","signal","removeListener","MCPToolWrapper"],"mappings":"AAMA,SAASA,UAAU,EAAEC,SAAS,QAAQ,KAAK;AAC3C,SAASC,SAAS,QAAkB,cAAc;AAClD,OAAOC,UAAU,OAAO;AAExB,OAAOC,cAAc,WAAW;AAChC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAAeC,GAAG,EAAEC,IAAI,EAA+BC,UAAU,QAAQ,oBAAoB;AAC7F,SAGEC,kBAAkB,QAEb,mCAAmC;AAC1C,SACEC,eAAe,QAGV,+BAA+B;AAGtC,OAAOC,cAAc,iBAAiB;AAOtC,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,gBAAgB,QAAQ,uBAAuB;AACxD,SAASC,gBAAgB,QAAQ,wBAAwB;AACzD,SAASC,kBAAkB,QAAQ,+BAA+B;AAClE,SAASC,sBAAsB,QAAQ,iCAAiC;AACxE,SAASC,wBAAwB,QAAQ,sCAAsC;AAC/E,SAASC,qBAAqB,QAAQ,gCAAgC;AAEtE,SAASC;IACPC,QAAQC,GAAG,CAAC,CAAC;AACf,EAAEjB,MAAMkB,MAAM,CAAC,mCAAmC;;AAElD,EAAElB,MAAMmB,IAAI,CAAC,UAAU;;;AAGvB,EAAEnB,MAAMmB,IAAI,CAAC,gBAAgB;EAC3B,EAAEnB,MAAMoB,KAAK,CAAC,QAAQ;EACtB,EAAEpB,MAAMoB,KAAK,CAAC,SAAS;EACvB,EAAEpB,MAAMoB,KAAK,CAAC,UAAU;EACxB,EAAEpB,MAAMoB,KAAK,CAAC,UAAU;EACx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AAMoB,KAAK,CAAC,OAAO;oBAC/BJ,QAAQC,GAAG,CAACjB,MAAMsB,IAAI,CAAC;oBACvBN,QAAQC,GAAG,CAACjB,MAAMmB,IAAI,CAAC,CAAC,+BAA+B,EAAE4G,WAAW;oBACpE/G,QAAQC,GAAG;oBAEXmJ,QAAQjK,IAAI,CAAC;gBACf,EAAE,OAAOmD,OAAO;oBACdtC,QAAQsC,KAAK,CAACtD,MAAMwD,GAAG,CAAC,2BAA2BF,MAAMG,OAAO;oBAChE2G,QAAQjK,IAAI,CAAC;gBACf;YACF;YAEAiK,QAAQC,EAAE,CAAC,UAAUT;YACrBQ,QAAQC,EAAE,CAAC,WAAWT;YAGtBiK,cAAcxJ,EAAE,CAAC,QAAQ,OAAOiK,MAAMiF;gBACpC,IAAI,CAAC5P,WAAW;oBACd3I,QAAQC,GAAG,CAAC,OAAOjB,MAAMkB,MAAM,CAAC;oBAGhCkJ,QAAQoP,cAAc,CAAC,UAAU5P;oBACjCQ,QAAQoP,cAAc,CAAC,WAAW5P;oBAGlC9B,eAAe5F,KAAK;oBAEpBkI,QAAQjK,IAAI,CAACmU,QAAQ;gBACvB;YACF;YAEAtT,QAAQC,GAAG,CAACjB,MAAMoB,KAAK,CAAC;YACxBJ,QAAQC,GAAG,CAACjB,MAAMqB,IAAI,CAAC,CAAC,wBAAwB,EAAEiS,YAAY;QAChE;IACF,EAAE,OAAOhQ,OAAO;QACdtC,QAAQsC,KAAK,CAACtD,MAAMwD,GAAG,CAAC,kCAAkCF,MAAMG,OAAO;IACzE;AACF;AAKA,eAAeuN;IACb,MAAM,EAAEyI,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC;IACxC,OAAO,IAAIA;AACb;AAGA,SAAS1Y,gBAAgB,EAAES,YAAY,EAAEqD,UAAU,EAAEX,UAAU,GAAG"} \ No newline at end of file +{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence\nimport Database from 'better-sqlite3';\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('๐Ÿง  Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('๐Ÿ')} Queen-led coordination with worker specialization\n ${chalk.cyan('๐Ÿง ')} Collective memory and knowledge sharing\n ${chalk.cyan('๐Ÿค')} Consensus building for critical decisions\n ${chalk.cyan('โšก')} Parallel task execution with auto-scaling\n ${chalk.cyan('๐Ÿ”„')} Work stealing and load balancing\n ${chalk.cyan('๐Ÿ“Š')} Real-time metrics and performance tracking\n ${chalk.cyan('๐Ÿ›ก๏ธ')} Fault tolerance and self-healing\n ${chalk.cyan('๐Ÿ”’')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type Queen coordinator type (strategic, tactical, adaptive)\n --max-workers Maximum worker agents (default: 8)\n --consensus Consensus algorithm (majority, weighted, byzantine)\n --memory-size Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind system...').start();\n\n try {\n // Create hive mind directory structure\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n if (!existsSync(hiveMindDir)) {\n mkdirSync(hiveMindDir, { recursive: true });\n }\n\n // Initialize SQLite database\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const db = new Database(dbPath);\n\n // Create tables\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n queen_type TEXT DEFAULT 'strategic',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n `);\n\n db.close();\n\n // Create configuration file\n const config = {\n version: '2.0.0',\n initialized: new Date().toISOString(),\n defaults: {\n queenType: 'strategic',\n maxWorkers: 8,\n consensusAlgorithm: 'majority',\n memorySize: 100,\n autoScale: true,\n encryption: false,\n },\n mcpTools: {\n enabled: true,\n parallel: true,\n timeout: 60000,\n },\n };\n\n await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));\n\n spinner.succeed('Hive Mind system initialized successfully!');\n\n console.log('\\n' + chalk.green('โœ“') + ' Created .hive-mind directory');\n console.log(chalk.green('โœ“') + ' Initialized SQLite database');\n console.log(chalk.green('โœ“') + ' Created configuration file');\n console.log('\\n' + chalk.yellow('Next steps:'));\n console.log(\n ' 1. Run ' + chalk.cyan('claude-flow hive-mind spawn') + ' to create your first swarm',\n );\n console.log(\n ' 2. Use ' + chalk.cyan('claude-flow hive-mind wizard') + ' for interactive setup',\n );\n } catch (error) {\n spinner.fail('Failed to initialize Hive Mind system');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Interactive wizard for hive mind operations\n */\n// Wrapped wizard function that handles non-interactive environments\nconst hiveMindWizard = safeInteractive(\n // Interactive version\n async function (flags = {}) {\n console.log(chalk.yellow('\\n๐Ÿง™ Hive Mind Interactive Wizard\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: '๐Ÿ Create new swarm', value: 'spawn' },\n { name: '๐Ÿ“Š View swarm status', value: 'status' },\n { name: '๐Ÿง  Manage collective memory', value: 'memory' },\n { name: '๐Ÿค View consensus decisions', value: 'consensus' },\n { name: '๐Ÿ“ˆ Performance metrics', value: 'metrics' },\n { name: '๐Ÿ”ง Configure hive mind', value: 'config' },\n { name: 'โŒ Exit', value: 'exit' },\n ],\n },\n ]);\n\n switch (action) {\n case 'spawn':\n await spawnSwarmWizard();\n break;\n case 'status':\n await showStatus({});\n break;\n case 'memory':\n await manageMemoryWizard();\n break;\n case 'consensus':\n await showConsensus({});\n break;\n case 'metrics':\n await showMetrics({});\n break;\n case 'config':\n await configureWizard();\n break;\n case 'exit':\n console.log(chalk.gray('Exiting wizard...'));\n break;\n }\n },\n // Non-interactive fallback\n async function (flags = {}) {\n console.log(chalk.yellow('\\n๐Ÿง™ Hive Mind - Non-Interactive Mode\\n'));\n\n // Default to creating a swarm with sensible defaults\n console.log(chalk.cyan('Creating new swarm with default settings...'));\n console.log(chalk.gray('Use command-line flags to customize:'));\n console.log(chalk.gray(' --objective \"Your task\" Set swarm objective'));\n console.log(chalk.gray(' --queen-type strategic Set queen type'));\n console.log(chalk.gray(' --max-workers 8 Set worker count'));\n console.log();\n\n const objective = flags.objective || 'General task coordination';\n const config = {\n name: flags.name || `swarm-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale || flags['auto-scale'] || false,\n namespace: flags.namespace || 'default',\n verbose: flags.verbose || false,\n encryption: flags.encryption || false,\n };\n\n await spawnSwarm([objective], {\n ...flags,\n name: config.name,\n queenType: config.queenType,\n maxWorkers: config.maxWorkers,\n consensusAlgorithm: config.consensusAlgorithm,\n autoScale: config.autoScale,\n encryption: config.encryption,\n nonInteractive: true,\n });\n },\n);\n\n/**\n * Spawn swarm wizard\n */\nasync function spawnSwarmWizard() {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'objective',\n message: 'What is the swarm objective?',\n validate: (input) => input.trim().length > 0 || 'Please enter an objective',\n },\n {\n type: 'input',\n name: 'name',\n message: 'Swarm name (optional):',\n default: (answers) => `swarm-${Date.now()}`,\n },\n {\n type: 'list',\n name: 'queenType',\n message: 'Select queen coordinator type:',\n choices: [\n { name: 'Strategic - High-level planning and coordination', value: 'strategic' },\n { name: 'Tactical - Detailed task management', value: 'tactical' },\n { name: 'Adaptive - Learns and adapts strategies', value: 'adaptive' },\n ],\n default: 'strategic',\n },\n {\n type: 'number',\n name: 'maxWorkers',\n message: 'Maximum number of worker agents:',\n default: 8,\n validate: (input) => (input > 0 && input <= 20) || 'Please enter a number between 1 and 20',\n },\n {\n type: 'checkbox',\n name: 'workerTypes',\n message: 'Select worker agent types:',\n choices: [\n { name: 'Researcher', value: 'researcher', checked: true },\n { name: 'Coder', value: 'coder', checked: true },\n { name: 'Analyst', value: 'analyst', checked: true },\n { name: 'Tester', value: 'tester', checked: true },\n { name: 'Architect', value: 'architect' },\n { name: 'Reviewer', value: 'reviewer' },\n { name: 'Optimizer', value: 'optimizer' },\n { name: 'Documenter', value: 'documenter' },\n ],\n },\n {\n type: 'list',\n name: 'consensusAlgorithm',\n message: 'Consensus algorithm for decisions:',\n choices: [\n { name: 'Majority - Simple majority voting', value: 'majority' },\n { name: 'Weighted - Expertise-weighted voting', value: 'weighted' },\n { name: 'Byzantine - Fault-tolerant consensus', value: 'byzantine' },\n ],\n default: 'majority',\n },\n {\n type: 'confirm',\n name: 'autoScale',\n message: 'Enable auto-scaling?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'monitor',\n message: 'Launch monitoring dashboard?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'spawnClaude',\n message: 'Spawn Claude Code instance with hive-mind coordination?',\n default: true,\n },\n ]);\n\n // Spawn the swarm with collected parameters\n const swarmResult = await spawnSwarm([answers.objective], {\n name: answers.name,\n queenType: answers.queenType,\n 'queen-type': answers.queenType,\n maxWorkers: answers.maxWorkers,\n 'max-workers': answers.maxWorkers,\n workerTypes: answers.workerTypes.join(','),\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n 'auto-scale': answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false,\n spawnClaude: answers.spawnClaude, // Pass the Claude spawning preference\n });\n\n // If Claude Code spawning was requested, launch it using the same function as --claude flag\n if (answers.spawnClaude && swarmResult && swarmResult.swarmId) {\n // Create workers array in the same format expected by spawnClaudeCodeInstances\n const workers = answers.workerTypes.map((type, index) => ({\n id: `worker-${index + 1}`,\n type,\n role: 'worker',\n status: 'active',\n capabilities: getAgentCapabilities(type)\n }));\n \n // Create flags object with the wizard settings\n const claudeFlags = {\n queenType: answers.queenType,\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false\n };\n \n // Use the same Claude spawning function as the --claude flag\n console.log(chalk.cyan(`\\n๐ŸŽฏ Objective from wizard: \"${answers.objective}\"`));\n await spawnClaudeCodeInstances(\n swarmResult.swarmId,\n answers.name,\n answers.objective,\n workers,\n claudeFlags\n );\n }\n \n return swarmResult;\n}\n\n/**\n * Spawn a hive mind swarm\n */\nasync function spawnSwarm(args, flags) {\n const objective = args.join(' ').trim();\n\n // Check for non-interactive mode FIRST\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n if (!objective && !flags.wizard) {\n if (isNonInteractive) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n } else {\n console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));\n console.log('Example: claude-flow hive-mind spawn \"Build REST API\"');\n }\n return;\n }\n \n // Log non-interactive mode status\n if (isNonInteractive && flags.verbose) {\n console.log(chalk.cyan('๐Ÿค– Running in non-interactive mode'));\n }\n\n // Validate parameters\n if (flags.verbose) {\n console.log(chalk.gray('๐Ÿ” Debug: Parsed flags:'));\n console.log(chalk.gray(JSON.stringify(flags, null, 2)));\n }\n\n // Validate queen type\n const validQueenTypes = ['strategic', 'tactical', 'adaptive'];\n const queenType = flags.queenType || flags['queen-type'] || 'strategic';\n if (!validQueenTypes.includes(queenType)) {\n console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));\n return;\n }\n\n // Validate max workers\n const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');\n if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {\n console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));\n return;\n }\n\n // Validate consensus algorithm\n const validConsensusTypes = ['majority', 'weighted', 'byzantine'];\n const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';\n if (!validConsensusTypes.includes(consensusAlgorithm)) {\n console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));\n return;\n }\n\n const spinner = ora('Spawning Hive Mind swarm...').start();\n\n try {\n // Initialize hive mind core with error handling\n let hiveMind;\n try {\n spinner.text = 'Initializing Hive Mind Core...';\n hiveMind = new HiveMindCore({\n objective,\n name: flags.name || `hive-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale !== undefined ? flags.autoScale : (flags['auto-scale'] !== undefined ? flags['auto-scale'] : true),\n namespace: flags.namespace || 'default',\n encryption: flags.encryption || false,\n });\n } catch (error) {\n console.error('HiveMindCore initialization failed:', error);\n throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);\n }\n\n spinner.text = 'Setting up database connection...';\n // Initialize database connection\n const dbDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(dbDir, 'hive.db');\n\n // Ensure .hive-mind directory exists\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Check if database file exists and try to create a clean one if needed\n let db;\n try {\n spinner.text = 'Creating database connection...';\n db = new Database(dbPath);\n // Test the database with a simple query\n db.prepare('SELECT 1').get();\n spinner.text = 'Database connection established';\n } catch (error) {\n console.warn('Database issue detected, recreating...', error.message);\n spinner.text = 'Recreating database...';\n // Remove corrupted database\n if (existsSync(dbPath)) {\n try {\n const fs = await import('fs');\n fs.unlinkSync(dbPath);\n } catch (e) {\n console.warn('Could not remove corrupted database:', e.message);\n }\n }\n // Create new database\n db = new Database(dbPath);\n }\n\n // Initialize database schema if not exists\n spinner.text = 'Creating database schema...';\n try {\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n queen_type TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT NOT NULL,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n swarm_name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n paused_at DATETIME,\n resumed_at DATETIME,\n completion_percentage REAL DEFAULT 0,\n checkpoint_data TEXT,\n metadata TEXT,\n parent_pid INTEGER,\n child_pids TEXT,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_checkpoints (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n checkpoint_name TEXT NOT NULL,\n checkpoint_data TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_logs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\n log_level TEXT DEFAULT 'info',\n message TEXT,\n agent_id TEXT,\n data TEXT,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n `);\n spinner.text = 'Database schema created successfully';\n } catch (error) {\n console.error('Database schema creation failed:', error);\n throw new Error(`Failed to create database schema: ${error.message}`);\n }\n\n // Create swarm record with safe ID generation\n spinner.text = 'Creating swarm record...';\n const timestamp = Date.now();\n const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr\n const swarmId = `swarm-${timestamp}-${randomPart}`;\n try {\n db.prepare(\n `\n INSERT INTO swarms (id, name, objective, queen_type)\n VALUES (?, ?, ?, ?)\n `,\n ).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);\n } catch (error) {\n console.error('Failed to create swarm record:', error);\n throw new Error(`Failed to create swarm record: ${error.message}`);\n }\n\n // Create session for this swarm\n spinner.text = 'Creating session tracking...';\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {\n queenType: hiveMind.config.queenType,\n maxWorkers: hiveMind.config.maxWorkers,\n consensusAlgorithm: hiveMind.config.consensusAlgorithm,\n autoScale: hiveMind.config.autoScale,\n encryption: hiveMind.config.encryption,\n workerTypes: flags.workerTypes,\n });\n\n spinner.text = 'Session tracking established...';\n\n // Initialize auto-save middleware (use the same session manager)\n const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {\n saveInterval: 30000, // Save every 30 seconds\n autoStart: true,\n });\n\n // Close session manager after auto-save is set up\n // sessionManager.close(); // Don't close yet as auto-save needs it\n\n // Track initial swarm creation\n autoSave.trackChange('swarm_created', {\n swarmId,\n swarmName: hiveMind.config.name,\n objective,\n workerCount: hiveMind.config.maxWorkers,\n });\n\n spinner.text = 'Initializing Queen coordinator...';\n\n // Initialize Queen\n const queen = new QueenCoordinator({\n swarmId,\n type: hiveMind.config.queenType,\n objective,\n });\n\n // Spawn Queen agent\n const queenAgent = {\n id: `queen-${swarmId}`,\n swarmId,\n name: 'Queen Coordinator',\n type: 'coordinator',\n role: 'queen',\n status: 'active',\n capabilities: JSON.stringify(['coordination', 'planning', 'decision-making']),\n };\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(queenAgent));\n\n spinner.text = 'Spawning worker agents...';\n\n // Determine worker types\n const workerTypes = flags.workerTypes\n ? flags.workerTypes.split(',')\n : ['researcher', 'coder', 'analyst', 'tester'];\n\n // Spawn worker agents\n const workers = [];\n for (let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++) {\n const workerType = workerTypes[i % workerTypes.length];\n const workerId = `worker-${swarmId}-${i}`;\n\n const worker = {\n id: workerId,\n swarmId,\n name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,\n type: workerType,\n role: 'worker',\n status: 'idle',\n capabilities: JSON.stringify(getAgentCapabilities(workerType)),\n };\n\n workers.push(worker);\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(worker));\n\n // Track agent spawning for auto-save\n autoSave.trackAgentActivity(workerId, 'spawned', {\n type: workerType,\n name: worker.name,\n });\n }\n\n spinner.text = 'Initializing collective memory...';\n\n // Initialize collective memory\n const memory = new CollectiveMemory({\n swarmId,\n maxSize: flags.memorySize || 100,\n });\n\n // Store initial context\n memory.store('objective', objective, 'context');\n memory.store('queen_type', hiveMind.config.queenType, 'config');\n memory.store('worker_count', workers.length, 'metrics');\n memory.store('session_id', sessionId, 'system');\n\n spinner.text = 'Establishing communication channels...';\n\n // Initialize communication system\n const communication = new SwarmCommunication({\n swarmId,\n encryption: hiveMind.config.encryption,\n });\n\n db.close();\n\n spinner.succeed('Hive Mind swarm spawned successfully!');\n\n // Display swarm summary\n console.log('\\n' + chalk.bold('๐Ÿ Swarm Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Name:'), hiveMind.config.name);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);\n console.log(chalk.cyan('Workers:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));\n console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);\n console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n // Launch monitoring if requested\n if (flags.monitor) {\n console.log('\\n' + chalk.yellow('Launching monitoring dashboard...'));\n // TODO: Implement monitoring dashboard\n }\n\n // Enhanced coordination instructions with MCP tools\n console.log('\\n' + chalk.green('โœ“') + ' Swarm is ready for coordination');\n console.log(chalk.gray('Use \"claude-flow hive-mind status\" to view swarm activity'));\n console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));\n console.log(chalk.blue('๐Ÿ’ก To pause:') + ' Press Ctrl+C to safely pause and resume later');\n console.log(chalk.blue('๐Ÿ’ก To resume:') + ' claude-flow hive-mind resume ' + sessionId);\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session...'));\n \n try {\n // Save current checkpoint using the existing session manager\n // const sessionManager = new HiveMindSessionManager(); // Use existing one\n \n // Create checkpoint data\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n workerCount: workers.length,\n workerTypes,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C',\n };\n \n // Save checkpoint\n await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);\n \n // Pause the session\n await sessionManager.pauseSession(sessionId);\n \n // Close session manager\n sessionManager.close();\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n // Clean up auto-save if active\n if (global.autoSaveInterval) {\n clearInterval(global.autoSaveInterval);\n }\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Offer to spawn Claude Code instances with coordination instructions\n // Spawn Claude if --claude or --spawn flag is set\n if (flags.claude || flags.spawn) {\n await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);\n } else {\n console.log(\n '\\n' +\n chalk.blue('๐Ÿ’ก Pro Tip:') +\n ' Add --claude to spawn coordinated Claude Code instances',\n );\n console.log(chalk.gray(' claude-flow hive-mind spawn \"objective\" --claude'));\n }\n\n // Return swarm info for wizard use\n return { swarmId, hiveMind };\n } catch (error) {\n spinner.fail('Failed to spawn Hive Mind swarm');\n console.error(chalk.red('Error:'), error.message);\n\n // If error contains \"sha3\", provide specific guidance\n if (error.message.includes('sha3') || error.message.includes('SHA3')) {\n console.error('\\n๐Ÿ” SHA3 Function Error Detected');\n console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');\n console.error('\\nPossible solutions:');\n console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');\n console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');\n console.error('3. Check if any SQLite extensions are conflicting');\n console.error('\\n๐Ÿšจ Detailed error:');\n console.error(error.stack || error.message);\n }\n\n exit(1);\n }\n}\n\n/**\n * Get agent capabilities based on type\n */\nfunction getAgentCapabilities(type) {\n const capabilities = {\n researcher: ['web-search', 'data-gathering', 'analysis', 'synthesis'],\n coder: ['code-generation', 'implementation', 'refactoring', 'debugging'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting', 'visualization'],\n tester: ['test-generation', 'quality-assurance', 'bug-detection', 'validation'],\n architect: ['system-design', 'architecture', 'planning', 'documentation'],\n reviewer: ['code-review', 'quality-check', 'feedback', 'improvement'],\n optimizer: ['performance-tuning', 'optimization', 'profiling', 'enhancement'],\n documenter: ['documentation', 'explanation', 'tutorial-creation', 'knowledge-base'],\n };\n\n return capabilities[type] || ['general'];\n}\n\n/**\n * Show hive mind status\n */\nasync function showStatus(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n\n if (!existsSync(dbPath)) {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Use the metrics reader for real data\n const metricsReader = new HiveMindMetricsReader(dbPath);\n const swarms = metricsReader.getActiveSwarms();\n\n if (swarms.length === 0) {\n console.log(chalk.gray('No active swarms found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿ Active Hive Mind Swarms\\n'));\n\n for (const swarm of swarms) {\n console.log(chalk.yellow('โ•'.repeat(60)));\n console.log(chalk.cyan('Swarm:'), swarm.name);\n console.log(chalk.cyan('ID:'), swarm.id);\n console.log(chalk.cyan('Objective:'), swarm.objective);\n console.log(chalk.cyan('Queen Type:'), swarm.queen_type);\n console.log(chalk.cyan('Status:'), chalk.green(swarm.status));\n console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());\n \n // Show real agent count\n console.log(chalk.cyan('Total Agents:'), swarm.agent_count || 0);\n\n console.log('\\n' + chalk.bold('Agents:'));\n\n // Group by role using real agent data\n const agents = swarm.agents || [];\n const queen = agents.find((a) => a.role === 'queen');\n const workers = agents.filter((a) => a.role === 'worker');\n\n if (queen) {\n console.log(' ' + chalk.magenta('๐Ÿ‘‘ Queen:'), queen.name, chalk.gray(`(${queen.status})`));\n } else {\n console.log(' ' + chalk.gray('No queen assigned yet'));\n }\n\n console.log(' ' + chalk.blue('๐Ÿ Workers:'));\n if (workers.length > 0) {\n workers.forEach((worker) => {\n const statusColor =\n worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';\n console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);\n });\n } else {\n console.log(' ' + chalk.gray('No workers spawned yet'));\n }\n\n // Get real task statistics\n const taskStats = swarm.task_metrics || {\n total: 0,\n completed: 0,\n in_progress: 0,\n pending: 0,\n failed: 0\n };\n\n console.log('\\n' + chalk.bold('Tasks:'));\n console.log(` Total: ${taskStats.total}`);\n console.log(` Completed: ${chalk.green(taskStats.completed || 0)}`);\n console.log(` In Progress: ${chalk.yellow(taskStats.in_progress || 0)}`);\n console.log(` Pending: ${chalk.gray(taskStats.pending || 0)}`);\n console.log(` ${chalk.bold('Completion:')} ${swarm.completion_percentage || 0}%`);\n\n // Show real memory count\n console.log('\\n' + chalk.bold('Collective Memory:'));\n console.log(` Entries: ${swarm.memory_count || 0}`);\n\n // Show real consensus count\n console.log('\\n' + chalk.bold('Consensus Decisions:'));\n console.log(` Total: ${swarm.consensus_count || 0}`);\n }\n\n console.log(chalk.yellow('โ•'.repeat(60)) + '\\n');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show consensus decisions\n */\nasync function showConsensus(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const decisions = db\n .prepare(\n `\n SELECT cd.*, s.name as swarm_name\n FROM consensus_decisions cd\n JOIN swarms s ON cd.swarm_id = s.id\n ORDER BY cd.created_at DESC\n LIMIT 20\n `,\n )\n .all();\n\n if (decisions.length === 0) {\n console.log(chalk.gray('No consensus decisions found'));\n db.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿค Recent Consensus Decisions\\n'));\n\n decisions.forEach((decision) => {\n console.log(chalk.yellow('โ”€'.repeat(50)));\n console.log(chalk.cyan('Swarm:'), decision.swarm_name);\n console.log(chalk.cyan('Topic:'), decision.topic);\n console.log(chalk.cyan('Decision:'), decision.decision);\n console.log(chalk.cyan('Algorithm:'), decision.algorithm);\n console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);\n console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());\n\n if (decision.votes) {\n const votes = JSON.parse(decision.votes);\n console.log(chalk.cyan('Votes:'));\n\n // Handle vote summary format (for/against/abstain/details)\n if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {\n console.log(` - for: ${votes.for || 0}`);\n console.log(` - against: ${votes.against || 0}`);\n console.log(` - abstain: ${votes.abstain || 0}`);\n\n // Display vote details properly if they exist\n if (votes.details && Array.isArray(votes.details)) {\n console.log(' - details:');\n votes.details.forEach((detail, index) => {\n if (typeof detail === 'object') {\n // Extract available fields\n const agent =\n detail.agentId ||\n detail.agent ||\n detail.id ||\n detail.name ||\n `agent-${index + 1}`;\n const vote = detail.vote || detail.choice || detail.decision || 'unknown';\n const reason = detail.reason || detail.justification || detail.rationale;\n\n // Build display string\n let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;\n\n // Add reason if available\n if (reason && reason !== 'N/A' && reason !== '') {\n displayString += `, Reason: ${reason}`;\n }\n\n console.log(displayString);\n } else {\n console.log(` ${index + 1}. ${detail}`);\n }\n });\n }\n } else {\n // Handle individual agent votes format\n Object.entries(votes).forEach(([agent, vote]) => {\n console.log(` - ${agent}: ${vote}`);\n });\n }\n }\n });\n\n console.log(chalk.yellow('โ”€'.repeat(50)) + '\\n');\n\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show performance metrics\n */\nasync function showMetrics(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n // Get overall metrics\n const overallStats = db\n .prepare(\n `\n SELECT \n (SELECT COUNT(*) FROM swarms) as total_swarms,\n (SELECT COUNT(*) FROM agents) as total_agents,\n (SELECT COUNT(*) FROM tasks) as total_tasks,\n (SELECT COUNT(*) FROM tasks WHERE status = 'completed') as completed_tasks\n `,\n )\n .get();\n\n console.log(chalk.bold('\\n๐Ÿ“Š Hive Mind Performance Metrics\\n'));\n\n // Get task status breakdown\n const taskBreakdown = db\n .prepare(\n `\n SELECT \n status,\n COUNT(*) as count\n FROM tasks\n GROUP BY status\n ORDER BY count DESC\n `,\n )\n .all();\n\n console.log(chalk.cyan('Overall Statistics:'));\n console.log(` Total Swarms: ${overallStats.total_swarms}`);\n console.log(` Total Agents: ${overallStats.total_agents}`);\n console.log(` Total Tasks: ${overallStats.total_tasks}`);\n console.log(` Completed Tasks: ${overallStats.completed_tasks}`);\n console.log(\n ` Success Rate: ${\n overallStats.total_tasks > 0\n ? ((overallStats.completed_tasks / overallStats.total_tasks) * 100).toFixed(1) + '%'\n : 'N/A'\n }`,\n );\n\n if (taskBreakdown.length > 0) {\n console.log('\\n' + chalk.cyan('Task Status Breakdown:'));\n taskBreakdown.forEach((status) => {\n const percentage =\n overallStats.total_tasks > 0\n ? ((status.count / overallStats.total_tasks) * 100).toFixed(1)\n : '0';\n const statusColor =\n status.status === 'completed'\n ? 'green'\n : status.status === 'in_progress'\n ? 'yellow'\n : status.status === 'failed'\n ? 'red'\n : 'gray';\n console.log(\n ` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`,\n );\n });\n }\n\n // Get agent performance (check for completed_at column)\n let agentPerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent performance:', error.message);\n }\n\n if (agentPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Top Performing Agents:'));\n agentPerf.forEach((agent, index) => {\n const successRate =\n agent.tasks_assigned > 0\n ? ((agent.tasks_completed / agent.tasks_assigned) * 100).toFixed(1)\n : '0';\n console.log(` ${index + 1}. ${agent.name} (${agent.type})`);\n console.log(\n ` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`,\n );\n if (agent.avg_completion_minutes) {\n console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n\n // Get swarm performance\n const swarmPerf = db\n .prepare(\n `\n SELECT \n s.name,\n s.objective,\n (SELECT COUNT(*) FROM agents a WHERE a.swarm_id = s.id) as agent_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id) as task_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id AND t.status = 'completed') as completed_count,\n (SELECT COUNT(*) FROM collective_memory cm WHERE cm.swarm_id = s.id) as memory_entries,\n (SELECT COUNT(*) FROM consensus_decisions cd WHERE cd.swarm_id = s.id) as consensus_count\n FROM swarms s\n WHERE s.status = 'active'\n ORDER BY s.created_at DESC\n LIMIT 5\n `,\n )\n .all();\n\n if (swarmPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Active Swarm Performance:'));\n swarmPerf.forEach((swarm) => {\n const successRate =\n swarm.task_count > 0\n ? ((swarm.completed_count / swarm.task_count) * 100).toFixed(1)\n : '0';\n console.log(`\\n ${chalk.yellow(swarm.name)}`);\n console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);\n console.log(\n ` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`,\n );\n console.log(\n ` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`,\n );\n });\n }\n\n // Get performance insights\n let avgTaskTime = { avg_minutes: null };\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n avgTaskTime = db\n .prepare(\n `\n SELECT \n AVG(CASE WHEN completed_at IS NOT NULL \n THEN (julianday(completed_at) - julianday(created_at)) * 24 * 60 \n ELSE NULL END) as avg_minutes\n FROM tasks\n WHERE status = 'completed'\n `,\n )\n .get();\n }\n } catch (error) {\n console.warn('Could not calculate average task time:', error.message);\n }\n\n // Get agent type performance\n let agentTypePerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent type performance:', error.message);\n }\n\n if (avgTaskTime.avg_minutes) {\n console.log('\\n' + chalk.cyan('Performance Insights:'));\n console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);\n\n if (agentTypePerf.length > 0) {\n console.log('\\n' + chalk.cyan('Agent Type Performance:'));\n agentTypePerf.forEach((type) => {\n const successRate =\n type.total_tasks > 0\n ? ((type.completed_tasks / type.total_tasks) * 100).toFixed(1)\n : '0';\n console.log(\n ` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`,\n );\n if (type.avg_completion_minutes) {\n console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n }\n\n console.log('\\n');\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Manage collective memory wizard\n */\nasync function manageMemoryWizard() {\n console.log(chalk.blue('\\n๐Ÿง  Collective Memory Management\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do with collective memory?',\n choices: [\n { name: '๐Ÿ“‹ View all memories', value: 'list' },\n { name: '๐Ÿ” Search memories', value: 'search' },\n { name: '๐Ÿ’พ Store new memory', value: 'store' },\n { name: '๐Ÿ“Š Memory statistics', value: 'stats' },\n { name: '๐Ÿ—‘๏ธ Clean old memories', value: 'clean' },\n { name: '๐Ÿ“ค Export memory backup', value: 'export' },\n { name: 'โฌ…๏ธ Back to main menu', value: 'back' },\n ],\n },\n ]);\n\n switch (action) {\n case 'list':\n await listMemories();\n break;\n case 'search':\n await searchMemories();\n break;\n case 'store':\n await storeMemoryWizard();\n break;\n case 'stats':\n await showMemoryStats();\n break;\n case 'clean':\n await cleanMemories();\n break;\n case 'export':\n await exportMemoryBackup();\n break;\n case 'back':\n await hiveMindWizard();\n return;\n }\n\n // Ask if user wants to continue\n const { continue: continueAction } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'continue',\n message: 'Would you like to perform another memory operation?',\n default: true,\n },\n ]);\n\n if (continueAction) {\n await manageMemoryWizard();\n }\n}\n\n/**\n * Configure hive mind wizard\n */\nasync function configureWizard() {\n // TODO: Implement configuration wizard\n console.log(chalk.yellow('Configuration wizard coming soon...'));\n}\n\n/**\n * Main hive mind command handler\n */\nexport async function hiveMindCommand(args, flags) {\n const subcommand = args[0];\n const subArgs = args.slice(1);\n\n // Handle help flags\n if (\n !subcommand ||\n subcommand === '--help' ||\n subcommand === '-h' ||\n subcommand === 'help' ||\n flags.help\n ) {\n showHiveMindHelp();\n return;\n }\n\n // Warn about non-interactive environments for certain commands\n if ((subcommand === 'spawn' && (flags.claude || flags.spawn)) || subcommand === 'wizard') {\n warnNonInteractive('hive-mind ' + subcommand);\n }\n\n switch (subcommand) {\n case 'init':\n await initHiveMind(flags);\n break;\n\n case 'spawn':\n // Check for non-interactive mode FIRST (like alpha.83)\n if (flags['non-interactive'] || flags.nonInteractive) {\n // In non-interactive mode, skip wizard and use defaults\n if (subArgs.length === 0) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n return;\n }\n await spawnSwarm(subArgs, flags);\n } else if (flags.wizard || subArgs.length === 0) {\n await spawnSwarmWizard();\n } else {\n await spawnSwarm(subArgs, flags);\n }\n break;\n\n case 'status':\n await showStatus(flags);\n break;\n\n case 'sessions':\n await showSessions(flags);\n break;\n\n case 'resume':\n await resumeSession(subArgs, flags);\n break;\n\n case 'stop':\n await stopSession(subArgs, flags);\n break;\n\n case 'consensus':\n await showConsensus(flags);\n break;\n\n case 'memory':\n await manageMemoryWizard();\n break;\n\n case 'metrics':\n await showMetrics(flags);\n break;\n\n case 'wizard':\n await hiveMindWizard(flags);\n break;\n\n case 'help':\n case '--help':\n case '-h':\n showHiveMindHelp();\n break;\n\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log('Run \"claude-flow hive-mind help\" for usage information');\n exit(1);\n }\n}\n\n/**\n * List all memories in the collective memory store\n */\nasync function listMemories() {\n try {\n console.log(chalk.blue('\\n๐Ÿ“‹ Collective Memory Store\\n'));\n\n // Read directly from hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all();\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found in the collective store.'));\n console.log(\n chalk.gray('Try storing some memories first using the \"๐Ÿ’พ Store new memory\" option.'),\n );\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.cyan(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n console.log(` Created by: ${memory.created_by || 'system'}`);\n \n // Parse and display value\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed);\n } catch {\n // Keep as string\n }\n \n if (displayValue.length > 100) {\n console.log(` Value: ${displayValue.substring(0, 100)}...`);\n } else {\n console.log(` Value: ${displayValue}`);\n }\n \n if (memory.confidence !== null && memory.confidence !== 1) {\n console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);\n }\n \n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error listing memories:'), error.message);\n console.log(chalk.gray('This might be because no memories have been stored yet.'));\n }\n}\n\n/**\n * Search memories by keyword\n */\nasync function searchMemories() {\n try {\n const { searchTerm } = await inquirer.prompt([\n {\n type: 'input',\n name: 'searchTerm',\n message: 'Enter search term:',\n validate: (input) => input.length > 0,\n },\n ]);\n\n console.log(chalk.blue(`\\n๐Ÿ” Searching for: \"${searchTerm}\"\\n`));\n\n // Search directly in hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const searchPattern = `%${searchTerm}%`;\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n WHERE cm.key LIKE ? OR cm.value LIKE ? OR cm.type LIKE ?\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all(searchPattern, searchPattern, searchPattern);\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found matching your search.'));\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories matching \"${searchTerm}\":\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.green(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n \n // Parse and display value with highlighting\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed, null, 2);\n } catch {\n // Keep as string\n }\n \n console.log(` Value: ${displayValue}`);\n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error searching memories:'), error.message);\n }\n}\n\n/**\n * Store new memory wizard\n */\nasync function storeMemoryWizard() {\n try {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'key',\n message: 'Memory key (identifier):',\n validate: (input) => input.length > 0,\n },\n {\n type: 'list',\n name: 'category',\n message: 'Memory category:',\n choices: [\n 'consensus',\n 'decision',\n 'pattern',\n 'learning',\n 'coordination',\n 'performance',\n 'configuration',\n 'general',\n ],\n },\n {\n type: 'editor',\n name: 'value',\n message: 'Memory content (JSON or text):',\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n let memoryValue;\n\n // Try to parse as JSON, fall back to string\n try {\n memoryValue = JSON.parse(answers.value);\n } catch {\n memoryValue = answers.value;\n }\n\n await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);\n\n console.log(chalk.green(`\\nโœ… Memory stored successfully!`));\n console.log(`Key: ${answers.key}`);\n console.log(`Category: ${answers.category}`);\n } catch (error) {\n console.error(chalk.red('Error storing memory:'), error.message);\n }\n}\n\n/**\n * Show memory statistics\n */\nasync function showMemoryStats() {\n try {\n console.log(chalk.blue('\\n๐Ÿ“Š Memory Statistics\\n'));\n\n const mcpWrapper = await getMcpWrapper();\n\n // Search for all memories with an empty pattern to get everything\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found.'));\n console.log(chalk.gray('Use \"Store new memory\" to create your first memory.'));\n return;\n }\n\n // Calculate statistics\n const stats = {\n total: memories.length,\n categories: {},\n oldestDate: null,\n newestDate: null,\n totalSize: 0,\n };\n\n memories.forEach((memory) => {\n // Count by category\n const category = memory.category || memory.type || 'general';\n stats.categories[category] = (stats.categories[category] || 0) + 1;\n\n // Track dates\n const date = new Date(memory.timestamp || Date.now());\n if (!stats.oldestDate || date < stats.oldestDate) {\n stats.oldestDate = date;\n }\n if (!stats.newestDate || date > stats.newestDate) {\n stats.newestDate = date;\n }\n\n // Estimate size\n stats.totalSize += JSON.stringify(memory).length;\n });\n\n console.log(chalk.cyan('Total memories:'), stats.total);\n console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);\n console.log(\n chalk.cyan('Date range:'),\n `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`,\n );\n\n console.log(chalk.cyan('\\nBy category:'));\n Object.entries(stats.categories).forEach(([category, count]) => {\n console.log(` ${category}: ${count}`);\n });\n } catch (error) {\n console.error(chalk.red('Error getting memory stats:'), error.message);\n }\n}\n\n/**\n * Clean old memories\n */\nasync function cleanMemories() {\n try {\n const { days } = await inquirer.prompt([\n {\n type: 'number',\n name: 'days',\n message: 'Remove memories older than how many days?',\n default: 30,\n validate: (input) => input > 0,\n },\n ]);\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete memories older than ${days} days?`,\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(chalk.yellow('Operation cancelled.'));\n return;\n }\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories first\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - days);\n\n // Filter memories older than cutoff date\n const oldMemories = memories.filter((memory) => {\n const memoryDate = new Date(memory.timestamp || 0);\n return memoryDate < cutoffDate;\n });\n\n if (oldMemories.length === 0) {\n console.log(chalk.yellow('\\n๐ŸŽ‰ No old memories found to clean.'));\n return;\n }\n\n console.log(chalk.green(`\\nโœ… Found ${oldMemories.length} old memories to clean.`));\n console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));\n console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));\n } catch (error) {\n console.error(chalk.red('Error cleaning memories:'), error.message);\n }\n}\n\n/**\n * Export memory backup\n */\nasync function exportMemoryBackup() {\n try {\n const { filename } = await inquirer.prompt([\n {\n type: 'input',\n name: 'filename',\n message: 'Export filename:',\n default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`,\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories using search\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const backup = {\n exportDate: new Date().toISOString(),\n version: '1.0',\n totalMemories: memories.length,\n namespace: 'hive-mind',\n memories: memories,\n };\n\n const fs = await import('fs');\n fs.writeFileSync(filename, JSON.stringify(backup, null, 2));\n\n console.log(chalk.green(`\\nโœ… Memory backup exported to: ${filename}`));\n console.log(chalk.cyan(`Exported ${memories.length} memories`));\n } catch (error) {\n console.error(chalk.red('Error exporting memory backup:'), error.message);\n }\n}\n\n/**\n * Get active session ID for a swarm\n */\nasync function getActiveSessionId(swarmId) {\n const sessionManager = new HiveMindSessionManager();\n try {\n const sessions = await sessionManager.getActiveSessions();\n const activeSession = sessions.find(s => s.swarm_id === swarmId && s.status === 'active');\n return activeSession ? activeSession.id : null;\n } finally {\n sessionManager.close();\n }\n}\n\n/**\n * Spawn Claude Code with Hive Mind coordination instructions\n */\nasync function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {\n console.log('\\n' + chalk.bold('๐Ÿš€ Launching Claude Code with Hive Mind Coordination'));\n console.log(chalk.gray('โ”€'.repeat(60)));\n\n const spinner = ora('Preparing Hive Mind coordination prompt...').start();\n\n try {\n // Generate comprehensive Hive Mind prompt\n const workerGroups = groupWorkersByType(workers);\n const hiveMindPrompt = generateHiveMindPrompt(\n swarmId,\n swarmName,\n objective,\n workers,\n workerGroups,\n flags,\n );\n\n spinner.succeed('Hive Mind coordination prompt ready!');\n\n // Display coordination summary\n console.log('\\n' + chalk.bold('๐Ÿง  Hive Mind Configuration'));\n console.log(chalk.gray('โ”€'.repeat(60)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');\n console.log(chalk.cyan('Worker Count:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));\n console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');\n console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');\n\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n\n const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\nโœ“ Hive Mind prompt saved to: ${promptFile}`));\n\n // Check if claude command exists\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\nโš ๏ธ Claude Code CLI not found in PATH'));\n console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\nFalling back to displaying instructions...'));\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Inject memory coordination protocol into CLAUDE.md\n try {\n const { injectMemoryProtocol, enhanceHiveMindPrompt } = await import('./inject-memory-protocol.js');\n await injectMemoryProtocol();\n \n // Enhance the prompt with memory coordination instructions\n hiveMindPrompt = enhanceHiveMindPrompt(hiveMindPrompt, workers);\n console.log(chalk.green('๐Ÿ“ Memory coordination protocol injected into CLAUDE.md'));\n } catch (err) {\n // If injection module not available, continue with original prompt\n console.log(chalk.yellow('โš ๏ธ Memory protocol injection not available, using standard prompt'));\n }\n \n // Check if we should run in non-interactive mode\n // Respect --non-interactive flag regardless of --claude\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n \n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming \n claudeArgs.push('--verbose'); // Verbose output\n console.log(chalk.cyan('๐Ÿค– Running in non-interactive mode'));\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n chalk.yellow(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n }\n \n // Add the prompt as the LAST argument\n claudeArgs.push(hiveMindPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n // Track child process PID in session\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await getActiveSessionId(swarmId);\n if (sessionId && claudeProcess.pid) {\n sessionManager.addChildPid(sessionId, claudeProcess.pid);\n }\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n\n // Save checkpoint and pause session\n if (sessionId) {\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C during Claude Code execution',\n claudePid: claudeProcess.pid,\n };\n \n await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);\n await sessionManager.pauseSession(sessionId);\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n }\n \n sessionManager.close();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n sessionManager.close();\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle stdout\n if (claudeProcess.stdout) {\n claudeProcess.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n }\n\n // Handle stderr\n if (claudeProcess.stderr) {\n claudeProcess.stderr.on('data', (data) => {\n console.error(chalk.red(data.toString()));\n });\n }\n\n // Handle process exit\n claudeProcess.on('exit', (code) => {\n // Remove child PID from session\n if (sessionId && claudeProcess.pid) {\n sessionManager.removeChildPid(sessionId, claudeProcess.pid);\n sessionManager.close();\n }\n\n if (code === 0) {\n console.log(chalk.green('\\nโœ“ Claude Code completed successfully'));\n } else if (code !== null) {\n console.log(chalk.red(`\\nโœ— Claude Code exited with code ${code}`));\n }\n });\n\n console.log(chalk.green('\\nโœ“ Claude Code launched with Hive Mind coordination'));\n console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));\n console.log(\n chalk.blue(' Use MCP tools for collective intelligence and task distribution'),\n );\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n } else if (flags.dryRun) {\n console.log(chalk.blue('\\nDry run - would execute Claude Code with prompt:'));\n console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');\n console.log(chalk.gray('\\nFirst 500 characters of prompt:'));\n console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));\n console.log(chalk.gray(`\\nFull prompt saved to: ${promptFile}`));\n } else {\n // Claude not available - show instructions with already saved prompt\n console.log(chalk.yellow('\\n๐Ÿ“‹ Manual Execution Instructions:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.gray('1. Install Claude Code:'));\n console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\n2. Run with the saved prompt:'));\n console.log(chalk.green(` claude < ${promptFile}`));\n console.log(chalk.gray('\\n3. Or copy the prompt manually:'));\n console.log(chalk.green(` cat ${promptFile} | claude`));\n console.log(chalk.gray('\\n4. With auto-permissions:'));\n console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('\\nFailed to launch Claude Code:'), error.message);\n\n // Save prompt as fallback\n const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\nโœ“ Prompt saved to: ${promptFile}`));\n console.log(chalk.yellow('\\nYou can run Claude Code manually with the saved prompt'));\n }\n\n console.log('\\n' + chalk.bold('๐Ÿ’ก Pro Tips:'));\n console.log(chalk.gray('โ”€'.repeat(30)));\n console.log('โ€ข Use --auto-spawn to launch instances automatically');\n console.log('โ€ข Add --verbose for detailed coordination context');\n console.log('โ€ข Monitor with: claude-flow hive-mind status');\n console.log('โ€ข Share memories: mcp__ruv-swarm__memory_usage');\n } catch (error) {\n spinner.fail('Failed to prepare Claude Code coordination');\n console.error(chalk.red('Error:'), error.message);\n }\n}\n\n/**\n * Generate comprehensive Hive Mind prompt for Claude Code\n */\nfunction generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {\n console.log(chalk.cyan(`\\n๐Ÿ” generateHiveMindPrompt received objective: \"${objective}\"`));\n const currentTime = new Date().toISOString();\n const workerTypes = Object.keys(workerGroups);\n const queenType = flags.queenType || 'strategic';\n const consensusAlgorithm = flags.consensus || 'majority';\n\n return `๐Ÿง  HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM\nโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n\nYou are the Queen coordinator of a Hive Mind swarm with collective intelligence capabilities.\n\nHIVE MIND CONFIGURATION:\n๐Ÿ“Œ Swarm ID: ${swarmId}\n๐Ÿ“Œ Swarm Name: ${swarmName}\n๐ŸŽฏ Objective: ${objective}\n๐Ÿ‘‘ Queen Type: ${queenType}\n๐Ÿ Worker Count: ${workers.length}\n๐Ÿค Consensus Algorithm: ${consensusAlgorithm}\nโฐ Initialized: ${currentTime}\n\nWORKER DISTRIBUTION:\n${workerTypes.map((type) => `โ€ข ${type}: ${workerGroups[type].length} agents`).join('\\n')}\n\n๐Ÿ”ง AVAILABLE MCP TOOLS FOR HIVE MIND COORDINATION:\n\n1๏ธโƒฃ **COLLECTIVE INTELLIGENCE**\n mcp__claude-flow__consensus_vote - Democratic decision making\n mcp__claude-flow__memory_share - Share knowledge across the hive\n mcp__claude-flow__neural_sync - Synchronize neural patterns\n mcp__claude-flow__swarm_think - Collective problem solving\n\n2๏ธโƒฃ **QUEEN COORDINATION**\n mcp__claude-flow__queen_command - Issue directives to workers\n mcp__claude-flow__queen_monitor - Monitor swarm health\n mcp__claude-flow__queen_delegate - Delegate complex tasks\n mcp__claude-flow__queen_aggregate - Aggregate worker results\n\n3๏ธโƒฃ **WORKER MANAGEMENT**\n mcp__claude-flow__agent_spawn - Create specialized workers\n mcp__claude-flow__agent_assign - Assign tasks to workers\n mcp__claude-flow__agent_communicate - Inter-agent communication\n mcp__claude-flow__agent_metrics - Track worker performance\n\n4๏ธโƒฃ **TASK ORCHESTRATION**\n mcp__claude-flow__task_create - Create hierarchical tasks\n mcp__claude-flow__task_distribute - Distribute work efficiently\n mcp__claude-flow__task_monitor - Track task progress\n mcp__claude-flow__task_aggregate - Combine task results\n\n5๏ธโƒฃ **MEMORY & LEARNING**\n mcp__claude-flow__memory_store - Store collective knowledge\n mcp__claude-flow__memory_retrieve - Access shared memory\n mcp__claude-flow__neural_train - Learn from experiences\n mcp__claude-flow__pattern_recognize - Identify patterns\n\n๐Ÿ“‹ HIVE MIND EXECUTION PROTOCOL:\n\nAs the Queen coordinator, you must:\n\n1. **INITIALIZE THE HIVE** (CRITICAL: Use Claude Code's Task Tool for Agents):\n \n Step 1: Optional MCP Coordination Setup (Single Message):\n [MCP Tools - Coordination Only]:\n ${workerTypes.map((type) => ` mcp__claude-flow__agent_spawn { \"type\": \"${type}\", \"count\": ${workerGroups[type].length} }`).join('\\n')}\n mcp__claude-flow__memory_store { \"key\": \"hive/objective\", \"value\": \"${objective}\" }\n mcp__claude-flow__memory_store { \"key\": \"hive/queen\", \"value\": \"${queenType}\" }\n mcp__claude-flow__swarm_think { \"topic\": \"initial_strategy\" }\n \n Step 2: REQUIRED - Spawn ACTUAL Agents with Claude Code's Task Tool (Single Message):\n [Claude Code Task Tool - CONCURRENT Agent Execution]:\n ${workerTypes.map((type) => ` Task(\"${type.charAt(0).toUpperCase() + type.slice(1)} Agent\", \"You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\\n')[0]}\", \"${type}\")`).join('\\n')}\n \n Step 3: Batch ALL Todos Together (Single TodoWrite Call):\n TodoWrite { \"todos\": [\n { \"id\": \"1\", \"content\": \"Initialize hive mind collective\", \"status\": \"in_progress\", \"priority\": \"high\" },\n { \"id\": \"2\", \"content\": \"Establish consensus protocols\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"3\", \"content\": \"Distribute initial tasks to workers\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"4\", \"content\": \"Set up collective memory\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"5\", \"content\": \"Monitor worker health\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"6\", \"content\": \"Aggregate worker outputs\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"7\", \"content\": \"Learn from patterns\", \"status\": \"pending\", \"priority\": \"low\" },\n { \"id\": \"8\", \"content\": \"Optimize performance\", \"status\": \"pending\", \"priority\": \"low\" }\n ] }\n\n2. **ESTABLISH COLLECTIVE INTELLIGENCE**:\n - Use consensus_vote for major decisions\n - Share all discoveries via memory_share\n - Synchronize learning with neural_sync\n - Coordinate strategy with swarm_think\n\n3. **QUEEN LEADERSHIP PATTERNS**:\n ${\n queenType === 'strategic'\n ? `\n - Focus on high-level planning and coordination\n - Delegate implementation details to workers\n - Monitor overall progress and adjust strategy\n - Make executive decisions when consensus fails`\n : ''\n }\n ${\n queenType === 'tactical'\n ? `\n - Manage detailed task breakdowns and assignments\n - Closely monitor worker progress and efficiency\n - Optimize resource allocation and load balancing\n - Intervene directly when workers need guidance`\n : ''\n }\n ${\n queenType === 'adaptive'\n ? `\n - Learn from swarm performance and adapt strategies\n - Experiment with different coordination patterns\n - Use neural training to improve over time\n - Balance between strategic and tactical approaches`\n : ''\n }\n\n4. **WORKER COORDINATION**:\n - Spawn workers based on task requirements\n - Assign tasks according to worker specializations\n - Enable peer-to-peer communication for collaboration\n - Monitor and rebalance workloads as needed\n\n5. **CONSENSUS MECHANISMS**:\n ${consensusAlgorithm === 'majority' ? '- Decisions require >50% worker agreement' : ''}\n ${consensusAlgorithm === 'unanimous' ? '- All workers must agree for major decisions' : ''}\n ${consensusAlgorithm === 'weighted' ? '- Worker votes weighted by expertise and performance' : ''}\n ${consensusAlgorithm === 'quorum' ? '- Decisions require 2/3 worker participation' : ''}\n\n6. **COLLECTIVE MEMORY**:\n - Store all important decisions in shared memory\n - Tag memories with worker IDs and timestamps\n - Use memory namespaces: hive/, queen/, workers/, tasks/\n - Implement memory consensus for critical data\n\n7. **PERFORMANCE OPTIMIZATION**:\n - Monitor swarm metrics continuously\n - Identify and resolve bottlenecks\n - Train neural networks on successful patterns\n - Scale worker count based on workload\n\n๐Ÿ’ก HIVE MIND BEST PRACTICES:\n\nโœ… ALWAYS use BatchTool for parallel operations\nโœ… Store decisions in collective memory immediately\nโœ… Use consensus for critical path decisions\nโœ… Monitor worker health and reassign if needed\nโœ… Learn from failures and adapt strategies\nโœ… Maintain constant inter-agent communication\nโœ… Aggregate results before final delivery\n\nโŒ NEVER make unilateral decisions without consensus\nโŒ NEVER let workers operate in isolation\nโŒ NEVER ignore performance metrics\nโŒ NEVER skip memory synchronization\nโŒ NEVER abandon failing workers\n\n๐ŸŽฏ OBJECTIVE EXECUTION STRATEGY:\n\nFor the objective: \"${objective}\"\n\n1. Break down into major phases using swarm_think\n2. Create specialized worker teams for each phase\n3. Establish success criteria and checkpoints\n4. Implement feedback loops and adaptation\n5. Aggregate and synthesize all worker outputs\n6. Deliver comprehensive solution with consensus\n\nโšก CRITICAL: CONCURRENT EXECUTION WITH CLAUDE CODE'S TASK TOOL:\n\nThe Hive Mind MUST use Claude Code's Task tool for actual agent execution:\n\nโœ… CORRECT Pattern:\n[Single Message - All Agents Spawned Concurrently]:\n Task(\"Researcher\", \"Research patterns and best practices...\", \"researcher\")\n Task(\"Coder\", \"Implement core features...\", \"coder\")\n Task(\"Tester\", \"Create comprehensive tests...\", \"tester\")\n Task(\"Analyst\", \"Analyze performance metrics...\", \"analyst\")\n TodoWrite { todos: [8-10 todos ALL in ONE call] }\n\nโŒ WRONG Pattern:\nMessage 1: Task(\"agent1\", ...)\nMessage 2: Task(\"agent2\", ...)\nMessage 3: TodoWrite { single todo }\n// This breaks parallel coordination!\n\nRemember:\n- Use Claude Code's Task tool to spawn ALL agents in ONE message\n- MCP tools are ONLY for coordination setup, not agent execution\n- Batch ALL TodoWrite operations (5-10+ todos minimum)\n- Execute ALL file operations concurrently\n- Store multiple memories simultaneously\n\n๐Ÿš€ BEGIN HIVE MIND EXECUTION:\n\nInitialize the swarm now with the configuration above. Use your collective intelligence to solve the objective efficiently. The Queen must coordinate, workers must collaborate, and the hive must think as one.\n\nRemember: You are not just coordinating agents - you are orchestrating a collective intelligence that is greater than the sum of its parts.`;\n}\n\n/**\n * Generate comprehensive coordination instructions for Claude Code instances\n */\nfunction generateCoordinationInstructions(swarmId, swarmName, objective, workers) {\n return {\n swarmId,\n swarmName,\n objective,\n hiveMindEndpoint: 'ws://localhost:3000/hive-mind',\n mcpTools: [\n 'mcp__ruv-swarm__memory_usage',\n 'mcp__ruv-swarm__swarm_monitor',\n 'mcp__ruv-swarm__task_orchestrate',\n 'mcp__ruv-swarm__neural_train',\n 'mcp__ruv-swarm__consensus_vote',\n 'mcp__ruv-swarm__agent_spawn',\n 'mcp__ruv-swarm__swarm_status',\n ],\n coordinationProtocol: {\n memoryNamespace: `hive-mind-${swarmId}`,\n consensusThreshold: 0.7,\n taskUpdateInterval: 30000,\n healthCheckInterval: 60000,\n },\n workerCapabilities: workers.map((w) => ({\n id: w.id,\n type: w.type,\n capabilities: JSON.parse(w.capabilities),\n })),\n };\n}\n\n/**\n * Group workers by type for specialized spawning\n */\nfunction groupWorkersByType(workers) {\n return workers.reduce((groups, worker) => {\n if (!groups[worker.type]) {\n groups[worker.type] = [];\n }\n groups[worker.type].push(worker);\n return groups;\n }, {});\n}\n\n/**\n * Create Claude Code spawn command with coordination context\n */\nfunction createClaudeCodeSpawnCommand(\n swarmId,\n swarmName,\n objective,\n workerType,\n typeWorkers,\n instructions,\n) {\n const context = `You are a ${workerType} agent in the \"${swarmName}\" Hive Mind swarm.\n\n๐ŸŽฏ MISSION: ${objective}\n\n๐Ÿ SWARM COORDINATION:\n- Swarm ID: ${swarmId}\n- Your Role: ${workerType.toUpperCase()} specialist\n- Team Size: ${typeWorkers.length} ${workerType}(s)\n- Coordination: Hive Mind collective intelligence\n\n๐Ÿง  MANDATORY COORDINATION PROTOCOL:\n1. BEFORE starting work:\n mcp__ruv-swarm__memory_usage {\"action\": \"retrieve\", \"key\": \"hive-mind-${swarmId}/status\"}\n mcp__ruv-swarm__swarm_status {\"swarmId\": \"${swarmId}\"}\n\n2. DURING work (after each major step):\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/${workerType}/progress\", \"value\": {\"step\": \"X\", \"status\": \"Y\", \"findings\": \"Z\"}}\n mcp__ruv-swarm__task_orchestrate {\"swarmId\": \"${swarmId}\", \"update\": {\"agentId\": \"your-id\", \"progress\": \"details\"}}\n\n3. FOR decisions requiring consensus:\n mcp__ruv-swarm__consensus_vote {\"swarmId\": \"${swarmId}\", \"topic\": \"decision topic\", \"vote\": \"your choice\", \"rationale\": \"reasoning\"}\n\n4. WHEN sharing insights:\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/insights/${workerType}\", \"value\": {\"insight\": \"your discovery\", \"impact\": \"significance\"}}\n\n5. BEFORE completing work:\n mcp__ruv-swarm__neural_train {\"swarmId\": \"${swarmId}\", \"experience\": {\"what\": \"learned\", \"outcome\": \"result\"}}\n\n๐Ÿ”ง SPECIALIZED CAPABILITIES:\n${getWorkerTypeInstructions(workerType)}\n\n๐Ÿค COORDINATION RULES:\n- Share ALL discoveries via memory_usage\n- Vote on critical decisions using consensus_vote\n- Update progress every 15 minutes via task_orchestrate\n- Monitor other agents via swarm_status\n- Learn from patterns via neural_train\n\nRemember: You are part of a COLLECTIVE INTELLIGENCE. Your individual success depends on swarm coordination!`;\n\n const command = `claude code --context \"${context.replace(/\"/g, '\\\\\"')}\"`;\n\n return {\n title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,\n command,\n context,\n workerType,\n count: typeWorkers.length,\n };\n}\n\n/**\n * Get specialized instructions for each worker type\n */\nfunction getWorkerTypeInstructions(workerType) {\n const instructions = {\n researcher: `- Conduct thorough research using WebSearch and WebFetch\n- Document findings in structured formats\n- Validate source credibility and relevance\n- Synthesize insights from multiple sources\n- Share research methodology and results`,\n\n coder: `- Write clean, maintainable, well-documented code\n- Follow project conventions and best practices\n- Test implementations thoroughly\n- Document code changes and decisions\n- Review and optimize existing code`,\n\n analyst: `- Analyze data patterns and trends\n- Create comprehensive reports and visualizations\n- Identify key insights and recommendations\n- Validate analytical methodologies\n- Correlate findings across data sources`,\n\n tester: `- Design comprehensive test strategies\n- Execute functional, integration, and performance tests\n- Document test results and issues\n- Verify bug fixes and improvements\n- Ensure quality standards and coverage`,\n\n coordinator: `- Monitor overall progress and coordination\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Optimize resource allocation\n- Ensure alignment with objectives`,\n\n architect: `- Design system architecture and components\n- Define technical standards and patterns\n- Create implementation guidelines\n- Review and approve design decisions\n- Ensure scalability and maintainability`,\n };\n\n return (\n instructions[workerType] ||\n `- Execute tasks according to ${workerType} best practices\n- Collaborate effectively with team members\n- Document work and share insights\n- Maintain quality standards\n- Contribute to collective objectives`\n );\n}\n\n/**\n * Show all hive mind sessions\n */\nasync function showSessions(flags) {\n try {\n // Use metrics reader for real session data\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n \n if (!existsSync(dbPath)) {\n console.log(chalk.gray('No hive mind database found'));\n return;\n }\n \n const metricsReader = new HiveMindMetricsReader(dbPath);\n const sessions = metricsReader.getActiveSessions();\n\n if (sessions.length === 0) {\n console.log(chalk.gray('No active or paused sessions found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n๐Ÿ—‚๏ธ Hive Mind Sessions\\n'));\n\n sessions.forEach((session, index) => {\n const statusColor =\n session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';\n const statusIcon =\n session.status === 'active' ? '๐ŸŸข' : session.status === 'paused' ? '๐ŸŸก' : 'โšซ';\n\n console.log(chalk.yellow('โ•'.repeat(60)));\n console.log(`${statusIcon} ${chalk.bold(session.swarm_name || session.id)}`);\n console.log(chalk.cyan('Session ID:'), session.id);\n console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));\n console.log(chalk.cyan('Objective:'), session.objective || 'Not set');\n console.log(chalk.cyan('Progress:'), `${session.completion_percentage || 0}%`);\n console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());\n console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());\n\n if (session.paused_at) {\n console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());\n }\n\n console.log('\\n' + chalk.bold('Real Progress:'));\n console.log(` Agents: ${session.agent_count || 0}`);\n console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);\n console.log(` In Progress: ${session.in_progress_tasks || 0}`);\n console.log(` Pending: ${session.pending_tasks || 0}`);\n\n if (session.checkpoint_data) {\n console.log('\\n' + chalk.bold('Last Checkpoint:'));\n const checkpointStr = typeof session.checkpoint_data === 'string' \n ? session.checkpoint_data \n : JSON.stringify(session.checkpoint_data, null, 2);\n console.log(\n chalk.gray(checkpointStr.substring(0, 200) + (checkpointStr.length > 200 ? '...' : '')),\n );\n }\n });\n\n console.log(chalk.yellow('โ•'.repeat(60)) + '\\n');\n\n console.log(chalk.blue('๐Ÿ’ก Tips:'));\n console.log(' โ€ข Resume a session: claude-flow hive-mind resume ');\n console.log(' โ€ข View session details: claude-flow hive-mind status');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Resume a paused hive mind session\n */\nasync function resumeSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind resume ');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Resuming Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Allow resuming any session regardless of status\n spinner.text = `Resuming session from status: ${session.status}...`;\n\n if (session.status === 'stopped') {\n spinner.text = 'Restarting stopped session with original configuration...';\n }\n\n // Resume the session\n const resumedSession = await sessionManager.resumeSession(sessionId);\n\n spinner.succeed('Session resumed successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('๐Ÿ“‹ Resumed Session Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);\n console.log(chalk.cyan('Objective:'), resumedSession.objective);\n console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);\n console.log(\n chalk.cyan('Active Agents:'),\n `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`,\n );\n console.log(\n chalk.cyan('Tasks:'),\n `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`,\n );\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n // Show task breakdown\n console.log('\\n' + chalk.bold('๐Ÿ“Š Task Status:'));\n console.log(` โœ… Completed: ${resumedSession.statistics.completedTasks}`);\n console.log(` ๐Ÿ”„ In Progress: ${resumedSession.statistics.inProgressTasks}`);\n console.log(` โณ Pending: ${resumedSession.statistics.pendingTasks}`);\n\n // Show recent activity\n if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {\n console.log('\\n' + chalk.bold('๐Ÿ“œ Recent Activity:'));\n resumedSession.recentLogs.slice(0, 5).forEach((log) => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n console.log(` [${timestamp}] ${log.message}`);\n });\n }\n\n // Restore checkpoint if available\n if (resumedSession.checkpoint_data) {\n console.log('\\n' + chalk.bold('โ™ป๏ธ Restoring from checkpoint...'));\n console.log(chalk.gray('Checkpoint data available for restoration'));\n }\n\n sessionManager.close();\n\n // Offer to spawn Claude Code with restored context\n if (flags.claude || flags.spawn) {\n console.log('\\n' + chalk.yellow('๐Ÿš€ Launching Claude Code with restored context...'));\n\n // Generate prompt with session context\n const restoredPrompt = generateRestoredSessionPrompt(resumedSession);\n\n // Launch Claude Code with restored context\n await launchClaudeWithContext(restoredPrompt, flags, sessionId);\n } else {\n console.log(\n '\\n' +\n chalk.blue('๐Ÿ’ก Pro Tip:') +\n ' Add --claude to spawn Claude Code with restored context',\n );\n console.log(chalk.gray(' claude-flow hive-mind resume ' + sessionId + ' --claude'));\n }\n } catch (error) {\n spinner.fail('Failed to resume session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Stop a hive mind session\n */\nasync function stopSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind stop ');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Stopping Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Stop the session\n await sessionManager.stopSession(sessionId);\n\n spinner.succeed('Session stopped successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('๐Ÿ›‘ Stopped Session Summary:'));\n console.log(chalk.gray('โ”€'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');\n console.log(chalk.cyan('Final Status:'), 'Stopped');\n console.log(\n chalk.cyan('Active Agents:'),\n session.statistics ? session.statistics.activeAgents : 0,\n );\n console.log(chalk.gray('โ”€'.repeat(50)));\n\n console.log('\\n' + chalk.yellow('๐Ÿ’ก Session has been stopped and all processes cleaned up.'));\n console.log(\n chalk.gray('To resume this session later, use: claude-flow hive-mind resume ' + sessionId),\n );\n\n sessionManager.close();\n } catch (error) {\n spinner.fail('Failed to stop session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Generate prompt for restored session\n */\nfunction generateRestoredSessionPrompt(session) {\n // Get all agents, not just active ones\n const allAgents = session.agents || [];\n const activeAgents = allAgents.filter((a) => a.status === 'active' || a.status === 'busy');\n const idleAgents = allAgents.filter((a) => a.status === 'idle');\n \n // Get all tasks categorized by status\n const allTasks = session.tasks || [];\n const completedTasks = allTasks.filter((t) => t.status === 'completed');\n const inProgressTasks = allTasks.filter((t) => t.status === 'in_progress');\n const pendingTasks = allTasks.filter((t) => t.status === 'pending');\n \n // Calculate session duration\n const sessionStart = new Date(session.created_at);\n const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();\n const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes\n \n // Get more checkpoint history\n const checkpointHistory = session.checkpoints || [];\n \n // Get more activity logs\n const activityLogs = session.recentLogs || [];\n \n // Format agent details with their current tasks\n const formatAgentDetails = (agents) => {\n if (!agents.length) return 'No agents found';\n return agents.map(agent => {\n const agentTasks = allTasks.filter(t => t.agent_id === agent.id);\n const currentTask = agentTasks.find(t => t.status === 'in_progress');\n return `โ€ข ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\\n โ””โ”€ Working on: ${currentTask.description}` : ''}`;\n }).join('\\n');\n };\n \n // Format task details with more information\n const formatTaskDetails = (tasks, limit = 15) => {\n if (!tasks.length) return 'No tasks found';\n const displayTasks = tasks.slice(0, limit);\n return displayTasks.map(task => {\n const agent = allAgents.find(a => a.id === task.agent_id);\n return `โ€ข [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;\n }).join('\\n') + (tasks.length > limit ? `\\n... and ${tasks.length - limit} more tasks` : '');\n };\n \n // Format checkpoint details\n const formatCheckpoints = (checkpoints, limit = 5) => {\n if (!checkpoints.length) return 'No checkpoints found';\n const displayCheckpoints = checkpoints.slice(0, limit);\n return displayCheckpoints.map(cp => \n `โ€ข ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`\n ).join('\\n');\n };\n \n // Format activity logs with more detail\n const formatActivityLogs = (logs, limit = 20) => {\n if (!logs.length) return 'No activity logs found';\n const displayLogs = logs.slice(0, limit);\n return displayLogs.map(log => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n const agent = log.agent_id ? allAgents.find(a => a.id === log.agent_id) : null;\n return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;\n }).join('\\n');\n };\n \n // Extract metadata if available\n const metadata = session.metadata || {};\n const metadataStr = Object.keys(metadata).length > 0 ? \n Object.entries(metadata).map(([k, v]) => `โ€ข ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`).join('\\n') : \n 'No metadata available';\n\n return `๐Ÿ”„ RESUMING HIVE MIND SESSION\nโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•\n\nYou are resuming a Hive Mind session with comprehensive context:\n\n๐Ÿ“‹ SESSION DETAILS:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n๐Ÿ“Œ Session ID: ${session.id}\n๐Ÿ“Œ Swarm ID: ${session.swarm_id}\n๐Ÿ“Œ Swarm Name: ${session.swarm_name}\n๐ŸŽฏ Objective: ${session.objective}\n๐Ÿ“Š Overall Progress: ${session.statistics.completionPercentage}% complete\nโฑ๏ธ Session Duration: ${duration} minutes\n๐Ÿ“… Created: ${new Date(session.created_at).toLocaleString()}\nโธ๏ธ Paused: ${session.paused_at ? new Date(session.paused_at).toLocaleString() : 'N/A'}\nโ–ถ๏ธ Resumed: ${new Date().toLocaleString()}\n๐Ÿ”„ Status: ${session.status}\n\n๐Ÿ“Š TASK STATISTICS:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nโ€ข Total Tasks: ${session.statistics.totalTasks}\nโ€ข Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round((completedTasks.length / session.statistics.totalTasks) * 100) : 0}%)\nโ€ข In Progress: ${inProgressTasks.length}\nโ€ข Pending: ${pendingTasks.length}\n\n๐Ÿ‘ฅ SWARM COMPOSITION (${allAgents.length} agents):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nActive Agents (${activeAgents.length}):\n${formatAgentDetails(activeAgents)}\n\nIdle Agents (${idleAgents.length}):\n${formatAgentDetails(idleAgents)}\n\n๐Ÿ“ COMPLETED TASKS (${completedTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(completedTasks, 10)}\n\n๐Ÿ”„ IN-PROGRESS TASKS (${inProgressTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(inProgressTasks)}\n\nโณ PENDING TASKS (${pendingTasks.length}):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatTaskDetails(pendingTasks)}\n\n๐Ÿ’พ CHECKPOINT HISTORY (${checkpointHistory.length} total):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatCheckpoints(checkpointHistory)}\n\n๐Ÿ“Š SESSION METADATA:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${metadataStr}\n\n๐Ÿ’พ LAST CHECKPOINT DATA:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${session.checkpoint_data ? JSON.stringify(session.checkpoint_data, null, 2) : 'No checkpoint data available'}\n\n๐Ÿ“œ ACTIVITY LOG (Last ${Math.min(20, activityLogs.length)} entries):\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n${formatActivityLogs(activityLogs, 20)}\n\n๐ŸŽฏ RESUMPTION PROTOCOL:\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n1. **RESTORE CONTEXT**:\n - Review all checkpoint data and activity history above\n - Use mcp__claude-flow__memory_usage to retrieve collective memory\n - Check agent statuses and reassign tasks if needed\n - Verify all in-progress tasks are still valid\n\n2. **CONTINUE EXECUTION**:\n - Resume in-progress tasks with their assigned agents\n - Process pending tasks based on priority (CRITICAL > HIGH > NORMAL > LOW)\n - Maintain agent coordination through memory sharing\n - Update progress tracking after each task completion\n\n3. **COORDINATION REQUIREMENTS**:\n - Use mcp__claude-flow__memory_usage for all cross-agent communication\n - Apply consensus mechanisms for important decisions\n - Maintain swarm topology: ${session.swarm?.topology || 'unknown'}\n - Keep session checkpoint data updated regularly\n\n4. **MEMORY CONTEXT**:\n - Session memory namespace: session-${session.id}\n - Swarm memory namespace: swarm-${session.swarm_id}\n - Use these namespaces to access historical decisions and context\n\nResume the hive mind operation with full context awareness and continue working towards the objective.`;\n}\n\n/**\n * Launch Claude Code with context\n */\nasync function launchClaudeWithContext(prompt, flags, sessionId) {\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);\n await writeFile(promptFile, prompt);\n console.log(chalk.green(`\\nโœ“ Session context saved to: ${promptFile}`));\n\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\nโš ๏ธ Claude Code CLI not found'));\n console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray(`Run with: claude < ${promptFile}`));\n return;\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Debug logging to track spawn calls\n console.log(chalk.blue('\\n๐Ÿ” Debug: About to spawn Claude Code process...'));\n console.log(chalk.gray(` Session ID: ${sessionId}`));\n console.log(chalk.gray(` Process ID: ${process.pid}`));\n \n // Remove --print to allow interactive session (same as initial spawn)\n const claudeArgs = [prompt];\n\n // Add --dangerously-skip-permissions by default for hive-mind operations\n // unless explicitly disabled with --no-auto-permissions\n if (!flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log(\n chalk.yellow(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n\n console.log(chalk.blue('๐Ÿ” Debug: Spawning with args:'), claudeArgs.slice(0, 1).map(a => a.substring(0, 50) + '...'));\n \n // Use 'inherit' for interactive session (same as initial spawn)\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n \n console.log(chalk.blue('๐Ÿ” Debug: Claude process spawned with PID:'), claudeProcess.pid);\n\n // Track child process PID in session (same as initial spawn)\n const sessionManager = new HiveMindSessionManager();\n if (claudeProcess.pid) {\n const sessions = await sessionManager.getActiveSessions();\n const currentSession = sessions.find(s => s.id === sessionId);\n if (currentSession) {\n await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);\n }\n }\n\n // Set up SIGINT handler for automatic session pausing (same as initial spawn)\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('โธ๏ธ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process if still running\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n \n // Clean up and close session manager\n sessionManager.close();\n \n console.log(chalk.green('โœ“') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error during shutdown:'), error.message);\n process.exit(1);\n }\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle process exit (same as initial spawn)\n claudeProcess.on('exit', async (code, signal) => {\n if (!isExiting) {\n console.log('\\n' + chalk.yellow('Claude Code has exited'));\n \n // Clean up signal handlers\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigintHandler);\n \n // Close session manager\n sessionManager.close();\n \n process.exit(code || 0);\n }\n });\n\n console.log(chalk.green('\\nโœ“ Claude Code launched with restored session context'));\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('Failed to launch Claude Code:'), error.message);\n }\n}\n\n/**\n * Get MCP wrapper instance\n */\nasync function getMcpWrapper() {\n const { MCPToolWrapper } = await import('./hive-mind/mcp-wrapper.js');\n return new MCPToolWrapper();\n}\n\n// Export for testing\nexport { showHiveMindHelp, initHiveMind, spawnSwarm, showStatus };\n"],"names":["existsSync","mkdirSync","writeFile","path","inquirer","chalk","ora","cwd","exit","mkdirAsync","warnNonInteractive","safeInteractive","Database","HiveMindCore","QueenCoordinator","CollectiveMemory","SwarmCommunication","HiveMindSessionManager","createAutoSaveMiddleware","HiveMindMetricsReader","showHiveMindHelp","console","log","yellow","bold","green","gray","cyan","blue","initHiveMind","flags","spinner","start","hiveMindDir","join","recursive","dbPath","db","exec","close","config","version","initialized","Date","toISOString","defaults","queenType","maxWorkers","consensusAlgorithm","memorySize","autoScale","encryption","mcpTools","enabled","parallel","timeout","JSON","stringify","succeed","error","fail","red","message","hiveMindWizard","action","prompt","type","name","choices","value","spawnSwarmWizard","showStatus","manageMemoryWizard","showConsensus","showMetrics","configureWizard","objective","now","parseInt","consensus","namespace","verbose","spawnSwarm","nonInteractive","answers","validate","input","trim","length","default","checked","swarmResult","workerTypes","monitor","spawnClaude","swarmId","workers","map","index","id","role","status","capabilities","getAgentCapabilities","claudeFlags","spawnClaudeCodeInstances","args","isNonInteractive","wizard","validQueenTypes","includes","isNaN","validConsensusTypes","hiveMind","text","undefined","Error","dbDir","prepare","get","warn","fs","unlinkSync","e","timestamp","randomPart","Math","random","toString","substring","run","sessionManager","sessionId","createSession","autoSave","saveInterval","autoStart","trackChange","swarmName","workerCount","queen","queenAgent","Object","values","split","i","min","workerType","workerId","worker","charAt","toUpperCase","slice","push","trackAgentActivity","memory","maxSize","store","communication","repeat","isExiting","sigintHandler","checkpointData","reason","saveCheckpoint","pauseSession","global","autoSaveInterval","clearInterval","process","on","claude","spawn","stack","researcher","coder","analyst","tester","architect","reviewer","optimizer","documenter","metricsReader","swarms","getActiveSwarms","swarm","queen_type","created_at","toLocaleString","agent_count","agents","find","a","filter","magenta","forEach","statusColor","taskStats","task_metrics","total","completed","in_progress","pending","failed","completion_percentage","memory_count","consensus_count","decisions","all","decision","swarm_name","topic","algorithm","confidence","toFixed","votes","parse","for","against","abstain","details","Array","isArray","detail","agent","agentId","vote","choice","justification","rationale","displayString","entries","overallStats","taskBreakdown","total_swarms","total_agents","total_tasks","completed_tasks","percentage","count","agentPerf","hasCompletedAt","successRate","tasks_assigned","tasks_completed","avg_completion_minutes","swarmPerf","task_count","completed_count","memory_entries","avgTaskTime","avg_minutes","agentTypePerf","listMemories","searchMemories","storeMemoryWizard","showMemoryStats","cleanMemories","exportMemoryBackup","continue","continueAction","hiveMindCommand","subcommand","subArgs","help","showSessions","resumeSession","stopSession","memories","key","swarm_id","created_by","displayValue","parsed","searchTerm","searchPattern","mcpWrapper","getMcpWrapper","memoryValue","storeMemory","category","searchResult","searchMemory","results","data","stats","categories","oldestDate","newestDate","totalSize","date","toLocaleDateString","days","confirm","cutoffDate","setDate","getDate","oldMemories","memoryDate","filename","backup","exportDate","totalMemories","writeFileSync","getActiveSessionId","sessions","getActiveSessions","activeSession","s","workerGroups","groupWorkersByType","hiveMindPrompt","generateHiveMindPrompt","keys","sessionsDir","promptFile","childSpawn","execSync","claudeAvailable","stdio","dryRun","injectMemoryProtocol","enhanceHiveMindPrompt","err","claudeArgs","claudeProcess","shell","pid","addChildPid","killed","kill","claudePid","stdout","stderr","code","removeChildPid","currentTime","getWorkerTypeInstructions","generateCoordinationInstructions","hiveMindEndpoint","coordinationProtocol","memoryNamespace","consensusThreshold","taskUpdateInterval","healthCheckInterval","workerCapabilities","w","reduce","groups","createClaudeCodeSpawnCommand","typeWorkers","instructions","context","command","replace","title","coordinator","session","statusIcon","updated_at","paused_at","in_progress_tasks","pending_tasks","checkpoint_data","checkpointStr","getSession","resumedSession","statistics","completionPercentage","activeAgents","totalAgents","completedTasks","totalTasks","inProgressTasks","pendingTasks","recentLogs","toLocaleTimeString","restoredPrompt","generateRestoredSessionPrompt","launchClaudeWithContext","allAgents","idleAgents","allTasks","tasks","t","sessionStart","sessionPaused","duration","round","checkpointHistory","checkpoints","activityLogs","formatAgentDetails","agentTasks","agent_id","currentTask","description","formatTaskDetails","limit","displayTasks","task","priority","formatCheckpoints","displayCheckpoints","cp","checkpoint_name","formatActivityLogs","logs","displayLogs","metadata","metadataStr","k","v","topology","currentSession","signal","removeListener","MCPToolWrapper"],"mappings":"AAMA,SAASA,UAAU,EAAEC,SAAS,QAAQ,KAAK;AAC3C,SAASC,SAAS,QAAkB,cAAc;AAClD,OAAOC,UAAU,OAAO;AAExB,OAAOC,cAAc,WAAW;AAChC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAAeC,GAAG,EAAEC,IAAI,EAA+BC,UAAU,QAAQ,oBAAoB;AAC7F,SAGEC,kBAAkB,QAEb,mCAAmC;AAC1C,SACEC,eAAe,QAGV,+BAA+B;AAGtC,OAAOC,cAAc,iBAAiB;AAOtC,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,gBAAgB,QAAQ,uBAAuB;AACxD,SAASC,gBAAgB,QAAQ,wBAAwB;AACzD,SAASC,kBAAkB,QAAQ,+BAA+B;AAClE,SAASC,sBAAsB,QAAQ,iCAAiC;AACxE,SAASC,wBAAwB,QAAQ,sCAAsC;AAC/E,SAASC,qBAAqB,QAAQ,gCAAgC;AAEtE,SAASC;IACPC,QAAQC,GAAG,CAAC,CAAC;AACf,EAAEjB,MAAMkB,MAAM,CAAC,mCAAmC;;AAElD,EAAElB,MAAMmB,IAAI,CAAC,UAAU;;;AAGvB,EAAEnB,MAAMmB,IAAI,CAAC,gBAAgB;EAC3B,EAAEnB,MAAMoB,KAAK,CAAC,QAAQ;EACtB,EAAEpB,MAAMoB,KAAK,CAAC,SAAS;EACvB,EAAEpB,MAAMoB,KAAK,CAAC,UAAU;EACxB,EAAEpB,MAAMoB,KAAK,CAAC,UAAU;EACxB,EAAEpB,MAAMoB,KAAK,CAAC,QAAQ;EACtB,EAAEpB,MAAMoB,KAAK,CAAC,YAAY;EAC1B,EAAEpB,MAAMoB,KAAK,CAAC,aAAa;EAC3B,EA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Y,gBAAgB,EAAES,YAAY,EAAEqD,UAAU,EAAEX,UAAU,GAAG"} \ No newline at end of file diff --git a/dist-cjs/src/cli/simple-commands/swarm.js b/dist-cjs/src/cli/simple-commands/swarm.js index ff4bf23c75..4cbacf5340 100644 --- a/dist-cjs/src/cli/simple-commands/swarm.js +++ b/dist-cjs/src/cli/simple-commands/swarm.js @@ -706,12 +706,20 @@ Start by spawning a coordinator agent and creating the initial task structure. U The swarm should be self-documenting - use memory_store to save all important information, decisions, and results throughout the execution.`; if (flags && flags.claude) { + try { + const { injectMemoryProtocol, enhanceSwarmPrompt } = await import('./inject-memory-protocol.js'); + await injectMemoryProtocol(); + swarmPrompt = enhanceSwarmPrompt(swarmPrompt, maxAgents); + } catch (err) { + console.log('โš ๏ธ Memory protocol injection not available, using standard prompt'); + } console.log('๐Ÿ Launching Claude Flow Swarm System...'); console.log(`๐Ÿ“‹ Objective: ${objective}`); console.log(`๐ŸŽฏ Strategy: ${strategy}`); console.log(`๐Ÿ—๏ธ Mode: ${mode}`); console.log(`๐Ÿค– Max Agents: ${maxAgents}\n`); console.log('๐Ÿš€ Launching Claude Code with Swarm Coordination'); + console.log('๐Ÿ“ Memory protocol injected into CLAUDE.md'); console.log('โ”€'.repeat(60)); const claudeArgs = []; if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) { diff --git a/dist-cjs/src/cli/simple-commands/swarm.js.map b/dist-cjs/src/cli/simple-commands/swarm.js.map index 378345773e..a5441a44e4 100644 --- a/dist-cjs/src/cli/simple-commands/swarm.js.map +++ b/dist-cjs/src/cli/simple-commands/swarm.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/cli/simple-commands/swarm.js"],"sourcesContent":["/**\n * Swarm command wrapper for simple CLI\n */\n\nimport { args, mkdirAsync, writeTextFile, exit, cwd } from '../node-compat.js';\nimport { spawn, execSync } from 'child_process';\nimport { existsSync, chmodSync, statSync, readFileSync } from 'fs';\nimport { open } from 'fs/promises';\nimport process from 'process';\nimport path from 'path';\n\n/**\n * Detects if the environment is headless (non-interactive)\n */\nfunction isHeadlessEnvironment() {\n // Check for common CI environment variables\n const ciEnvironments = [\n 'CI',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'CIRCLECI',\n 'TRAVIS',\n 'BUILDKITE',\n 'DRONE',\n 'DOCKER_CONTAINER',\n ];\n \n const isCI = ciEnvironments.some(env => process.env[env]);\n \n // Check if running in Docker\n let isDocker = existsSync('/.dockerenv');\n \n // Additional Docker check for cgroup\n if (!isDocker && existsSync('/proc/1/cgroup')) {\n try {\n const cgroupContent = readFileSync('/proc/1/cgroup', 'utf8');\n isDocker = cgroupContent.includes('docker');\n } catch {\n // Ignore read errors\n }\n }\n \n // Check TTY availability\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n \n return isCI || isDocker || !hasTTY;\n}\n\n/**\n * Basic swarm implementation for fallback scenarios\n */\nasync function basicSwarmNew(args, flags) {\n const objective = (args || []).join(' ').trim();\n \n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n const isHeadless = isHeadlessEnvironment();\n \n // Configure for headless mode\n if (isHeadless) {\n console.log('๐Ÿค– Headless environment detected - running in non-interactive mode');\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json', // Use stream-json for Claude compatibility\n 'no-auto-permissions': false,\n };\n }\n\n // Set up graceful shutdown handlers\n const cleanup = () => {\n console.log('\\n๐Ÿ›‘ Shutting down swarm gracefully...');\n process.exit(0);\n };\n\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n try {\n // Try to use the swarm executor\n const { executeSwarm } = await import('./swarm-executor.js');\n \n console.log(`๐Ÿ Starting basic swarm execution...`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n \n if (isHeadless) {\n console.log(`๐Ÿ–ฅ๏ธ Headless Mode: Enabled`);\n console.log(`๐Ÿ“„ Output Format: ${flags['output-format']}`);\n }\n\n const result = await executeSwarm(objective, flags);\n\n // Handle output based on format\n if (flags['output-format'] === 'json') {\n // In JSON mode, output clean JSON\n const output = {\n success: result.success,\n swarmId: result.summary?.swarmId,\n objective: objective,\n duration: result.summary?.duration,\n agents: result.summary?.totalAgents,\n tasks: result.summary?.totalTasks,\n timestamp: new Date().toISOString(),\n };\n \n if (flags['output-file']) {\n const fs = await import('fs/promises');\n await fs.writeFile(flags['output-file'], JSON.stringify(output, null, 2));\n console.log(`โœ… Output saved to: ${flags['output-file']}`);\n } else {\n console.log(JSON.stringify(output, null, 2));\n }\n } else {\n // Text mode output\n if (result.success) {\n console.log(`\\nโœ… Swarm execution completed successfully!`);\n if (result.summary) {\n console.log(` Duration: ${result.summary.duration}`);\n console.log(` Agents: ${result.summary.totalAgents}`);\n console.log(` Tasks: ${result.summary.totalTasks}`);\n }\n } else {\n console.error(`\\nโŒ Swarm execution failed: ${result.error}`);\n }\n }\n\n return result;\n } catch (error) {\n console.error(`โŒ Basic swarm execution error: ${error.message}`);\n \n // In headless mode, ensure we output JSON error\n if (flags['output-format'] === 'json') {\n const errorOutput = {\n success: false,\n error: error.message,\n timestamp: new Date().toISOString(),\n };\n console.log(JSON.stringify(errorOutput, null, 2));\n }\n \n throw error;\n }\n}\n\nfunction showSwarmHelp() {\n console.log(`\n๐Ÿ Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API with authentication\"\n claude-flow swarm \"Research cloud architecture patterns\" --strategy research\n claude-flow swarm \"Analyze database performance\" --max-agents 3 --parallel\n claude-flow swarm \"Develop user registration feature\" --mode distributed\n claude-flow swarm \"Optimize React app performance\" --strategy optimization\n claude-flow swarm \"Create microservice\" --executor # Use built-in executor\n claude-flow swarm \"Build API\" --claude # Open Claude Code CLI\n claude-flow swarm \"Build API endpoints\" --output-format json # Get JSON output\n claude-flow swarm \"Research AI trends\" --output-format json --output-file results.json\n\nDEFAULT BEHAVIOR:\n Swarm attempts to open Claude Code CLI with comprehensive MCP tool instructions\n including memory coordination, agent management, and task orchestration.\n \n If Claude CLI is not available:\n โ€ข Use --claude flag to open Claude Code CLI\n โ€ข Use --executor flag to run with the built-in executor\n\nSTRATEGIES:\n auto Automatically determine best approach (default)\n research Research and information gathering\n development Software development and coding\n analysis Data analysis and insights\n testing Testing and quality assurance\n optimization Performance optimization\n maintenance System maintenance\n\nMODES:\n centralized Single coordinator (default)\n distributed Multiple coordinators\n hierarchical Tree structure coordination\n mesh Peer-to-peer coordination\n hybrid Mixed coordination strategies\n\nKEY FEATURES:\n ๐Ÿค– Intelligent agent management with specialized types\n โšก Timeout-free background task execution\n ๐Ÿง  Distributed memory sharing between agents\n ๐Ÿ”„ Work stealing and advanced load balancing\n ๐Ÿ›ก๏ธ Circuit breaker patterns for fault tolerance\n ๐Ÿ“Š Real-time monitoring and comprehensive metrics\n ๐ŸŽ›๏ธ Multiple coordination strategies and algorithms\n ๐Ÿ’พ Persistent state with backup and recovery\n ๐Ÿ”’ Security features with encryption options\n ๐Ÿ–ฅ๏ธ Interactive terminal UI for management\n\nOPTIONS:\n --strategy Execution strategy (default: auto)\n --mode Coordination mode (default: centralized)\n --max-agents Maximum agents (default: 5)\n --timeout Timeout in minutes (default: 60)\n --task-timeout-minutes Task execution timeout in minutes (default: 59)\n --parallel Enable parallel execution\n --distributed Enable distributed coordination\n --monitor Enable real-time monitoring\n --ui Launch terminal UI interface\n --background Run in background mode\n --review Enable peer review\n --testing Enable automated testing\n --encryption Enable encryption\n --verbose Enable detailed logging\n --dry-run Show configuration without executing\n --executor Use built-in executor instead of Claude Code\n --claude Open Claude Code CLI\n --output-format Output format: json, text (default: text)\n --output-file Save output to file instead of stdout\n --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)\n --auto (Deprecated: auto-permissions enabled by default)\n --no-auto-permissions Disable automatic --dangerously-skip-permissions\n --analysis Enable analysis/read-only mode (no code changes)\n --read-only Enable read-only mode (alias for --analysis)\n\nADVANCED OPTIONS:\n --quality-threshold Quality threshold 0-1 (default: 0.8)\n --memory-namespace Memory namespace (default: swarm)\n --agent-selection Agent selection strategy\n --task-scheduling Task scheduling algorithm\n --load-balancing Load balancing method\n --fault-tolerance Fault tolerance strategy\n --headless Force headless mode for CI/Docker environments\n --health-check Perform health check and exit (for Docker health)\n --json-logs Output all logs in JSON format for log aggregation\n\nHEADLESS MODE:\n Automatically detected and enabled when running in:\n - CI/CD environments (GitHub Actions, GitLab CI, Jenkins, etc.)\n - Docker containers without TTY\n - Non-interactive shells (no stdin/stdout TTY)\n \n In headless mode:\n - Output defaults to JSON format\n - Non-interactive mode is enabled\n - Graceful shutdown on SIGTERM/SIGINT\n - Suitable for containerized deployments\n\nFor complete documentation and examples:\nhttps://github.com/ruvnet/claude-code-flow/docs/swarm.md\n`);\n}\n\nexport async function swarmCommand(args, flags) {\n // Handle headless mode early\n if (flags && flags.headless) {\n const isHeadless = isHeadlessEnvironment();\n // Configure for headless mode\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json',\n 'no-auto-permissions': false,\n };\n }\n \n // Handle health check first\n if (flags && flags['health-check']) {\n try {\n // Quick health check for Docker/K8s\n console.log(JSON.stringify({\n status: 'healthy',\n service: 'claude-flow-swarm',\n version: process.env.npm_package_version || '2.0.0',\n timestamp: new Date().toISOString()\n }));\n process.exit(0);\n } catch (error) {\n console.error(JSON.stringify({\n status: 'unhealthy',\n error: error.message,\n timestamp: new Date().toISOString()\n }));\n process.exit(1);\n }\n }\n\n const objective = (args || []).join(' ').trim();\n\n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n // Force headless mode if flag is set\n if (flags && flags.headless) {\n const isHeadless = isHeadlessEnvironment();\n if (!isHeadless) {\n console.log('๐Ÿค– Forcing headless mode as requested');\n }\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'json',\n 'no-auto-permissions': false,\n };\n }\n\n // Handle JSON output format\n const outputFormat = flags && flags['output-format'];\n const outputFile = flags && flags['output-file'];\n const isJsonOutput = outputFormat === 'json';\n const isNonInteractive = isJsonOutput || (flags && flags['no-interactive']);\n const useJsonLogs = flags && flags['json-logs'];\n\n // Override console.log for JSON logs if requested\n if (useJsonLogs) {\n const originalLog = console.log;\n const originalError = console.error;\n \n console.log = (...args) => {\n originalLog(JSON.stringify({\n level: 'info',\n message: args.join(' '),\n timestamp: new Date().toISOString(),\n service: 'claude-flow-swarm'\n }));\n };\n \n console.error = (...args) => {\n originalError(JSON.stringify({\n level: 'error',\n message: args.join(' '),\n timestamp: new Date().toISOString(),\n service: 'claude-flow-swarm'\n }));\n };\n }\n\n // Handle analysis/read-only mode\n const isAnalysisMode = flags && (flags.analysis || flags['read-only']);\n const analysisMode = isAnalysisMode ? 'analysis' : 'standard';\n\n // For JSON output, allow using Claude with stream-json format\n // Only force executor mode if explicitly using 'json' format (not 'stream-json')\n if (flags && flags['output-format'] === 'json' && !(flags && flags.executor)) {\n // Keep backward compatibility - regular 'json' format uses executor\n flags = { ...(flags || {}), executor: true };\n }\n\n // Check if we should use the old executor (opt-in with --executor flag)\n if (flags && flags.executor) {\n // Continue with the old swarm executor implementation below\n } else {\n // Default behavior: spawn Claude Code with comprehensive swarm MCP instructions\n try {\n const { execSync, spawn } = await import('child_process');\n\n // Get configuration values first\n const strategy = flags.strategy || 'auto';\n const mode = flags.mode || 'centralized';\n const maxAgents = flags['max-agents'] || 5;\n\n // Get strategy-specific guidance\n const strategyGuidance = getStrategyGuidance(strategy, objective);\n const modeGuidance = getModeGuidance(mode);\n const agentRecommendations = getAgentRecommendations(strategy, maxAgents, objective);\n\n const enableSparc =\n flags.sparc !== false && (strategy === 'development' || strategy === 'auto');\n\n // Build the complete swarm prompt before checking for claude\n const swarmPrompt = `You are orchestrating a Claude Flow Swarm using Claude Code's Task tool for agent execution.\n\n๐Ÿšจ CRITICAL INSTRUCTION: Use Claude Code's Task Tool for ALL Agent Spawning!\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nโœ… Claude Code's Task tool = Spawns agents that DO the actual work\nโŒ MCP tools = Only for coordination setup, NOT for execution\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n๐ŸŽฏ OBJECTIVE: ${objective}\n\n๐Ÿ SWARM CONFIGURATION:\n- Strategy: ${strategy}\n- Mode: ${mode}\n- Max Agents: ${maxAgents}\n- Timeout: ${flags.timeout || 60} minutes\n- Parallel Execution: MANDATORY (Always use BatchTool)\n- Review Mode: ${flags.review || false}\n- Testing Mode: ${flags.testing || false}\n- Analysis Mode: ${isAnalysisMode ? 'ENABLED (Read-Only)' : 'DISABLED'}\n\n${\n isAnalysisMode\n ? `๐Ÿ” ANALYSIS MODE CONSTRAINTS:\n\nโš ๏ธ READ-ONLY MODE ACTIVE - NO CODE MODIFICATIONS ALLOWED\n\nREQUIRED BEHAVIORS:\n1. โœ… READ files for analysis (Read tool)\n2. โœ… SEARCH codebases (Glob, Grep tools)\n3. โœ… ANALYZE code structure and patterns\n4. โœ… GENERATE reports and documentation\n5. โœ… CREATE analysis summaries\n6. โœ… STORE findings in memory for collaboration\n7. โœ… COMMUNICATE between agents about findings\n\nFORBIDDEN OPERATIONS:\n1. โŒ NEVER use Write tool to modify files\n2. โŒ NEVER use Edit or MultiEdit tools\n3. โŒ NEVER use Bash to run commands that modify files\n4. โŒ NEVER create new files or directories\n5. โŒ NEVER install packages or dependencies\n6. โŒ NEVER modify configuration files\n7. โŒ NEVER execute code that changes system state\n\nALL AGENTS MUST OPERATE IN READ-ONLY MODE. Focus on:\n- Code analysis and understanding\n- Security vulnerability assessment\n- Performance bottleneck identification\n- Architecture documentation\n- Technical debt analysis\n- Dependency mapping\n- Testing strategy recommendations\n\nGenerate comprehensive reports instead of making changes.\n\n`\n : ''\n}๐Ÿšจ CRITICAL: PARALLEL EXECUTION IS MANDATORY! ๐Ÿšจ\n\n๐Ÿ“‹ CLAUDE-FLOW SWARM BATCHTOOL INSTRUCTIONS\n\nโšก THE GOLDEN RULE:\nIf you need to do X operations, they should be in 1 message, not X messages.\n\n๐ŸŽฏ MANDATORY PATTERNS FOR CLAUDE-FLOW SWARMS:\n\n1๏ธโƒฃ **SWARM INITIALIZATION** - Use Claude Code's Task Tool for Agents:\n\nStep A: Optional MCP Coordination Setup (Single Message):\n\\`\\`\\`javascript\n[MCP Tools - Coordination ONLY]:\n // Set up coordination topology (OPTIONAL)\n mcp__claude-flow__swarm_init {\"topology\": \"mesh\", \"maxAgents\": ${maxAgents}}\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/config\", \"value\": {\"strategy\": \"${strategy}\"}}\n\\`\\`\\`\n\nStep B: REQUIRED - Claude Code Task Tool for ACTUAL Agent Execution (Single Message):\n\\`\\`\\`javascript\n[Claude Code Task Tool - CONCURRENT Agent Spawning]:\n // Spawn ALL agents using Task tool in ONE message\n Task(\"Coordinator\", \"Lead swarm coordination. Use hooks for memory sharing.\", \"coordinator\")\n Task(\"Researcher\", \"Analyze requirements and patterns. Coordinate via hooks.\", \"researcher\")\n Task(\"Backend Dev\", \"Implement server-side features. Share progress via hooks.\", \"coder\")\n Task(\"Frontend Dev\", \"Build UI components. Sync with backend via memory.\", \"coder\")\n Task(\"QA Engineer\", \"Create and run tests. Report findings via hooks.\", \"tester\")\n \n // Batch ALL todos in ONE TodoWrite call (5-10+ todos)\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize ${maxAgents} agent swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Analyze: ${objective}\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Design architecture\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Implement backend\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Implement frontend\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"6\", \"content\": \"Write unit tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"7\", \"content\": \"Integration testing\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"8\", \"content\": \"Performance optimization\", \"status\": \"pending\", \"priority\": \"low\"},\n {\"id\": \"9\", \"content\": \"Documentation\", \"status\": \"pending\", \"priority\": \"low\"}\n ]}\n\\`\\`\\`\n\nโš ๏ธ CRITICAL: Claude Code's Task tool does the ACTUAL work!\n- MCP tools = Coordination setup only\n- Task tool = Spawns agents that execute real work\n- ALL agents MUST be spawned in ONE message\n- ALL todos MUST be batched in ONE TodoWrite call\n\n2๏ธโƒฃ **TASK COORDINATION** - Batch ALL assignments:\n\\`\\`\\`javascript\n[Single Message]:\n // Assign all tasks\n mcp__claude-flow__task_assign {\"taskId\": \"research-1\", \"agentId\": \"researcher-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"design-1\", \"agentId\": \"architect-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"code-1\", \"agentId\": \"coder-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"code-2\", \"agentId\": \"coder-2\"}\n \n // Communicate to all agents\n mcp__claude-flow__agent_communicate {\"to\": \"all\", \"message\": \"Begin phase 1\"}\n \n // Update multiple task statuses\n mcp__claude-flow__task_update {\"taskId\": \"research-1\", \"status\": \"in_progress\"}\n mcp__claude-flow__task_update {\"taskId\": \"design-1\", \"status\": \"pending\"}\n\\`\\`\\`\n\n3๏ธโƒฃ **MEMORY COORDINATION** - Store/retrieve in batches:\n\\`\\`\\`javascript\n[Single Message]:\n // Store multiple findings\n mcp__claude-flow__memory_store {\"key\": \"research/requirements\", \"value\": {...}}\n mcp__claude-flow__memory_store {\"key\": \"research/constraints\", \"value\": {...}}\n mcp__claude-flow__memory_store {\"key\": \"architecture/decisions\", \"value\": {...}}\n \n // Retrieve related data\n mcp__claude-flow__memory_retrieve {\"key\": \"research/*\"}\n mcp__claude-flow__memory_search {\"pattern\": \"architecture\"}\n\\`\\`\\`\n\n4๏ธโƒฃ **FILE & CODE OPERATIONS** - Parallel execution:\n\\`\\`\\`javascript\n[Single Message]:\n // Read multiple files\n Read {\"file_path\": \"/src/index.js\"}\n Read {\"file_path\": \"/src/config.js\"}\n Read {\"file_path\": \"/package.json\"}\n \n // Write multiple files\n Write {\"file_path\": \"/src/api/auth.js\", \"content\": \"...\"}\n Write {\"file_path\": \"/src/api/users.js\", \"content\": \"...\"}\n Write {\"file_path\": \"/tests/auth.test.js\", \"content\": \"...\"}\n \n // Update memory with results\n mcp__claude-flow__memory_store {\"key\": \"code/api/auth\", \"value\": \"implemented\"}\n mcp__claude-flow__memory_store {\"key\": \"code/api/users\", \"value\": \"implemented\"}\n\\`\\`\\`\n\n5๏ธโƒฃ **MONITORING & STATUS** - Combined checks:\n\\`\\`\\`javascript\n[Single Message]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__swarm_status {}\n mcp__claude-flow__agent_list {\"status\": \"active\"}\n mcp__claude-flow__task_status {\"includeCompleted\": false}\n TodoRead {}\n\\`\\`\\`\n\nโŒ NEVER DO THIS (Sequential = SLOW):\n\\`\\`\\`\nMessage 1: mcp__claude-flow__agent_spawn\nMessage 2: mcp__claude-flow__agent_spawn\nMessage 3: TodoWrite (one todo)\nMessage 4: Read file\nMessage 5: mcp__claude-flow__memory_store\n\\`\\`\\`\n\nโœ… ALWAYS DO THIS (Batch = FAST):\n\\`\\`\\`\nMessage 1: [All operations in one message]\n\\`\\`\\`\n\n๐Ÿ’ก BATCHTOOL BEST PRACTICES:\n- Group by operation type (all spawns, all reads, all writes)\n- Use TodoWrite with 5-10 todos at once\n- Combine file operations when analyzing codebases\n- Store multiple memory items per message\n- Never send more than one message for related operations\n\n${strategyGuidance}\n\n${modeGuidance}\n\n${agentRecommendations}\n\n๐Ÿ“‹ MANDATORY PARALLEL WORKFLOW:\n\n1. **INITIAL SPAWN (Single BatchTool Message):**\n - Spawn ALL agents at once\n - Create ALL initial todos at once\n - Store initial memory state\n - Create task hierarchy\n \n Example:\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__agent_spawn (coordinator)\n mcp__claude-flow__agent_spawn (architect)\n mcp__claude-flow__agent_spawn (coder-1)\n mcp__claude-flow__agent_spawn (coder-2)\n mcp__claude-flow__agent_spawn (tester)\n mcp__claude-flow__memory_store { key: \"init\", value: {...} }\n mcp__claude-flow__task_create { name: \"Main\", subtasks: [...] }\n TodoWrite { todos: [5-10 todos at once] }\n \\`\\`\\`\n\n2. **TASK EXECUTION (Parallel Batches):**\n - Assign multiple tasks in one batch\n - Update multiple statuses together\n - Store multiple results simultaneously\n \n3. **MONITORING (Combined Operations):**\n - Check all agent statuses together\n - Retrieve multiple memory items\n - Update all progress markers\n\n๐Ÿ”ง AVAILABLE MCP TOOLS FOR SWARM COORDINATION:\n\n๐Ÿ“Š MONITORING & STATUS:\n- mcp__claude-flow__swarm_status - Check current swarm status and agent activity\n- mcp__claude-flow__swarm_monitor - Real-time monitoring of swarm execution\n- mcp__claude-flow__agent_list - List all active agents and their capabilities\n- mcp__claude-flow__task_status - Check task progress and dependencies\n\n๐Ÿง  MEMORY & KNOWLEDGE:\n- mcp__claude-flow__memory_store - Store knowledge in swarm collective memory\n- mcp__claude-flow__memory_retrieve - Retrieve shared knowledge from memory\n- mcp__claude-flow__memory_search - Search collective memory by pattern\n- mcp__claude-flow__memory_sync - Synchronize memory across agents\n\n๐Ÿค– AGENT MANAGEMENT:\n- mcp__claude-flow__agent_spawn - Spawn specialized agents for tasks\n- mcp__claude-flow__agent_assign - Assign tasks to specific agents\n- mcp__claude-flow__agent_communicate - Send messages between agents\n- mcp__claude-flow__agent_coordinate - Coordinate agent activities\n\n๐Ÿ“‹ TASK ORCHESTRATION:\n- mcp__claude-flow__task_create - Create new tasks with dependencies\n- mcp__claude-flow__task_assign - Assign tasks to agents\n- mcp__claude-flow__task_update - Update task status and progress\n- mcp__claude-flow__task_complete - Mark tasks as complete with results\n\n๐ŸŽ›๏ธ COORDINATION MODES:\n1. CENTRALIZED (default): Single coordinator manages all agents\n - Use when: Clear hierarchy needed, simple workflows\n - Tools: agent_assign, task_create, swarm_monitor\n\n2. DISTRIBUTED: Multiple coordinators share responsibility\n - Use when: Large scale tasks, fault tolerance needed\n - Tools: agent_coordinate, memory_sync, task_update\n\n3. HIERARCHICAL: Tree structure with team leads\n - Use when: Complex projects with sub-teams\n - Tools: agent_spawn (with parent), task_create (with subtasks)\n\n4. MESH: Peer-to-peer agent coordination\n - Use when: Maximum flexibility, self-organizing teams\n - Tools: agent_communicate, memory_store/retrieve\n\nโšก EXECUTION WORKFLOW - ALWAYS USE BATCHTOOL:\n${\n enableSparc\n ? `\n1. SPARC METHODOLOGY WITH PARALLEL EXECUTION:\n \n S - Specification Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__memory_store { key: \"specs/requirements\", value: {...} }\n mcp__claude-flow__task_create { name: \"Requirement 1\" }\n mcp__claude-flow__task_create { name: \"Requirement 2\" }\n mcp__claude-flow__task_create { name: \"Requirement 3\" }\n mcp__claude-flow__agent_spawn { type: \"researcher\", name: \"SpecAnalyst\" }\n \\`\\`\\`\n \n P - Pseudocode Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__memory_store { key: \"pseudocode/main\", value: {...} }\n mcp__claude-flow__task_create { name: \"Design API\" }\n mcp__claude-flow__task_create { name: \"Design Data Model\" }\n mcp__claude-flow__agent_communicate { to: \"all\", message: \"Review design\" }\n \\`\\`\\`\n \n A - Architecture Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__agent_spawn { type: \"architect\", name: \"LeadArchitect\" }\n mcp__claude-flow__memory_store { key: \"architecture/decisions\", value: {...} }\n mcp__claude-flow__task_create { name: \"Backend\", subtasks: [...] }\n mcp__claude-flow__task_create { name: \"Frontend\", subtasks: [...] }\n \\`\\`\\`\n \n R - Refinement Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__task_update { taskId: \"1\", progress: 50 }\n mcp__claude-flow__task_update { taskId: \"2\", progress: 75 }\n mcp__claude-flow__memory_store { key: \"learnings/iteration1\", value: {...} }\n \\`\\`\\`\n \n C - Completion Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_complete { taskId: \"1\", results: {...} }\n mcp__claude-flow__task_complete { taskId: \"2\", results: {...} }\n mcp__claude-flow__memory_retrieve { pattern: \"**/*\" }\n TodoWrite { todos: [{content: \"Final review\", status: \"completed\"}] }\n \\`\\`\\`\n`\n : `\n1. STANDARD SWARM EXECUTION WITH PARALLEL OPERATIONS:\n \n Initial Setup (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_create { name: \"Main\", subtasks: [...] }\n mcp__claude-flow__agent_spawn { type: \"coordinator\" }\n mcp__claude-flow__agent_spawn { type: \"coder\" }\n mcp__claude-flow__agent_spawn { type: \"tester\" }\n mcp__claude-flow__memory_store { key: \"init\", value: {...} }\n \\`\\`\\`\n \n Task Assignment (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_assign { taskId: \"1\", agentId: \"agent-1\" }\n mcp__claude-flow__task_assign { taskId: \"2\", agentId: \"agent-2\" }\n mcp__claude-flow__task_assign { taskId: \"3\", agentId: \"agent-3\" }\n \\`\\`\\`\n \n Monitoring & Updates (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__agent_communicate { to: \"all\", message: \"Status update\" }\n mcp__claude-flow__memory_store { key: \"progress\", value: {...} }\n \\`\\`\\`\n`\n}\n\n๐Ÿค AGENT TYPES & THEIR MCP TOOL USAGE:\n\nCOORDINATOR:\n- Primary tools: swarm_monitor, agent_assign, task_create\n- Monitors overall progress and assigns work\n- Uses memory_store for decisions and memory_retrieve for context\n\nRESEARCHER:\n- Primary tools: memory_search, memory_store\n- Gathers information and stores findings\n- Uses agent_communicate to share discoveries\n\nCODER:\n- Primary tools: task_update, memory_retrieve, memory_store\n- Implements solutions and updates progress\n- Retrieves specs from memory, stores code artifacts\n\nANALYST:\n- Primary tools: memory_search, swarm_monitor\n- Analyzes data and patterns\n- Stores insights and recommendations\n\nTESTER:\n- Primary tools: task_status, agent_communicate\n- Validates implementations\n- Reports issues via task_update\n\n๐Ÿ“ EXAMPLE MCP TOOL USAGE PATTERNS:\n\n1. Starting a swarm:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__memory_store {\"key\": \"objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Main Objective\", \"type\": \"parent\"}\n\n2. Spawning worker agents:\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"capabilities\": [\"web-search\"]}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"capabilities\": [\"python\", \"testing\"]}\n mcp__claude-flow__task_assign {\"taskId\": \"task-123\", \"agentId\": \"agent-456\"}\n\n3. Coordinating work:\n mcp__claude-flow__agent_communicate {\"to\": \"agent-123\", \"message\": \"Begin phase 2\"}\n mcp__claude-flow__memory_store {\"key\": \"phase1/results\", \"value\": {...}}\n mcp__claude-flow__task_update {\"taskId\": \"task-123\", \"progress\": 75}\n\n4. Monitoring progress:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__task_status {\"includeCompleted\": true}\n mcp__claude-flow__agent_list {\"status\": \"active\"}\n\n๐Ÿ’พ MEMORY PATTERNS:\n\nUse hierarchical keys for organization:\n- \"specs/requirements\" - Store specifications\n- \"architecture/decisions\" - Architecture choices\n- \"code/modules/[name]\" - Code artifacts\n- \"tests/results/[id]\" - Test outcomes\n- \"docs/api/[endpoint]\" - Documentation\n\n๐Ÿš€ BEGIN SWARM EXECUTION:\n\nStart by spawning a coordinator agent and creating the initial task structure. Use the MCP tools to orchestrate the swarm, coordinate agents, and track progress. Remember to store important decisions and artifacts in collective memory for other agents to access.\n\nThe swarm should be self-documenting - use memory_store to save all important information, decisions, and results throughout the execution.`;\n\n // If --claude flag is used, force Claude Code even if CLI not available\n if (flags && flags.claude) {\n // --claude flag means interactive mode, so don't apply non-interactive\n console.log('๐Ÿ Launching Claude Flow Swarm System...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${strategy}`);\n console.log(`๐Ÿ—๏ธ Mode: ${mode}`);\n console.log(`๐Ÿค– Max Agents: ${maxAgents}\\n`);\n \n console.log('๐Ÿš€ Launching Claude Code with Swarm Coordination');\n console.log('โ”€'.repeat(60));\n \n // Build arguments properly: for interactive mode, prompt can be first\n const claudeArgs = [];\n \n // Add auto-permission flag first\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log('๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless swarm execution');\n }\n \n // Add the prompt (for interactive mode, position doesn't matter as much)\n claudeArgs.push(swarmPrompt);\n \n // --claude flag means interactive mode, so don't add non-interactive flags\n \n // For --claude interactive mode, spawn Claude directly\n // Temporarily disable telemetry to avoid console output interference\n const claudeEnv = { ...process.env };\n \n // Remove telemetry env vars to prevent console output\n delete claudeEnv.CLAUDE_CODE_ENABLE_TELEMETRY;\n delete claudeEnv.OTEL_METRICS_EXPORTER;\n delete claudeEnv.OTEL_LOGS_EXPORTER;\n \n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n env: claudeEnv\n });\n \n console.log('\\nโœ“ Claude Code launched with swarm coordination prompt!');\n console.log(' The swarm coordinator will orchestrate all agent tasks');\n console.log(' Use MCP tools for coordination and memory sharing');\n \n console.log('\\n๐Ÿ’ก Pro Tips:');\n console.log('โ”€'.repeat(30));\n console.log('โ€ข Use TodoWrite to track parallel tasks');\n console.log('โ€ข Store results with mcp__claude-flow__memory_usage');\n console.log('โ€ข Monitor progress with mcp__claude-flow__swarm_monitor');\n console.log('โ€ข Check task status with mcp__claude-flow__task_status');\n \n // Set up clean termination\n const cleanup = () => {\n console.log('\\n๐Ÿ›‘ Shutting down swarm gracefully...');\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n process.exit(0);\n };\n \n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n \n // Wait for claude to exit\n claudeProcess.on('exit', (code) => {\n if (code === 0) {\n console.log('\\nโœ“ Swarm execution completed successfully');\n } else if (code !== null) {\n console.log(`\\nโœ— Swarm execution exited with code ${code}`);\n }\n process.exit(code || 0);\n });\n \n // Handle spawn errors (e.g., claude not found)\n claudeProcess.on('error', (err) => {\n if (err.code === 'ENOENT') {\n console.error('\\nโŒ Claude Code CLI not found. Please install Claude Code:');\n console.error(' https://claude.ai/download');\n } else {\n console.error('\\nโŒ Failed to launch Claude Code:', err.message);\n }\n process.exit(1);\n });\n \n return;\n }\n\n // Check if we're in non-interactive/headless mode FIRST (like alpha.83)\n const isNonInteractive = flags['no-interactive'] || \n flags['non-interactive'] || \n flags['output-format'] === 'stream-json' ||\n isHeadlessEnvironment();\n \n // Check if claude command exists\n let claudeAvailable = false;\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n if (!isNonInteractive) {\n console.log('โš ๏ธ Claude Code CLI not found in PATH');\n console.log('Install it with: npm install -g @anthropic-ai/claude-code');\n console.log('Or use --claude flag to open Claude Code CLI');\n console.log('\\nWould spawn Claude Code with swarm objective:');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log('\\nOptions:');\n console.log(' โ€ข Use --executor flag for built-in executor: claude-flow swarm \"objective\" --executor');\n console.log(' โ€ข Use --claude flag to open Claude Code CLI: claude-flow swarm \"objective\" --claude');\n } else {\n // In non-interactive mode, output JSON error\n console.error(JSON.stringify({\n error: 'Claude Code CLI not found',\n message: 'Install with: npm install -g @anthropic-ai/claude-code',\n fallback: 'Use --executor flag for built-in executor'\n }));\n }\n return;\n }\n\n // Claude is available, use it to run swarm\n if (!isNonInteractive) {\n console.log('๐Ÿ Launching Claude Flow Swarm System...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n if (isAnalysisMode) {\n console.log(`๐Ÿ” Analysis Mode: ENABLED (Read-Only - No Code Changes)`);\n }\n console.log();\n } else {\n // Non-interactive mode output\n console.log('๐Ÿค– Running in non-interactive mode with Claude');\n console.log('๐Ÿ“‹ Command: claude [prompt] -p --output-format stream-json --verbose');\n }\n\n // Continue with the default swarm behavior if not using --claude flag\n\n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n\n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming\n claudeArgs.push('--verbose'); // Verbose output\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless swarm execution',\n );\n }\n }\n\n // Add the prompt as the LAST argument\n claudeArgs.push(swarmPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n if (!isNonInteractive) {\n console.log('โœ“ Claude Code launched with swarm coordination prompt!');\n console.log('\\n๐Ÿš€ The swarm coordination instructions have been injected into Claude Code');\n console.log(' The prompt includes:');\n console.log(' โ€ข Strategy-specific guidance for', strategy);\n console.log(' โ€ข Coordination patterns for', mode, 'mode');\n console.log(' โ€ข Recommended agents and MCP tool usage');\n console.log(' โ€ข Complete workflow documentation\\n');\n }\n\n // Handle process events\n claudeProcess.on('error', (err) => {\n console.error('โŒ Failed to launch Claude Code:', err.message);\n });\n\n // Don't wait for completion - let it run\n return;\n } catch (error) {\n console.error('โŒ Failed to spawn Claude Code:', error.message);\n console.log('\\nFalling back to built-in executor...');\n // Fall through to executor implementation\n }\n }\n\n // Check if we should run in background mode\n if (flags && flags.background && !process.env.CLAUDE_SWARM_NO_BG) {\n // Check if we're in Deno environment\n if (typeof Deno !== 'undefined') {\n // In Deno, spawn a new process for true background execution\n const objective = (args || []).join(' ').trim();\n const swarmId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n const swarmRunDir = `./swarm-runs/${swarmId}`;\n\n // Create swarm directory\n await mkdirAsync(swarmRunDir, { recursive: true });\n\n console.log(`๐Ÿ Launching swarm in background mode...`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n console.log(`๐Ÿ“ Results: ${swarmRunDir}`);\n\n // Build command args without background flag (to prevent infinite loop)\n const commandArgs = ['run', '--allow-all', import.meta.url, objective];\n const newFlags = { ...flags };\n delete newFlags.background; // Remove background flag\n\n for (const [key, value] of Object.entries(newFlags)) {\n commandArgs.push(`--${key}`);\n if (value !== true) {\n commandArgs.push(String(value));\n }\n }\n\n // Create log file\n const logFile = `${swarmRunDir}/swarm.log`;\n const logHandle = await open(logFile, 'w');\n\n // Create a script to run the swarm without background flag\n const scriptContent = `#!/usr/bin/env -S deno run --allow-all\nimport { swarmCommand } from \"${import.meta.url}\";\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport process from 'process';\n\n// Remove background flag to prevent recursion\nconst flags = ${JSON.stringify(newFlags)};\nconst args = ${JSON.stringify(args)};\n\n// Set env to prevent background spawning\nprocess.env.CLAUDE_SWARM_NO_BG = 'true';\n\n// Run the swarm\nawait swarmCommand(args, flags);\n`;\n\n const scriptPath = `${swarmRunDir}/run-swarm.js`;\n await writeTextFile(scriptPath, scriptContent);\n\n // Save process info first\n await writeTextFile(\n `${swarmRunDir}/process.json`,\n JSON.stringify(\n {\n swarmId: swarmId,\n objective: objective,\n startTime: new Date().toISOString(),\n logFile: logFile,\n status: 'starting',\n },\n null,\n 2,\n ),\n );\n\n // Close log handle before spawning\n logHandle.close();\n\n // Use the bash script for true background execution\n const binDir = new URL('../../../bin/', import.meta.url).pathname;\n const bgScriptPath = `${binDir}claude-flow-swarm-bg`;\n\n try {\n // Check if the background script exists\n statSync(bgScriptPath);\n\n // Build command args for the background script\n const bgArgs = [objective];\n for (const [key, value] of Object.entries(newFlags)) {\n bgArgs.push(`--${key}`);\n if (value !== true) {\n bgArgs.push(String(value));\n }\n }\n\n // Use the bash background script\n const bgProcess = spawn(bgScriptPath, bgArgs, {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n // Read and display output\n const decoder = new TextDecoder();\n const output = await bgProcess.output();\n console.log(decoder.decode(output.stdout));\n\n // Exit immediately after launching\n exit(0);\n } catch (error) {\n // Fallback: create a double-fork pattern using a shell script\n console.log(`\\nโš ๏ธ Background script not found, using fallback method`);\n\n // Create a shell script that will run the swarm\n const shellScript = `#!/bin/bash\n# Double fork to detach from parent\n(\n (\n node \"${scriptPath}\" > \"${logFile}\" 2>&1 &\n echo $! > \"${swarmRunDir}/swarm.pid\"\n ) &\n)\nexit 0\n`;\n\n const shellScriptPath = `${swarmRunDir}/launch-background.sh`;\n await writeTextFile(shellScriptPath, shellScript);\n chmodSync(shellScriptPath, 0o755);\n\n // Execute the shell script\n const shellProcess = spawn('bash', [shellScriptPath], {\n stdio: 'ignore',\n detached: true,\n });\n shellProcess.unref();\n\n console.log(`\\nโœ… Swarm launched in background!`);\n console.log(`๐Ÿ“„ Logs: tail -f ${logFile}`);\n console.log(`๐Ÿ“Š Status: claude-flow swarm status ${swarmId}`);\n console.log(`\\nThe swarm will continue running independently.`);\n\n // Exit immediately\n exit(0);\n }\n }\n\n // Node.js environment - use background script\n const { execSync } = await import('child_process');\n const path = await import('path');\n const fs = await import('fs');\n\n const objective = (args || []).join(' ').trim();\n\n // Get the claude-flow-swarm-bg script path\n const bgScriptPath = path.join(\n path.dirname(new URL(import.meta.url).pathname),\n '../../../bin/claude-flow-swarm-bg',\n );\n\n // Check if background script exists\n if (fs.existsSync(bgScriptPath)) {\n // Build command args\n const commandArgs = [objective];\n for (const [key, value] of Object.entries(flags)) {\n if (key !== 'background') {\n // Skip background flag\n commandArgs.push(`--${key}`);\n if (value !== true) {\n commandArgs.push(String(value));\n }\n }\n }\n\n // Execute the background script\n try {\n execSync(`\"${bgScriptPath}\" ${commandArgs.map((arg) => `\"${arg}\"`).join(' ')}`, {\n stdio: 'inherit',\n });\n } catch (error) {\n console.error('Failed to launch background swarm:', error.message);\n }\n } else {\n // Fallback to simple message\n console.log(`๐Ÿ Background mode requested`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`\\nโš ๏ธ Background execution requires the claude-flow-swarm-bg script.`);\n console.log(`\\nFor true background execution, use:`);\n console.log(\n ` nohup claude-flow swarm \"${objective}\" ${Object.entries(flags)\n .filter(([k, v]) => k !== 'background' && v)\n .map(([k, v]) => `--${k}${v !== true ? ` ${v}` : ''}`)\n .join(' ')} > swarm.log 2>&1 &`,\n );\n }\n return;\n }\n\n try {\n // Try to load the compiled JavaScript module first\n let swarmAction;\n try {\n // Try the compiled version first (for production/npm packages)\n const distPath = new URL('../../../dist/cli/commands/swarm-new.js', import.meta.url);\n const module = await import(distPath);\n swarmAction = module.swarmAction;\n } catch (distError) {\n // Instead of immediately falling back to basic mode, \n // continue to the Claude integration below\n console.log('๐Ÿ“ฆ Compiled swarm module not found, checking for Claude CLI...');\n }\n\n // Only call swarmAction if it was successfully loaded\n if (swarmAction) {\n // Create command context compatible with TypeScript version\n const ctx = {\n args: args || [],\n flags: flags || {},\n command: 'swarm',\n };\n\n await swarmAction(ctx);\n return; // Exit after successful execution\n }\n } catch (error) {\n // If import fails (e.g., in node_modules), provide inline implementation\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.code === 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING' ||\n error.code === 'ERR_UNKNOWN_FILE_EXTENSION'\n ) {\n // Provide a basic swarm implementation that works without TypeScript imports\n const objective = (args || []).join(' ').trim();\n\n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n // Try to use the swarm executor directly\n try {\n const { executeSwarm } = await import('./swarm-executor.js');\n const result = await executeSwarm(objective, flags);\n\n // If execution was successful, exit\n if (result && result.success) {\n return;\n }\n } catch (execError) {\n console.log(`โš ๏ธ Swarm executor error: ${execError.message}`);\n // If swarm executor fails, try to create files directly\n try {\n await createSwarmFiles(objective, flags);\n return;\n } catch (createError) {\n console.log(`โš ๏ธ Direct file creation error: ${createError.message}`);\n // Continue with fallback implementation\n }\n }\n\n // Provide a basic inline swarm implementation for npm packages\n console.log('๐Ÿ Launching swarm system...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n console.log();\n\n // Generate swarm ID\n const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;\n\n if (flags['dry-run']) {\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n console.log(`๐Ÿ“Š Max Tasks: ${flags['max-tasks'] || 100}`);\n console.log(`โฐ Timeout: ${flags.timeout || 60} minutes`);\n console.log(`๐Ÿ”„ Parallel: ${flags.parallel || false}`);\n console.log(`๐ŸŒ Distributed: ${flags.distributed || false}`);\n console.log(`๐Ÿ” Monitoring: ${flags.monitor || false}`);\n console.log(`๐Ÿ‘ฅ Review Mode: ${flags.review || false}`);\n console.log(`๐Ÿงช Testing: ${flags.testing || false}`);\n console.log(`๐Ÿง  Memory Namespace: ${flags['memory-namespace'] || 'swarm'}`);\n console.log(`๐Ÿ’พ Persistence: ${flags.persistence !== false}`);\n console.log(`๐Ÿ”’ Encryption: ${flags.encryption || false}`);\n console.log(`๐Ÿ“Š Quality Threshold: ${flags['quality-threshold'] || 0.8}`);\n console.log();\n console.log('๐ŸŽ›๏ธ Coordination Strategy:');\n console.log(` โ€ข Agent Selection: ${flags['agent-selection'] || 'capability-based'}`);\n console.log(` โ€ข Task Scheduling: ${flags['task-scheduling'] || 'priority'}`);\n console.log(` โ€ข Load Balancing: ${flags['load-balancing'] || 'work-stealing'}`);\n console.log(` โ€ข Fault Tolerance: ${flags['fault-tolerance'] || 'retry'}`);\n console.log(` โ€ข Communication: ${flags.communication || 'event-driven'}`);\n console.log('โš ๏ธ DRY RUN - Advanced Swarm Configuration');\n return;\n }\n\n // For actual execution in npm context, try to find and run swarm-demo.ts\n try {\n const path = await import('path');\n const { fileURLToPath } = await import('url');\n const fs = await import('fs');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n\n // Look for swarm-demo.ts in the package\n const possiblePaths = [\n path.join(__dirname, '../../../swarm-demo.ts'),\n path.join(__dirname, '../../swarm-demo.ts'),\n ];\n\n let swarmDemoPath = null;\n for (const p of possiblePaths) {\n if (fs.existsSync(p)) {\n swarmDemoPath = p;\n break;\n }\n }\n\n if (swarmDemoPath && Deno) {\n // Run swarm-demo.ts directly with Deno\n const swarmArgs = [objective];\n for (const [key, value] of Object.entries(flags || {})) {\n swarmArgs.push(`--${key}`);\n if (value !== true) {\n swarmArgs.push(String(value));\n }\n }\n\n console.log('๐Ÿš€ Starting advanced swarm execution...');\n const swarmProcess = spawn('node', [swarmDemoPath, ...swarmArgs], {\n stdio: 'inherit',\n });\n\n swarmProcess.on('error', (err) => {\n console.error('โŒ Failed to launch swarm:', err.message);\n });\n\n swarmProcess.on('exit', (code) => {\n if (code !== 0) {\n console.error(`โŒ Swarm exited with code ${code}`);\n }\n });\n return;\n }\n } catch (e) {\n // Fallback to basic message if can't run swarm-demo.ts\n }\n\n // Try to use Claude wrapper approach like SPARC does\n try {\n const { execSync } = await import('child_process');\n\n // Check if claude command exists\n try {\n execSync('which claude', { stdio: 'ignore' });\n } catch (e) {\n // Claude not found, show fallback message\n console.log(`โœ… Swarm initialized with ID: ${swarmId}`);\n console.log('\\nโš ๏ธ Note: Advanced swarm features require Claude or local installation.');\n console.log('Install Claude: https://claude.ai/code');\n console.log('Or install locally: npm install -g claude-flow@latest');\n console.log('\\nThe swarm system would coordinate the following:');\n console.log('1. Agent spawning and task distribution');\n console.log('2. Parallel execution of subtasks');\n console.log('3. Memory sharing between agents');\n console.log('4. Progress monitoring and reporting');\n console.log('5. Result aggregation and quality checks');\n return;\n }\n\n // Claude is available, use it to run swarm\n console.log('๐Ÿš€ Launching swarm via Claude wrapper...');\n if (flags.sparc !== false) {\n console.log('๐Ÿงช SPARC methodology enabled - using full TDD workflow');\n }\n\n // Build the prompt for Claude using SPARC methodology\n const enableSparc = flags.sparc !== false;\n const swarmPrompt = `Execute a swarm coordination task using ${enableSparc ? 'the full SPARC methodology' : 'standard approach'}:\n\nOBJECTIVE: ${objective}\n\nCONFIGURATION:\n- Strategy: ${flags.strategy || 'auto'}\n- Mode: ${flags.mode || 'centralized'}\n- Max Agents: ${flags['max-agents'] || 5}\n- Memory Namespace: ${flags['memory-namespace'] || 'swarm'}\n- Quality Threshold: ${flags['quality-threshold'] || 0.8}\n${enableSparc ? '- SPARC Enabled: YES - Use full Specification, Pseudocode, Architecture, Refinement (TDD), Completion methodology' : ''}\n\n${\n enableSparc\n ? `\nSPARC METHODOLOGY REQUIREMENTS:\n\n1. SPECIFICATION PHASE:\n - Create detailed requirements and acceptance criteria\n - Define user stories with clear objectives\n - Document functional and non-functional requirements\n - Establish quality metrics and success criteria\n\n2. PSEUDOCODE PHASE:\n - Design algorithms and data structures\n - Create flow diagrams and logic patterns\n - Define interfaces and contracts\n - Plan error handling strategies\n\n3. ARCHITECTURE PHASE:\n - Design system architecture with proper components\n - Define APIs and service boundaries\n - Plan database schemas if applicable\n - Create deployment architecture\n\n4. REFINEMENT PHASE (TDD):\n - RED: Write comprehensive failing tests first\n - GREEN: Implement minimal code to pass tests\n - REFACTOR: Optimize and clean up implementation\n - Ensure >80% test coverage\n\n5. COMPLETION PHASE:\n - Integrate all components\n - Create comprehensive documentation\n - Perform end-to-end testing\n - Validate against original requirements\n`\n : ''\n}\n\nEXECUTION APPROACH:\n1. Analyze the objective and break it down into specific tasks\n2. Create a comprehensive implementation plan\n3. ${enableSparc ? 'Follow SPARC phases sequentially with proper artifacts for each phase' : 'Implement the solution directly'}\n4. Generate production-ready code with proper structure\n5. Include all necessary files (source code, tests, configs, documentation)\n6. Ensure the implementation is complete and functional\n\nTARGET DIRECTORY:\nExtract from the objective or use a sensible default. Create all files in the appropriate directory structure.\n\nIMPORTANT:\n- Create actual, working implementations - not templates or placeholders\n- Include comprehensive tests using appropriate testing frameworks\n- Add proper error handling and logging\n- Include configuration files (package.json, requirements.txt, etc.)\n- Create detailed README with setup and usage instructions\n- Follow best practices for the technology stack\n- Make the code production-ready, not just examples\n\nBegin execution now. Create all necessary files and provide a complete, working solution.`;\n\n // Execute Claude non-interactively by piping the prompt\n const { spawn } = await import('child_process');\n\n const claudeArgs = [];\n\n // Add auto-permission flag by default for swarm mode (unless explicitly disabled)\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n // Spawn claude process\n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: ['pipe', 'inherit', 'inherit'],\n shell: false,\n });\n\n // Write the prompt to stdin and close it\n claudeProcess.stdin.write(swarmPrompt);\n claudeProcess.stdin.end();\n\n // Wait for the process to complete\n await new Promise((resolve, reject) => {\n claudeProcess.on('close', (code) => {\n if (code === 0) {\n resolve();\n } else {\n reject(new Error(`Claude process exited with code ${code}`));\n }\n });\n\n claudeProcess.on('error', (err) => {\n reject(err);\n });\n });\n } catch (error) {\n // Fallback if Claude execution fails\n console.log(`โœ… Swarm initialized with ID: ${swarmId}`);\n console.log('\\nโš ๏ธ Note: Advanced swarm features require Claude or local installation.');\n console.log('Install Claude: https://claude.ai/code');\n console.log('Or install locally: npm install -g claude-flow@latest');\n console.log('\\nThe swarm system would coordinate the following:');\n console.log('1. Agent spawning and task distribution');\n console.log('2. Parallel execution of subtasks');\n console.log('3. Memory sharing between agents');\n console.log('4. Progress monitoring and reporting');\n console.log('5. Result aggregation and quality checks');\n }\n\n return;\n }\n\n console.error('Swarm command error:', error);\n\n // Fallback to comprehensive help if there's an import error\n console.log(`\n๐Ÿ Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API\" --strategy development\n claude-flow swarm \"Research cloud architecture\" --strategy research --ui\n claude-flow swarm \"Analyze data trends\" --strategy analysis --parallel\n claude-flow swarm \"Optimize performance\" --distributed --monitor\n\nSTRATEGIES:\n auto Automatically determine best approach (default)\n research Research and information gathering\n development Software development and coding\n analysis Data analysis and insights\n testing Testing and quality assurance\n optimization Performance optimization\n maintenance System maintenance\n\nMODES:\n centralized Single coordinator (default)\n distributed Multiple coordinators\n hierarchical Tree structure coordination\n mesh Peer-to-peer coordination\n hybrid Mixed coordination strategies\n\nKEY FEATURES:\n ๐Ÿค– Intelligent agent management with specialized types\n โšก Timeout-free background task execution\n ๐Ÿง  Distributed memory sharing between agents\n ๐Ÿ”„ Work stealing and advanced load balancing\n ๐Ÿ›ก๏ธ Circuit breaker patterns for fault tolerance\n ๐Ÿ“Š Real-time monitoring and comprehensive metrics\n ๐ŸŽ›๏ธ Multiple coordination strategies and algorithms\n ๐Ÿ’พ Persistent state with backup and recovery\n ๐Ÿ”’ Security features with encryption options\n ๐Ÿ–ฅ๏ธ Interactive terminal UI for management\n\nOPTIONS:\n --strategy Execution strategy (default: auto)\n --mode Coordination mode (default: centralized)\n --max-agents Maximum agents (default: 5)\n --timeout Timeout in minutes (default: 60)\n --task-timeout-minutes Task execution timeout in minutes (default: 59)\n --parallel Enable parallel execution\n --distributed Enable distributed coordination\n --monitor Enable real-time monitoring\n --ui Launch terminal UI interface\n --background Run in background mode\n --review Enable peer review\n --testing Enable automated testing\n --encryption Enable encryption\n --verbose Enable detailed logging\n --dry-run Show configuration without executing\n --executor Use built-in executor instead of Claude Code\n --claude Open Claude Code CLI\n --output-format Output format: json, text (default: text)\n --output-file Save output to file instead of stdout\n --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)\n --auto (Deprecated: auto-permissions enabled by default)\n --no-auto-permissions Disable automatic --dangerously-skip-permissions\n --analysis Enable analysis/read-only mode (no code changes)\n --read-only Enable read-only mode (alias for --analysis)\n\nADVANCED OPTIONS:\n --quality-threshold Quality threshold 0-1 (default: 0.8)\n --memory-namespace Memory namespace (default: swarm)\n --agent-selection Agent selection strategy\n --task-scheduling Task scheduling algorithm\n --load-balancing Load balancing method\n --fault-tolerance Fault tolerance strategy\n\nFor complete documentation and examples:\nhttps://github.com/ruvnet/claude-code-flow/docs/swarm.md\n`);\n }\n}\n\n// Function to create swarm files directly\nasync function createSwarmFiles(objective, flags) {\n const fs = await import('fs');\n const path = await import('path');\n\n const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;\n\n console.log(`๐Ÿ Swarm Execution Started: ${swarmId}`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n\n // Extract target directory from objective\n const targetMatch = objective.match(/in\\s+([^\\s]+)\\/?$/i);\n let targetDir = targetMatch ? targetMatch[1] : 'output';\n\n // Resolve relative paths\n if (!targetDir.startsWith('/')) {\n targetDir = path.join(process.cwd(), targetDir);\n }\n\n console.log(`๐Ÿ“ Target directory: ${targetDir}`);\n\n // Ensure target directory exists\n await fs.promises.mkdir(targetDir, { recursive: true });\n\n // Determine what to build based on objective\n const isRestAPI =\n objective.toLowerCase().includes('rest api') || objective.toLowerCase().includes('api');\n\n if (isRestAPI) {\n // Create REST API\n const apiDir = path.join(targetDir, 'rest-api');\n await fs.promises.mkdir(apiDir, { recursive: true });\n\n console.log(`\\n๐Ÿ—๏ธ Creating REST API...`);\n console.log(` ๐Ÿค– Agent developer-1: Creating server implementation`);\n\n // Create server.js\n const serverCode = `const express = require('express');\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Health check endpoint\napp.get('/health', (req, res) => {\n res.json({ \n status: 'healthy',\n service: 'REST API',\n swarmId: '${swarmId}',\n created: new Date().toISOString()\n });\n});\n\n// Sample endpoints\napp.get('/api/v1/items', (req, res) => {\n res.json({\n items: [\n { id: 1, name: 'Item 1', description: 'First item' },\n { id: 2, name: 'Item 2', description: 'Second item' }\n ],\n total: 2\n });\n});\n\napp.get('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({\n id,\n name: \\`Item \\${id}\\`,\n description: \\`Description for item \\${id}\\`\n });\n});\n\napp.post('/api/v1/items', (req, res) => {\n const newItem = {\n id: Date.now(),\n ...req.body,\n createdAt: new Date().toISOString()\n };\n res.status(201).json(newItem);\n});\n\n// Start server\napp.listen(port, () => {\n console.log(\\`REST API server running on port \\${port}\\`);\n console.log('Created by Claude Flow Swarm');\n});\n\nmodule.exports = app;\n`;\n\n await fs.promises.writeFile(path.join(apiDir, 'server.js'), serverCode);\n console.log(` โœ… Created: server.js`);\n\n // Create package.json\n const packageJson = {\n name: 'rest-api',\n version: '1.0.0',\n description: 'REST API created by Claude Flow Swarm',\n main: 'server.js',\n scripts: {\n start: 'node server.js',\n dev: 'nodemon server.js',\n test: 'jest',\n },\n keywords: ['rest', 'api', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n dependencies: {\n express: '^4.18.2',\n },\n devDependencies: {\n nodemon: '^3.0.1',\n jest: '^29.7.0',\n supertest: '^6.3.3',\n },\n swarmMetadata: {\n swarmId,\n strategy: flags.strategy || 'development',\n created: new Date().toISOString(),\n },\n };\n\n await fs.promises.writeFile(\n path.join(apiDir, 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n console.log(` โœ… Created: package.json`);\n\n // Create README\n const readme = `# REST API\n\nThis REST API was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${swarmId}\n- Strategy: ${flags.strategy || 'development'}\n- Generated: ${new Date().toISOString()}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Usage\n\nStart the server:\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\n## API Endpoints\n\n- \\`GET /health\\` - Health check\n- \\`GET /api/v1/items\\` - Get all items\n- \\`GET /api/v1/items/:id\\` - Get item by ID\n- \\`POST /api/v1/items\\` - Create new item\n\n---\nCreated by Claude Flow Swarm\n`;\n\n await fs.promises.writeFile(path.join(apiDir, 'README.md'), readme);\n console.log(` โœ… Created: README.md`);\n\n console.log(`\\nโœ… Swarm completed successfully!`);\n console.log(`๐Ÿ“ Files created in: ${apiDir}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n } else {\n // Create generic application\n console.log(`\\n๐Ÿ—๏ธ Creating application...`);\n\n const appCode = `// Application created by Claude Flow Swarm\n// Objective: ${objective}\n// Swarm ID: ${swarmId}\n\nfunction main() {\n console.log('Executing swarm objective: ${objective}');\n console.log('Implementation would be based on the specific requirements');\n}\n\nmain();\n`;\n\n await fs.promises.writeFile(path.join(targetDir, 'app.js'), appCode);\n console.log(` โœ… Created: app.js`);\n\n const packageJson = {\n name: 'swarm-app',\n version: '1.0.0',\n description: `Application created by Claude Flow Swarm: ${objective}`,\n main: 'app.js',\n scripts: {\n start: 'node app.js',\n },\n swarmMetadata: {\n swarmId,\n objective,\n created: new Date().toISOString(),\n },\n };\n\n await fs.promises.writeFile(\n path.join(targetDir, 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n console.log(` โœ… Created: package.json`);\n\n console.log(`\\nโœ… Swarm completed successfully!`);\n console.log(`๐Ÿ“ Files created in: ${targetDir}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n }\n}\n\n/**\n * Get strategy-specific guidance for swarm execution\n */\nfunction getStrategyGuidance(strategy, objective) {\n const guidanceMap = {\n auto: `๐Ÿค– AUTO STRATEGY - INTELLIGENT TASK ANALYSIS:\nThe swarm will analyze \"${objective}\" and automatically determine the best approach.\n\nANALYSIS APPROACH:\n1. Task Decomposition: Break down the objective into subtasks\n2. Skill Matching: Identify required capabilities and expertise\n3. Agent Selection: Spawn appropriate agent types based on needs\n4. Workflow Design: Create optimal execution flow\n\nMCP TOOL PATTERN:\n- Start with memory_store to save the objective analysis\n- Use task_create to build a hierarchical task structure\n- Spawn agents with agent_spawn based on detected requirements\n- Monitor with swarm_monitor and adjust strategy as needed`,\n\n research: `๐Ÿ”ฌ RESEARCH STRATEGY - INFORMATION GATHERING & ANALYSIS:\nOptimized for: \"${objective}\"\n\nRESEARCH PHASES:\n1. Discovery: Broad information gathering\n2. Analysis: Deep dive into findings\n3. Synthesis: Combine insights\n4. Reporting: Document conclusions\n\nRECOMMENDED AGENTS:\n- Lead Researcher: Coordinates research efforts\n- Data Analysts: Process and analyze findings\n- Subject Experts: Domain-specific investigation\n- Documentation Specialist: Compile reports\n\nMCP TOOL USAGE:\n- memory_store: Save all research findings with structured keys\n- memory_search: Find related information across research\n- agent_communicate: Share discoveries between researchers\n- task_create: Break research into focused sub-investigations`,\n\n development: `๐Ÿ’ป DEVELOPMENT STRATEGY - SOFTWARE CREATION:\nBuilding: \"${objective}\"\n\nDEVELOPMENT WORKFLOW:\n1. Architecture: Design system structure\n2. Implementation: Build components\n3. Integration: Connect systems\n4. Testing: Validate functionality\n5. Documentation: Create guides\n\nRECOMMENDED AGENTS:\n- System Architect: Overall design\n- Backend Developers: API/server implementation\n- Frontend Developers: UI/UX implementation\n- DevOps Engineer: Infrastructure setup\n- QA Engineers: Testing and validation\n\nMCP TOOL USAGE:\n- memory_store: Save architecture decisions, code modules\n- task_create: Create implementation tasks with dependencies\n- agent_assign: Assign specific components to developers\n- swarm_monitor: Track build progress and blockers`,\n\n analysis: `๐Ÿ“Š ANALYSIS STRATEGY - DATA EXAMINATION:\nAnalyzing: \"${objective}\"\n\nANALYSIS FRAMEWORK:\n1. Data Collection: Gather relevant information\n2. Processing: Clean and prepare data\n3. Analysis: Apply analytical methods\n4. Visualization: Create insights\n5. Recommendations: Actionable outcomes\n\nRECOMMENDED AGENTS:\n- Lead Analyst: Coordinate analysis efforts\n- Data Engineers: Prepare data pipelines\n- Statistical Analysts: Apply analytical methods\n- Visualization Experts: Create dashboards\n- Business Analysts: Translate to recommendations\n\nMCP TOOL USAGE:\n- memory_store: Save datasets and analysis results\n- memory_retrieve: Access historical analysis\n- task_create: Define analysis pipelines\n- agent_coordinate: Sync analysis phases`,\n\n testing: `๐Ÿงช TESTING STRATEGY - QUALITY ASSURANCE:\nTesting: \"${objective}\"\n\nTESTING PHASES:\n1. Test Planning: Define test scenarios\n2. Test Development: Create test cases\n3. Execution: Run test suites\n4. Bug Tracking: Document issues\n5. Regression: Ensure fixes work\n\nRECOMMENDED AGENTS:\n- Test Lead: Coordinate testing efforts\n- Unit Testers: Component-level testing\n- Integration Testers: System-level testing\n- Performance Testers: Load and stress testing\n- Security Testers: Vulnerability assessment\n\nMCP TOOL USAGE:\n- task_create: Create test cases and scenarios\n- memory_store: Save test results and bug reports\n- agent_communicate: Report bugs to developers\n- swarm_monitor: Track testing coverage and progress`,\n\n optimization: `โšก OPTIMIZATION STRATEGY - PERFORMANCE IMPROVEMENT:\nOptimizing: \"${objective}\"\n\nOPTIMIZATION PROCESS:\n1. Profiling: Identify bottlenecks\n2. Analysis: Understand root causes\n3. Implementation: Apply optimizations\n4. Validation: Measure improvements\n5. Documentation: Record changes\n\nRECOMMENDED AGENTS:\n- Performance Lead: Coordinate optimization\n- System Profilers: Identify bottlenecks\n- Algorithm Experts: Optimize logic\n- Database Specialists: Query optimization\n- Infrastructure Engineers: System tuning\n\nMCP TOOL USAGE:\n- memory_store: Save performance baselines and results\n- task_create: Create optimization tasks by priority\n- swarm_monitor: Track performance improvements\n- agent_communicate: Coordinate optimization efforts`,\n\n maintenance: `๐Ÿ”ง MAINTENANCE STRATEGY - SYSTEM UPKEEP:\nMaintaining: \"${objective}\"\n\nMAINTENANCE WORKFLOW:\n1. Assessment: Evaluate current state\n2. Planning: Prioritize updates\n3. Implementation: Apply changes\n4. Testing: Verify stability\n5. Documentation: Update records\n\nRECOMMENDED AGENTS:\n- Maintenance Lead: Coordinate efforts\n- System Administrators: Infrastructure updates\n- Security Engineers: Patch vulnerabilities\n- Database Administrators: Data maintenance\n- Documentation Writers: Update guides\n\nMCP TOOL USAGE:\n- memory_retrieve: Access system history\n- task_create: Schedule maintenance tasks\n- agent_assign: Delegate specific updates\n- memory_store: Document all changes`,\n };\n\n return guidanceMap[strategy] || guidanceMap['auto'];\n}\n\n/**\n * Get mode-specific guidance for coordination\n */\nfunction getModeGuidance(mode) {\n const modeMap = {\n centralized: `๐ŸŽฏ CENTRALIZED MODE - SINGLE COORDINATOR:\nAll decisions flow through one coordinator agent.\n\nCOORDINATION PATTERN:\n- Spawn a single COORDINATOR as the first agent\n- All other agents report to the coordinator\n- Coordinator assigns tasks and monitors progress\n- Use agent_assign for task delegation\n- Use swarm_monitor for oversight\n\nBENEFITS:\n- Clear chain of command\n- Consistent decision making\n- Simple communication flow\n- Easy progress tracking\n\nBEST FOR:\n- Small to medium projects\n- Well-defined objectives\n- Clear task dependencies`,\n\n distributed: `๐ŸŒ DISTRIBUTED MODE - MULTIPLE COORDINATORS:\nMultiple coordinators share responsibility by domain.\n\nCOORDINATION PATTERN:\n- Spawn domain-specific coordinators (e.g., frontend-lead, backend-lead)\n- Each coordinator manages their domain agents\n- Use agent_coordinate for inter-coordinator sync\n- Use memory_sync to share state\n- Implement consensus protocols for decisions\n\nBENEFITS:\n- Fault tolerance\n- Parallel decision making\n- Domain expertise\n- Scalability\n\nBEST FOR:\n- Large projects\n- Multiple workstreams\n- Complex systems\n- High availability needs`,\n\n hierarchical: `๐Ÿ—๏ธ HIERARCHICAL MODE - TREE STRUCTURE:\nAgents organized in management layers.\n\nCOORDINATION PATTERN:\n- Spawn top-level coordinator\n- Spawn team leads under coordinator\n- Spawn workers under team leads\n- Use parent parameter in agent_spawn\n- Tasks flow down, results flow up\n\nBENEFITS:\n- Clear reporting structure\n- Efficient for large teams\n- Natural work breakdown\n- Manageable span of control\n\nBEST FOR:\n- Enterprise projects\n- Multi-team efforts\n- Complex hierarchies\n- Phased deliveries`,\n\n mesh: `๐Ÿ”— MESH MODE - PEER-TO-PEER:\nAgents coordinate directly without central authority.\n\nCOORDINATION PATTERN:\n- All agents are peers\n- Use agent_communicate for direct messaging\n- Consensus through voting or protocols\n- Self-organizing teams\n- Emergent leadership\n\nBENEFITS:\n- Maximum flexibility\n- Fast local decisions\n- Resilient to failures\n- Creative solutions\n\nBEST FOR:\n- Research projects\n- Exploratory work\n- Innovation tasks\n- Small expert teams`,\n\n hybrid: `๐ŸŽจ HYBRID MODE - MIXED STRATEGIES:\nCombine different coordination patterns as needed.\n\nCOORDINATION PATTERN:\n- Start with one mode, adapt as needed\n- Mix hierarchical for structure with mesh for innovation\n- Use distributed for resilience with centralized for control\n- Dynamic reorganization based on task needs\n\nBENEFITS:\n- Adaptability\n- Best of all modes\n- Task-appropriate structure\n- Evolution over time\n\nBEST FOR:\n- Complex projects\n- Uncertain requirements\n- Long-term efforts\n- Diverse objectives`,\n };\n\n return modeMap[mode] || modeMap['centralized'];\n}\n\n/**\n * Get agent recommendations based on strategy\n */\nfunction getAgentRecommendations(strategy, maxAgents, objective) {\n const recommendations = {\n auto: `\n๐Ÿค– RECOMMENDED AGENT COMPOSITION (Auto-detected):\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"RequirementsAnalyst\"}\n mcp__claude-flow__agent_spawn {\"type\": \"architect\", \"name\": \"SystemDesigner\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Analyze Requirements\", \"assignTo\": \"RequirementsAnalyst\"}\n mcp__claude-flow__task_create {\"name\": \"Design Architecture\", \"assignTo\": \"SystemDesigner\", \"dependsOn\": [\"Analyze Requirements\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize swarm coordination\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Analyze objective requirements\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Design system architecture\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Spawn additional agents as needed\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n research: `\n๐Ÿ”ฌ RECOMMENDED RESEARCH AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"ResearchLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"PrimaryInvestigator\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DataScientist\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"LiteratureExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"InsightsCompiler\"}\n mcp__claude-flow__memory_store {\"key\": \"research/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Literature Review\", \"assignTo\": \"LiteratureExpert\"}\n mcp__claude-flow__task_create {\"name\": \"Primary Research\", \"assignTo\": \"PrimaryInvestigator\"}\n mcp__claude-flow__task_create {\"name\": \"Data Analysis\", \"assignTo\": \"DataScientist\"}\n mcp__claude-flow__task_create {\"name\": \"Compile Insights\", \"assignTo\": \"InsightsCompiler\", \"dependsOn\": [\"Literature Review\", \"Primary Research\", \"Data Analysis\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize research swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Conduct literature review\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Execute primary research\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Analyze collected data\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Compile and synthesize insights\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n development: `\n๐Ÿ’ป RECOMMENDED DEVELOPMENT AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"TechLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"architect\", \"name\": \"SystemArchitect\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"BackendDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"FrontendDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"QAEngineer\"}\n mcp__claude-flow__memory_store {\"key\": \"dev/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"System Architecture\", \"assignTo\": \"SystemArchitect\"}\n mcp__claude-flow__task_create {\"name\": \"Backend Implementation\", \"assignTo\": \"BackendDev\", \"dependsOn\": [\"System Architecture\"]}\n mcp__claude-flow__task_create {\"name\": \"Frontend Implementation\", \"assignTo\": \"FrontendDev\", \"dependsOn\": [\"System Architecture\"]}\n mcp__claude-flow__task_create {\"name\": \"Testing Suite\", \"assignTo\": \"QAEngineer\", \"dependsOn\": [\"Backend Implementation\", \"Frontend Implementation\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize development swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Design system architecture\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Implement backend services\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Implement frontend UI\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Create comprehensive tests\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n analysis: `\n๐Ÿ“Š RECOMMENDED ANALYSIS AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"AnalysisLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DataEngineer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"StatisticalExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"VisualizationDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"BusinessAnalyst\"}\n mcp__claude-flow__memory_store {\"key\": \"analysis/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Data Pipeline Setup\", \"assignTo\": \"DataEngineer\"}\n mcp__claude-flow__task_create {\"name\": \"Statistical Analysis\", \"assignTo\": \"StatisticalExpert\", \"dependsOn\": [\"Data Pipeline Setup\"]}\n mcp__claude-flow__task_create {\"name\": \"Create Visualizations\", \"assignTo\": \"VisualizationDev\", \"dependsOn\": [\"Statistical Analysis\"]}\n mcp__claude-flow__task_create {\"name\": \"Business Insights\", \"assignTo\": \"BusinessAnalyst\", \"dependsOn\": [\"Statistical Analysis\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize analysis swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Setup data pipelines\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Perform statistical analysis\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Create data visualizations\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"5\", \"content\": \"Generate business insights\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n testing: `\n๐Ÿงช RECOMMENDED TESTING AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"QALead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"UnitTestEngineer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"IntegrationTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"PerformanceTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"SecurityAuditor\"}\n mcp__claude-flow__memory_store {\"key\": \"testing/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Unit Test Suite\", \"assignTo\": \"UnitTestEngineer\"}\n mcp__claude-flow__task_create {\"name\": \"Integration Tests\", \"assignTo\": \"IntegrationTester\"}\n mcp__claude-flow__task_create {\"name\": \"Performance Tests\", \"assignTo\": \"PerformanceTester\"}\n mcp__claude-flow__task_create {\"name\": \"Security Audit\", \"assignTo\": \"SecurityAuditor\"}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize testing swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Create unit tests\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Create integration tests\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Run performance tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"5\", \"content\": \"Execute security audit\", \"status\": \"pending\", \"priority\": \"high\"}\n ]}\n\\`\\`\\``,\n\n optimization: `\nโšก RECOMMENDED OPTIMIZATION AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"OptimizationLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"PerformanceProfiler\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"AlgorithmExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DatabaseOptimizer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"SystemsTuner\"}\n mcp__claude-flow__memory_store {\"key\": \"optimization/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Performance Profiling\", \"assignTo\": \"PerformanceProfiler\"}\n mcp__claude-flow__task_create {\"name\": \"Algorithm Optimization\", \"assignTo\": \"AlgorithmExpert\", \"dependsOn\": [\"Performance Profiling\"]}\n mcp__claude-flow__task_create {\"name\": \"Database Optimization\", \"assignTo\": \"DatabaseOptimizer\", \"dependsOn\": [\"Performance Profiling\"]}\n mcp__claude-flow__task_create {\"name\": \"System Tuning\", \"assignTo\": \"SystemsTuner\", \"dependsOn\": [\"Performance Profiling\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize optimization swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Profile system performance\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Optimize algorithms\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Optimize database queries\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Tune system parameters\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n maintenance: `\n๐Ÿ”ง RECOMMENDED MAINTENANCE AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"MaintenanceLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"SystemAuditor\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"PatchDeveloper\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"RegressionTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DocumentationUpdater\"}\n mcp__claude-flow__memory_store {\"key\": \"maintenance/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"System Audit\", \"assignTo\": \"SystemAuditor\"}\n mcp__claude-flow__task_create {\"name\": \"Develop Patches\", \"assignTo\": \"PatchDeveloper\", \"dependsOn\": [\"System Audit\"]}\n mcp__claude-flow__task_create {\"name\": \"Regression Testing\", \"assignTo\": \"RegressionTester\", \"dependsOn\": [\"Develop Patches\"]}\n mcp__claude-flow__task_create {\"name\": \"Update Documentation\", \"assignTo\": \"DocumentationUpdater\", \"dependsOn\": [\"Develop Patches\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize maintenance swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Audit system health\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Develop necessary patches\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Run regression tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Update documentation\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n };\n\n return recommendations[strategy] || recommendations['auto'];\n}\n\n// Allow direct execution\nif (import.meta.main) {\n // When called directly as a script, parse all arguments\n const args = [];\n const flags = {};\n\n // Parse arguments and flags\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg.startsWith('--')) {\n const flagName = arg.substring(2);\n const nextArg = args[i + 1];\n\n if (nextArg && !nextArg.startsWith('--')) {\n flags[flagName] = nextArg;\n i++; // Skip the next argument\n } else {\n flags[flagName] = true;\n }\n } else {\n args.push(arg);\n }\n }\n\n // The objective is all non-flag arguments joined\n const objective = args.join(' ');\n\n // Execute the swarm command\n await swarmCommand([objective], flags);\n}\n"],"names":["mkdirAsync","writeTextFile","exit","spawn","existsSync","chmodSync","statSync","readFileSync","open","process","isHeadlessEnvironment","ciEnvironments","isCI","some","env","isDocker","cgroupContent","includes","hasTTY","stdin","isTTY","stdout","basicSwarmNew","args","flags","objective","join","trim","console","error","showSwarmHelp","isHeadless","log","cleanup","on","executeSwarm","strategy","mode","result","output","success","swarmId","summary","duration","agents","totalAgents","tasks","totalTasks","timestamp","Date","toISOString","fs","writeFile","JSON","stringify","message","errorOutput","swarmCommand","headless","status","service","version","npm_package_version","outputFormat","outputFile","isJsonOutput","isNonInteractive","useJsonLogs","originalLog","originalError","level","isAnalysisMode","analysis","analysisMode","executor","execSync","maxAgents","strategyGuidance","getStrategyGuidance","modeGuidance","getModeGuidance","agentRecommendations","getAgentRecommendations","enableSparc","sparc","swarmPrompt","timeout","review","testing","claude","repeat","claudeArgs","push","claudeEnv","CLAUDE_CODE_ENABLE_TELEMETRY","OTEL_METRICS_EXPORTER","OTEL_LOGS_EXPORTER","claudeProcess","stdio","shell","killed","kill","code","err","claudeAvailable","fallback","background","CLAUDE_SWARM_NO_BG","Deno","now","Math","random","toString","substr","swarmRunDir","recursive","commandArgs","url","newFlags","key","value","Object","entries","String","logFile","logHandle","scriptContent","scriptPath","startTime","close","binDir","URL","pathname","bgScriptPath","bgArgs","bgProcess","decoder","TextDecoder","decode","shellScript","shellScriptPath","shellProcess","detached","unref","path","dirname","map","arg","filter","k","v","swarmAction","distPath","module","distError","ctx","command","execError","createSwarmFiles","createError","substring","parallel","distributed","monitor","persistence","encryption","communication","fileURLToPath","__filename","__dirname","possiblePaths","swarmDemoPath","p","swarmArgs","swarmProcess","e","write","end","Promise","resolve","reject","Error","targetMatch","match","targetDir","startsWith","cwd","promises","mkdir","isRestAPI","toLowerCase","apiDir","serverCode","packageJson","name","description","main","scripts","start","dev","test","keywords","author","license","dependencies","express","devDependencies","nodemon","jest","supertest","swarmMetadata","created","readme","appCode","guidanceMap","auto","research","development","optimization","maintenance","modeMap","centralized","hierarchical","mesh","hybrid","recommendations","i","length","flagName","nextArg"],"mappings":"AAIA,SAAeA,UAAU,EAAEC,aAAa,EAAEC,IAAI,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IAAI/E,IAAIsC,UAAU,CAAC,OAAO;YACxB,MAAM2C,WAAWjF,IAAIa,SAAS,CAAC;YAC/B,MAAMqE,UAAU9M,IAAI,CAAC2M,IAAI,EAAE;YAE3B,IAAIG,WAAW,CAACA,QAAQ5C,UAAU,CAAC,OAAO;gBACxCjK,KAAK,CAAC4M,SAAS,GAAGC;gBAClBH;YACF,OAAO;gBACL1M,KAAK,CAAC4M,SAAS,GAAG;YACpB;QACF,OAAO;YACL7M,KAAKqE,IAAI,CAACuD;QACZ;IACF;IAGA,MAAM1H,YAAYF,KAAKG,IAAI,CAAC;IAG5B,MAAM+B,aAAa;QAAChC;KAAU,EAAED;AAClC"} \ No newline at end of file +{"version":3,"sources":["../../../../src/cli/simple-commands/swarm.js"],"sourcesContent":["/**\n * Swarm command wrapper for simple CLI\n */\n\nimport { args, mkdirAsync, writeTextFile, exit, cwd } from '../node-compat.js';\nimport { spawn, execSync } from 'child_process';\nimport { existsSync, chmodSync, statSync, readFileSync } from 'fs';\nimport { open } from 'fs/promises';\nimport process from 'process';\nimport path from 'path';\n\n/**\n * Detects if the environment is headless (non-interactive)\n */\nfunction isHeadlessEnvironment() {\n // Check for common CI environment variables\n const ciEnvironments = [\n 'CI',\n 'GITHUB_ACTIONS',\n 'GITLAB_CI',\n 'JENKINS_URL',\n 'CIRCLECI',\n 'TRAVIS',\n 'BUILDKITE',\n 'DRONE',\n 'DOCKER_CONTAINER',\n ];\n \n const isCI = ciEnvironments.some(env => process.env[env]);\n \n // Check if running in Docker\n let isDocker = existsSync('/.dockerenv');\n \n // Additional Docker check for cgroup\n if (!isDocker && existsSync('/proc/1/cgroup')) {\n try {\n const cgroupContent = readFileSync('/proc/1/cgroup', 'utf8');\n isDocker = cgroupContent.includes('docker');\n } catch {\n // Ignore read errors\n }\n }\n \n // Check TTY availability\n const hasTTY = process.stdin.isTTY && process.stdout.isTTY;\n \n return isCI || isDocker || !hasTTY;\n}\n\n/**\n * Basic swarm implementation for fallback scenarios\n */\nasync function basicSwarmNew(args, flags) {\n const objective = (args || []).join(' ').trim();\n \n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n const isHeadless = isHeadlessEnvironment();\n \n // Configure for headless mode\n if (isHeadless) {\n console.log('๐Ÿค– Headless environment detected - running in non-interactive mode');\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json', // Use stream-json for Claude compatibility\n 'no-auto-permissions': false,\n };\n }\n\n // Set up graceful shutdown handlers\n const cleanup = () => {\n console.log('\\n๐Ÿ›‘ Shutting down swarm gracefully...');\n process.exit(0);\n };\n\n process.on('SIGTERM', cleanup);\n process.on('SIGINT', cleanup);\n\n try {\n // Try to use the swarm executor\n const { executeSwarm } = await import('./swarm-executor.js');\n \n console.log(`๐Ÿ Starting basic swarm execution...`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n \n if (isHeadless) {\n console.log(`๐Ÿ–ฅ๏ธ Headless Mode: Enabled`);\n console.log(`๐Ÿ“„ Output Format: ${flags['output-format']}`);\n }\n\n const result = await executeSwarm(objective, flags);\n\n // Handle output based on format\n if (flags['output-format'] === 'json') {\n // In JSON mode, output clean JSON\n const output = {\n success: result.success,\n swarmId: result.summary?.swarmId,\n objective: objective,\n duration: result.summary?.duration,\n agents: result.summary?.totalAgents,\n tasks: result.summary?.totalTasks,\n timestamp: new Date().toISOString(),\n };\n \n if (flags['output-file']) {\n const fs = await import('fs/promises');\n await fs.writeFile(flags['output-file'], JSON.stringify(output, null, 2));\n console.log(`โœ… Output saved to: ${flags['output-file']}`);\n } else {\n console.log(JSON.stringify(output, null, 2));\n }\n } else {\n // Text mode output\n if (result.success) {\n console.log(`\\nโœ… Swarm execution completed successfully!`);\n if (result.summary) {\n console.log(` Duration: ${result.summary.duration}`);\n console.log(` Agents: ${result.summary.totalAgents}`);\n console.log(` Tasks: ${result.summary.totalTasks}`);\n }\n } else {\n console.error(`\\nโŒ Swarm execution failed: ${result.error}`);\n }\n }\n\n return result;\n } catch (error) {\n console.error(`โŒ Basic swarm execution error: ${error.message}`);\n \n // In headless mode, ensure we output JSON error\n if (flags['output-format'] === 'json') {\n const errorOutput = {\n success: false,\n error: error.message,\n timestamp: new Date().toISOString(),\n };\n console.log(JSON.stringify(errorOutput, null, 2));\n }\n \n throw error;\n }\n}\n\nfunction showSwarmHelp() {\n console.log(`\n๐Ÿ Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API with authentication\"\n claude-flow swarm \"Research cloud architecture patterns\" --strategy research\n claude-flow swarm \"Analyze database performance\" --max-agents 3 --parallel\n claude-flow swarm \"Develop user registration feature\" --mode distributed\n claude-flow swarm \"Optimize React app performance\" --strategy optimization\n claude-flow swarm \"Create microservice\" --executor # Use built-in executor\n claude-flow swarm \"Build API\" --claude # Open Claude Code CLI\n claude-flow swarm \"Build API endpoints\" --output-format json # Get JSON output\n claude-flow swarm \"Research AI trends\" --output-format json --output-file results.json\n\nDEFAULT BEHAVIOR:\n Swarm attempts to open Claude Code CLI with comprehensive MCP tool instructions\n including memory coordination, agent management, and task orchestration.\n \n If Claude CLI is not available:\n โ€ข Use --claude flag to open Claude Code CLI\n โ€ข Use --executor flag to run with the built-in executor\n\nSTRATEGIES:\n auto Automatically determine best approach (default)\n research Research and information gathering\n development Software development and coding\n analysis Data analysis and insights\n testing Testing and quality assurance\n optimization Performance optimization\n maintenance System maintenance\n\nMODES:\n centralized Single coordinator (default)\n distributed Multiple coordinators\n hierarchical Tree structure coordination\n mesh Peer-to-peer coordination\n hybrid Mixed coordination strategies\n\nKEY FEATURES:\n ๐Ÿค– Intelligent agent management with specialized types\n โšก Timeout-free background task execution\n ๐Ÿง  Distributed memory sharing between agents\n ๐Ÿ”„ Work stealing and advanced load balancing\n ๐Ÿ›ก๏ธ Circuit breaker patterns for fault tolerance\n ๐Ÿ“Š Real-time monitoring and comprehensive metrics\n ๐ŸŽ›๏ธ Multiple coordination strategies and algorithms\n ๐Ÿ’พ Persistent state with backup and recovery\n ๐Ÿ”’ Security features with encryption options\n ๐Ÿ–ฅ๏ธ Interactive terminal UI for management\n\nOPTIONS:\n --strategy Execution strategy (default: auto)\n --mode Coordination mode (default: centralized)\n --max-agents Maximum agents (default: 5)\n --timeout Timeout in minutes (default: 60)\n --task-timeout-minutes Task execution timeout in minutes (default: 59)\n --parallel Enable parallel execution\n --distributed Enable distributed coordination\n --monitor Enable real-time monitoring\n --ui Launch terminal UI interface\n --background Run in background mode\n --review Enable peer review\n --testing Enable automated testing\n --encryption Enable encryption\n --verbose Enable detailed logging\n --dry-run Show configuration without executing\n --executor Use built-in executor instead of Claude Code\n --claude Open Claude Code CLI\n --output-format Output format: json, text (default: text)\n --output-file Save output to file instead of stdout\n --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)\n --auto (Deprecated: auto-permissions enabled by default)\n --no-auto-permissions Disable automatic --dangerously-skip-permissions\n --analysis Enable analysis/read-only mode (no code changes)\n --read-only Enable read-only mode (alias for --analysis)\n\nADVANCED OPTIONS:\n --quality-threshold Quality threshold 0-1 (default: 0.8)\n --memory-namespace Memory namespace (default: swarm)\n --agent-selection Agent selection strategy\n --task-scheduling Task scheduling algorithm\n --load-balancing Load balancing method\n --fault-tolerance Fault tolerance strategy\n --headless Force headless mode for CI/Docker environments\n --health-check Perform health check and exit (for Docker health)\n --json-logs Output all logs in JSON format for log aggregation\n\nHEADLESS MODE:\n Automatically detected and enabled when running in:\n - CI/CD environments (GitHub Actions, GitLab CI, Jenkins, etc.)\n - Docker containers without TTY\n - Non-interactive shells (no stdin/stdout TTY)\n \n In headless mode:\n - Output defaults to JSON format\n - Non-interactive mode is enabled\n - Graceful shutdown on SIGTERM/SIGINT\n - Suitable for containerized deployments\n\nFor complete documentation and examples:\nhttps://github.com/ruvnet/claude-code-flow/docs/swarm.md\n`);\n}\n\nexport async function swarmCommand(args, flags) {\n // Handle headless mode early\n if (flags && flags.headless) {\n const isHeadless = isHeadlessEnvironment();\n // Configure for headless mode\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'stream-json',\n 'no-auto-permissions': false,\n };\n }\n \n // Handle health check first\n if (flags && flags['health-check']) {\n try {\n // Quick health check for Docker/K8s\n console.log(JSON.stringify({\n status: 'healthy',\n service: 'claude-flow-swarm',\n version: process.env.npm_package_version || '2.0.0',\n timestamp: new Date().toISOString()\n }));\n process.exit(0);\n } catch (error) {\n console.error(JSON.stringify({\n status: 'unhealthy',\n error: error.message,\n timestamp: new Date().toISOString()\n }));\n process.exit(1);\n }\n }\n\n const objective = (args || []).join(' ').trim();\n\n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n // Force headless mode if flag is set\n if (flags && flags.headless) {\n const isHeadless = isHeadlessEnvironment();\n if (!isHeadless) {\n console.log('๐Ÿค– Forcing headless mode as requested');\n }\n flags = {\n ...flags,\n 'non-interactive': true,\n 'output-format': flags['output-format'] || 'json',\n 'no-auto-permissions': false,\n };\n }\n\n // Handle JSON output format\n const outputFormat = flags && flags['output-format'];\n const outputFile = flags && flags['output-file'];\n const isJsonOutput = outputFormat === 'json';\n const isNonInteractive = isJsonOutput || (flags && flags['no-interactive']);\n const useJsonLogs = flags && flags['json-logs'];\n\n // Override console.log for JSON logs if requested\n if (useJsonLogs) {\n const originalLog = console.log;\n const originalError = console.error;\n \n console.log = (...args) => {\n originalLog(JSON.stringify({\n level: 'info',\n message: args.join(' '),\n timestamp: new Date().toISOString(),\n service: 'claude-flow-swarm'\n }));\n };\n \n console.error = (...args) => {\n originalError(JSON.stringify({\n level: 'error',\n message: args.join(' '),\n timestamp: new Date().toISOString(),\n service: 'claude-flow-swarm'\n }));\n };\n }\n\n // Handle analysis/read-only mode\n const isAnalysisMode = flags && (flags.analysis || flags['read-only']);\n const analysisMode = isAnalysisMode ? 'analysis' : 'standard';\n\n // For JSON output, allow using Claude with stream-json format\n // Only force executor mode if explicitly using 'json' format (not 'stream-json')\n if (flags && flags['output-format'] === 'json' && !(flags && flags.executor)) {\n // Keep backward compatibility - regular 'json' format uses executor\n flags = { ...(flags || {}), executor: true };\n }\n\n // Check if we should use the old executor (opt-in with --executor flag)\n if (flags && flags.executor) {\n // Continue with the old swarm executor implementation below\n } else {\n // Default behavior: spawn Claude Code with comprehensive swarm MCP instructions\n try {\n const { execSync, spawn } = await import('child_process');\n\n // Get configuration values first\n const strategy = flags.strategy || 'auto';\n const mode = flags.mode || 'centralized';\n const maxAgents = flags['max-agents'] || 5;\n\n // Get strategy-specific guidance\n const strategyGuidance = getStrategyGuidance(strategy, objective);\n const modeGuidance = getModeGuidance(mode);\n const agentRecommendations = getAgentRecommendations(strategy, maxAgents, objective);\n\n const enableSparc =\n flags.sparc !== false && (strategy === 'development' || strategy === 'auto');\n\n // Build the complete swarm prompt before checking for claude\n const swarmPrompt = `You are orchestrating a Claude Flow Swarm using Claude Code's Task tool for agent execution.\n\n๐Ÿšจ CRITICAL INSTRUCTION: Use Claude Code's Task Tool for ALL Agent Spawning!\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\nโœ… Claude Code's Task tool = Spawns agents that DO the actual work\nโŒ MCP tools = Only for coordination setup, NOT for execution\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n\n๐ŸŽฏ OBJECTIVE: ${objective}\n\n๐Ÿ SWARM CONFIGURATION:\n- Strategy: ${strategy}\n- Mode: ${mode}\n- Max Agents: ${maxAgents}\n- Timeout: ${flags.timeout || 60} minutes\n- Parallel Execution: MANDATORY (Always use BatchTool)\n- Review Mode: ${flags.review || false}\n- Testing Mode: ${flags.testing || false}\n- Analysis Mode: ${isAnalysisMode ? 'ENABLED (Read-Only)' : 'DISABLED'}\n\n${\n isAnalysisMode\n ? `๐Ÿ” ANALYSIS MODE CONSTRAINTS:\n\nโš ๏ธ READ-ONLY MODE ACTIVE - NO CODE MODIFICATIONS ALLOWED\n\nREQUIRED BEHAVIORS:\n1. โœ… READ files for analysis (Read tool)\n2. โœ… SEARCH codebases (Glob, Grep tools)\n3. โœ… ANALYZE code structure and patterns\n4. โœ… GENERATE reports and documentation\n5. โœ… CREATE analysis summaries\n6. โœ… STORE findings in memory for collaboration\n7. โœ… COMMUNICATE between agents about findings\n\nFORBIDDEN OPERATIONS:\n1. โŒ NEVER use Write tool to modify files\n2. โŒ NEVER use Edit or MultiEdit tools\n3. โŒ NEVER use Bash to run commands that modify files\n4. โŒ NEVER create new files or directories\n5. โŒ NEVER install packages or dependencies\n6. โŒ NEVER modify configuration files\n7. โŒ NEVER execute code that changes system state\n\nALL AGENTS MUST OPERATE IN READ-ONLY MODE. Focus on:\n- Code analysis and understanding\n- Security vulnerability assessment\n- Performance bottleneck identification\n- Architecture documentation\n- Technical debt analysis\n- Dependency mapping\n- Testing strategy recommendations\n\nGenerate comprehensive reports instead of making changes.\n\n`\n : ''\n}๐Ÿšจ CRITICAL: PARALLEL EXECUTION IS MANDATORY! ๐Ÿšจ\n\n๐Ÿ“‹ CLAUDE-FLOW SWARM BATCHTOOL INSTRUCTIONS\n\nโšก THE GOLDEN RULE:\nIf you need to do X operations, they should be in 1 message, not X messages.\n\n๐ŸŽฏ MANDATORY PATTERNS FOR CLAUDE-FLOW SWARMS:\n\n1๏ธโƒฃ **SWARM INITIALIZATION** - Use Claude Code's Task Tool for Agents:\n\nStep A: Optional MCP Coordination Setup (Single Message):\n\\`\\`\\`javascript\n[MCP Tools - Coordination ONLY]:\n // Set up coordination topology (OPTIONAL)\n mcp__claude-flow__swarm_init {\"topology\": \"mesh\", \"maxAgents\": ${maxAgents}}\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/config\", \"value\": {\"strategy\": \"${strategy}\"}}\n\\`\\`\\`\n\nStep B: REQUIRED - Claude Code Task Tool for ACTUAL Agent Execution (Single Message):\n\\`\\`\\`javascript\n[Claude Code Task Tool - CONCURRENT Agent Spawning]:\n // Spawn ALL agents using Task tool in ONE message\n Task(\"Coordinator\", \"Lead swarm coordination. Use hooks for memory sharing.\", \"coordinator\")\n Task(\"Researcher\", \"Analyze requirements and patterns. Coordinate via hooks.\", \"researcher\")\n Task(\"Backend Dev\", \"Implement server-side features. Share progress via hooks.\", \"coder\")\n Task(\"Frontend Dev\", \"Build UI components. Sync with backend via memory.\", \"coder\")\n Task(\"QA Engineer\", \"Create and run tests. Report findings via hooks.\", \"tester\")\n \n // Batch ALL todos in ONE TodoWrite call (5-10+ todos)\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize ${maxAgents} agent swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Analyze: ${objective}\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Design architecture\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Implement backend\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Implement frontend\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"6\", \"content\": \"Write unit tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"7\", \"content\": \"Integration testing\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"8\", \"content\": \"Performance optimization\", \"status\": \"pending\", \"priority\": \"low\"},\n {\"id\": \"9\", \"content\": \"Documentation\", \"status\": \"pending\", \"priority\": \"low\"}\n ]}\n\\`\\`\\`\n\nโš ๏ธ CRITICAL: Claude Code's Task tool does the ACTUAL work!\n- MCP tools = Coordination setup only\n- Task tool = Spawns agents that execute real work\n- ALL agents MUST be spawned in ONE message\n- ALL todos MUST be batched in ONE TodoWrite call\n\n2๏ธโƒฃ **TASK COORDINATION** - Batch ALL assignments:\n\\`\\`\\`javascript\n[Single Message]:\n // Assign all tasks\n mcp__claude-flow__task_assign {\"taskId\": \"research-1\", \"agentId\": \"researcher-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"design-1\", \"agentId\": \"architect-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"code-1\", \"agentId\": \"coder-1\"}\n mcp__claude-flow__task_assign {\"taskId\": \"code-2\", \"agentId\": \"coder-2\"}\n \n // Communicate to all agents\n mcp__claude-flow__agent_communicate {\"to\": \"all\", \"message\": \"Begin phase 1\"}\n \n // Update multiple task statuses\n mcp__claude-flow__task_update {\"taskId\": \"research-1\", \"status\": \"in_progress\"}\n mcp__claude-flow__task_update {\"taskId\": \"design-1\", \"status\": \"pending\"}\n\\`\\`\\`\n\n3๏ธโƒฃ **MEMORY COORDINATION** - Store/retrieve in batches:\n\\`\\`\\`javascript\n[Single Message]:\n // Store multiple findings\n mcp__claude-flow__memory_store {\"key\": \"research/requirements\", \"value\": {...}}\n mcp__claude-flow__memory_store {\"key\": \"research/constraints\", \"value\": {...}}\n mcp__claude-flow__memory_store {\"key\": \"architecture/decisions\", \"value\": {...}}\n \n // Retrieve related data\n mcp__claude-flow__memory_retrieve {\"key\": \"research/*\"}\n mcp__claude-flow__memory_search {\"pattern\": \"architecture\"}\n\\`\\`\\`\n\n4๏ธโƒฃ **FILE & CODE OPERATIONS** - Parallel execution:\n\\`\\`\\`javascript\n[Single Message]:\n // Read multiple files\n Read {\"file_path\": \"/src/index.js\"}\n Read {\"file_path\": \"/src/config.js\"}\n Read {\"file_path\": \"/package.json\"}\n \n // Write multiple files\n Write {\"file_path\": \"/src/api/auth.js\", \"content\": \"...\"}\n Write {\"file_path\": \"/src/api/users.js\", \"content\": \"...\"}\n Write {\"file_path\": \"/tests/auth.test.js\", \"content\": \"...\"}\n \n // Update memory with results\n mcp__claude-flow__memory_store {\"key\": \"code/api/auth\", \"value\": \"implemented\"}\n mcp__claude-flow__memory_store {\"key\": \"code/api/users\", \"value\": \"implemented\"}\n\\`\\`\\`\n\n5๏ธโƒฃ **MONITORING & STATUS** - Combined checks:\n\\`\\`\\`javascript\n[Single Message]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__swarm_status {}\n mcp__claude-flow__agent_list {\"status\": \"active\"}\n mcp__claude-flow__task_status {\"includeCompleted\": false}\n TodoRead {}\n\\`\\`\\`\n\nโŒ NEVER DO THIS (Sequential = SLOW):\n\\`\\`\\`\nMessage 1: mcp__claude-flow__agent_spawn\nMessage 2: mcp__claude-flow__agent_spawn\nMessage 3: TodoWrite (one todo)\nMessage 4: Read file\nMessage 5: mcp__claude-flow__memory_store\n\\`\\`\\`\n\nโœ… ALWAYS DO THIS (Batch = FAST):\n\\`\\`\\`\nMessage 1: [All operations in one message]\n\\`\\`\\`\n\n๐Ÿ’ก BATCHTOOL BEST PRACTICES:\n- Group by operation type (all spawns, all reads, all writes)\n- Use TodoWrite with 5-10 todos at once\n- Combine file operations when analyzing codebases\n- Store multiple memory items per message\n- Never send more than one message for related operations\n\n${strategyGuidance}\n\n${modeGuidance}\n\n${agentRecommendations}\n\n๐Ÿ“‹ MANDATORY PARALLEL WORKFLOW:\n\n1. **INITIAL SPAWN (Single BatchTool Message):**\n - Spawn ALL agents at once\n - Create ALL initial todos at once\n - Store initial memory state\n - Create task hierarchy\n \n Example:\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__agent_spawn (coordinator)\n mcp__claude-flow__agent_spawn (architect)\n mcp__claude-flow__agent_spawn (coder-1)\n mcp__claude-flow__agent_spawn (coder-2)\n mcp__claude-flow__agent_spawn (tester)\n mcp__claude-flow__memory_store { key: \"init\", value: {...} }\n mcp__claude-flow__task_create { name: \"Main\", subtasks: [...] }\n TodoWrite { todos: [5-10 todos at once] }\n \\`\\`\\`\n\n2. **TASK EXECUTION (Parallel Batches):**\n - Assign multiple tasks in one batch\n - Update multiple statuses together\n - Store multiple results simultaneously\n \n3. **MONITORING (Combined Operations):**\n - Check all agent statuses together\n - Retrieve multiple memory items\n - Update all progress markers\n\n๐Ÿ”ง AVAILABLE MCP TOOLS FOR SWARM COORDINATION:\n\n๐Ÿ“Š MONITORING & STATUS:\n- mcp__claude-flow__swarm_status - Check current swarm status and agent activity\n- mcp__claude-flow__swarm_monitor - Real-time monitoring of swarm execution\n- mcp__claude-flow__agent_list - List all active agents and their capabilities\n- mcp__claude-flow__task_status - Check task progress and dependencies\n\n๐Ÿง  MEMORY & KNOWLEDGE:\n- mcp__claude-flow__memory_store - Store knowledge in swarm collective memory\n- mcp__claude-flow__memory_retrieve - Retrieve shared knowledge from memory\n- mcp__claude-flow__memory_search - Search collective memory by pattern\n- mcp__claude-flow__memory_sync - Synchronize memory across agents\n\n๐Ÿค– AGENT MANAGEMENT:\n- mcp__claude-flow__agent_spawn - Spawn specialized agents for tasks\n- mcp__claude-flow__agent_assign - Assign tasks to specific agents\n- mcp__claude-flow__agent_communicate - Send messages between agents\n- mcp__claude-flow__agent_coordinate - Coordinate agent activities\n\n๐Ÿ“‹ TASK ORCHESTRATION:\n- mcp__claude-flow__task_create - Create new tasks with dependencies\n- mcp__claude-flow__task_assign - Assign tasks to agents\n- mcp__claude-flow__task_update - Update task status and progress\n- mcp__claude-flow__task_complete - Mark tasks as complete with results\n\n๐ŸŽ›๏ธ COORDINATION MODES:\n1. CENTRALIZED (default): Single coordinator manages all agents\n - Use when: Clear hierarchy needed, simple workflows\n - Tools: agent_assign, task_create, swarm_monitor\n\n2. DISTRIBUTED: Multiple coordinators share responsibility\n - Use when: Large scale tasks, fault tolerance needed\n - Tools: agent_coordinate, memory_sync, task_update\n\n3. HIERARCHICAL: Tree structure with team leads\n - Use when: Complex projects with sub-teams\n - Tools: agent_spawn (with parent), task_create (with subtasks)\n\n4. MESH: Peer-to-peer agent coordination\n - Use when: Maximum flexibility, self-organizing teams\n - Tools: agent_communicate, memory_store/retrieve\n\nโšก EXECUTION WORKFLOW - ALWAYS USE BATCHTOOL:\n${\n enableSparc\n ? `\n1. SPARC METHODOLOGY WITH PARALLEL EXECUTION:\n \n S - Specification Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__memory_store { key: \"specs/requirements\", value: {...} }\n mcp__claude-flow__task_create { name: \"Requirement 1\" }\n mcp__claude-flow__task_create { name: \"Requirement 2\" }\n mcp__claude-flow__task_create { name: \"Requirement 3\" }\n mcp__claude-flow__agent_spawn { type: \"researcher\", name: \"SpecAnalyst\" }\n \\`\\`\\`\n \n P - Pseudocode Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__memory_store { key: \"pseudocode/main\", value: {...} }\n mcp__claude-flow__task_create { name: \"Design API\" }\n mcp__claude-flow__task_create { name: \"Design Data Model\" }\n mcp__claude-flow__agent_communicate { to: \"all\", message: \"Review design\" }\n \\`\\`\\`\n \n A - Architecture Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__agent_spawn { type: \"architect\", name: \"LeadArchitect\" }\n mcp__claude-flow__memory_store { key: \"architecture/decisions\", value: {...} }\n mcp__claude-flow__task_create { name: \"Backend\", subtasks: [...] }\n mcp__claude-flow__task_create { name: \"Frontend\", subtasks: [...] }\n \\`\\`\\`\n \n R - Refinement Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__task_update { taskId: \"1\", progress: 50 }\n mcp__claude-flow__task_update { taskId: \"2\", progress: 75 }\n mcp__claude-flow__memory_store { key: \"learnings/iteration1\", value: {...} }\n \\`\\`\\`\n \n C - Completion Phase (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_complete { taskId: \"1\", results: {...} }\n mcp__claude-flow__task_complete { taskId: \"2\", results: {...} }\n mcp__claude-flow__memory_retrieve { pattern: \"**/*\" }\n TodoWrite { todos: [{content: \"Final review\", status: \"completed\"}] }\n \\`\\`\\`\n`\n : `\n1. STANDARD SWARM EXECUTION WITH PARALLEL OPERATIONS:\n \n Initial Setup (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_create { name: \"Main\", subtasks: [...] }\n mcp__claude-flow__agent_spawn { type: \"coordinator\" }\n mcp__claude-flow__agent_spawn { type: \"coder\" }\n mcp__claude-flow__agent_spawn { type: \"tester\" }\n mcp__claude-flow__memory_store { key: \"init\", value: {...} }\n \\`\\`\\`\n \n Task Assignment (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__task_assign { taskId: \"1\", agentId: \"agent-1\" }\n mcp__claude-flow__task_assign { taskId: \"2\", agentId: \"agent-2\" }\n mcp__claude-flow__task_assign { taskId: \"3\", agentId: \"agent-3\" }\n \\`\\`\\`\n \n Monitoring & Updates (Single BatchTool):\n \\`\\`\\`\n [BatchTool]:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__agent_communicate { to: \"all\", message: \"Status update\" }\n mcp__claude-flow__memory_store { key: \"progress\", value: {...} }\n \\`\\`\\`\n`\n}\n\n๐Ÿค AGENT TYPES & THEIR MCP TOOL USAGE:\n\nCOORDINATOR:\n- Primary tools: swarm_monitor, agent_assign, task_create\n- Monitors overall progress and assigns work\n- Uses memory_store for decisions and memory_retrieve for context\n\nRESEARCHER:\n- Primary tools: memory_search, memory_store\n- Gathers information and stores findings\n- Uses agent_communicate to share discoveries\n\nCODER:\n- Primary tools: task_update, memory_retrieve, memory_store\n- Implements solutions and updates progress\n- Retrieves specs from memory, stores code artifacts\n\nANALYST:\n- Primary tools: memory_search, swarm_monitor\n- Analyzes data and patterns\n- Stores insights and recommendations\n\nTESTER:\n- Primary tools: task_status, agent_communicate\n- Validates implementations\n- Reports issues via task_update\n\n๐Ÿ“ EXAMPLE MCP TOOL USAGE PATTERNS:\n\n1. Starting a swarm:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__memory_store {\"key\": \"objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Main Objective\", \"type\": \"parent\"}\n\n2. Spawning worker agents:\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"capabilities\": [\"web-search\"]}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"capabilities\": [\"python\", \"testing\"]}\n mcp__claude-flow__task_assign {\"taskId\": \"task-123\", \"agentId\": \"agent-456\"}\n\n3. Coordinating work:\n mcp__claude-flow__agent_communicate {\"to\": \"agent-123\", \"message\": \"Begin phase 2\"}\n mcp__claude-flow__memory_store {\"key\": \"phase1/results\", \"value\": {...}}\n mcp__claude-flow__task_update {\"taskId\": \"task-123\", \"progress\": 75}\n\n4. Monitoring progress:\n mcp__claude-flow__swarm_monitor {}\n mcp__claude-flow__task_status {\"includeCompleted\": true}\n mcp__claude-flow__agent_list {\"status\": \"active\"}\n\n๐Ÿ’พ MEMORY PATTERNS:\n\nUse hierarchical keys for organization:\n- \"specs/requirements\" - Store specifications\n- \"architecture/decisions\" - Architecture choices\n- \"code/modules/[name]\" - Code artifacts\n- \"tests/results/[id]\" - Test outcomes\n- \"docs/api/[endpoint]\" - Documentation\n\n๐Ÿš€ BEGIN SWARM EXECUTION:\n\nStart by spawning a coordinator agent and creating the initial task structure. Use the MCP tools to orchestrate the swarm, coordinate agents, and track progress. Remember to store important decisions and artifacts in collective memory for other agents to access.\n\nThe swarm should be self-documenting - use memory_store to save all important information, decisions, and results throughout the execution.`;\n\n // If --claude flag is used, force Claude Code even if CLI not available\n if (flags && flags.claude) {\n // Inject memory coordination protocol into CLAUDE.md\n try {\n const { injectMemoryProtocol, enhanceSwarmPrompt } = await import('./inject-memory-protocol.js');\n await injectMemoryProtocol();\n \n // Enhance the prompt with memory coordination instructions\n swarmPrompt = enhanceSwarmPrompt(swarmPrompt, maxAgents);\n } catch (err) {\n // If injection module not available, continue with original prompt\n console.log('โš ๏ธ Memory protocol injection not available, using standard prompt');\n }\n \n // --claude flag means interactive mode, so don't apply non-interactive\n console.log('๐Ÿ Launching Claude Flow Swarm System...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${strategy}`);\n console.log(`๐Ÿ—๏ธ Mode: ${mode}`);\n console.log(`๐Ÿค– Max Agents: ${maxAgents}\\n`);\n \n console.log('๐Ÿš€ Launching Claude Code with Swarm Coordination');\n console.log('๐Ÿ“ Memory protocol injected into CLAUDE.md');\n console.log('โ”€'.repeat(60));\n \n // Build arguments properly: for interactive mode, prompt can be first\n const claudeArgs = [];\n \n // Add auto-permission flag first\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log('๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless swarm execution');\n }\n \n // Add the enhanced prompt\n claudeArgs.push(swarmPrompt);\n \n // --claude flag means interactive mode, so don't add non-interactive flags\n \n // For --claude interactive mode, spawn Claude directly\n // Temporarily disable telemetry to avoid console output interference\n const claudeEnv = { ...process.env };\n \n // Remove telemetry env vars to prevent console output\n delete claudeEnv.CLAUDE_CODE_ENABLE_TELEMETRY;\n delete claudeEnv.OTEL_METRICS_EXPORTER;\n delete claudeEnv.OTEL_LOGS_EXPORTER;\n \n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n env: claudeEnv\n });\n \n console.log('\\nโœ“ Claude Code launched with swarm coordination prompt!');\n console.log(' The swarm coordinator will orchestrate all agent tasks');\n console.log(' Use MCP tools for coordination and memory sharing');\n \n console.log('\\n๐Ÿ’ก Pro Tips:');\n console.log('โ”€'.repeat(30));\n console.log('โ€ข Use TodoWrite to track parallel tasks');\n console.log('โ€ข Store results with mcp__claude-flow__memory_usage');\n console.log('โ€ข Monitor progress with mcp__claude-flow__swarm_monitor');\n console.log('โ€ข Check task status with mcp__claude-flow__task_status');\n \n // Set up clean termination\n const cleanup = () => {\n console.log('\\n๐Ÿ›‘ Shutting down swarm gracefully...');\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n process.exit(0);\n };\n \n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n \n // Wait for claude to exit\n claudeProcess.on('exit', (code) => {\n if (code === 0) {\n console.log('\\nโœ“ Swarm execution completed successfully');\n } else if (code !== null) {\n console.log(`\\nโœ— Swarm execution exited with code ${code}`);\n }\n process.exit(code || 0);\n });\n \n // Handle spawn errors (e.g., claude not found)\n claudeProcess.on('error', (err) => {\n if (err.code === 'ENOENT') {\n console.error('\\nโŒ Claude Code CLI not found. Please install Claude Code:');\n console.error(' https://claude.ai/download');\n } else {\n console.error('\\nโŒ Failed to launch Claude Code:', err.message);\n }\n process.exit(1);\n });\n \n return;\n }\n\n // Check if we're in non-interactive/headless mode FIRST (like alpha.83)\n const isNonInteractive = flags['no-interactive'] || \n flags['non-interactive'] || \n flags['output-format'] === 'stream-json' ||\n isHeadlessEnvironment();\n \n // Check if claude command exists\n let claudeAvailable = false;\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n if (!isNonInteractive) {\n console.log('โš ๏ธ Claude Code CLI not found in PATH');\n console.log('Install it with: npm install -g @anthropic-ai/claude-code');\n console.log('Or use --claude flag to open Claude Code CLI');\n console.log('\\nWould spawn Claude Code with swarm objective:');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log('\\nOptions:');\n console.log(' โ€ข Use --executor flag for built-in executor: claude-flow swarm \"objective\" --executor');\n console.log(' โ€ข Use --claude flag to open Claude Code CLI: claude-flow swarm \"objective\" --claude');\n } else {\n // In non-interactive mode, output JSON error\n console.error(JSON.stringify({\n error: 'Claude Code CLI not found',\n message: 'Install with: npm install -g @anthropic-ai/claude-code',\n fallback: 'Use --executor flag for built-in executor'\n }));\n }\n return;\n }\n\n // Claude is available, use it to run swarm\n if (!isNonInteractive) {\n console.log('๐Ÿ Launching Claude Flow Swarm System...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n if (isAnalysisMode) {\n console.log(`๐Ÿ” Analysis Mode: ENABLED (Read-Only - No Code Changes)`);\n }\n console.log();\n } else {\n // Non-interactive mode output\n console.log('๐Ÿค– Running in non-interactive mode with Claude');\n console.log('๐Ÿ“‹ Command: claude [prompt] -p --output-format stream-json --verbose');\n }\n\n // Continue with the default swarm behavior if not using --claude flag\n\n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n\n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming\n claudeArgs.push('--verbose'); // Verbose output\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n '๐Ÿ”“ Using --dangerously-skip-permissions by default for seamless swarm execution',\n );\n }\n }\n\n // Add the prompt as the LAST argument\n claudeArgs.push(swarmPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n if (!isNonInteractive) {\n console.log('โœ“ Claude Code launched with swarm coordination prompt!');\n console.log('\\n๐Ÿš€ The swarm coordination instructions have been injected into Claude Code');\n console.log(' The prompt includes:');\n console.log(' โ€ข Strategy-specific guidance for', strategy);\n console.log(' โ€ข Coordination patterns for', mode, 'mode');\n console.log(' โ€ข Recommended agents and MCP tool usage');\n console.log(' โ€ข Complete workflow documentation\\n');\n }\n\n // Handle process events\n claudeProcess.on('error', (err) => {\n console.error('โŒ Failed to launch Claude Code:', err.message);\n });\n\n // Don't wait for completion - let it run\n return;\n } catch (error) {\n console.error('โŒ Failed to spawn Claude Code:', error.message);\n console.log('\\nFalling back to built-in executor...');\n // Fall through to executor implementation\n }\n }\n\n // Check if we should run in background mode\n if (flags && flags.background && !process.env.CLAUDE_SWARM_NO_BG) {\n // Check if we're in Deno environment\n if (typeof Deno !== 'undefined') {\n // In Deno, spawn a new process for true background execution\n const objective = (args || []).join(' ').trim();\n const swarmId = `swarm_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n const swarmRunDir = `./swarm-runs/${swarmId}`;\n\n // Create swarm directory\n await mkdirAsync(swarmRunDir, { recursive: true });\n\n console.log(`๐Ÿ Launching swarm in background mode...`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n console.log(`๐Ÿ“ Results: ${swarmRunDir}`);\n\n // Build command args without background flag (to prevent infinite loop)\n const commandArgs = ['run', '--allow-all', import.meta.url, objective];\n const newFlags = { ...flags };\n delete newFlags.background; // Remove background flag\n\n for (const [key, value] of Object.entries(newFlags)) {\n commandArgs.push(`--${key}`);\n if (value !== true) {\n commandArgs.push(String(value));\n }\n }\n\n // Create log file\n const logFile = `${swarmRunDir}/swarm.log`;\n const logHandle = await open(logFile, 'w');\n\n // Create a script to run the swarm without background flag\n const scriptContent = `#!/usr/bin/env -S deno run --allow-all\nimport { swarmCommand } from \"${import.meta.url}\";\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport process from 'process';\n\n// Remove background flag to prevent recursion\nconst flags = ${JSON.stringify(newFlags)};\nconst args = ${JSON.stringify(args)};\n\n// Set env to prevent background spawning\nprocess.env.CLAUDE_SWARM_NO_BG = 'true';\n\n// Run the swarm\nawait swarmCommand(args, flags);\n`;\n\n const scriptPath = `${swarmRunDir}/run-swarm.js`;\n await writeTextFile(scriptPath, scriptContent);\n\n // Save process info first\n await writeTextFile(\n `${swarmRunDir}/process.json`,\n JSON.stringify(\n {\n swarmId: swarmId,\n objective: objective,\n startTime: new Date().toISOString(),\n logFile: logFile,\n status: 'starting',\n },\n null,\n 2,\n ),\n );\n\n // Close log handle before spawning\n logHandle.close();\n\n // Use the bash script for true background execution\n const binDir = new URL('../../../bin/', import.meta.url).pathname;\n const bgScriptPath = `${binDir}claude-flow-swarm-bg`;\n\n try {\n // Check if the background script exists\n statSync(bgScriptPath);\n\n // Build command args for the background script\n const bgArgs = [objective];\n for (const [key, value] of Object.entries(newFlags)) {\n bgArgs.push(`--${key}`);\n if (value !== true) {\n bgArgs.push(String(value));\n }\n }\n\n // Use the bash background script\n const bgProcess = spawn(bgScriptPath, bgArgs, {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n // Read and display output\n const decoder = new TextDecoder();\n const output = await bgProcess.output();\n console.log(decoder.decode(output.stdout));\n\n // Exit immediately after launching\n exit(0);\n } catch (error) {\n // Fallback: create a double-fork pattern using a shell script\n console.log(`\\nโš ๏ธ Background script not found, using fallback method`);\n\n // Create a shell script that will run the swarm\n const shellScript = `#!/bin/bash\n# Double fork to detach from parent\n(\n (\n node \"${scriptPath}\" > \"${logFile}\" 2>&1 &\n echo $! > \"${swarmRunDir}/swarm.pid\"\n ) &\n)\nexit 0\n`;\n\n const shellScriptPath = `${swarmRunDir}/launch-background.sh`;\n await writeTextFile(shellScriptPath, shellScript);\n chmodSync(shellScriptPath, 0o755);\n\n // Execute the shell script\n const shellProcess = spawn('bash', [shellScriptPath], {\n stdio: 'ignore',\n detached: true,\n });\n shellProcess.unref();\n\n console.log(`\\nโœ… Swarm launched in background!`);\n console.log(`๐Ÿ“„ Logs: tail -f ${logFile}`);\n console.log(`๐Ÿ“Š Status: claude-flow swarm status ${swarmId}`);\n console.log(`\\nThe swarm will continue running independently.`);\n\n // Exit immediately\n exit(0);\n }\n }\n\n // Node.js environment - use background script\n const { execSync } = await import('child_process');\n const path = await import('path');\n const fs = await import('fs');\n\n const objective = (args || []).join(' ').trim();\n\n // Get the claude-flow-swarm-bg script path\n const bgScriptPath = path.join(\n path.dirname(new URL(import.meta.url).pathname),\n '../../../bin/claude-flow-swarm-bg',\n );\n\n // Check if background script exists\n if (fs.existsSync(bgScriptPath)) {\n // Build command args\n const commandArgs = [objective];\n for (const [key, value] of Object.entries(flags)) {\n if (key !== 'background') {\n // Skip background flag\n commandArgs.push(`--${key}`);\n if (value !== true) {\n commandArgs.push(String(value));\n }\n }\n }\n\n // Execute the background script\n try {\n execSync(`\"${bgScriptPath}\" ${commandArgs.map((arg) => `\"${arg}\"`).join(' ')}`, {\n stdio: 'inherit',\n });\n } catch (error) {\n console.error('Failed to launch background swarm:', error.message);\n }\n } else {\n // Fallback to simple message\n console.log(`๐Ÿ Background mode requested`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`\\nโš ๏ธ Background execution requires the claude-flow-swarm-bg script.`);\n console.log(`\\nFor true background execution, use:`);\n console.log(\n ` nohup claude-flow swarm \"${objective}\" ${Object.entries(flags)\n .filter(([k, v]) => k !== 'background' && v)\n .map(([k, v]) => `--${k}${v !== true ? ` ${v}` : ''}`)\n .join(' ')} > swarm.log 2>&1 &`,\n );\n }\n return;\n }\n\n try {\n // Try to load the compiled JavaScript module first\n let swarmAction;\n try {\n // Try the compiled version first (for production/npm packages)\n const distPath = new URL('../../../dist/cli/commands/swarm-new.js', import.meta.url);\n const module = await import(distPath);\n swarmAction = module.swarmAction;\n } catch (distError) {\n // Instead of immediately falling back to basic mode, \n // continue to the Claude integration below\n console.log('๐Ÿ“ฆ Compiled swarm module not found, checking for Claude CLI...');\n }\n\n // Only call swarmAction if it was successfully loaded\n if (swarmAction) {\n // Create command context compatible with TypeScript version\n const ctx = {\n args: args || [],\n flags: flags || {},\n command: 'swarm',\n };\n\n await swarmAction(ctx);\n return; // Exit after successful execution\n }\n } catch (error) {\n // If import fails (e.g., in node_modules), provide inline implementation\n if (\n error.code === 'ERR_MODULE_NOT_FOUND' ||\n error.code === 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING' ||\n error.code === 'ERR_UNKNOWN_FILE_EXTENSION'\n ) {\n // Provide a basic swarm implementation that works without TypeScript imports\n const objective = (args || []).join(' ').trim();\n\n if (!objective) {\n console.error('โŒ Usage: swarm ');\n showSwarmHelp();\n return;\n }\n\n // Try to use the swarm executor directly\n try {\n const { executeSwarm } = await import('./swarm-executor.js');\n const result = await executeSwarm(objective, flags);\n\n // If execution was successful, exit\n if (result && result.success) {\n return;\n }\n } catch (execError) {\n console.log(`โš ๏ธ Swarm executor error: ${execError.message}`);\n // If swarm executor fails, try to create files directly\n try {\n await createSwarmFiles(objective, flags);\n return;\n } catch (createError) {\n console.log(`โš ๏ธ Direct file creation error: ${createError.message}`);\n // Continue with fallback implementation\n }\n }\n\n // Provide a basic inline swarm implementation for npm packages\n console.log('๐Ÿ Launching swarm system...');\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n console.log(`๐Ÿ—๏ธ Mode: ${flags.mode || 'centralized'}`);\n console.log(`๐Ÿค– Max Agents: ${flags['max-agents'] || 5}`);\n console.log();\n\n // Generate swarm ID\n const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;\n\n if (flags['dry-run']) {\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n console.log(`๐Ÿ“Š Max Tasks: ${flags['max-tasks'] || 100}`);\n console.log(`โฐ Timeout: ${flags.timeout || 60} minutes`);\n console.log(`๐Ÿ”„ Parallel: ${flags.parallel || false}`);\n console.log(`๐ŸŒ Distributed: ${flags.distributed || false}`);\n console.log(`๐Ÿ” Monitoring: ${flags.monitor || false}`);\n console.log(`๐Ÿ‘ฅ Review Mode: ${flags.review || false}`);\n console.log(`๐Ÿงช Testing: ${flags.testing || false}`);\n console.log(`๐Ÿง  Memory Namespace: ${flags['memory-namespace'] || 'swarm'}`);\n console.log(`๐Ÿ’พ Persistence: ${flags.persistence !== false}`);\n console.log(`๐Ÿ”’ Encryption: ${flags.encryption || false}`);\n console.log(`๐Ÿ“Š Quality Threshold: ${flags['quality-threshold'] || 0.8}`);\n console.log();\n console.log('๐ŸŽ›๏ธ Coordination Strategy:');\n console.log(` โ€ข Agent Selection: ${flags['agent-selection'] || 'capability-based'}`);\n console.log(` โ€ข Task Scheduling: ${flags['task-scheduling'] || 'priority'}`);\n console.log(` โ€ข Load Balancing: ${flags['load-balancing'] || 'work-stealing'}`);\n console.log(` โ€ข Fault Tolerance: ${flags['fault-tolerance'] || 'retry'}`);\n console.log(` โ€ข Communication: ${flags.communication || 'event-driven'}`);\n console.log('โš ๏ธ DRY RUN - Advanced Swarm Configuration');\n return;\n }\n\n // For actual execution in npm context, try to find and run swarm-demo.ts\n try {\n const path = await import('path');\n const { fileURLToPath } = await import('url');\n const fs = await import('fs');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n\n // Look for swarm-demo.ts in the package\n const possiblePaths = [\n path.join(__dirname, '../../../swarm-demo.ts'),\n path.join(__dirname, '../../swarm-demo.ts'),\n ];\n\n let swarmDemoPath = null;\n for (const p of possiblePaths) {\n if (fs.existsSync(p)) {\n swarmDemoPath = p;\n break;\n }\n }\n\n if (swarmDemoPath && Deno) {\n // Run swarm-demo.ts directly with Deno\n const swarmArgs = [objective];\n for (const [key, value] of Object.entries(flags || {})) {\n swarmArgs.push(`--${key}`);\n if (value !== true) {\n swarmArgs.push(String(value));\n }\n }\n\n console.log('๐Ÿš€ Starting advanced swarm execution...');\n const swarmProcess = spawn('node', [swarmDemoPath, ...swarmArgs], {\n stdio: 'inherit',\n });\n\n swarmProcess.on('error', (err) => {\n console.error('โŒ Failed to launch swarm:', err.message);\n });\n\n swarmProcess.on('exit', (code) => {\n if (code !== 0) {\n console.error(`โŒ Swarm exited with code ${code}`);\n }\n });\n return;\n }\n } catch (e) {\n // Fallback to basic message if can't run swarm-demo.ts\n }\n\n // Try to use Claude wrapper approach like SPARC does\n try {\n const { execSync } = await import('child_process');\n\n // Check if claude command exists\n try {\n execSync('which claude', { stdio: 'ignore' });\n } catch (e) {\n // Claude not found, show fallback message\n console.log(`โœ… Swarm initialized with ID: ${swarmId}`);\n console.log('\\nโš ๏ธ Note: Advanced swarm features require Claude or local installation.');\n console.log('Install Claude: https://claude.ai/code');\n console.log('Or install locally: npm install -g claude-flow@latest');\n console.log('\\nThe swarm system would coordinate the following:');\n console.log('1. Agent spawning and task distribution');\n console.log('2. Parallel execution of subtasks');\n console.log('3. Memory sharing between agents');\n console.log('4. Progress monitoring and reporting');\n console.log('5. Result aggregation and quality checks');\n return;\n }\n\n // Claude is available, use it to run swarm\n console.log('๐Ÿš€ Launching swarm via Claude wrapper...');\n if (flags.sparc !== false) {\n console.log('๐Ÿงช SPARC methodology enabled - using full TDD workflow');\n }\n\n // Build the prompt for Claude using SPARC methodology\n const enableSparc = flags.sparc !== false;\n const swarmPrompt = `Execute a swarm coordination task using ${enableSparc ? 'the full SPARC methodology' : 'standard approach'}:\n\nOBJECTIVE: ${objective}\n\nCONFIGURATION:\n- Strategy: ${flags.strategy || 'auto'}\n- Mode: ${flags.mode || 'centralized'}\n- Max Agents: ${flags['max-agents'] || 5}\n- Memory Namespace: ${flags['memory-namespace'] || 'swarm'}\n- Quality Threshold: ${flags['quality-threshold'] || 0.8}\n${enableSparc ? '- SPARC Enabled: YES - Use full Specification, Pseudocode, Architecture, Refinement (TDD), Completion methodology' : ''}\n\n${\n enableSparc\n ? `\nSPARC METHODOLOGY REQUIREMENTS:\n\n1. SPECIFICATION PHASE:\n - Create detailed requirements and acceptance criteria\n - Define user stories with clear objectives\n - Document functional and non-functional requirements\n - Establish quality metrics and success criteria\n\n2. PSEUDOCODE PHASE:\n - Design algorithms and data structures\n - Create flow diagrams and logic patterns\n - Define interfaces and contracts\n - Plan error handling strategies\n\n3. ARCHITECTURE PHASE:\n - Design system architecture with proper components\n - Define APIs and service boundaries\n - Plan database schemas if applicable\n - Create deployment architecture\n\n4. REFINEMENT PHASE (TDD):\n - RED: Write comprehensive failing tests first\n - GREEN: Implement minimal code to pass tests\n - REFACTOR: Optimize and clean up implementation\n - Ensure >80% test coverage\n\n5. COMPLETION PHASE:\n - Integrate all components\n - Create comprehensive documentation\n - Perform end-to-end testing\n - Validate against original requirements\n`\n : ''\n}\n\nEXECUTION APPROACH:\n1. Analyze the objective and break it down into specific tasks\n2. Create a comprehensive implementation plan\n3. ${enableSparc ? 'Follow SPARC phases sequentially with proper artifacts for each phase' : 'Implement the solution directly'}\n4. Generate production-ready code with proper structure\n5. Include all necessary files (source code, tests, configs, documentation)\n6. Ensure the implementation is complete and functional\n\nTARGET DIRECTORY:\nExtract from the objective or use a sensible default. Create all files in the appropriate directory structure.\n\nIMPORTANT:\n- Create actual, working implementations - not templates or placeholders\n- Include comprehensive tests using appropriate testing frameworks\n- Add proper error handling and logging\n- Include configuration files (package.json, requirements.txt, etc.)\n- Create detailed README with setup and usage instructions\n- Follow best practices for the technology stack\n- Make the code production-ready, not just examples\n\nBegin execution now. Create all necessary files and provide a complete, working solution.`;\n\n // Execute Claude non-interactively by piping the prompt\n const { spawn } = await import('child_process');\n\n const claudeArgs = [];\n\n // Add auto-permission flag by default for swarm mode (unless explicitly disabled)\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n // Spawn claude process\n const claudeProcess = spawn('claude', claudeArgs, {\n stdio: ['pipe', 'inherit', 'inherit'],\n shell: false,\n });\n\n // Write the prompt to stdin and close it\n claudeProcess.stdin.write(swarmPrompt);\n claudeProcess.stdin.end();\n\n // Wait for the process to complete\n await new Promise((resolve, reject) => {\n claudeProcess.on('close', (code) => {\n if (code === 0) {\n resolve();\n } else {\n reject(new Error(`Claude process exited with code ${code}`));\n }\n });\n\n claudeProcess.on('error', (err) => {\n reject(err);\n });\n });\n } catch (error) {\n // Fallback if Claude execution fails\n console.log(`โœ… Swarm initialized with ID: ${swarmId}`);\n console.log('\\nโš ๏ธ Note: Advanced swarm features require Claude or local installation.');\n console.log('Install Claude: https://claude.ai/code');\n console.log('Or install locally: npm install -g claude-flow@latest');\n console.log('\\nThe swarm system would coordinate the following:');\n console.log('1. Agent spawning and task distribution');\n console.log('2. Parallel execution of subtasks');\n console.log('3. Memory sharing between agents');\n console.log('4. Progress monitoring and reporting');\n console.log('5. Result aggregation and quality checks');\n }\n\n return;\n }\n\n console.error('Swarm command error:', error);\n\n // Fallback to comprehensive help if there's an import error\n console.log(`\n๐Ÿ Claude Flow Advanced Swarm System\n\nUSAGE:\n claude-flow swarm [options]\n\nEXAMPLES:\n claude-flow swarm \"Build a REST API\" --strategy development\n claude-flow swarm \"Research cloud architecture\" --strategy research --ui\n claude-flow swarm \"Analyze data trends\" --strategy analysis --parallel\n claude-flow swarm \"Optimize performance\" --distributed --monitor\n\nSTRATEGIES:\n auto Automatically determine best approach (default)\n research Research and information gathering\n development Software development and coding\n analysis Data analysis and insights\n testing Testing and quality assurance\n optimization Performance optimization\n maintenance System maintenance\n\nMODES:\n centralized Single coordinator (default)\n distributed Multiple coordinators\n hierarchical Tree structure coordination\n mesh Peer-to-peer coordination\n hybrid Mixed coordination strategies\n\nKEY FEATURES:\n ๐Ÿค– Intelligent agent management with specialized types\n โšก Timeout-free background task execution\n ๐Ÿง  Distributed memory sharing between agents\n ๐Ÿ”„ Work stealing and advanced load balancing\n ๐Ÿ›ก๏ธ Circuit breaker patterns for fault tolerance\n ๐Ÿ“Š Real-time monitoring and comprehensive metrics\n ๐ŸŽ›๏ธ Multiple coordination strategies and algorithms\n ๐Ÿ’พ Persistent state with backup and recovery\n ๐Ÿ”’ Security features with encryption options\n ๐Ÿ–ฅ๏ธ Interactive terminal UI for management\n\nOPTIONS:\n --strategy Execution strategy (default: auto)\n --mode Coordination mode (default: centralized)\n --max-agents Maximum agents (default: 5)\n --timeout Timeout in minutes (default: 60)\n --task-timeout-minutes Task execution timeout in minutes (default: 59)\n --parallel Enable parallel execution\n --distributed Enable distributed coordination\n --monitor Enable real-time monitoring\n --ui Launch terminal UI interface\n --background Run in background mode\n --review Enable peer review\n --testing Enable automated testing\n --encryption Enable encryption\n --verbose Enable detailed logging\n --dry-run Show configuration without executing\n --executor Use built-in executor instead of Claude Code\n --claude Open Claude Code CLI\n --output-format Output format: json, text (default: text)\n --output-file Save output to file instead of stdout\n --no-interactive Run in non-interactive mode (auto-enabled with --output-format json)\n --auto (Deprecated: auto-permissions enabled by default)\n --no-auto-permissions Disable automatic --dangerously-skip-permissions\n --analysis Enable analysis/read-only mode (no code changes)\n --read-only Enable read-only mode (alias for --analysis)\n\nADVANCED OPTIONS:\n --quality-threshold Quality threshold 0-1 (default: 0.8)\n --memory-namespace Memory namespace (default: swarm)\n --agent-selection Agent selection strategy\n --task-scheduling Task scheduling algorithm\n --load-balancing Load balancing method\n --fault-tolerance Fault tolerance strategy\n\nFor complete documentation and examples:\nhttps://github.com/ruvnet/claude-code-flow/docs/swarm.md\n`);\n }\n}\n\n// Function to create swarm files directly\nasync function createSwarmFiles(objective, flags) {\n const fs = await import('fs');\n const path = await import('path');\n\n const swarmId = `swarm_${Math.random().toString(36).substring(2, 11)}_${Math.random().toString(36).substring(2, 11)}`;\n\n console.log(`๐Ÿ Swarm Execution Started: ${swarmId}`);\n console.log(`๐Ÿ“‹ Objective: ${objective}`);\n console.log(`๐ŸŽฏ Strategy: ${flags.strategy || 'auto'}`);\n\n // Extract target directory from objective\n const targetMatch = objective.match(/in\\s+([^\\s]+)\\/?$/i);\n let targetDir = targetMatch ? targetMatch[1] : 'output';\n\n // Resolve relative paths\n if (!targetDir.startsWith('/')) {\n targetDir = path.join(process.cwd(), targetDir);\n }\n\n console.log(`๐Ÿ“ Target directory: ${targetDir}`);\n\n // Ensure target directory exists\n await fs.promises.mkdir(targetDir, { recursive: true });\n\n // Determine what to build based on objective\n const isRestAPI =\n objective.toLowerCase().includes('rest api') || objective.toLowerCase().includes('api');\n\n if (isRestAPI) {\n // Create REST API\n const apiDir = path.join(targetDir, 'rest-api');\n await fs.promises.mkdir(apiDir, { recursive: true });\n\n console.log(`\\n๐Ÿ—๏ธ Creating REST API...`);\n console.log(` ๐Ÿค– Agent developer-1: Creating server implementation`);\n\n // Create server.js\n const serverCode = `const express = require('express');\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Middleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n\n// Health check endpoint\napp.get('/health', (req, res) => {\n res.json({ \n status: 'healthy',\n service: 'REST API',\n swarmId: '${swarmId}',\n created: new Date().toISOString()\n });\n});\n\n// Sample endpoints\napp.get('/api/v1/items', (req, res) => {\n res.json({\n items: [\n { id: 1, name: 'Item 1', description: 'First item' },\n { id: 2, name: 'Item 2', description: 'Second item' }\n ],\n total: 2\n });\n});\n\napp.get('/api/v1/items/:id', (req, res) => {\n const id = parseInt(req.params.id);\n res.json({\n id,\n name: \\`Item \\${id}\\`,\n description: \\`Description for item \\${id}\\`\n });\n});\n\napp.post('/api/v1/items', (req, res) => {\n const newItem = {\n id: Date.now(),\n ...req.body,\n createdAt: new Date().toISOString()\n };\n res.status(201).json(newItem);\n});\n\n// Start server\napp.listen(port, () => {\n console.log(\\`REST API server running on port \\${port}\\`);\n console.log('Created by Claude Flow Swarm');\n});\n\nmodule.exports = app;\n`;\n\n await fs.promises.writeFile(path.join(apiDir, 'server.js'), serverCode);\n console.log(` โœ… Created: server.js`);\n\n // Create package.json\n const packageJson = {\n name: 'rest-api',\n version: '1.0.0',\n description: 'REST API created by Claude Flow Swarm',\n main: 'server.js',\n scripts: {\n start: 'node server.js',\n dev: 'nodemon server.js',\n test: 'jest',\n },\n keywords: ['rest', 'api', 'swarm', 'claude-flow'],\n author: 'Claude Flow Swarm',\n license: 'MIT',\n dependencies: {\n express: '^4.18.2',\n },\n devDependencies: {\n nodemon: '^3.0.1',\n jest: '^29.7.0',\n supertest: '^6.3.3',\n },\n swarmMetadata: {\n swarmId,\n strategy: flags.strategy || 'development',\n created: new Date().toISOString(),\n },\n };\n\n await fs.promises.writeFile(\n path.join(apiDir, 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n console.log(` โœ… Created: package.json`);\n\n // Create README\n const readme = `# REST API\n\nThis REST API was created by the Claude Flow Swarm system.\n\n## Swarm Details\n- Swarm ID: ${swarmId}\n- Strategy: ${flags.strategy || 'development'}\n- Generated: ${new Date().toISOString()}\n\n## Installation\n\n\\`\\`\\`bash\nnpm install\n\\`\\`\\`\n\n## Usage\n\nStart the server:\n\\`\\`\\`bash\nnpm start\n\\`\\`\\`\n\n## API Endpoints\n\n- \\`GET /health\\` - Health check\n- \\`GET /api/v1/items\\` - Get all items\n- \\`GET /api/v1/items/:id\\` - Get item by ID\n- \\`POST /api/v1/items\\` - Create new item\n\n---\nCreated by Claude Flow Swarm\n`;\n\n await fs.promises.writeFile(path.join(apiDir, 'README.md'), readme);\n console.log(` โœ… Created: README.md`);\n\n console.log(`\\nโœ… Swarm completed successfully!`);\n console.log(`๐Ÿ“ Files created in: ${apiDir}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n } else {\n // Create generic application\n console.log(`\\n๐Ÿ—๏ธ Creating application...`);\n\n const appCode = `// Application created by Claude Flow Swarm\n// Objective: ${objective}\n// Swarm ID: ${swarmId}\n\nfunction main() {\n console.log('Executing swarm objective: ${objective}');\n console.log('Implementation would be based on the specific requirements');\n}\n\nmain();\n`;\n\n await fs.promises.writeFile(path.join(targetDir, 'app.js'), appCode);\n console.log(` โœ… Created: app.js`);\n\n const packageJson = {\n name: 'swarm-app',\n version: '1.0.0',\n description: `Application created by Claude Flow Swarm: ${objective}`,\n main: 'app.js',\n scripts: {\n start: 'node app.js',\n },\n swarmMetadata: {\n swarmId,\n objective,\n created: new Date().toISOString(),\n },\n };\n\n await fs.promises.writeFile(\n path.join(targetDir, 'package.json'),\n JSON.stringify(packageJson, null, 2),\n );\n console.log(` โœ… Created: package.json`);\n\n console.log(`\\nโœ… Swarm completed successfully!`);\n console.log(`๐Ÿ“ Files created in: ${targetDir}`);\n console.log(`๐Ÿ†” Swarm ID: ${swarmId}`);\n }\n}\n\n/**\n * Get strategy-specific guidance for swarm execution\n */\nfunction getStrategyGuidance(strategy, objective) {\n const guidanceMap = {\n auto: `๐Ÿค– AUTO STRATEGY - INTELLIGENT TASK ANALYSIS:\nThe swarm will analyze \"${objective}\" and automatically determine the best approach.\n\nANALYSIS APPROACH:\n1. Task Decomposition: Break down the objective into subtasks\n2. Skill Matching: Identify required capabilities and expertise\n3. Agent Selection: Spawn appropriate agent types based on needs\n4. Workflow Design: Create optimal execution flow\n\nMCP TOOL PATTERN:\n- Start with memory_store to save the objective analysis\n- Use task_create to build a hierarchical task structure\n- Spawn agents with agent_spawn based on detected requirements\n- Monitor with swarm_monitor and adjust strategy as needed`,\n\n research: `๐Ÿ”ฌ RESEARCH STRATEGY - INFORMATION GATHERING & ANALYSIS:\nOptimized for: \"${objective}\"\n\nRESEARCH PHASES:\n1. Discovery: Broad information gathering\n2. Analysis: Deep dive into findings\n3. Synthesis: Combine insights\n4. Reporting: Document conclusions\n\nRECOMMENDED AGENTS:\n- Lead Researcher: Coordinates research efforts\n- Data Analysts: Process and analyze findings\n- Subject Experts: Domain-specific investigation\n- Documentation Specialist: Compile reports\n\nMCP TOOL USAGE:\n- memory_store: Save all research findings with structured keys\n- memory_search: Find related information across research\n- agent_communicate: Share discoveries between researchers\n- task_create: Break research into focused sub-investigations`,\n\n development: `๐Ÿ’ป DEVELOPMENT STRATEGY - SOFTWARE CREATION:\nBuilding: \"${objective}\"\n\nDEVELOPMENT WORKFLOW:\n1. Architecture: Design system structure\n2. Implementation: Build components\n3. Integration: Connect systems\n4. Testing: Validate functionality\n5. Documentation: Create guides\n\nRECOMMENDED AGENTS:\n- System Architect: Overall design\n- Backend Developers: API/server implementation\n- Frontend Developers: UI/UX implementation\n- DevOps Engineer: Infrastructure setup\n- QA Engineers: Testing and validation\n\nMCP TOOL USAGE:\n- memory_store: Save architecture decisions, code modules\n- task_create: Create implementation tasks with dependencies\n- agent_assign: Assign specific components to developers\n- swarm_monitor: Track build progress and blockers`,\n\n analysis: `๐Ÿ“Š ANALYSIS STRATEGY - DATA EXAMINATION:\nAnalyzing: \"${objective}\"\n\nANALYSIS FRAMEWORK:\n1. Data Collection: Gather relevant information\n2. Processing: Clean and prepare data\n3. Analysis: Apply analytical methods\n4. Visualization: Create insights\n5. Recommendations: Actionable outcomes\n\nRECOMMENDED AGENTS:\n- Lead Analyst: Coordinate analysis efforts\n- Data Engineers: Prepare data pipelines\n- Statistical Analysts: Apply analytical methods\n- Visualization Experts: Create dashboards\n- Business Analysts: Translate to recommendations\n\nMCP TOOL USAGE:\n- memory_store: Save datasets and analysis results\n- memory_retrieve: Access historical analysis\n- task_create: Define analysis pipelines\n- agent_coordinate: Sync analysis phases`,\n\n testing: `๐Ÿงช TESTING STRATEGY - QUALITY ASSURANCE:\nTesting: \"${objective}\"\n\nTESTING PHASES:\n1. Test Planning: Define test scenarios\n2. Test Development: Create test cases\n3. Execution: Run test suites\n4. Bug Tracking: Document issues\n5. Regression: Ensure fixes work\n\nRECOMMENDED AGENTS:\n- Test Lead: Coordinate testing efforts\n- Unit Testers: Component-level testing\n- Integration Testers: System-level testing\n- Performance Testers: Load and stress testing\n- Security Testers: Vulnerability assessment\n\nMCP TOOL USAGE:\n- task_create: Create test cases and scenarios\n- memory_store: Save test results and bug reports\n- agent_communicate: Report bugs to developers\n- swarm_monitor: Track testing coverage and progress`,\n\n optimization: `โšก OPTIMIZATION STRATEGY - PERFORMANCE IMPROVEMENT:\nOptimizing: \"${objective}\"\n\nOPTIMIZATION PROCESS:\n1. Profiling: Identify bottlenecks\n2. Analysis: Understand root causes\n3. Implementation: Apply optimizations\n4. Validation: Measure improvements\n5. Documentation: Record changes\n\nRECOMMENDED AGENTS:\n- Performance Lead: Coordinate optimization\n- System Profilers: Identify bottlenecks\n- Algorithm Experts: Optimize logic\n- Database Specialists: Query optimization\n- Infrastructure Engineers: System tuning\n\nMCP TOOL USAGE:\n- memory_store: Save performance baselines and results\n- task_create: Create optimization tasks by priority\n- swarm_monitor: Track performance improvements\n- agent_communicate: Coordinate optimization efforts`,\n\n maintenance: `๐Ÿ”ง MAINTENANCE STRATEGY - SYSTEM UPKEEP:\nMaintaining: \"${objective}\"\n\nMAINTENANCE WORKFLOW:\n1. Assessment: Evaluate current state\n2. Planning: Prioritize updates\n3. Implementation: Apply changes\n4. Testing: Verify stability\n5. Documentation: Update records\n\nRECOMMENDED AGENTS:\n- Maintenance Lead: Coordinate efforts\n- System Administrators: Infrastructure updates\n- Security Engineers: Patch vulnerabilities\n- Database Administrators: Data maintenance\n- Documentation Writers: Update guides\n\nMCP TOOL USAGE:\n- memory_retrieve: Access system history\n- task_create: Schedule maintenance tasks\n- agent_assign: Delegate specific updates\n- memory_store: Document all changes`,\n };\n\n return guidanceMap[strategy] || guidanceMap['auto'];\n}\n\n/**\n * Get mode-specific guidance for coordination\n */\nfunction getModeGuidance(mode) {\n const modeMap = {\n centralized: `๐ŸŽฏ CENTRALIZED MODE - SINGLE COORDINATOR:\nAll decisions flow through one coordinator agent.\n\nCOORDINATION PATTERN:\n- Spawn a single COORDINATOR as the first agent\n- All other agents report to the coordinator\n- Coordinator assigns tasks and monitors progress\n- Use agent_assign for task delegation\n- Use swarm_monitor for oversight\n\nBENEFITS:\n- Clear chain of command\n- Consistent decision making\n- Simple communication flow\n- Easy progress tracking\n\nBEST FOR:\n- Small to medium projects\n- Well-defined objectives\n- Clear task dependencies`,\n\n distributed: `๐ŸŒ DISTRIBUTED MODE - MULTIPLE COORDINATORS:\nMultiple coordinators share responsibility by domain.\n\nCOORDINATION PATTERN:\n- Spawn domain-specific coordinators (e.g., frontend-lead, backend-lead)\n- Each coordinator manages their domain agents\n- Use agent_coordinate for inter-coordinator sync\n- Use memory_sync to share state\n- Implement consensus protocols for decisions\n\nBENEFITS:\n- Fault tolerance\n- Parallel decision making\n- Domain expertise\n- Scalability\n\nBEST FOR:\n- Large projects\n- Multiple workstreams\n- Complex systems\n- High availability needs`,\n\n hierarchical: `๐Ÿ—๏ธ HIERARCHICAL MODE - TREE STRUCTURE:\nAgents organized in management layers.\n\nCOORDINATION PATTERN:\n- Spawn top-level coordinator\n- Spawn team leads under coordinator\n- Spawn workers under team leads\n- Use parent parameter in agent_spawn\n- Tasks flow down, results flow up\n\nBENEFITS:\n- Clear reporting structure\n- Efficient for large teams\n- Natural work breakdown\n- Manageable span of control\n\nBEST FOR:\n- Enterprise projects\n- Multi-team efforts\n- Complex hierarchies\n- Phased deliveries`,\n\n mesh: `๐Ÿ”— MESH MODE - PEER-TO-PEER:\nAgents coordinate directly without central authority.\n\nCOORDINATION PATTERN:\n- All agents are peers\n- Use agent_communicate for direct messaging\n- Consensus through voting or protocols\n- Self-organizing teams\n- Emergent leadership\n\nBENEFITS:\n- Maximum flexibility\n- Fast local decisions\n- Resilient to failures\n- Creative solutions\n\nBEST FOR:\n- Research projects\n- Exploratory work\n- Innovation tasks\n- Small expert teams`,\n\n hybrid: `๐ŸŽจ HYBRID MODE - MIXED STRATEGIES:\nCombine different coordination patterns as needed.\n\nCOORDINATION PATTERN:\n- Start with one mode, adapt as needed\n- Mix hierarchical for structure with mesh for innovation\n- Use distributed for resilience with centralized for control\n- Dynamic reorganization based on task needs\n\nBENEFITS:\n- Adaptability\n- Best of all modes\n- Task-appropriate structure\n- Evolution over time\n\nBEST FOR:\n- Complex projects\n- Uncertain requirements\n- Long-term efforts\n- Diverse objectives`,\n };\n\n return modeMap[mode] || modeMap['centralized'];\n}\n\n/**\n * Get agent recommendations based on strategy\n */\nfunction getAgentRecommendations(strategy, maxAgents, objective) {\n const recommendations = {\n auto: `\n๐Ÿค– RECOMMENDED AGENT COMPOSITION (Auto-detected):\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"SwarmLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"RequirementsAnalyst\"}\n mcp__claude-flow__agent_spawn {\"type\": \"architect\", \"name\": \"SystemDesigner\"}\n mcp__claude-flow__memory_store {\"key\": \"swarm/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Analyze Requirements\", \"assignTo\": \"RequirementsAnalyst\"}\n mcp__claude-flow__task_create {\"name\": \"Design Architecture\", \"assignTo\": \"SystemDesigner\", \"dependsOn\": [\"Analyze Requirements\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize swarm coordination\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Analyze objective requirements\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Design system architecture\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Spawn additional agents as needed\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n research: `\n๐Ÿ”ฌ RECOMMENDED RESEARCH AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"ResearchLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"PrimaryInvestigator\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DataScientist\"}\n mcp__claude-flow__agent_spawn {\"type\": \"researcher\", \"name\": \"LiteratureExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"InsightsCompiler\"}\n mcp__claude-flow__memory_store {\"key\": \"research/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Literature Review\", \"assignTo\": \"LiteratureExpert\"}\n mcp__claude-flow__task_create {\"name\": \"Primary Research\", \"assignTo\": \"PrimaryInvestigator\"}\n mcp__claude-flow__task_create {\"name\": \"Data Analysis\", \"assignTo\": \"DataScientist\"}\n mcp__claude-flow__task_create {\"name\": \"Compile Insights\", \"assignTo\": \"InsightsCompiler\", \"dependsOn\": [\"Literature Review\", \"Primary Research\", \"Data Analysis\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize research swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Conduct literature review\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Execute primary research\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Analyze collected data\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Compile and synthesize insights\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n development: `\n๐Ÿ’ป RECOMMENDED DEVELOPMENT AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"TechLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"architect\", \"name\": \"SystemArchitect\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"BackendDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"FrontendDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"QAEngineer\"}\n mcp__claude-flow__memory_store {\"key\": \"dev/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"System Architecture\", \"assignTo\": \"SystemArchitect\"}\n mcp__claude-flow__task_create {\"name\": \"Backend Implementation\", \"assignTo\": \"BackendDev\", \"dependsOn\": [\"System Architecture\"]}\n mcp__claude-flow__task_create {\"name\": \"Frontend Implementation\", \"assignTo\": \"FrontendDev\", \"dependsOn\": [\"System Architecture\"]}\n mcp__claude-flow__task_create {\"name\": \"Testing Suite\", \"assignTo\": \"QAEngineer\", \"dependsOn\": [\"Backend Implementation\", \"Frontend Implementation\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize development swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Design system architecture\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Implement backend services\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Implement frontend UI\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Create comprehensive tests\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n analysis: `\n๐Ÿ“Š RECOMMENDED ANALYSIS AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"AnalysisLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DataEngineer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"StatisticalExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"VisualizationDev\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"BusinessAnalyst\"}\n mcp__claude-flow__memory_store {\"key\": \"analysis/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Data Pipeline Setup\", \"assignTo\": \"DataEngineer\"}\n mcp__claude-flow__task_create {\"name\": \"Statistical Analysis\", \"assignTo\": \"StatisticalExpert\", \"dependsOn\": [\"Data Pipeline Setup\"]}\n mcp__claude-flow__task_create {\"name\": \"Create Visualizations\", \"assignTo\": \"VisualizationDev\", \"dependsOn\": [\"Statistical Analysis\"]}\n mcp__claude-flow__task_create {\"name\": \"Business Insights\", \"assignTo\": \"BusinessAnalyst\", \"dependsOn\": [\"Statistical Analysis\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize analysis swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Setup data pipelines\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Perform statistical analysis\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Create data visualizations\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"5\", \"content\": \"Generate business insights\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n testing: `\n๐Ÿงช RECOMMENDED TESTING AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"QALead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"UnitTestEngineer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"IntegrationTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"PerformanceTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"SecurityAuditor\"}\n mcp__claude-flow__memory_store {\"key\": \"testing/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Unit Test Suite\", \"assignTo\": \"UnitTestEngineer\"}\n mcp__claude-flow__task_create {\"name\": \"Integration Tests\", \"assignTo\": \"IntegrationTester\"}\n mcp__claude-flow__task_create {\"name\": \"Performance Tests\", \"assignTo\": \"PerformanceTester\"}\n mcp__claude-flow__task_create {\"name\": \"Security Audit\", \"assignTo\": \"SecurityAuditor\"}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize testing swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Create unit tests\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Create integration tests\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Run performance tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"5\", \"content\": \"Execute security audit\", \"status\": \"pending\", \"priority\": \"high\"}\n ]}\n\\`\\`\\``,\n\n optimization: `\nโšก RECOMMENDED OPTIMIZATION AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"OptimizationLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"PerformanceProfiler\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"AlgorithmExpert\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DatabaseOptimizer\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"SystemsTuner\"}\n mcp__claude-flow__memory_store {\"key\": \"optimization/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"Performance Profiling\", \"assignTo\": \"PerformanceProfiler\"}\n mcp__claude-flow__task_create {\"name\": \"Algorithm Optimization\", \"assignTo\": \"AlgorithmExpert\", \"dependsOn\": [\"Performance Profiling\"]}\n mcp__claude-flow__task_create {\"name\": \"Database Optimization\", \"assignTo\": \"DatabaseOptimizer\", \"dependsOn\": [\"Performance Profiling\"]}\n mcp__claude-flow__task_create {\"name\": \"System Tuning\", \"assignTo\": \"SystemsTuner\", \"dependsOn\": [\"Performance Profiling\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize optimization swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Profile system performance\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Optimize algorithms\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Optimize database queries\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Tune system parameters\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n\n maintenance: `\n๐Ÿ”ง RECOMMENDED MAINTENANCE AGENTS:\nโšก SPAWN ALL AGENTS IN ONE BATCH - Copy this entire block:\n\n\\`\\`\\`\n[BatchTool - Single Message]:\n mcp__claude-flow__agent_spawn {\"type\": \"coordinator\", \"name\": \"MaintenanceLead\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"SystemAuditor\"}\n mcp__claude-flow__agent_spawn {\"type\": \"coder\", \"name\": \"PatchDeveloper\"}\n mcp__claude-flow__agent_spawn {\"type\": \"tester\", \"name\": \"RegressionTester\"}\n mcp__claude-flow__agent_spawn {\"type\": \"analyst\", \"name\": \"DocumentationUpdater\"}\n mcp__claude-flow__memory_store {\"key\": \"maintenance/objective\", \"value\": \"${objective}\"}\n mcp__claude-flow__task_create {\"name\": \"System Audit\", \"assignTo\": \"SystemAuditor\"}\n mcp__claude-flow__task_create {\"name\": \"Develop Patches\", \"assignTo\": \"PatchDeveloper\", \"dependsOn\": [\"System Audit\"]}\n mcp__claude-flow__task_create {\"name\": \"Regression Testing\", \"assignTo\": \"RegressionTester\", \"dependsOn\": [\"Develop Patches\"]}\n mcp__claude-flow__task_create {\"name\": \"Update Documentation\", \"assignTo\": \"DocumentationUpdater\", \"dependsOn\": [\"Develop Patches\"]}\n TodoWrite {\"todos\": [\n {\"id\": \"1\", \"content\": \"Initialize maintenance swarm\", \"status\": \"completed\", \"priority\": \"high\"},\n {\"id\": \"2\", \"content\": \"Audit system health\", \"status\": \"in_progress\", \"priority\": \"high\"},\n {\"id\": \"3\", \"content\": \"Develop necessary patches\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"4\", \"content\": \"Run regression tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"5\", \"content\": \"Update documentation\", \"status\": \"pending\", \"priority\": \"medium\"}\n ]}\n\\`\\`\\``,\n };\n\n return recommendations[strategy] || recommendations['auto'];\n}\n\n// Allow direct execution\nif (import.meta.main) {\n // When called directly as a script, parse all arguments\n const args = [];\n const flags = {};\n\n // Parse arguments and flags\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg.startsWith('--')) {\n const flagName = arg.substring(2);\n const nextArg = args[i + 1];\n\n if (nextArg && !nextArg.startsWith('--')) {\n flags[flagName] = nextArg;\n i++; // Skip the next argument\n } else {\n flags[flagName] = true;\n }\n } else {\n args.push(arg);\n }\n }\n\n // The objective is all non-flag arguments joined\n const objective = args.join(' ');\n\n // Execute the swarm command\n await swarmCommand([objective], flags);\n}\n"],"names":["mkdirAsync","writeTextFile","exit","spawn","existsSync","chmodSync","statSync","readFileSync","open","process","isHeadlessEnvironment","ciEnvironments","isCI","some","env","isDocker","cgroupContent","includes","hasTTY","stdin","isTTY","stdout","basicSwarmNew","args","flags","objective","join","trim","console","error","showSwarmHelp","isHeadless","log","cleanup","on","executeSwarm","strategy","mode","result","output","success","swarmId","summary","duration","agents","totalAgents","tasks","totalTasks","timestamp","Date","toISOString","fs","writeFile","JSON","stringify","message","errorOutput","swarmCommand","headless","status","service","version","npm_package_version","outputFormat","outputFile","isJsonOutput","isNonInteractive","useJsonLogs","originalLog","originalError","level","isAnalysisMode","analysis","analysisMode","executor","execSync","maxAgents","strategyGuidance","getStrategyGuidance","modeGuidance","getModeGuidance","agentRecommendations","getAgentRecommendations","enableSparc","sparc","swarmPrompt","timeout","review","testing","claude","injectMemoryProtocol","enhanceSwarmPrompt","err","repeat","claudeArgs","push","claudeEnv","CLAUDE_CODE_ENABLE_TELEMETRY","OTEL_METRICS_EXPORTER","OTEL_LOGS_EXPORTER","claudeProcess","stdio","shell","killed","kill","code","claudeAvailable","fallback","background","CLAUDE_SWARM_NO_BG","Deno","now","Math","random","toString","substr","swarmRunDir","recursive","commandArgs","url","newFlags","key","value","Object","entries","String","logFile","logHandle","scriptContent","scriptPath","startTime","close","binDir","URL","pathname","bgScriptPath","bgArgs","bgProcess","decoder","TextDecoder","decode","shellScript","shellScriptPath","shellProcess","detached","unref","path","dirname","map","arg","filter","k","v","swarmAction","distPath","module","distError","ctx","command","execError","createSwarmFiles","createError","substring","parallel","distributed","monitor","persistence","encryption","communication","fileURLToPath","__filename","__dirname","possiblePaths","swarmDemoPath","p","swarmArgs","swarmProcess","e","write","end","Promise","resolve","reject","Error","targetMatch","match","targetDir","startsWith","cwd","promises","mkdir","isRestAPI","toLowerCase","apiDir","serverCode","packageJson","name","description","main","scripts","start","dev","test","keywords","author","license","dependencies","express","devDependencies","nodemon","jest","supertest","swarmMetadata","created","readme","appCode","guidanceMap","auto","research","development","optimization","maintenance","modeMap","centralized","hierarchical","mesh","hybrid","recommendations","i","length","flagName","nextArg"],"mappings":"AAIA,SAAeA,UAAU,EAAEC,aAAa,EAAEC,IAAI,QAAa,oBAAoB;AAC/E,SAASC,KAAK,QAAkB,gBAAgB;AAChD,SAASC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,EAAEC,YAAY,QAAQ,KAAK;AACnE,SAASC,IAAI,QAAQ,cAAc;AACnC,OAAOC,aAAa,UAAU;AAM9B,SAASC;IAEP,MAAMC,iBAAiB;QACrB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD;IAED,MAAMC,O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a,SAAS,CAAC;YAC/B,MAAMqE,UAAUhN,IAAI,CAAC6M,IAAI,EAAE;YAE3B,IAAIG,WAAW,CAACA,QAAQ5C,UAAU,CAAC,OAAO;gBACxCnK,KAAK,CAAC8M,SAAS,GAAGC;gBAClBH;YACF,OAAO;gBACL5M,KAAK,CAAC8M,SAAS,GAAG;YACpB;QACF,OAAO;YACL/M,KAAKwE,IAAI,CAACsD;QACZ;IACF;IAGA,MAAM5H,YAAYF,KAAKG,IAAI,CAAC;IAG5B,MAAM+B,aAAa;QAAChC;KAAU,EAAED;AAClC"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/analysis-tools.js b/dist-cjs/src/ui/console/js/analysis-tools.js deleted file mode 100644 index 3fb3493bac..0000000000 --- a/dist-cjs/src/ui/console/js/analysis-tools.js +++ /dev/null @@ -1,941 +0,0 @@ -let AnalysisTools = class AnalysisTools { - constructor(){ - this.ws = null; - this.charts = {}; - this.currentTab = 'metrics'; - this.isConnected = false; - this.metricsCache = new Map(); - this.updateInterval = null; - this.init(); - } - init() { - this.setupWebSocket(); - this.setupEventListeners(); - this.initializeCharts(); - this.startRealTimeUpdates(); - } - setupWebSocket() { - try { - this.ws = new WebSocket('ws://localhost:3000/analysis'); - this.ws.onopen = ()=>{ - this.isConnected = true; - console.log('Analysis WebSocket connected'); - this.updateConnectionStatus('connected'); - }; - this.ws.onmessage = (event)=>{ - const data = JSON.parse(event.data); - this.handleWebSocketData(data); - }; - this.ws.onclose = ()=>{ - this.isConnected = false; - console.log('Analysis WebSocket disconnected'); - this.updateConnectionStatus('disconnected'); - setTimeout(()=>this.setupWebSocket(), 5000); - }; - this.ws.onerror = (error)=>{ - console.error('Analysis WebSocket error:', error); - this.updateConnectionStatus('error'); - }; - } catch (error) { - console.error('Failed to setup WebSocket:', error); - this.updateConnectionStatus('error'); - } - } - setupEventListeners() { - document.querySelectorAll('.analysis-tab').forEach((tab)=>{ - tab.addEventListener('click', (e)=>{ - this.switchTab(e.target.dataset.tab); - }); - }); - document.querySelectorAll('.export-btn').forEach((btn)=>{ - btn.addEventListener('click', (e)=>{ - const format = e.target.dataset.format; - const type = e.target.dataset.type; - this.exportData(type, format); - }); - }); - document.querySelectorAll('.tool-btn').forEach((btn)=>{ - btn.addEventListener('click', (e)=>{ - const tool = e.target.dataset.tool; - this.executeTool(tool); - }); - }); - document.querySelectorAll('.refresh-btn').forEach((btn)=>{ - btn.addEventListener('click', (e)=>{ - const section = e.target.dataset.section; - this.refreshSection(section); - }); - }); - } - initializeCharts() { - this.charts.performance = new Chart(document.getElementById('performance-chart'), { - type: 'line', - data: { - labels: [], - datasets: [ - { - label: 'Response Time (ms)', - data: [], - borderColor: '#3b82f6', - backgroundColor: 'rgba(59, 130, 246, 0.1)', - tension: 0.4 - }, - { - label: 'Throughput (req/s)', - data: [], - borderColor: '#10b981', - backgroundColor: 'rgba(16, 185, 129, 0.1)', - tension: 0.4 - } - ] - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'top' - } - }, - scales: { - x: { - display: true, - title: { - display: true, - text: 'Time' - } - }, - y: { - display: true, - title: { - display: true, - text: 'Value' - } - } - } - } - }); - this.charts.tokenUsage = new Chart(document.getElementById('token-usage-chart'), { - type: 'doughnut', - data: { - labels: [ - 'Input Tokens', - 'Output Tokens', - 'Cached Tokens' - ], - datasets: [ - { - data: [ - 0, - 0, - 0 - ], - backgroundColor: [ - '#3b82f6', - '#10b981', - '#f59e0b' - ], - borderWidth: 2 - } - ] - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'bottom' - } - } - } - }); - this.charts.systemHealth = new Chart(document.getElementById('system-health-chart'), { - type: 'radar', - data: { - labels: [ - 'CPU', - 'Memory', - 'Disk', - 'Network', - 'API', - 'Database' - ], - datasets: [ - { - label: 'Health Score', - data: [ - 100, - 100, - 100, - 100, - 100, - 100 - ], - borderColor: '#10b981', - backgroundColor: 'rgba(16, 185, 129, 0.2)', - pointBackgroundColor: '#10b981', - pointBorderColor: '#fff', - pointHoverBackgroundColor: '#fff', - pointHoverBorderColor: '#10b981' - } - ] - }, - options: { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - max: 100 - } - } - } - }); - this.charts.loadMonitor = new Chart(document.getElementById('load-monitor-chart'), { - type: 'bar', - data: { - labels: [ - '1m', - '5m', - '15m', - '30m', - '1h', - '24h' - ], - datasets: [ - { - label: 'Average Load', - data: [ - 0, - 0, - 0, - 0, - 0, - 0 - ], - backgroundColor: 'rgba(59, 130, 246, 0.7)', - borderColor: '#3b82f6', - borderWidth: 1 - } - ] - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'top' - } - }, - scales: { - y: { - beginAtZero: true - } - } - } - }); - } - startRealTimeUpdates() { - this.updateInterval = setInterval(()=>{ - if (this.isConnected) { - this.requestMetricsUpdate(); - } - }, 5000); - } - requestMetricsUpdate() { - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(JSON.stringify({ - type: 'request_metrics', - timestamp: Date.now() - })); - } - } - handleWebSocketData(data) { - switch(data.type){ - case 'metrics_update': - this.updateMetrics(data.payload); - break; - case 'alert': - this.handleAlert(data.payload); - break; - case 'health_status': - this.updateHealthStatus(data.payload); - break; - default: - console.log('Unknown WebSocket message type:', data.type); - } - } - updateMetrics(metrics) { - this.metricsCache.set('latest', metrics); - if (this.charts.performance && metrics.performance) { - const chart = this.charts.performance; - const now = new Date().toLocaleTimeString(); - chart.data.labels.push(now); - chart.data.datasets[0].data.push(metrics.performance.responseTime); - chart.data.datasets[1].data.push(metrics.performance.throughput); - if (chart.data.labels.length > 20) { - chart.data.labels.shift(); - chart.data.datasets[0].data.shift(); - chart.data.datasets[1].data.shift(); - } - chart.update('none'); - } - if (this.charts.tokenUsage && metrics.tokens) { - const chart = this.charts.tokenUsage; - chart.data.datasets[0].data = [ - metrics.tokens.input, - metrics.tokens.output, - metrics.tokens.cached - ]; - chart.update('none'); - } - if (this.charts.systemHealth && metrics.health) { - const chart = this.charts.systemHealth; - chart.data.datasets[0].data = [ - metrics.health.cpu, - metrics.health.memory, - metrics.health.disk, - metrics.health.network, - metrics.health.api, - metrics.health.database - ]; - chart.update('none'); - } - if (this.charts.loadMonitor && metrics.load) { - const chart = this.charts.loadMonitor; - chart.data.datasets[0].data = [ - metrics.load.oneMin, - metrics.load.fiveMin, - metrics.load.fifteenMin, - metrics.load.thirtyMin, - metrics.load.oneHour, - metrics.load.twentyFourHour - ]; - chart.update('none'); - } - this.updateMetricDisplays(metrics); - } - updateMetricDisplays(metrics) { - const perfSection = document.getElementById('performance-metrics'); - if (perfSection && metrics.performance) { - perfSection.innerHTML = ` -
-
Response Time
-
${metrics.performance.responseTime}ms
-
-
-
Throughput
-
${metrics.performance.throughput} req/s
-
-
-
Error Rate
-
${metrics.performance.errorRate}%
-
-
-
Uptime
-
${metrics.performance.uptime}
-
- `; - } - const tokenSection = document.getElementById('token-metrics'); - if (tokenSection && metrics.tokens) { - const total = metrics.tokens.input + metrics.tokens.output + metrics.tokens.cached; - tokenSection.innerHTML = ` -
-
Total Tokens
-
${total.toLocaleString()}
-
-
-
Input Tokens
-
${metrics.tokens.input.toLocaleString()}
-
-
-
Output Tokens
-
${metrics.tokens.output.toLocaleString()}
-
-
-
Cache Hit Rate
-
${(metrics.tokens.cached / total * 100).toFixed(1)}%
-
- `; - } - const healthSection = document.getElementById('health-status'); - if (healthSection && metrics.health) { - const overallHealth = Math.round((metrics.health.cpu + metrics.health.memory + metrics.health.disk + metrics.health.network + metrics.health.api + metrics.health.database) / 6); - healthSection.innerHTML = ` -
-
- ${overallHealth}% -
-
Overall Health
-
-
-
- CPU - ${metrics.health.cpu}% -
-
- Memory - ${metrics.health.memory}% -
-
- Disk - ${metrics.health.disk}% -
-
- Network - ${metrics.health.network}% -
-
- API - ${metrics.health.api}% -
-
- Database - ${metrics.health.database}% -
-
- `; - } - } - getHealthClass(score) { - if (score >= 90) return 'health-excellent'; - if (score >= 70) return 'health-good'; - if (score >= 50) return 'health-warning'; - return 'health-critical'; - } - handleAlert(alert) { - const alertsContainer = document.getElementById('alerts-container'); - if (alertsContainer) { - const alertElement = document.createElement('div'); - alertElement.className = `alert alert-${alert.severity}`; - alertElement.innerHTML = ` -
- ${alert.title} - ${new Date(alert.timestamp).toLocaleTimeString()} -
-
${alert.message}
- - `; - alertsContainer.insertBefore(alertElement, alertsContainer.firstChild); - if (alert.severity === 'info') { - setTimeout(()=>{ - if (alertElement.parentElement) { - alertElement.remove(); - } - }, 10000); - } - } - } - switchTab(tabName) { - this.currentTab = tabName; - document.querySelectorAll('.analysis-tab').forEach((tab)=>{ - tab.classList.remove('active'); - }); - document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); - document.querySelectorAll('.analysis-panel').forEach((panel)=>{ - panel.classList.remove('active'); - }); - document.getElementById(`${tabName}-panel`).classList.add('active'); - setTimeout(()=>{ - Object.values(this.charts).forEach((chart)=>{ - if (chart && chart.resize) { - chart.resize(); - } - }); - }, 100); - } - async executeTool(toolName) { - const button = document.querySelector(`[data-tool="${toolName}"]`); - if (button) { - button.classList.add('loading'); - button.disabled = true; - } - try { - switch(toolName){ - case 'performance_report': - await this.performanceReport(); - break; - case 'bottleneck_analyze': - await this.bottleneckAnalyze(); - break; - case 'token_usage': - await this.tokenUsage(); - break; - case 'benchmark_run': - await this.benchmarkRun(); - break; - case 'metrics_collect': - await this.metricsCollect(); - break; - case 'trend_analysis': - await this.trendAnalysis(); - break; - case 'cost_analysis': - await this.costAnalysis(); - break; - case 'quality_assess': - await this.qualityAssess(); - break; - case 'error_analysis': - await this.errorAnalysis(); - break; - case 'usage_stats': - await this.usageStats(); - break; - case 'health_check': - await this.healthCheck(); - break; - case 'load_monitor': - await this.loadMonitor(); - break; - case 'capacity_plan': - await this.capacityPlan(); - break; - default: - console.warn('Unknown tool:', toolName); - } - } catch (error) { - console.error(`Error executing tool ${toolName}:`, error); - this.showError(`Failed to execute ${toolName}: ${error.message}`); - } finally{ - if (button) { - button.classList.remove('loading'); - button.disabled = false; - } - } - } - async performanceReport() { - try { - const report = await this.fetchAnalysisData('/api/analysis/performance-report'); - this.displayReport('performance-report-output', report); - await this.notifyToolCompletion('performance_report'); - } catch (error) { - this.displayError('performance-report-output', 'Unable to fetch performance report. Please ensure the analysis service is running.'); - } - } - async bottleneckAnalyze() { - try { - const analysis = await this.fetchAnalysisData('/api/analysis/bottleneck-analyze'); - this.displayAnalysis('bottleneck-analysis-output', analysis); - await this.notifyToolCompletion('bottleneck_analyze'); - } catch (error) { - this.displayError('bottleneck-analysis-output', 'Unable to fetch bottleneck analysis. Please ensure the analysis service is running.'); - } - } - async tokenUsage() { - try { - const usage = await this.fetchAnalysisData('/api/analysis/token-usage'); - this.displayUsage('token-usage-output', usage); - await this.notifyToolCompletion('token_usage'); - } catch (error) { - this.displayError('token-usage-output', 'Unable to fetch token usage data. Please ensure the analysis service is running.'); - } - } - async benchmarkRun() { - try { - const benchmark = await this.fetchAnalysisData('/api/analysis/benchmark-run'); - this.displayBenchmark('benchmark-output', benchmark); - await this.notifyToolCompletion('benchmark_run'); - } catch (error) { - this.displayError('benchmark-output', 'Unable to run benchmark. Please ensure the analysis service is running.'); - } - } - async metricsCollect() { - try { - const metrics = await this.fetchAnalysisData('/api/analysis/metrics-collect'); - this.displayMetrics('metrics-output', metrics); - await this.notifyToolCompletion('metrics_collect'); - } catch (error) { - this.displayError('metrics-output', 'Unable to collect metrics. Please ensure the analysis service is running.'); - } - } - async trendAnalysis() { - try { - const trends = await this.fetchAnalysisData('/api/analysis/trend-analysis'); - this.displayTrends('trends-output', trends); - await this.notifyToolCompletion('trend_analysis'); - } catch (error) { - this.displayError('trends-output', 'Unable to fetch trend analysis. Please ensure the analysis service is running.'); - } - } - async costAnalysis() { - try { - const costs = await this.fetchAnalysisData('/api/analysis/cost-analysis'); - this.displayCosts('costs-output', costs); - await this.notifyToolCompletion('cost_analysis'); - } catch (error) { - this.displayError('costs-output', 'Unable to fetch cost analysis. Please ensure the analysis service is running.'); - } - } - async qualityAssess() { - try { - const quality = await this.fetchAnalysisData('/api/analysis/quality-assess'); - this.displayQuality('quality-output', quality); - await this.notifyToolCompletion('quality_assess'); - } catch (error) { - this.displayError('quality-output', 'Unable to assess quality. Please ensure the analysis service is running.'); - } - } - async errorAnalysis() { - try { - const errors = await this.fetchAnalysisData('/api/analysis/error-analysis'); - this.displayErrors('errors-output', errors); - await this.notifyToolCompletion('error_analysis'); - } catch (error) { - this.displayError('errors-output', 'Unable to fetch error analysis. Please ensure the analysis service is running.'); - } - } - async usageStats() { - try { - const stats = await this.fetchAnalysisData('/api/analysis/usage-stats'); - this.displayStats('stats-output', stats); - await this.notifyToolCompletion('usage_stats'); - } catch (error) { - this.displayError('stats-output', 'Unable to fetch usage statistics. Please ensure the analysis service is running.'); - } - } - async healthCheck() { - try { - const health = await this.fetchAnalysisData('/api/analysis/health-check'); - this.displayHealth('health-output', health); - await this.notifyToolCompletion('health_check'); - } catch (error) { - this.displayError('health-output', 'Unable to perform health check. Please ensure the analysis service is running.'); - } - } - async loadMonitor() { - try { - const load = await this.fetchAnalysisData('/api/analysis/load-monitor'); - this.displayLoad('load-output', load); - await this.notifyToolCompletion('load_monitor'); - } catch (error) { - this.displayError('load-output', 'Unable to monitor load. Please ensure the analysis service is running.'); - } - } - async capacityPlan() { - try { - const capacity = await this.fetchAnalysisData('/api/analysis/capacity-plan'); - this.displayCapacity('capacity-output', capacity); - await this.notifyToolCompletion('capacity_plan'); - } catch (error) { - this.displayError('capacity-output', 'Unable to fetch capacity plan. Please ensure the analysis service is running.'); - } - } - async fetchAnalysisData(endpoint) { - try { - const response = await fetch(endpoint); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - return await response.json(); - } catch (error) { - console.error('Fetch error:', error); - this.showError(`Failed to fetch data from ${endpoint}: ${error.message}`); - throw error; - } - } - getMockData(endpoint) { - const mockData = { - '/api/analysis/performance-report': { - summary: 'System performance is within acceptable ranges', - metrics: { - averageResponseTime: 245, - throughput: 1250, - errorRate: 0.02, - uptime: '99.8%' - }, - recommendations: [ - 'Consider caching frequently accessed data', - 'Optimize database queries for better performance', - 'Monitor memory usage during peak hours' - ] - }, - '/api/analysis/bottleneck-analyze': { - bottlenecks: [ - { - component: 'Database', - severity: 'medium', - impact: 'Response time +15%' - }, - { - component: 'API Gateway', - severity: 'low', - impact: 'Throughput -5%' - } - ], - recommendations: [ - 'Add database read replicas', - 'Implement connection pooling', - 'Optimize slow queries' - ] - }, - '/api/analysis/token-usage': { - totalTokens: 2450000, - inputTokens: 1200000, - outputTokens: 950000, - cachedTokens: 300000, - cost: 245.5, - efficiency: 85.2 - } - }; - return mockData[endpoint] || { - message: 'No data available' - }; - } - displayReport(containerId, report) { - const container = document.getElementById(containerId); - if (!container) return; - container.innerHTML = ` -
-

Performance Report

-

${report.summary}

-
-
-
-
- - ${report.metrics.averageResponseTime}ms -
-
- - ${report.metrics.throughput} req/s -
-
- - ${(report.metrics.errorRate * 100).toFixed(2)}% -
-
- - ${report.metrics.uptime} -
-
-
-
-

Recommendations

-
    - ${report.recommendations.map((rec)=>`
  • ${rec}
  • `).join('')} -
-
- `; - } - displayAnalysis(containerId, analysis) { - const container = document.getElementById(containerId); - if (!container) return; - container.innerHTML = ` -
-

Bottleneck Analysis

-
- ${analysis.bottlenecks.map((bottleneck)=>` -
-
${bottleneck.component}
-
${bottleneck.severity}
-
${bottleneck.impact}
-
- `).join('')} -
-
-

Recommendations

-
    - ${analysis.recommendations.map((rec)=>`
  • ${rec}
  • `).join('')} -
-
-
- `; - } - displayUsage(containerId, usage) { - const container = document.getElementById(containerId); - if (!container) return; - container.innerHTML = ` -
-

Token Usage Analysis

-
-
- - ${usage.totalTokens.toLocaleString()} -
-
- - ${usage.inputTokens.toLocaleString()} -
-
- - ${usage.outputTokens.toLocaleString()} -
-
- - ${usage.cachedTokens.toLocaleString()} -
-
- - $${usage.cost.toFixed(2)} -
-
- - ${usage.efficiency.toFixed(1)}% -
-
-
- `; - } - exportData(type, format) { - const data = this.metricsCache.get('latest') || {}; - const timestamp = new Date().toISOString().split('T')[0]; - const filename = `${type}_${timestamp}.${format}`; - if (format === 'json') { - this.downloadJSON(data, filename); - } else if (format === 'csv') { - this.downloadCSV(data, filename); - } - } - downloadJSON(data, filename) { - const blob = new Blob([ - JSON.stringify(data, null, 2) - ], { - type: 'application/json' - }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); - URL.revokeObjectURL(url); - } - downloadCSV(data, filename) { - const csv = this.jsonToCSV(data); - const blob = new Blob([ - csv - ], { - type: 'text/csv' - }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); - URL.revokeObjectURL(url); - } - jsonToCSV(json) { - const flatten = (obj, prefix = '')=>{ - const flattened = {}; - for(const key in obj){ - if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) { - Object.assign(flattened, flatten(obj[key], prefix + key + '.')); - } else { - flattened[prefix + key] = Array.isArray(obj[key]) ? JSON.stringify(obj[key]) : obj[key]; - } - } - return flattened; - }; - const flattened = flatten(json); - const headers = Object.keys(flattened); - const valueRow = headers.map((header)=>{ - const value = flattened[header]; - if (value === null || value === undefined) { - return ''; - } - let strValue = String(value); - if (strValue.includes(',') || strValue.includes('"') || strValue.includes('\n')) { - strValue = '"' + strValue.replace(/"/g, '""') + '"'; - } - return strValue; - }).join(','); - return [ - headers.join(','), - valueRow - ].join('\n'); - } - refreshSection(section) { - switch(section){ - case 'metrics': - this.requestMetricsUpdate(); - break; - case 'charts': - Object.values(this.charts).forEach((chart)=>{ - if (chart && chart.update) { - chart.update(); - } - }); - break; - case 'alerts': - document.getElementById('alerts-container').innerHTML = ''; - break; - default: - console.warn('Unknown section:', section); - } - } - updateConnectionStatus(status) { - const statusElement = document.getElementById('connection-status'); - if (statusElement) { - statusElement.className = `connection-status ${status}`; - statusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1); - } - } - showError(message) { - const errorElement = document.createElement('div'); - errorElement.className = 'error-message'; - errorElement.textContent = message; - document.body.appendChild(errorElement); - setTimeout(()=>{ - errorElement.remove(); - }, 5000); - } - displayError(containerId, message) { - const container = document.getElementById(containerId); - if (!container) return; - container.innerHTML = ` -
-
โŒ
-
-

Error

-

${message}

-
-
- - -
-
- `; - } - async notifyToolCompletion(toolName) { - try { - const response = await fetch('/api/swarm/notify', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - message: `${toolName} completed`, - timestamp: Date.now(), - agent: 'analysis-tools' - }) - }); - if (!response.ok) { - console.warn('Failed to notify swarm'); - } - } catch (error) { - console.error('Error notifying swarm:', error); - } - } - destroy() { - if (this.updateInterval) { - clearInterval(this.updateInterval); - } - if (this.ws) { - this.ws.close(); - } - Object.values(this.charts).forEach((chart)=>{ - if (chart && chart.destroy) { - chart.destroy(); - } - }); - } -}; -document.addEventListener('DOMContentLoaded', ()=>{ - window.analysisTools = new AnalysisTools(); -}); -if (typeof module !== 'undefined' && module.exports) { - module.exports = AnalysisTools; -} - -//# sourceMappingURL=analysis-tools.js.map \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/analysis-tools.js.map b/dist-cjs/src/ui/console/js/analysis-tools.js.map deleted file mode 100644 index 2ccd56c169..0000000000 --- a/dist-cjs/src/ui/console/js/analysis-tools.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../../../src/ui/console/js/analysis-tools.js"],"sourcesContent":["/**\n * Analysis & Monitoring Tools for Claude Flow Web UI\n * Agent 2 - Analysis & Monitoring Tools Developer\n *\n * Features:\n * - 13 analysis and monitoring tools\n * - Real-time dashboards and visualizations\n * - WebSocket integration for live data\n * - Export functionality for reports\n * - 4 main tabs: Metrics, Reports, Analysis, Health\n */\n\nclass AnalysisTools {\n constructor() {\n this.ws = null;\n this.charts = {};\n this.currentTab = 'metrics';\n this.isConnected = false;\n this.metricsCache = new Map();\n this.updateInterval = null;\n this.init();\n }\n\n init() {\n this.setupWebSocket();\n this.setupEventListeners();\n this.initializeCharts();\n this.startRealTimeUpdates();\n }\n\n setupWebSocket() {\n try {\n this.ws = new WebSocket('ws://localhost:3000/analysis');\n\n this.ws.onopen = () => {\n this.isConnected = true;\n console.log('Analysis WebSocket connected');\n this.updateConnectionStatus('connected');\n };\n\n this.ws.onmessage = (event) => {\n const data = JSON.parse(event.data);\n this.handleWebSocketData(data);\n };\n\n this.ws.onclose = () => {\n this.isConnected = false;\n console.log('Analysis WebSocket disconnected');\n this.updateConnectionStatus('disconnected');\n setTimeout(() => this.setupWebSocket(), 5000);\n };\n\n this.ws.onerror = (error) => {\n console.error('Analysis WebSocket error:', error);\n this.updateConnectionStatus('error');\n };\n } catch (error) {\n console.error('Failed to setup WebSocket:', error);\n this.updateConnectionStatus('error');\n }\n }\n\n setupEventListeners() {\n // Tab switching\n document.querySelectorAll('.analysis-tab').forEach((tab) => {\n tab.addEventListener('click', (e) => {\n this.switchTab(e.target.dataset.tab);\n });\n });\n\n // Export buttons\n document.querySelectorAll('.export-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const format = e.target.dataset.format;\n const type = e.target.dataset.type;\n this.exportData(type, format);\n });\n });\n\n // Tool buttons\n document.querySelectorAll('.tool-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const tool = e.target.dataset.tool;\n this.executeTool(tool);\n });\n });\n\n // Refresh buttons\n document.querySelectorAll('.refresh-btn').forEach((btn) => {\n btn.addEventListener('click', (e) => {\n const section = e.target.dataset.section;\n this.refreshSection(section);\n });\n });\n }\n\n initializeCharts() {\n // Performance metrics chart\n this.charts.performance = new Chart(document.getElementById('performance-chart'), {\n type: 'line',\n data: {\n labels: [],\n datasets: [\n {\n label: 'Response Time (ms)',\n data: [],\n borderColor: '#3b82f6',\n backgroundColor: 'rgba(59, 130, 246, 0.1)',\n tension: 0.4,\n },\n {\n label: 'Throughput (req/s)',\n data: [],\n borderColor: '#10b981',\n backgroundColor: 'rgba(16, 185, 129, 0.1)',\n tension: 0.4,\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: {\n position: 'top',\n },\n },\n scales: {\n x: {\n display: true,\n title: {\n display: true,\n text: 'Time',\n },\n },\n y: {\n display: true,\n title: {\n display: true,\n text: 'Value',\n },\n },\n },\n },\n });\n\n // Token usage chart\n this.charts.tokenUsage = new Chart(document.getElementById('token-usage-chart'), {\n type: 'doughnut',\n data: {\n labels: ['Input Tokens', 'Output Tokens', 'Cached Tokens'],\n datasets: [\n {\n data: [0, 0, 0],\n backgroundColor: ['#3b82f6', '#10b981', '#f59e0b'],\n borderWidth: 2,\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: {\n position: 'bottom',\n },\n },\n },\n });\n\n // System health chart\n this.charts.systemHealth = new Chart(document.getElementById('system-health-chart'), {\n type: 'radar',\n data: {\n labels: ['CPU', 'Memory', 'Disk', 'Network', 'API', 'Database'],\n datasets: [\n {\n label: 'Health Score',\n data: [100, 100, 100, 100, 100, 100],\n borderColor: '#10b981',\n backgroundColor: 'rgba(16, 185, 129, 0.2)',\n pointBackgroundColor: '#10b981',\n pointBorderColor: '#fff',\n pointHoverBackgroundColor: '#fff',\n pointHoverBorderColor: '#10b981',\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n scales: {\n r: {\n beginAtZero: true,\n max: 100,\n },\n },\n },\n });\n\n // Load monitoring chart\n this.charts.loadMonitor = new Chart(document.getElementById('load-monitor-chart'), {\n type: 'bar',\n data: {\n labels: ['1m', '5m', '15m', '30m', '1h', '24h'],\n datasets: [\n {\n label: 'Average Load',\n data: [0, 0, 0, 0, 0, 0],\n backgroundColor: 'rgba(59, 130, 246, 0.7)',\n borderColor: '#3b82f6',\n borderWidth: 1,\n },\n ],\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n plugins: {\n legend: {\n position: 'top',\n },\n },\n scales: {\n y: {\n beginAtZero: true,\n },\n },\n },\n });\n }\n\n startRealTimeUpdates() {\n this.updateInterval = setInterval(() => {\n if (this.isConnected) {\n this.requestMetricsUpdate();\n }\n }, 5000);\n }\n\n requestMetricsUpdate() {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(\n JSON.stringify({\n type: 'request_metrics',\n timestamp: Date.now(),\n }),\n );\n }\n }\n\n handleWebSocketData(data) {\n switch (data.type) {\n case 'metrics_update':\n this.updateMetrics(data.payload);\n break;\n case 'alert':\n this.handleAlert(data.payload);\n break;\n case 'health_status':\n this.updateHealthStatus(data.payload);\n break;\n default:\n console.log('Unknown WebSocket message type:', data.type);\n }\n }\n\n updateMetrics(metrics) {\n this.metricsCache.set('latest', metrics);\n\n // Update performance chart\n if (this.charts.performance && metrics.performance) {\n const chart = this.charts.performance;\n const now = new Date().toLocaleTimeString();\n\n chart.data.labels.push(now);\n chart.data.datasets[0].data.push(metrics.performance.responseTime);\n chart.data.datasets[1].data.push(metrics.performance.throughput);\n\n // Keep only last 20 data points\n if (chart.data.labels.length > 20) {\n chart.data.labels.shift();\n chart.data.datasets[0].data.shift();\n chart.data.datasets[1].data.shift();\n }\n\n chart.update('none');\n }\n\n // Update token usage chart\n if (this.charts.tokenUsage && metrics.tokens) {\n const chart = this.charts.tokenUsage;\n chart.data.datasets[0].data = [\n metrics.tokens.input,\n metrics.tokens.output,\n metrics.tokens.cached,\n ];\n chart.update('none');\n }\n\n // Update system health chart\n if (this.charts.systemHealth && metrics.health) {\n const chart = this.charts.systemHealth;\n chart.data.datasets[0].data = [\n metrics.health.cpu,\n metrics.health.memory,\n metrics.health.disk,\n metrics.health.network,\n metrics.health.api,\n metrics.health.database,\n ];\n chart.update('none');\n }\n\n // Update load monitor chart\n if (this.charts.loadMonitor && metrics.load) {\n const chart = this.charts.loadMonitor;\n chart.data.datasets[0].data = [\n metrics.load.oneMin,\n metrics.load.fiveMin,\n metrics.load.fifteenMin,\n metrics.load.thirtyMin,\n metrics.load.oneHour,\n metrics.load.twentyFourHour,\n ];\n chart.update('none');\n }\n\n // Update metric displays\n this.updateMetricDisplays(metrics);\n }\n\n updateMetricDisplays(metrics) {\n // Performance metrics\n const perfSection = document.getElementById('performance-metrics');\n if (perfSection && metrics.performance) {\n perfSection.innerHTML = `\n
\n
Response Time
\n
${metrics.performance.responseTime}ms
\n
\n
\n
Throughput
\n
${metrics.performance.throughput} req/s
\n
\n
\n
Error Rate
\n
${metrics.performance.errorRate}%
\n
\n
\n
Uptime
\n
${metrics.performance.uptime}
\n
\n `;\n }\n\n // Token usage metrics\n const tokenSection = document.getElementById('token-metrics');\n if (tokenSection && metrics.tokens) {\n const total = metrics.tokens.input + metrics.tokens.output + metrics.tokens.cached;\n tokenSection.innerHTML = `\n
\n
Total Tokens
\n
${total.toLocaleString()}
\n
\n
\n
Input Tokens
\n
${metrics.tokens.input.toLocaleString()}
\n
\n
\n
Output Tokens
\n
${metrics.tokens.output.toLocaleString()}
\n
\n
\n
Cache Hit Rate
\n
${((metrics.tokens.cached / total) * 100).toFixed(1)}%
\n
\n `;\n }\n\n // System health status\n const healthSection = document.getElementById('health-status');\n if (healthSection && metrics.health) {\n const overallHealth = Math.round(\n (metrics.health.cpu +\n metrics.health.memory +\n metrics.health.disk +\n metrics.health.network +\n metrics.health.api +\n metrics.health.database) /\n 6,\n );\n\n healthSection.innerHTML = `\n
\n
\n ${overallHealth}%\n
\n
Overall Health
\n
\n
\n
\n CPU\n ${metrics.health.cpu}%\n
\n
\n Memory\n ${metrics.health.memory}%\n
\n
\n Disk\n ${metrics.health.disk}%\n
\n
\n Network\n ${metrics.health.network}%\n
\n
\n API\n ${metrics.health.api}%\n
\n
\n Database\n ${metrics.health.database}%\n
\n
\n `;\n }\n }\n\n getHealthClass(score) {\n if (score >= 90) return 'health-excellent';\n if (score >= 70) return 'health-good';\n if (score >= 50) return 'health-warning';\n return 'health-critical';\n }\n\n handleAlert(alert) {\n const alertsContainer = document.getElementById('alerts-container');\n if (alertsContainer) {\n const alertElement = document.createElement('div');\n alertElement.className = `alert alert-${alert.severity}`;\n alertElement.innerHTML = `\n
\n ${alert.title}\n ${new Date(alert.timestamp).toLocaleTimeString()}\n
\n
${alert.message}
\n \n `;\n alertsContainer.insertBefore(alertElement, alertsContainer.firstChild);\n\n // Auto-dismiss after 10 seconds for info alerts\n if (alert.severity === 'info') {\n setTimeout(() => {\n if (alertElement.parentElement) {\n alertElement.remove();\n }\n }, 10000);\n }\n }\n }\n\n switchTab(tabName) {\n this.currentTab = tabName;\n\n // Update tab buttons\n document.querySelectorAll('.analysis-tab').forEach((tab) => {\n tab.classList.remove('active');\n });\n document.querySelector(`[data-tab=\"${tabName}\"]`).classList.add('active');\n\n // Update content panels\n document.querySelectorAll('.analysis-panel').forEach((panel) => {\n panel.classList.remove('active');\n });\n document.getElementById(`${tabName}-panel`).classList.add('active');\n\n // Refresh charts when switching tabs\n setTimeout(() => {\n Object.values(this.charts).forEach((chart) => {\n if (chart && chart.resize) {\n chart.resize();\n }\n });\n }, 100);\n }\n\n // Tool execution methods\n async executeTool(toolName) {\n const button = document.querySelector(`[data-tool=\"${toolName}\"]`);\n if (button) {\n button.classList.add('loading');\n button.disabled = true;\n }\n\n try {\n switch (toolName) {\n case 'performance_report':\n await this.performanceReport();\n break;\n case 'bottleneck_analyze':\n await this.bottleneckAnalyze();\n break;\n case 'token_usage':\n await this.tokenUsage();\n break;\n case 'benchmark_run':\n await this.benchmarkRun();\n break;\n case 'metrics_collect':\n await this.metricsCollect();\n break;\n case 'trend_analysis':\n await this.trendAnalysis();\n break;\n case 'cost_analysis':\n await this.costAnalysis();\n break;\n case 'quality_assess':\n await this.qualityAssess();\n break;\n case 'error_analysis':\n await this.errorAnalysis();\n break;\n case 'usage_stats':\n await this.usageStats();\n break;\n case 'health_check':\n await this.healthCheck();\n break;\n case 'load_monitor':\n await this.loadMonitor();\n break;\n case 'capacity_plan':\n await this.capacityPlan();\n break;\n default:\n console.warn('Unknown tool:', toolName);\n }\n } catch (error) {\n console.error(`Error executing tool ${toolName}:`, error);\n this.showError(`Failed to execute ${toolName}: ${error.message}`);\n } finally {\n if (button) {\n button.classList.remove('loading');\n button.disabled = false;\n }\n }\n }\n\n // Tool implementations\n async performanceReport() {\n try {\n const report = await this.fetchAnalysisData('/api/analysis/performance-report');\n this.displayReport('performance-report-output', report);\n await this.notifyToolCompletion('performance_report');\n } catch (error) {\n this.displayError(\n 'performance-report-output',\n 'Unable to fetch performance report. Please ensure the analysis service is running.',\n );\n }\n }\n\n async bottleneckAnalyze() {\n try {\n const analysis = await this.fetchAnalysisData('/api/analysis/bottleneck-analyze');\n this.displayAnalysis('bottleneck-analysis-output', analysis);\n await this.notifyToolCompletion('bottleneck_analyze');\n } catch (error) {\n this.displayError(\n 'bottleneck-analysis-output',\n 'Unable to fetch bottleneck analysis. Please ensure the analysis service is running.',\n );\n }\n }\n\n async tokenUsage() {\n try {\n const usage = await this.fetchAnalysisData('/api/analysis/token-usage');\n this.displayUsage('token-usage-output', usage);\n await this.notifyToolCompletion('token_usage');\n } catch (error) {\n this.displayError(\n 'token-usage-output',\n 'Unable to fetch token usage data. Please ensure the analysis service is running.',\n );\n }\n }\n\n async benchmarkRun() {\n try {\n const benchmark = await this.fetchAnalysisData('/api/analysis/benchmark-run');\n this.displayBenchmark('benchmark-output', benchmark);\n await this.notifyToolCompletion('benchmark_run');\n } catch (error) {\n this.displayError(\n 'benchmark-output',\n 'Unable to run benchmark. Please ensure the analysis service is running.',\n );\n }\n }\n\n async metricsCollect() {\n try {\n const metrics = await this.fetchAnalysisData('/api/analysis/metrics-collect');\n this.displayMetrics('metrics-output', metrics);\n await this.notifyToolCompletion('metrics_collect');\n } catch (error) {\n this.displayError(\n 'metrics-output',\n 'Unable to collect metrics. Please ensure the analysis service is running.',\n );\n }\n }\n\n async trendAnalysis() {\n try {\n const trends = await this.fetchAnalysisData('/api/analysis/trend-analysis');\n this.displayTrends('trends-output', trends);\n await this.notifyToolCompletion('trend_analysis');\n } catch (error) {\n this.displayError(\n 'trends-output',\n 'Unable to fetch trend analysis. Please ensure the analysis service is running.',\n );\n }\n }\n\n async costAnalysis() {\n try {\n const costs = await this.fetchAnalysisData('/api/analysis/cost-analysis');\n this.displayCosts('costs-output', costs);\n await this.notifyToolCompletion('cost_analysis');\n } catch (error) {\n this.displayError(\n 'costs-output',\n 'Unable to fetch cost analysis. Please ensure the analysis service is running.',\n );\n }\n }\n\n async qualityAssess() {\n try {\n const quality = await this.fetchAnalysisData('/api/analysis/quality-assess');\n this.displayQuality('quality-output', quality);\n await this.notifyToolCompletion('quality_assess');\n } catch (error) {\n this.displayError(\n 'quality-output',\n 'Unable to assess quality. Please ensure the analysis service is running.',\n );\n }\n }\n\n async errorAnalysis() {\n try {\n const errors = await this.fetchAnalysisData('/api/analysis/error-analysis');\n this.displayErrors('errors-output', errors);\n await this.notifyToolCompletion('error_analysis');\n } catch (error) {\n this.displayError(\n 'errors-output',\n 'Unable to fetch error analysis. Please ensure the analysis service is running.',\n );\n }\n }\n\n async usageStats() {\n try {\n const stats = await this.fetchAnalysisData('/api/analysis/usage-stats');\n this.displayStats('stats-output', stats);\n await this.notifyToolCompletion('usage_stats');\n } catch (error) {\n this.displayError(\n 'stats-output',\n 'Unable to fetch usage statistics. Please ensure the analysis service is running.',\n );\n }\n }\n\n async healthCheck() {\n try {\n const health = await this.fetchAnalysisData('/api/analysis/health-check');\n this.displayHealth('health-output', health);\n await this.notifyToolCompletion('health_check');\n } catch (error) {\n this.displayError(\n 'health-output',\n 'Unable to perform health check. Please ensure the analysis service is running.',\n );\n }\n }\n\n async loadMonitor() {\n try {\n const load = await this.fetchAnalysisData('/api/analysis/load-monitor');\n this.displayLoad('load-output', load);\n await this.notifyToolCompletion('load_monitor');\n } catch (error) {\n this.displayError(\n 'load-output',\n 'Unable to monitor load. Please ensure the analysis service is running.',\n );\n }\n }\n\n async capacityPlan() {\n try {\n const capacity = await this.fetchAnalysisData('/api/analysis/capacity-plan');\n this.displayCapacity('capacity-output', capacity);\n await this.notifyToolCompletion('capacity_plan');\n } catch (error) {\n this.displayError(\n 'capacity-output',\n 'Unable to fetch capacity plan. Please ensure the analysis service is running.',\n );\n }\n }\n\n async fetchAnalysisData(endpoint) {\n try {\n const response = await fetch(endpoint);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n return await response.json();\n } catch (error) {\n console.error('Fetch error:', error);\n // Show error message instead of falling back to mock data\n this.showError(`Failed to fetch data from ${endpoint}: ${error.message}`);\n throw error; // Re-throw to let calling functions handle the error\n }\n }\n\n getMockData(endpoint) {\n const mockData = {\n '/api/analysis/performance-report': {\n summary: 'System performance is within acceptable ranges',\n metrics: {\n averageResponseTime: 245,\n throughput: 1250,\n errorRate: 0.02,\n uptime: '99.8%',\n },\n recommendations: [\n 'Consider caching frequently accessed data',\n 'Optimize database queries for better performance',\n 'Monitor memory usage during peak hours',\n ],\n },\n '/api/analysis/bottleneck-analyze': {\n bottlenecks: [\n { component: 'Database', severity: 'medium', impact: 'Response time +15%' },\n { component: 'API Gateway', severity: 'low', impact: 'Throughput -5%' },\n ],\n recommendations: [\n 'Add database read replicas',\n 'Implement connection pooling',\n 'Optimize slow queries',\n ],\n },\n '/api/analysis/token-usage': {\n totalTokens: 2450000,\n inputTokens: 1200000,\n outputTokens: 950000,\n cachedTokens: 300000,\n cost: 245.5,\n efficiency: 85.2,\n },\n };\n return mockData[endpoint] || { message: 'No data available' };\n }\n\n displayReport(containerId, report) {\n const container = document.getElementById(containerId);\n if (!container) return;\n\n container.innerHTML = `\n
\n

Performance Report

\n

${report.summary}

\n
\n
\n
\n
\n \n ${report.metrics.averageResponseTime}ms\n
\n
\n \n ${report.metrics.throughput} req/s\n
\n
\n \n ${(report.metrics.errorRate * 100).toFixed(2)}%\n
\n
\n \n ${report.metrics.uptime}\n
\n
\n
\n
\n

Recommendations

\n
    \n ${report.recommendations.map((rec) => `
  • ${rec}
  • `).join('')}\n
\n
\n `;\n }\n\n displayAnalysis(containerId, analysis) {\n const container = document.getElementById(containerId);\n if (!container) return;\n\n container.innerHTML = `\n
\n

Bottleneck Analysis

\n
\n ${analysis.bottlenecks\n .map(\n (bottleneck) => `\n
\n
${bottleneck.component}
\n
${bottleneck.severity}
\n
${bottleneck.impact}
\n
\n `,\n )\n .join('')}\n
\n
\n

Recommendations

\n
    \n ${analysis.recommendations.map((rec) => `
  • ${rec}
  • `).join('')}\n
\n
\n
\n `;\n }\n\n displayUsage(containerId, usage) {\n const container = document.getElementById(containerId);\n if (!container) return;\n\n container.innerHTML = `\n
\n

Token Usage Analysis

\n
\n
\n \n ${usage.totalTokens.toLocaleString()}\n
\n
\n \n ${usage.inputTokens.toLocaleString()}\n
\n
\n \n ${usage.outputTokens.toLocaleString()}\n
\n
\n \n ${usage.cachedTokens.toLocaleString()}\n
\n
\n \n $${usage.cost.toFixed(2)}\n
\n
\n \n ${usage.efficiency.toFixed(1)}%\n
\n
\n
\n `;\n }\n\n exportData(type, format) {\n const data = this.metricsCache.get('latest') || {};\n const timestamp = new Date().toISOString().split('T')[0];\n const filename = `${type}_${timestamp}.${format}`;\n\n if (format === 'json') {\n this.downloadJSON(data, filename);\n } else if (format === 'csv') {\n this.downloadCSV(data, filename);\n }\n }\n\n downloadJSON(data, filename) {\n const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n a.click();\n URL.revokeObjectURL(url);\n }\n\n downloadCSV(data, filename) {\n const csv = this.jsonToCSV(data);\n const blob = new Blob([csv], { type: 'text/csv' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n a.click();\n URL.revokeObjectURL(url);\n }\n\n jsonToCSV(json) {\n const flatten = (obj, prefix = '') => {\n const flattened = {};\n for (const key in obj) {\n if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {\n Object.assign(flattened, flatten(obj[key], prefix + key + '.'));\n } else {\n // Convert arrays to JSON strings for CSV\n flattened[prefix + key] = Array.isArray(obj[key]) ? JSON.stringify(obj[key]) : obj[key];\n }\n }\n return flattened;\n };\n\n const flattened = flatten(json);\n const headers = Object.keys(flattened);\n const valueRow = headers\n .map((header) => {\n const value = flattened[header];\n if (value === null || value === undefined) {\n return '';\n }\n let strValue = String(value);\n // Escape CSV values that contain commas, quotes, or newlines\n if (strValue.includes(',') || strValue.includes('\"') || strValue.includes('\\n')) {\n strValue = '\"' + strValue.replace(/\"/g, '\"\"') + '\"';\n }\n return strValue;\n })\n .join(',');\n\n return [headers.join(','), valueRow].join('\\n');\n }\n\n refreshSection(section) {\n switch (section) {\n case 'metrics':\n this.requestMetricsUpdate();\n break;\n case 'charts':\n Object.values(this.charts).forEach((chart) => {\n if (chart && chart.update) {\n chart.update();\n }\n });\n break;\n case 'alerts':\n document.getElementById('alerts-container').innerHTML = '';\n break;\n default:\n console.warn('Unknown section:', section);\n }\n }\n\n updateConnectionStatus(status) {\n const statusElement = document.getElementById('connection-status');\n if (statusElement) {\n statusElement.className = `connection-status ${status}`;\n statusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1);\n }\n }\n\n showError(message) {\n const errorElement = document.createElement('div');\n errorElement.className = 'error-message';\n errorElement.textContent = message;\n document.body.appendChild(errorElement);\n\n setTimeout(() => {\n errorElement.remove();\n }, 5000);\n }\n\n displayError(containerId, message) {\n const container = document.getElementById(containerId);\n if (!container) return;\n\n container.innerHTML = `\n
\n
โŒ
\n
\n

Error

\n

${message}

\n
\n
\n \n \n
\n
\n `;\n }\n\n async notifyToolCompletion(toolName) {\n try {\n // Notify swarm of tool completion\n const response = await fetch('/api/swarm/notify', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n message: `${toolName} completed`,\n timestamp: Date.now(),\n agent: 'analysis-tools',\n }),\n });\n\n if (!response.ok) {\n console.warn('Failed to notify swarm');\n }\n } catch (error) {\n console.error('Error notifying swarm:', error);\n }\n }\n\n destroy() {\n if (this.updateInterval) {\n clearInterval(this.updateInterval);\n }\n\n if (this.ws) {\n this.ws.close();\n }\n\n Object.values(this.charts).forEach((chart) => {\n if (chart && chart.destroy) {\n chart.destroy();\n }\n });\n }\n}\n\n// Initialize when DOM is ready\ndocument.addEventListener('DOMContentLoaded', () => {\n window.analysisTools = new AnalysisTools();\n});\n\n// Export for module use\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = AnalysisTools;\n}\n"],"names":["AnalysisTools","ws","charts","currentTab","isConnected","metricsCache","Map","updateInterval","init","setupWebSocket","setupEventListeners","initializeCharts","startRealTimeUpdates","WebSocket","onopen","console","log","updateConnectionStatus","onmessage","event","data","JSON","parse","handleWebSocketData","onclose","setTimeout","onerror","error","document","querySelectorAll","forEach","tab","addEventListener","e","switchTab","target","dataset","btn","format","type","exportData","tool","executeTool","section","refreshSection","performance","Chart","getElementById","labels","datasets","label","borderColor","backgroundColor","tension","options","responsive","maintainAspectRatio","plugins","legend","position","scales","x","display","title","text","y","tokenUsage","borderWidth","systemHealth","pointBackgroundColor","pointBorderColor","pointHoverBackgroundColor","pointHoverBorderColor","r","beginAtZero","max","loadMonitor","setInterval","requestMetricsUpdate","readyState","OPEN","send","stringify","timestamp","Date","now","updateMetrics","payload","handleAlert","updateHealthStatus","metrics","set","chart","toLocaleTimeString","push","responseTime","throughput","length","shift","update","tokens","input","output","cached","health","cpu","memory","disk","network","api","database","load","oneMin","fiveMin","fifteenMin","thirtyMin","oneHour","twentyFourHour","updateMetricDisplays","perfSection","innerHTML","errorRate","uptime","tokenSection","total","toLocaleString","toFixed","healthSection","overallHealth","Math","round","getHealthClass","score","alert","alertsContainer","alertElement","createElement","className","severity","message","insertBefore","firstChild","parentElement","remove","tabName","classList","querySelector","add","panel","Object","values","resize","toolName","button","disabled","performanceReport","bottleneckAnalyze","benchmarkRun","metricsCollect","trendAnalysis","costAnalysis","qualityAssess","errorAnalysis","usageStats","healthCheck","capacityPlan","warn","showError","report","fetchAnalysisData","displayReport","notifyToolCompletion","displayError","analysis","displayAnalysis","usage","displayUsage","benchmark","displayBenchmark","displayMetrics","trends","displayTrends","costs","displayCosts","quality","displayQuality","errors","displayErrors","stats","displayStats","displayHealth","displayLoad","capacity","displayCapacity","endpoint","response","fetch","ok","Error","status","json","getMockData","mockData","summary","averageResponseTime","recommendations","bottlenecks","component","impact","totalTokens","inputTokens","outputTokens","cachedTokens","cost","efficiency","containerId","container","map","rec","join","bottleneck","get","toISOString","split","filename","downloadJSON","downloadCSV","blob","Blob","url","URL","createObjectURL","a","href","download","click","revokeObjectURL","csv","jsonToCSV","flatten","obj","prefix","flattened","key","Array","isArray","assign","headers","keys","valueRow","header","value","undefined","strValue","String","includes","replace","statusElement","textContent","charAt","toUpperCase","slice","errorElement","body","appendChild","method","agent","destroy","clearInterval","close","window","analysisTools","module","exports"],"mappings":"AAYA,IAAA,AAAMA,gBAAN,MAAMA;IACJ,aAAc;QACZ,IAAI,CAACC,EAAE,GAAG;QACV,IAAI,CAACC,MAAM,GAAG,CAAC;QACf,IAAI,CAACC,UAAU,GAAG;QAClB,IAAI,CAACC,WAAW,GAAG;QACnB,IAAI,CAACC,YAAY,GAAG,IAAIC;QACxB,IAAI,CAACC,cAAc,GAAG;QACtB,IAAI,CAACC,IAAI;IACX;IAEAA,OAAO;QACL,IAAI,CAACC,cAAc;QACnB,IAAI,CAACC,mBAAmB;QACxB,IAAI,CAACC,gBAAgB;QACrB,IAAI,CAACC,oBAAoB;IAC3B;IAEAH,iBAAiB;QACf,IAAI;YACF,IAAI,CAACR,EAAE,GAAG,IAAIY,UAAU;YAExB,IAAI,CAACZ,EAAE,CAACa,MAAM,GAAG;gBACf,IAAI,CAACV,WAAW,GAAG;gBACnBW,QAAQC,GAAG,CAAC;gBACZ,IAAI,CAACC,sBAAsB,CAAC;YAC9B;YAEA,IAAI,CAAChB,EAAE,CAACiB,SAAS,GAAG,CAACC;gBACnB,MAAMC,OAAOC,KAAKC,KAAK,CAACH,MAAMC,IAAI;gBA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C,OAAO,EAAE;IACnDD,OAAOC,OAAO,GAAGjR;AACnB"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/command-handler.js b/dist-cjs/src/ui/console/js/command-handler.js deleted file mode 100644 index 5e5bb1cf80..0000000000 --- a/dist-cjs/src/ui/console/js/command-handler.js +++ /dev/null @@ -1,667 +0,0 @@ -export class CommandHandler { - constructor(terminal, wsClient){ - this.terminal = terminal; - this.wsClient = wsClient; - this.isProcessing = false; - this.builtinCommands = { - help: this.showHelp.bind(this), - clear: this.clearConsole.bind(this), - status: this.showStatus.bind(this), - connect: this.connectToServer.bind(this), - disconnect: this.disconnectFromServer.bind(this), - tools: this.listTools.bind(this), - health: this.checkHealth.bind(this), - history: this.showHistory.bind(this), - export: this.exportSession.bind(this), - theme: this.changeTheme.bind(this), - version: this.showVersion.bind(this) - }; - this.claudeFlowCommands = { - 'claude-flow': this.executeClaudeFlow.bind(this), - swarm: this.executeSwarm.bind(this), - init: this.initializeProject.bind(this), - config: this.manageConfig.bind(this), - memory: this.manageMemory.bind(this), - agents: this.manageAgents.bind(this), - benchmark: this.runBenchmark.bind(this), - sparc: this.executeSparc.bind(this) - }; - this.sparcModeCommands = { - coder: this.executeSparcMode.bind(this, 'coder'), - architect: this.executeSparcMode.bind(this, 'architect'), - analyst: this.executeSparcMode.bind(this, 'analyst'), - researcher: this.executeSparcMode.bind(this, 'researcher'), - reviewer: this.executeSparcMode.bind(this, 'reviewer'), - tester: this.executeSparcMode.bind(this, 'tester'), - debugger: this.executeSparcMode.bind(this, 'debugger'), - documenter: this.executeSparcMode.bind(this, 'documenter'), - optimizer: this.executeSparcMode.bind(this, 'optimizer'), - designer: this.executeSparcMode.bind(this, 'designer') - }; - this.allCommands = { - ...this.builtinCommands, - ...this.claudeFlowCommands, - ...this.sparcModeCommands - }; - } - async processCommand(command) { - if (this.isProcessing) { - this.terminal.writeWarning('Another command is still processing. Please wait...'); - return; - } - this.isProcessing = true; - this.terminal.setLocked(true); - try { - const { cmd, args } = this.parseCommand(command); - if (this.allCommands[cmd]) { - await this.allCommands[cmd](args); - } else { - await this.executeRemoteCommand(cmd, args); - } - } catch (error) { - this.terminal.writeError(error.message); - console.error('Command execution error:', error); - } finally{ - this.isProcessing = false; - this.terminal.setLocked(false); - } - } - parseCommand(commandString) { - const parts = commandString.trim().split(/\s+/); - const cmd = parts[0].toLowerCase(); - const args = parts.slice(1); - return { - cmd, - args - }; - } - async showHelp(args) { - if (args.length > 0) { - const command = args[0].toLowerCase(); - if (this.allCommands[command]) { - this.showCommandHelp(command); - } else { - this.terminal.writeError(`Unknown command: ${command}`); - } - return; - } - this.terminal.writeInfo('Claude Flow Console Commands:'); - this.terminal.writeLine(''); - this.terminal.writeInfo('Built-in Commands:'); - Object.keys(this.builtinCommands).forEach((cmd)=>{ - this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`); - }); - this.terminal.writeLine(''); - this.terminal.writeInfo('Claude Flow Commands:'); - Object.keys(this.claudeFlowCommands).forEach((cmd)=>{ - this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`); - }); - this.terminal.writeLine(''); - this.terminal.writeInfo('Tool Commands (from tools list):'); - this.terminal.writeLine(' system/health - Get system health status'); - this.terminal.writeLine(' memory/manage - Manage memory (list, store , retrieve )'); - this.terminal.writeLine(' agents/manage - Manage agents (list, create , status )'); - this.terminal.writeLine(' swarm/orchestrate - Swarm operations (status, create, start, stop)'); - this.terminal.writeLine(' sparc/execute - Execute SPARC modes (coder, architect, etc.)'); - this.terminal.writeLine(' benchmark/run - Run benchmarks (default, memory, cpu, network)'); - this.terminal.writeLine(' claude-flow/execute - Execute Claude Flow commands'); - this.terminal.writeLine(''); - this.terminal.writeInfo('Use "help " for detailed information about a specific command.'); - this.terminal.writeInfo('Use Ctrl+L to clear console, Ctrl+C to interrupt, Tab for autocomplete.'); - } - getCommandDescription(command) { - const descriptions = { - help: 'Show help information', - clear: 'Clear console output', - status: 'Show connection and system status', - connect: 'Connect to Claude Code server', - disconnect: 'Disconnect from server', - tools: 'List available tools', - health: 'Check server health', - history: 'Show command history', - export: 'Export session data', - theme: 'Change console theme', - version: 'Show version information', - 'claude-flow': 'Execute Claude Flow commands', - swarm: 'Manage and execute swarms', - init: 'Initialize new project', - config: 'Manage configuration', - memory: 'Manage memory and data', - agents: 'Manage agents', - benchmark: 'Run benchmarks', - sparc: 'Execute SPARC mode commands' - }; - return descriptions[command] || "No description available"; - } - showCommandHelp(command) { - const helpText = { - help: ` -Usage: help [command] -Show help information for all commands or a specific command. - -Examples: - help - Show all commands - help claude-flow - Show help for claude-flow command`, - clear: ` -Usage: clear -Clear the console output. You can also use Ctrl+L.`, - connect: ` -Usage: connect [url] [token] -Connect to Claude Code server. - -Arguments: - url - WebSocket URL (default: ws://localhost:3000/ws) - token - Authentication token (optional) - -Examples: - connect - connect ws://localhost:3000/ws - connect ws://localhost:3000/ws my-auth-token`, - 'claude-flow': ` -Usage: claude-flow [options] -Execute Claude Flow commands. - -Subcommands: - start [mode] - Start Claude Flow in specified mode - stop - Stop Claude Flow - status - Show Claude Flow status - modes - List available SPARC modes - -Examples: - claude-flow start coder - claude-flow status - claude-flow modes`, - swarm: ` -Usage: swarm [options] -Manage and execute swarms. - -Actions: - create - Create new swarm - start - Start existing swarm - stop - Stop running swarm - list - List all swarms - status - Show swarm status - -Examples: - swarm create my-swarm - swarm start my-swarm - swarm list` - }; - if (helpText[command]) { - this.terminal.writeInfo(helpText[command].trim()); - } else { - this.terminal.writeInfo(`No detailed help available for: ${command}`); - } - } - async clearConsole() { - this.terminal.clear(); - this.terminal.writeSuccess('Console cleared'); - } - async showStatus() { - const wsStatus = this.wsClient.getStatus(); - const terminalStats = this.terminal.getStats(); - this.terminal.writeInfo('System Status:'); - this.terminal.writeLine(''); - this.terminal.writeInfo('Connection:'); - this.terminal.writeLine(` Status: ${wsStatus.connected ? 'Connected' : 'Disconnected'}`); - this.terminal.writeLine(` URL: ${wsStatus.url || 'Not set'}`); - this.terminal.writeLine(` Reconnect attempts: ${wsStatus.reconnectAttempts}`); - this.terminal.writeLine(` Queued messages: ${wsStatus.queuedMessages}`); - this.terminal.writeLine(` Pending requests: ${wsStatus.pendingRequests}`); - this.terminal.writeLine(''); - this.terminal.writeInfo('Terminal:'); - this.terminal.writeLine(` Total lines: ${terminalStats.totalLines}`); - this.terminal.writeLine(` History size: ${terminalStats.historySize}`); - this.terminal.writeLine(` Input locked: ${terminalStats.isLocked}`); - this.terminal.writeLine(` Current prompt: ${terminalStats.currentPrompt}`); - if (wsStatus.connected) { - try { - const healthStatus = await this.wsClient.getHealthStatus(); - this.terminal.writeLine(''); - this.terminal.writeInfo('Server Health:'); - this.terminal.writeLine(` Status: ${healthStatus.healthy ? 'Healthy' : 'Unhealthy'}`); - if (healthStatus.metrics) { - Object.entries(healthStatus.metrics).forEach(([key, value])=>{ - this.terminal.writeLine(` ${key}: ${value}`); - }); - } - } catch (error) { - this.terminal.writeWarning('Failed to get server health status'); - } - } - } - async connectToServer(args) { - const url = args[0] || 'ws://localhost:3000/ws'; - const token = args[1] || ''; - this.terminal.writeInfo(`Connecting to ${url}...`); - try { - await this.wsClient.connect(url, token); - await this.wsClient.initializeSession(); - this.terminal.writeSuccess('Connected successfully'); - this.terminal.setPrompt('claude-flow>'); - } catch (error) { - this.terminal.writeError(`Connection failed: ${error.message}`); - } - } - async disconnectFromServer() { - this.wsClient.disconnect(); - this.terminal.writeSuccess('Disconnected from server'); - this.terminal.setPrompt('offline>'); - } - async listTools() { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const tools = await this.wsClient.getAvailableTools(); - this.terminal.writeInfo('Available Tools:'); - this.terminal.writeLine(''); - if (tools && tools.length > 0) { - tools.forEach((tool)=>{ - this.terminal.writeLine(` ${tool.name.padEnd(20)} - ${tool.description || "No description"}`); - }); - } else { - this.terminal.writeWarning('No tools available'); - } - } catch (error) { - this.terminal.writeError(`Failed to list tools: ${error.message}`); - } - } - async checkHealth() { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const health = await this.wsClient.getHealthStatus(); - if (health.healthy) { - this.terminal.writeSuccess('Server is healthy'); - } else { - this.terminal.writeError(`Server is unhealthy: ${health.error || 'Unknown error'}`); - } - if (health.metrics) { - this.terminal.writeLine(''); - this.terminal.writeInfo('Metrics:'); - Object.entries(health.metrics).forEach(([key, value])=>{ - this.terminal.writeLine(` ${key}: ${value}`); - }); - } - } catch (error) { - this.terminal.writeError(`Health check failed: ${error.message}`); - } - } - async showHistory() { - const history = this.terminal.history; - if (history.length === 0) { - this.terminal.writeInfo('No command history'); - return; - } - this.terminal.writeInfo('Command History:'); - history.forEach((cmd, index)=>{ - this.terminal.writeLine(` ${(index + 1).toString().padStart(3)}: ${cmd}`); - }); - } - async exportSession(args) { - const format = args[0] || 'json'; - const sessionData = { - timestamp: new Date().toISOString(), - terminal: this.terminal.exportHistory(), - history: this.terminal.history, - status: this.wsClient.getStatus() - }; - if (format === 'json') { - const blob = new Blob([ - JSON.stringify(sessionData, null, 2) - ], { - type: 'application/json' - }); - this.downloadFile(blob, `console-session-${Date.now()}.json`); - this.terminal.writeSuccess('Session exported as JSON'); - } else { - this.terminal.writeError(`Unsupported export format: ${format}`); - } - } - async changeTheme(args) { - const theme = args[0]; - const validThemes = [ - 'dark', - 'light', - 'classic', - 'matrix' - ]; - if (!theme) { - this.terminal.writeInfo(`Available themes: ${validThemes.join(', ')}`); - return; - } - if (!validThemes.includes(theme)) { - this.terminal.writeError(`Invalid theme: ${theme}`); - return; - } - document.documentElement.setAttribute('data-theme', theme); - localStorage.setItem('console_theme', theme); - this.terminal.writeSuccess(`Theme changed to: ${theme}`); - } - async showVersion() { - this.terminal.writeInfo('๐ŸŒŠ Claude Flow v2.0.0'); - this.terminal.writeLine('Advanced swarm orchestration platform'); - this.terminal.writeLine('Built with modern web technologies'); - } - async executeClaudeFlow(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - if (args.length === 0) { - this.terminal.writeError('Usage: claude-flow [options]'); - return; - } - const subcommand = args[0]; - const subArgs = args.slice(1); - try { - const result = await this.wsClient.executeCommand('claude-flow', { - subcommand, - args: subArgs - }); - this.terminal.writeSuccess(`Claude Flow ${subcommand} executed successfully`); - if (result && result.output) { - this.terminal.writeLine(result.output); - } - } catch (error) { - this.terminal.writeError(`Claude Flow command failed: ${error.message}`); - } - } - async executeSwarm(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const action = args[0] || 'status'; - this.terminal.writeInfo(`Executing swarm ${action}...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'swarm/status', - arguments: { - action, - args: args.slice(1) - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Swarm command executed successfully'); - } - } catch (error) { - this.terminal.writeError(`Swarm command failed: ${error.message}`); - } - } - async initializeProject(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - this.terminal.writeWarning('Project initialization not yet implemented in web console'); - } - async manageConfig(args) { - this.terminal.writeInfo('Use the Settings panel (โš™๏ธ button) to manage configuration'); - } - async manageMemory(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const operation = args[0] || 'list'; - const key = args[1]; - const value = args.slice(2).join(' '); - this.terminal.writeInfo(`Executing memory ${operation}...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'memory/manage', - arguments: { - operation, - key, - value - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Memory operation completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Memory command failed: ${error.message}`); - } - } - async manageAgents(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const action = args[0] || 'list'; - const agentType = args[1]; - const agentId = args[1]; - this.terminal.writeInfo(`Executing agents ${action}...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'agents/manage', - arguments: { - action, - agentType, - agentId - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Agent operation completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Agent command failed: ${error.message}`); - } - } - async runBenchmark(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const suite = args[0] || 'default'; - const iterations = parseInt(args[1]) || 10; - this.terminal.writeInfo(`Running benchmark suite: ${suite}...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'benchmark/run', - arguments: { - suite, - iterations - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Benchmark completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Benchmark failed: ${error.message}`); - } - } - async executeSparc(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - if (args.length === 0) { - this.terminal.writeInfo('Available SPARC modes:'); - const modes = [ - 'coder', - 'architect', - 'analyst', - 'researcher', - 'reviewer', - 'tester', - 'debugger', - 'documenter', - 'optimizer', - 'designer' - ]; - modes.forEach((mode)=>{ - this.terminal.writeLine(` ${mode}`); - }); - return; - } - try { - const mode = args[0]; - const task = args.slice(1).join(' ') || 'General task execution'; - const options = {}; - this.terminal.writeInfo(`Executing SPARC mode: ${mode}...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'sparc/execute', - arguments: { - mode, - task, - options - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`); - } - } catch (error) { - this.terminal.writeError(`SPARC execution failed: ${error.message}`); - } - } - async executeSparcMode(mode, args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - try { - const task = args.join(' ') || `Execute ${mode} mode tasks`; - const options = {}; - this.terminal.writeInfo(`Executing SPARC ${mode} mode...`); - const result = await this.wsClient.sendRequest('tools/call', { - name: 'sparc/execute', - arguments: { - mode, - task, - options - } - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`); - } - } catch (error) { - this.terminal.writeError(`SPARC ${mode} execution failed: ${error.message}`); - } - } - async executeRemoteCommand(command, args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server. Use "connect" command first.'); - return; - } - try { - if (command.includes('/')) { - return await this.executeToolDirect(command, args); - } - this.terminal.writeInfo(`Executing remote command: ${command}`); - const result = await this.wsClient.executeCommand(command, { - args - }); - if (result && result.output) { - this.terminal.writeLine(result.output); - } else { - this.terminal.writeSuccess('Command executed successfully'); - } - } catch (error) { - this.terminal.writeError(`Remote command failed: ${error.message}`); - } - } - async executeToolDirect(toolName, args) { - try { - this.terminal.writeInfo(`Executing tool: ${toolName}...`); - let toolArgs = {}; - switch(toolName){ - case 'system/health': - toolArgs = { - detailed: args.includes('--detailed') - }; - break; - case 'memory/manage': - toolArgs = { - operation: args[0] || 'list', - key: args[1], - value: args.slice(2).join(' ') - }; - break; - case 'agents/manage': - toolArgs = { - action: args[0] || 'list', - agentType: args[1], - agentId: args[1] - }; - break; - case 'swarm/orchestrate': - toolArgs = { - action: args[0] || 'status', - args: args.slice(1) - }; - break; - case 'sparc/execute': - toolArgs = { - mode: args[0] || 'coder', - task: args.slice(1).join(' ') || 'General task execution', - options: {} - }; - break; - case 'benchmark/run': - toolArgs = { - suite: args[0] || 'default', - iterations: parseInt(args[1]) || 10 - }; - break; - case 'claude-flow/execute': - toolArgs = { - command: args[0] || 'status', - args: args.slice(1) - }; - break; - default: - toolArgs = { - args - }; - } - const result = await this.wsClient.sendRequest('tools/call', { - name: toolName, - arguments: toolArgs - }); - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`Tool ${toolName} executed successfully`); - } - } catch (error) { - this.terminal.writeError(`Tool execution failed: ${error.message}`); - } - } - downloadFile(blob, filename) { - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - } - getCommandSuggestions(input) { - const allCommands = Object.keys(this.allCommands); - return allCommands.filter((cmd)=>cmd.startsWith(input.toLowerCase())); - } - hasCommand(command) { - return this.allCommands.hasOwnProperty(command.toLowerCase()); - } -} - -//# sourceMappingURL=command-handler.js.map \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/command-handler.js.map b/dist-cjs/src/ui/console/js/command-handler.js.map deleted file mode 100644 index da4aea7d92..0000000000 --- a/dist-cjs/src/ui/console/js/command-handler.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../../../src/ui/console/js/command-handler.js"],"sourcesContent":["/**\n * Command Handler for Claude Code Console\n * Processes and executes console commands\n */\n\nexport class CommandHandler {\n constructor(terminal, wsClient) {\n this.terminal = terminal;\n this.wsClient = wsClient;\n this.isProcessing = false;\n\n // Built-in commands\n this.builtinCommands = {\n help: this.showHelp.bind(this),\n clear: this.clearConsole.bind(this),\n status: this.showStatus.bind(this),\n connect: this.connectToServer.bind(this),\n disconnect: this.disconnectFromServer.bind(this),\n tools: this.listTools.bind(this),\n health: this.checkHealth.bind(this),\n history: this.showHistory.bind(this),\n export: this.exportSession.bind(this),\n theme: this.changeTheme.bind(this),\n version: this.showVersion.bind(this),\n };\n\n // Claude Flow commands\n this.claudeFlowCommands = {\n 'claude-flow': this.executeClaudeFlow.bind(this),\n swarm: this.executeSwarm.bind(this),\n init: this.initializeProject.bind(this),\n config: this.manageConfig.bind(this),\n memory: this.manageMemory.bind(this),\n agents: this.manageAgents.bind(this),\n benchmark: this.runBenchmark.bind(this),\n sparc: this.executeSparc.bind(this),\n };\n\n // Direct SPARC mode commands\n this.sparcModeCommands = {\n coder: this.executeSparcMode.bind(this, 'coder'),\n architect: this.executeSparcMode.bind(this, 'architect'),\n analyst: this.executeSparcMode.bind(this, 'analyst'),\n researcher: this.executeSparcMode.bind(this, 'researcher'),\n reviewer: this.executeSparcMode.bind(this, 'reviewer'),\n tester: this.executeSparcMode.bind(this, 'tester'),\n debugger: this.executeSparcMode.bind(this, 'debugger'),\n documenter: this.executeSparcMode.bind(this, 'documenter'),\n optimizer: this.executeSparcMode.bind(this, 'optimizer'),\n designer: this.executeSparcMode.bind(this, 'designer'),\n };\n\n this.allCommands = {\n ...this.builtinCommands,\n ...this.claudeFlowCommands,\n ...this.sparcModeCommands,\n };\n }\n\n /**\n * Process a command\n */\n async processCommand(command) {\n if (this.isProcessing) {\n this.terminal.writeWarning('Another command is still processing. Please wait...');\n return;\n }\n\n this.isProcessing = true;\n this.terminal.setLocked(true);\n\n try {\n const { cmd, args } = this.parseCommand(command);\n\n if (this.allCommands[cmd]) {\n await this.allCommands[cmd](args);\n } else {\n await this.executeRemoteCommand(cmd, args);\n }\n } catch (error) {\n this.terminal.writeError(error.message);\n console.error('Command execution error:', error);\n } finally {\n this.isProcessing = false;\n this.terminal.setLocked(false);\n }\n }\n\n /**\n * Parse command string into command and arguments\n */\n parseCommand(commandString) {\n const parts = commandString.trim().split(/\\s+/);\n const cmd = parts[0].toLowerCase();\n const args = parts.slice(1);\n\n return { cmd, args };\n }\n\n /**\n * Show help information\n */\n async showHelp(args) {\n if (args.length > 0) {\n const command = args[0].toLowerCase();\n if (this.allCommands[command]) {\n this.showCommandHelp(command);\n } else {\n this.terminal.writeError(`Unknown command: ${command}`);\n }\n return;\n }\n\n this.terminal.writeInfo('Claude Flow Console Commands:');\n this.terminal.writeLine('');\n\n this.terminal.writeInfo('Built-in Commands:');\n Object.keys(this.builtinCommands).forEach((cmd) => {\n this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);\n });\n\n this.terminal.writeLine('');\n this.terminal.writeInfo('Claude Flow Commands:');\n Object.keys(this.claudeFlowCommands).forEach((cmd) => {\n this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`);\n });\n\n this.terminal.writeLine('');\n this.terminal.writeInfo('Tool Commands (from tools list):');\n this.terminal.writeLine(' system/health - Get system health status');\n this.terminal.writeLine(\n ' memory/manage - Manage memory (list, store , retrieve )',\n );\n this.terminal.writeLine(\n ' agents/manage - Manage agents (list, create , status )',\n );\n this.terminal.writeLine(\n ' swarm/orchestrate - Swarm operations (status, create, start, stop)',\n );\n this.terminal.writeLine(\n ' sparc/execute - Execute SPARC modes (coder, architect, etc.)',\n );\n this.terminal.writeLine(\n ' benchmark/run - Run benchmarks (default, memory, cpu, network)',\n );\n this.terminal.writeLine(' claude-flow/execute - Execute Claude Flow commands');\n\n this.terminal.writeLine('');\n this.terminal.writeInfo(\n 'Use \"help \" for detailed information about a specific command.',\n );\n this.terminal.writeInfo(\n 'Use Ctrl+L to clear console, Ctrl+C to interrupt, Tab for autocomplete.',\n );\n }\n\n /**\n * Get command description\n */\n getCommandDescription(command) {\n const descriptions = {\n help: 'Show help information',\n clear: 'Clear console output',\n status: 'Show connection and system status',\n connect: 'Connect to Claude Code server',\n disconnect: 'Disconnect from server',\n tools: 'List available tools',\n health: 'Check server health',\n history: 'Show command history',\n export: 'Export session data',\n theme: 'Change console theme',\n version: 'Show version information',\n 'claude-flow': 'Execute Claude Flow commands',\n swarm: 'Manage and execute swarms',\n init: 'Initialize new project',\n config: 'Manage configuration',\n memory: 'Manage memory and data',\n agents: 'Manage agents',\n benchmark: 'Run benchmarks',\n sparc: 'Execute SPARC mode commands',\n };\n\n return descriptions[command] || 'No description available';\n }\n\n /**\n * Show detailed command help\n */\n showCommandHelp(command) {\n const helpText = {\n help: `\nUsage: help [command]\nShow help information for all commands or a specific command.\n\nExamples:\n help - Show all commands\n help claude-flow - Show help for claude-flow command`,\n\n clear: `\nUsage: clear\nClear the console output. You can also use Ctrl+L.`,\n\n connect: `\nUsage: connect [url] [token]\nConnect to Claude Code server.\n\nArguments:\n url - WebSocket URL (default: ws://localhost:3000/ws)\n token - Authentication token (optional)\n\nExamples:\n connect\n connect ws://localhost:3000/ws\n connect ws://localhost:3000/ws my-auth-token`,\n\n 'claude-flow': `\nUsage: claude-flow [options]\nExecute Claude Flow commands.\n\nSubcommands:\n start [mode] - Start Claude Flow in specified mode\n stop - Stop Claude Flow\n status - Show Claude Flow status\n modes - List available SPARC modes\n \nExamples:\n claude-flow start coder\n claude-flow status\n claude-flow modes`,\n\n swarm: `\nUsage: swarm [options]\nManage and execute swarms.\n\nActions:\n create - Create new swarm\n start - Start existing swarm\n stop - Stop running swarm\n list - List all swarms\n status - Show swarm status\n \nExamples:\n swarm create my-swarm\n swarm start my-swarm\n swarm list`,\n };\n\n if (helpText[command]) {\n this.terminal.writeInfo(helpText[command].trim());\n } else {\n this.terminal.writeInfo(`No detailed help available for: ${command}`);\n }\n }\n\n /**\n * Clear console\n */\n async clearConsole() {\n this.terminal.clear();\n this.terminal.writeSuccess('Console cleared');\n }\n\n /**\n * Show status\n */\n async showStatus() {\n const wsStatus = this.wsClient.getStatus();\n const terminalStats = this.terminal.getStats();\n\n this.terminal.writeInfo('System Status:');\n this.terminal.writeLine('');\n\n this.terminal.writeInfo('Connection:');\n this.terminal.writeLine(` Status: ${wsStatus.connected ? 'Connected' : 'Disconnected'}`);\n this.terminal.writeLine(` URL: ${wsStatus.url || 'Not set'}`);\n this.terminal.writeLine(` Reconnect attempts: ${wsStatus.reconnectAttempts}`);\n this.terminal.writeLine(` Queued messages: ${wsStatus.queuedMessages}`);\n this.terminal.writeLine(` Pending requests: ${wsStatus.pendingRequests}`);\n\n this.terminal.writeLine('');\n this.terminal.writeInfo('Terminal:');\n this.terminal.writeLine(` Total lines: ${terminalStats.totalLines}`);\n this.terminal.writeLine(` History size: ${terminalStats.historySize}`);\n this.terminal.writeLine(` Input locked: ${terminalStats.isLocked}`);\n this.terminal.writeLine(` Current prompt: ${terminalStats.currentPrompt}`);\n\n if (wsStatus.connected) {\n try {\n const healthStatus = await this.wsClient.getHealthStatus();\n this.terminal.writeLine('');\n this.terminal.writeInfo('Server Health:');\n this.terminal.writeLine(` Status: ${healthStatus.healthy ? 'Healthy' : 'Unhealthy'}`);\n\n if (healthStatus.metrics) {\n Object.entries(healthStatus.metrics).forEach(([key, value]) => {\n this.terminal.writeLine(` ${key}: ${value}`);\n });\n }\n } catch (error) {\n this.terminal.writeWarning('Failed to get server health status');\n }\n }\n }\n\n /**\n * Connect to server\n */\n async connectToServer(args) {\n const url = args[0] || 'ws://localhost:3000/ws';\n const token = args[1] || '';\n\n this.terminal.writeInfo(`Connecting to ${url}...`);\n\n try {\n await this.wsClient.connect(url, token);\n\n // Initialize session\n await this.wsClient.initializeSession();\n\n this.terminal.writeSuccess('Connected successfully');\n this.terminal.setPrompt('claude-flow>');\n } catch (error) {\n this.terminal.writeError(`Connection failed: ${error.message}`);\n }\n }\n\n /**\n * Disconnect from server\n */\n async disconnectFromServer() {\n this.wsClient.disconnect();\n this.terminal.writeSuccess('Disconnected from server');\n this.terminal.setPrompt('offline>');\n }\n\n /**\n * List available tools\n */\n async listTools() {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const tools = await this.wsClient.getAvailableTools();\n\n this.terminal.writeInfo('Available Tools:');\n this.terminal.writeLine('');\n\n if (tools && tools.length > 0) {\n tools.forEach((tool) => {\n this.terminal.writeLine(\n ` ${tool.name.padEnd(20)} - ${tool.description || 'No description'}`,\n );\n });\n } else {\n this.terminal.writeWarning('No tools available');\n }\n } catch (error) {\n this.terminal.writeError(`Failed to list tools: ${error.message}`);\n }\n }\n\n /**\n * Check server health\n */\n async checkHealth() {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const health = await this.wsClient.getHealthStatus();\n\n if (health.healthy) {\n this.terminal.writeSuccess('Server is healthy');\n } else {\n this.terminal.writeError(`Server is unhealthy: ${health.error || 'Unknown error'}`);\n }\n\n if (health.metrics) {\n this.terminal.writeLine('');\n this.terminal.writeInfo('Metrics:');\n Object.entries(health.metrics).forEach(([key, value]) => {\n this.terminal.writeLine(` ${key}: ${value}`);\n });\n }\n } catch (error) {\n this.terminal.writeError(`Health check failed: ${error.message}`);\n }\n }\n\n /**\n * Show command history\n */\n async showHistory() {\n const history = this.terminal.history;\n\n if (history.length === 0) {\n this.terminal.writeInfo('No command history');\n return;\n }\n\n this.terminal.writeInfo('Command History:');\n history.forEach((cmd, index) => {\n this.terminal.writeLine(` ${(index + 1).toString().padStart(3)}: ${cmd}`);\n });\n }\n\n /**\n * Export session data\n */\n async exportSession(args) {\n const format = args[0] || 'json';\n\n const sessionData = {\n timestamp: new Date().toISOString(),\n terminal: this.terminal.exportHistory(),\n history: this.terminal.history,\n status: this.wsClient.getStatus(),\n };\n\n if (format === 'json') {\n const blob = new Blob([JSON.stringify(sessionData, null, 2)], { type: 'application/json' });\n this.downloadFile(blob, `console-session-${Date.now()}.json`);\n this.terminal.writeSuccess('Session exported as JSON');\n } else {\n this.terminal.writeError(`Unsupported export format: ${format}`);\n }\n }\n\n /**\n * Change theme\n */\n async changeTheme(args) {\n const theme = args[0];\n const validThemes = ['dark', 'light', 'classic', 'matrix'];\n\n if (!theme) {\n this.terminal.writeInfo(`Available themes: ${validThemes.join(', ')}`);\n return;\n }\n\n if (!validThemes.includes(theme)) {\n this.terminal.writeError(`Invalid theme: ${theme}`);\n return;\n }\n\n document.documentElement.setAttribute('data-theme', theme);\n localStorage.setItem('console_theme', theme);\n this.terminal.writeSuccess(`Theme changed to: ${theme}`);\n }\n\n /**\n * Show version information\n */\n async showVersion() {\n this.terminal.writeInfo('๐ŸŒŠ Claude Flow v2.0.0');\n this.terminal.writeLine('Advanced swarm orchestration platform');\n this.terminal.writeLine('Built with modern web technologies');\n }\n\n /**\n * Execute Claude Flow command\n */\n async executeClaudeFlow(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n if (args.length === 0) {\n this.terminal.writeError('Usage: claude-flow [options]');\n return;\n }\n\n const subcommand = args[0];\n const subArgs = args.slice(1);\n\n try {\n const result = await this.wsClient.executeCommand('claude-flow', {\n subcommand,\n args: subArgs,\n });\n\n this.terminal.writeSuccess(`Claude Flow ${subcommand} executed successfully`);\n if (result && result.output) {\n this.terminal.writeLine(result.output);\n }\n } catch (error) {\n this.terminal.writeError(`Claude Flow command failed: ${error.message}`);\n }\n }\n\n /**\n * Execute swarm command\n */\n async executeSwarm(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const action = args[0] || 'status';\n this.terminal.writeInfo(`Executing swarm ${action}...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'swarm/status',\n arguments: { action, args: args.slice(1) },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess('Swarm command executed successfully');\n }\n } catch (error) {\n this.terminal.writeError(`Swarm command failed: ${error.message}`);\n }\n }\n\n /**\n * Initialize project\n */\n async initializeProject(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n this.terminal.writeWarning('Project initialization not yet implemented in web console');\n }\n\n /**\n * Manage configuration\n */\n async manageConfig(args) {\n this.terminal.writeInfo('Use the Settings panel (โš™๏ธ button) to manage configuration');\n }\n\n /**\n * Manage memory\n */\n async manageMemory(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const operation = args[0] || 'list';\n const key = args[1];\n const value = args.slice(2).join(' ');\n\n this.terminal.writeInfo(`Executing memory ${operation}...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'memory/manage',\n arguments: { operation, key, value },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess('Memory operation completed successfully');\n }\n } catch (error) {\n this.terminal.writeError(`Memory command failed: ${error.message}`);\n }\n }\n\n /**\n * Manage agents\n */\n async manageAgents(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const action = args[0] || 'list';\n const agentType = args[1];\n const agentId = args[1];\n\n this.terminal.writeInfo(`Executing agents ${action}...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'agents/manage',\n arguments: { action, agentType, agentId },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess('Agent operation completed successfully');\n }\n } catch (error) {\n this.terminal.writeError(`Agent command failed: ${error.message}`);\n }\n }\n\n /**\n * Run benchmark\n */\n async runBenchmark(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const suite = args[0] || 'default';\n const iterations = parseInt(args[1]) || 10;\n\n this.terminal.writeInfo(`Running benchmark suite: ${suite}...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'benchmark/run',\n arguments: { suite, iterations },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess('Benchmark completed successfully');\n }\n } catch (error) {\n this.terminal.writeError(`Benchmark failed: ${error.message}`);\n }\n }\n\n /**\n * Execute SPARC mode\n */\n async executeSparc(args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n if (args.length === 0) {\n this.terminal.writeInfo('Available SPARC modes:');\n const modes = [\n 'coder',\n 'architect',\n 'analyst',\n 'researcher',\n 'reviewer',\n 'tester',\n 'debugger',\n 'documenter',\n 'optimizer',\n 'designer',\n ];\n modes.forEach((mode) => {\n this.terminal.writeLine(` ${mode}`);\n });\n return;\n }\n\n try {\n const mode = args[0];\n const task = args.slice(1).join(' ') || 'General task execution';\n const options = {};\n\n this.terminal.writeInfo(`Executing SPARC mode: ${mode}...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'sparc/execute',\n arguments: { mode, task, options },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);\n }\n } catch (error) {\n this.terminal.writeError(`SPARC execution failed: ${error.message}`);\n }\n }\n\n /**\n * Execute specific SPARC mode\n */\n async executeSparcMode(mode, args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server');\n return;\n }\n\n try {\n const task = args.join(' ') || `Execute ${mode} mode tasks`;\n const options = {};\n\n this.terminal.writeInfo(`Executing SPARC ${mode} mode...`);\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: 'sparc/execute',\n arguments: { mode, task, options },\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`);\n }\n } catch (error) {\n this.terminal.writeError(`SPARC ${mode} execution failed: ${error.message}`);\n }\n }\n\n /**\n * Execute remote command via WebSocket\n */\n async executeRemoteCommand(command, args) {\n if (!this.wsClient.isConnected) {\n this.terminal.writeError('Not connected to server. Use \"connect\" command first.');\n return;\n }\n\n try {\n // Check if this is a tool name (contains slash)\n if (command.includes('/')) {\n return await this.executeToolDirect(command, args);\n }\n\n this.terminal.writeInfo(`Executing remote command: ${command}`);\n\n const result = await this.wsClient.executeCommand(command, { args });\n\n if (result && result.output) {\n this.terminal.writeLine(result.output);\n } else {\n this.terminal.writeSuccess('Command executed successfully');\n }\n } catch (error) {\n this.terminal.writeError(`Remote command failed: ${error.message}`);\n }\n }\n\n /**\n * Execute tool directly by name\n */\n async executeToolDirect(toolName, args) {\n try {\n this.terminal.writeInfo(`Executing tool: ${toolName}...`);\n\n // Prepare arguments based on tool\n let toolArgs = {};\n\n switch (toolName) {\n case 'system/health':\n toolArgs = { detailed: args.includes('--detailed') };\n break;\n\n case 'memory/manage':\n toolArgs = {\n operation: args[0] || 'list',\n key: args[1],\n value: args.slice(2).join(' '),\n };\n break;\n\n case 'agents/manage':\n toolArgs = {\n action: args[0] || 'list',\n agentType: args[1],\n agentId: args[1],\n };\n break;\n\n case 'swarm/orchestrate':\n toolArgs = {\n action: args[0] || 'status',\n args: args.slice(1),\n };\n break;\n\n case 'sparc/execute':\n toolArgs = {\n mode: args[0] || 'coder',\n task: args.slice(1).join(' ') || 'General task execution',\n options: {},\n };\n break;\n\n case 'benchmark/run':\n toolArgs = {\n suite: args[0] || 'default',\n iterations: parseInt(args[1]) || 10,\n };\n break;\n\n case 'claude-flow/execute':\n toolArgs = {\n command: args[0] || 'status',\n args: args.slice(1),\n };\n break;\n\n default:\n toolArgs = { args };\n }\n\n const result = await this.wsClient.sendRequest('tools/call', {\n name: toolName,\n arguments: toolArgs,\n });\n\n if (result && result.content && result.content[0]) {\n this.terminal.writeSuccess(result.content[0].text);\n } else {\n this.terminal.writeSuccess(`Tool ${toolName} executed successfully`);\n }\n } catch (error) {\n this.terminal.writeError(`Tool execution failed: ${error.message}`);\n }\n }\n\n /**\n * Download file helper\n */\n downloadFile(blob, filename) {\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = filename;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n URL.revokeObjectURL(url);\n }\n\n /**\n * Get command suggestions\n */\n getCommandSuggestions(input) {\n const allCommands = Object.keys(this.allCommands);\n return allCommands.filter((cmd) => cmd.startsWith(input.toLowerCase()));\n }\n\n /**\n * Check if command exists\n */\n hasCommand(command) {\n return this.allCommands.hasOwnProperty(command.toLowerCase());\n }\n}\n"],"names":["CommandHandler","terminal","wsClient","isProcessing","builtinCommands","help","showHelp","bind","clear","clearConsole","status","showStatus","connect","connectToServer","disconnect","disconnectFromServer","tools","listTools","health","checkHealth","history","showHistory","export","exportSession","theme","changeTheme","version","showVersion","claudeFlowCommands","executeClaudeFlow","swarm","executeSwarm","init","initializeProject","config","manageConfig","memory","manageMemory","agents","manageAgents","benchmark","runBenchmark","sparc","executeSparc","sparcModeCommands","coder","executeSparcMode","architect","analyst","researcher","reviewer","tester","debugger","documenter","optimizer","designer","allCommands","processCommand","command","writeWarning","setLocked","cmd","args","parseCommand","executeRemoteCommand","error","writeError","message","console","commandString","parts","trim","split","toLowerCase","slice","length","showCommandHelp","writeInfo","writeLine","Object","keys","forEach","padEnd","getCommandDescription","descriptions","helpText","writeSuccess","wsStatus","getStatus","terminalStats","getStats","connected","url","reconnectAttempts","queuedMessages","pendingRequests","totalLines","historySize","isLocked","currentPrompt","healthStatus","getHealthStatus","healthy","metrics","entries","key","value","token","initializeSession","setPrompt","isConnected","getAvailableTools","tool","name","description","index","toString","padStart","format","sessionData","timestamp","Date","toISOString","exportHistory","blob","Blob","JSON","stringify","type","downloadFile","now","validThemes","join","includes","document","documentElement","setAttribute","localStorage","setItem","subcommand","subArgs","result","executeCommand","output","action","sendRequest","arguments","content","text","operation","agentType","agentId","suite","iterations","parseInt","modes","mode","task","options","executeToolDirect","toolName","toolArgs","detailed","filename","URL","createObjectURL","a","createElement","href","download","body","appendChild","click","removeChild","revokeObjectURL","getCommandSuggestions","input","filter","startsWith","hasCommand","hasOwnProperty"],"mappings":"AAKA,OAAO,MAAMA;IACX,YAAYC,QAAQ,EAAEC,QAAQ,CAAE;QAC9B,IAAI,CAACD,QAAQ,GAAGA;QAChB,IAAI,CAACC,QAAQ,GAAGA;QAChB,IAAI,CAACC,YAAY,GAAG;QAGpB,IAAI,CAACC,eAAe,GAAG;YACrBC,MAAM,IAAI,CAACC,QAAQ,CAACC,IAAI,CAAC,IAAI;YAC7BC,OAAO,IAAI,CAACC,YAAY,CAACF,IAAI,CAAC,IAAI;YAClCG,QAAQ,IAAI,CAACC,UAAU,CAACJ,IAAI,CAAC,IAAI;YACjCK,SAAS,IAAI,CAACC,eAAe,CAACN,IAAI,CAAC,IAAI;YACvCO,YAAY,IAAI,CAACC,oBAAoB,CAACR,IAAI,CAAC,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Ac;gBAC3DhC,MAAM+C;gBACNd,WAAWe;YACb;YAEA,IAAIpB,UAAUA,OAAOM,OAAO,IAAIN,OAAOM,OAAO,CAAC,EAAE,EAAE;gBACjD,IAAI,CAAClJ,QAAQ,CAACqF,YAAY,CAACuD,OAAOM,OAAO,CAAC,EAAE,CAACC,IAAI;YACnD,OAAO;gBACL,IAAI,CAACnJ,QAAQ,CAACqF,YAAY,CAAC,CAAC,KAAK,EAAE0E,SAAS,sBAAsB,CAAC;YACrE;QACF,EAAE,OAAO/F,OAAO;YACd,IAAI,CAAChE,QAAQ,CAACiE,UAAU,CAAC,CAAC,uBAAuB,EAAED,MAAME,OAAO,EAAE;QACpE;IACF;IAKA8D,aAAaL,IAAI,EAAEuC,QAAQ,EAAE;QAC3B,MAAMvE,MAAMwE,IAAIC,eAAe,CAACzC;QAChC,MAAM0C,IAAIhC,SAASiC,aAAa,CAAC;QACjCD,EAAEE,IAAI,GAAG5E;QACT0E,EAAEG,QAAQ,GAAGN;QACb7B,SAASoC,IAAI,CAACC,WAAW,CAACL;QAC1BA,EAAEM,KAAK;QACPtC,SAASoC,IAAI,CAACG,WAAW,CAACP;QAC1BF,IAAIU,eAAe,CAAClF;IACtB;IAKAmF,sBAAsBC,KAAK,EAAE;QAC3B,MAAMxH,cAAcuB,OAAOC,IAAI,CAAC,IAAI,CAACxB,WAAW;QAChD,OAAOA,YAAYyH,MAAM,CAAC,CAACpH,MAAQA,IAAIqH,UAAU,CAACF,MAAMvG,WAAW;IACrE;IAKA0G,WAAWzH,OAAO,EAAE;QAClB,OAAO,IAAI,CAACF,WAAW,CAAC4H,cAAc,CAAC1H,QAAQe,WAAW;IAC5D;AACF"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/console.js b/dist-cjs/src/ui/console/js/console.js deleted file mode 100644 index eb10684254..0000000000 --- a/dist-cjs/src/ui/console/js/console.js +++ /dev/null @@ -1,410 +0,0 @@ -import { WebSocketClient } from './websocket-client.js'; -import { TerminalEmulator } from './terminal-emulator.js'; -import { CommandHandler } from './command-handler.js'; -import { SettingsManager } from './settings.js'; -let ClaudeCodeConsole = class ClaudeCodeConsole { - constructor(){ - this.wsClient = new WebSocketClient(); - this.terminal = null; - this.commandHandler = null; - this.settings = new SettingsManager(); - this.isInitialized = false; - this.startTime = Date.now(); - this.messageCount = 0; - this.activeAgents = 0; - this.elements = {}; - this.statusInterval = null; - this.uptimeInterval = null; - this.setupEventListeners(); - } - async init() { - if (this.isInitialized) return; - try { - this.showLoading('Initializing Claude Code Console...'); - this.getDOMElements(); - this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput); - this.commandHandler = new CommandHandler(this.terminal, this.wsClient); - this.settings.init(); - this.setupComponentInteractions(); - this.setupUIEventHandlers(); - this.applyInitialSettings(); - this.startStatusUpdates(); - this.hideLoading(); - this.showWelcomeMessage(); - if (this.settings.get('autoConnect')) { - await this.autoConnect(); - } - this.isInitialized = true; - console.log('Claude Code Console initialized successfully'); - } catch (error) { - console.error('Failed to initialize console:', error); - this.showError('Failed to initialize console: ' + error.message); - } - } - getDOMElements() { - this.elements = { - consoleOutput: document.getElementById('consoleOutput'), - consoleInput: document.getElementById('consoleInput'), - settingsPanel: document.getElementById('settingsPanel'), - loadingOverlay: document.getElementById('loadingOverlay'), - connectionStatus: document.getElementById('connectionStatus'), - statusIndicator: document.getElementById('statusIndicator'), - statusText: document.getElementById('statusText'), - currentMode: document.getElementById('currentMode'), - activeAgents: document.getElementById('activeAgents'), - uptime: document.getElementById('uptime'), - memoryUsage: document.getElementById('memoryUsage'), - messageCount: document.getElementById('messageCount'), - timestamp: document.getElementById('timestamp'), - clearConsole: document.getElementById('clearConsole'), - fullscreenToggle: document.getElementById('fullscreenToggle') - }; - const required = [ - 'consoleOutput', - 'consoleInput', - 'loadingOverlay' - ]; - for (const elementId of required){ - if (!this.elements[elementId]) { - throw new Error(`Required element not found: ${elementId}`); - } - } - } - setupComponentInteractions() { - this.terminal.on('command', (command)=>{ - this.commandHandler.processCommand(command); - }); - this.terminal.on('interrupt', ()=>{ - this.handleInterrupt(); - }); - this.wsClient.on('connected', ()=>{ - this.updateConnectionStatus(true, false); - this.terminal.writeSuccess('Connected to Claude Code server'); - this.terminal.setPrompt('claude-flow>'); - }); - this.wsClient.on('disconnected', (info)=>{ - this.updateConnectionStatus(false, false); - this.terminal.writeWarning('Disconnected from server'); - this.terminal.setPrompt('offline>'); - if (info && info.code !== 1000) { - this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`); - } - }); - this.wsClient.on('reconnecting', (info)=>{ - this.updateConnectionStatus(false, true); - this.terminal.writeInfo(`Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`); - }); - this.wsClient.on('error', (error)=>{ - this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown error'}`); - }); - this.wsClient.on('message_received', (message)=>{ - this.messageCount++; - this.handleIncomingMessage(message); - }); - this.wsClient.on('notification', (notification)=>{ - this.handleNotification(notification); - }); - this.settings.on('connect_requested', async (config)=>{ - await this.connect(config.url, config.token); - }); - this.settings.on('disconnect_requested', ()=>{ - this.disconnect(); - }); - this.settings.on('max_lines_changed', (maxLines)=>{ - this.terminal.setMaxLines(maxLines); - }); - this.settings.on('setting_changed', ({ key, value })=>{ - this.handleSettingChange(key, value); - }); - } - setupUIEventHandlers() { - if (this.elements.clearConsole) { - this.elements.clearConsole.addEventListener('click', ()=>{ - this.terminal.clear(); - }); - } - if (this.elements.fullscreenToggle) { - this.elements.fullscreenToggle.addEventListener('click', ()=>{ - this.toggleFullscreen(); - }); - } - if (this.elements.consoleOutput) { - this.elements.consoleOutput.addEventListener('click', ()=>{ - this.terminal.focus(); - }); - } - window.addEventListener('focus', ()=>{ - this.terminal.focus(); - }); - document.addEventListener('visibilitychange', ()=>{ - if (!document.hidden) { - this.updateTimestamp(); - } - }); - window.addEventListener('beforeunload', ()=>{ - this.cleanup(); - }); - } - applyInitialSettings() { - const maxLines = this.settings.get('maxLines'); - if (maxLines) { - this.terminal.setMaxLines(maxLines); - } - this.settings.updateConnectionStatus(this.wsClient.getStatus()); - } - showWelcomeMessage() { - this.terminal.showWelcomeMessage(); - this.terminal.writeInfo('Console ready. Type "help" for available commands.'); - const config = this.settings.getConnectionConfig(); - if (config.url && !config.autoConnect) { - this.terminal.writeInfo(`Use "connect" to connect to ${config.url}`); - } - } - async autoConnect() { - const config = this.settings.getConnectionConfig(); - if (config.url) { - this.terminal.writeInfo(`Auto-connecting to ${config.url}...`); - await this.connect(config.url, config.token); - } - } - async connect(url, token = '') { - try { - this.updateConnectionStatus(false, true); - await this.wsClient.connect(url, token); - await this.wsClient.initializeSession(); - this.settings.set('serverUrl', url); - if (token) { - this.settings.set('authToken', token); - } - } catch (error) { - this.updateConnectionStatus(false, false); - this.terminal.writeError(`Connection failed: ${error.message}`); - } - } - disconnect() { - this.wsClient.disconnect(); - this.updateConnectionStatus(false, false); - } - updateConnectionStatus(connected, connecting) { - const status = this.wsClient.getStatus(); - if (this.elements.statusIndicator) { - this.elements.statusIndicator.className = 'status-indicator ' + (connected ? 'connected' : connecting ? 'connecting' : ''); - } - if (this.elements.statusText) { - this.elements.statusText.textContent = connected ? 'Connected' : connecting ? 'Connecting...' : 'Disconnected'; - } - this.settings.updateConnectionStatus(status); - } - handleIncomingMessage(message) { - if (message.method === 'output/stream') { - this.handleStreamingOutput(message.params); - } - if (message.method && message.method.startsWith('claude-flow/')) { - this.handleClaudeFlowNotification(message); - } - } - handleNotification(notification) { - const { method, params } = notification; - switch(method){ - case 'agent/status': - this.handleAgentStatus(params); - break; - case 'swarm/update': - this.handleSwarmUpdate(params); - break; - case 'memory/update': - this.handleMemoryUpdate(params); - break; - case 'log/message': - this.handleLogMessage(params); - break; - case 'connection/established': - this.handleConnectionEstablished(params); - break; - default: - console.log('Unhandled notification:', method, params); - } - } - handleStreamingOutput(params) { - if (params && params.content) { - const type = params.type || 'output'; - if (params.streaming) { - this.terminal.streamText(params.content, 10); - } else { - this.terminal.write(params.content, type); - } - } - } - handleClaudeFlowNotification(message) { - const { method, params } = message; - switch(method){ - case 'claude-flow/started': - this.terminal.writeSuccess(`Claude Flow started in ${params.mode} mode`); - break; - case 'claude-flow/stopped': - this.terminal.writeInfo('Claude Flow stopped'); - break; - case 'claude-flow/error': - this.terminal.writeError(`Claude Flow error: ${params.message}`); - break; - default: - this.terminal.writeInfo(`Claude Flow: ${method} - ${JSON.stringify(params)}`); - } - } - handleAgentStatus(params) { - if (params.active !== undefined) { - this.activeAgents = params.active; - } - if (params.message) { - this.terminal.writeInfo(`Agent: ${params.message}`); - } - } - handleSwarmUpdate(params) { - if (params.message) { - this.terminal.writeInfo(`Swarm: ${params.message}`); - } - } - handleMemoryUpdate(params) { - if (params.message) { - this.terminal.writeInfo(`Memory: ${params.message}`); - } - } - handleLogMessage(params) { - if (params.level && params.message) { - const type = params.level === 'error' ? 'error' : params.level === 'warn' ? 'warning' : 'info'; - this.terminal.write(`[${params.level.toUpperCase()}] ${params.message}`, type); - } - } - handleConnectionEstablished(params) { - console.log('Connection established:', params); - } - handleInterrupt() { - this.terminal.writeWarning('Interrupt signal sent'); - } - handleSettingChange(key, value) { - switch(key){ - case 'theme': - document.documentElement.setAttribute('data-theme', value); - break; - case 'fontSize': - document.documentElement.style.setProperty('--font-size-base', `${value}px`); - break; - case 'lineHeight': - document.documentElement.style.setProperty('--line-height', value); - break; - } - } - startStatusUpdates() { - this.statusInterval = setInterval(()=>{ - this.updateStatus(); - }, 5000); - this.uptimeInterval = setInterval(()=>{ - this.updateUptime(); - this.updateTimestamp(); - }, 1000); - this.updateStatus(); - this.updateUptime(); - this.updateTimestamp(); - } - updateStatus() { - if (this.elements.activeAgents) { - this.elements.activeAgents.textContent = `Agents: ${this.activeAgents}`; - } - if (this.elements.messageCount) { - this.elements.messageCount.textContent = `Messages: ${this.messageCount}`; - } - if (this.elements.memoryUsage && performance.memory) { - const used = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024); - this.elements.memoryUsage.textContent = `Memory: ${used}MB`; - } - } - updateUptime() { - if (this.elements.uptime) { - const uptime = Date.now() - this.startTime; - const hours = Math.floor(uptime / (1000 * 60 * 60)); - const minutes = Math.floor(uptime % (1000 * 60 * 60) / (1000 * 60)); - const seconds = Math.floor(uptime % (1000 * 60) / 1000); - this.elements.uptime.textContent = `Uptime: ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; - } - } - updateTimestamp() { - if (this.elements.timestamp) { - this.elements.timestamp.textContent = new Date().toLocaleTimeString(); - } - } - toggleFullscreen() { - if (!document.fullscreenElement) { - document.documentElement.requestFullscreen().catch((err)=>{ - console.error('Error attempting to enable fullscreen:', err); - }); - } else { - document.exitFullscreen(); - } - } - showLoading(message = 'Loading...') { - if (this.elements.loadingOverlay) { - const loadingText = this.elements.loadingOverlay.querySelector('.loading-text'); - if (loadingText) { - loadingText.textContent = message; - } - this.elements.loadingOverlay.classList.remove('hidden'); - } - } - hideLoading() { - if (this.elements.loadingOverlay) { - this.elements.loadingOverlay.classList.add('hidden'); - } - } - showError(message) { - this.hideLoading(); - if (this.terminal) { - this.terminal.writeError(message); - } else { - console.error(message); - alert(message); - } - } - setupEventListeners() { - window.addEventListener('unhandledrejection', (event)=>{ - console.error('Unhandled promise rejection:', event.reason); - if (this.terminal) { - this.terminal.writeError(`Unhandled error: ${event.reason.message || event.reason}`); - } - }); - window.addEventListener('error', (event)=>{ - console.error('Global error:', event.error); - if (this.terminal) { - this.terminal.writeError(`Application error: ${event.error.message || event.error}`); - } - }); - } - cleanup() { - if (this.statusInterval) { - clearInterval(this.statusInterval); - } - if (this.uptimeInterval) { - clearInterval(this.uptimeInterval); - } - if (this.wsClient) { - this.wsClient.disconnect(); - } - } - getStats() { - return { - initialized: this.isInitialized, - uptime: Date.now() - this.startTime, - messageCount: this.messageCount, - activeAgents: this.activeAgents, - connection: this.wsClient.getStatus(), - terminal: this.terminal ? this.terminal.getStats() : null - }; - } -}; -document.addEventListener('DOMContentLoaded', async ()=>{ - const console1 = new ClaudeCodeConsole(); - window.claudeConsole = console1; - await console1.init(); -}); -export { ClaudeCodeConsole }; - -//# sourceMappingURL=console.js.map \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/console.js.map b/dist-cjs/src/ui/console/js/console.js.map deleted file mode 100644 index 54df9f1ae1..0000000000 --- a/dist-cjs/src/ui/console/js/console.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../../../src/ui/console/js/console.js"],"sourcesContent":["/**\n * Main Console Application\n * Coordinates all components of the Claude Code Console\n */\n\nimport { WebSocketClient } from './websocket-client.js';\nimport { TerminalEmulator } from './terminal-emulator.js';\nimport { CommandHandler } from './command-handler.js';\nimport { SettingsManager } from './settings.js';\n\nclass ClaudeCodeConsole {\n constructor() {\n // Initialize components\n this.wsClient = new WebSocketClient();\n this.terminal = null;\n this.commandHandler = null;\n this.settings = new SettingsManager();\n\n // State management\n this.isInitialized = false;\n this.startTime = Date.now();\n this.messageCount = 0;\n this.activeAgents = 0;\n\n // DOM elements\n this.elements = {};\n\n // Status update intervals\n this.statusInterval = null;\n this.uptimeInterval = null;\n\n this.setupEventListeners();\n }\n\n /**\n * Initialize the console application\n */\n async init() {\n if (this.isInitialized) return;\n\n try {\n // Show loading overlay\n this.showLoading('Initializing Claude Code Console...');\n\n // Get DOM elements\n this.getDOMElements();\n\n // Initialize terminal emulator\n this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput);\n\n // Initialize command handler\n this.commandHandler = new CommandHandler(this.terminal, this.wsClient);\n\n // Initialize settings\n this.settings.init();\n\n // Setup component interactions\n this.setupComponentInteractions();\n\n // Setup UI event handlers\n this.setupUIEventHandlers();\n\n // Apply initial settings\n this.applyInitialSettings();\n\n // Start status updates\n this.startStatusUpdates();\n\n // Hide loading overlay\n this.hideLoading();\n\n // Show welcome message\n this.showWelcomeMessage();\n\n // Auto-connect if enabled\n if (this.settings.get('autoConnect')) {\n await this.autoConnect();\n }\n\n this.isInitialized = true;\n console.log('Claude Code Console initialized successfully');\n } catch (error) {\n console.error('Failed to initialize console:', error);\n this.showError('Failed to initialize console: ' + error.message);\n }\n }\n\n /**\n * Get DOM elements\n */\n getDOMElements() {\n this.elements = {\n consoleOutput: document.getElementById('consoleOutput'),\n consoleInput: document.getElementById('consoleInput'),\n settingsPanel: document.getElementById('settingsPanel'),\n loadingOverlay: document.getElementById('loadingOverlay'),\n connectionStatus: document.getElementById('connectionStatus'),\n statusIndicator: document.getElementById('statusIndicator'),\n statusText: document.getElementById('statusText'),\n currentMode: document.getElementById('currentMode'),\n activeAgents: document.getElementById('activeAgents'),\n uptime: document.getElementById('uptime'),\n memoryUsage: document.getElementById('memoryUsage'),\n messageCount: document.getElementById('messageCount'),\n timestamp: document.getElementById('timestamp'),\n clearConsole: document.getElementById('clearConsole'),\n fullscreenToggle: document.getElementById('fullscreenToggle'),\n };\n\n // Validate required elements\n const required = ['consoleOutput', 'consoleInput', 'loadingOverlay'];\n for (const elementId of required) {\n if (!this.elements[elementId]) {\n throw new Error(`Required element not found: ${elementId}`);\n }\n }\n }\n\n /**\n * Setup component interactions\n */\n setupComponentInteractions() {\n // Terminal -> Command Handler\n this.terminal.on('command', (command) => {\n this.commandHandler.processCommand(command);\n });\n\n this.terminal.on('interrupt', () => {\n this.handleInterrupt();\n });\n\n // WebSocket -> Terminal\n this.wsClient.on('connected', () => {\n this.updateConnectionStatus(true, false);\n this.terminal.writeSuccess('Connected to Claude Code server');\n this.terminal.setPrompt('claude-flow>');\n });\n\n this.wsClient.on('disconnected', (info) => {\n this.updateConnectionStatus(false, false);\n this.terminal.writeWarning('Disconnected from server');\n this.terminal.setPrompt('offline>');\n\n if (info && info.code !== 1000) {\n this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`);\n }\n });\n\n this.wsClient.on('reconnecting', (info) => {\n this.updateConnectionStatus(false, true);\n this.terminal.writeInfo(\n `Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`,\n );\n });\n\n this.wsClient.on('error', (error) => {\n this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown error'}`);\n });\n\n this.wsClient.on('message_received', (message) => {\n this.messageCount++;\n this.handleIncomingMessage(message);\n });\n\n this.wsClient.on('notification', (notification) => {\n this.handleNotification(notification);\n });\n\n // Settings -> Application\n this.settings.on('connect_requested', async (config) => {\n await this.connect(config.url, config.token);\n });\n\n this.settings.on('disconnect_requested', () => {\n this.disconnect();\n });\n\n this.settings.on('max_lines_changed', (maxLines) => {\n this.terminal.setMaxLines(maxLines);\n });\n\n this.settings.on('setting_changed', ({ key, value }) => {\n this.handleSettingChange(key, value);\n });\n }\n\n /**\n * Setup UI event handlers\n */\n setupUIEventHandlers() {\n // Clear console button\n if (this.elements.clearConsole) {\n this.elements.clearConsole.addEventListener('click', () => {\n this.terminal.clear();\n });\n }\n\n // Fullscreen toggle\n if (this.elements.fullscreenToggle) {\n this.elements.fullscreenToggle.addEventListener('click', () => {\n this.toggleFullscreen();\n });\n }\n\n // Focus input when clicking on output area\n if (this.elements.consoleOutput) {\n this.elements.consoleOutput.addEventListener('click', () => {\n this.terminal.focus();\n });\n }\n\n // Handle window focus\n window.addEventListener('focus', () => {\n this.terminal.focus();\n });\n\n // Handle visibility change\n document.addEventListener('visibilitychange', () => {\n if (!document.hidden) {\n this.updateTimestamp();\n }\n });\n\n // Handle page unload\n window.addEventListener('beforeunload', () => {\n this.cleanup();\n });\n }\n\n /**\n * Apply initial settings\n */\n applyInitialSettings() {\n const maxLines = this.settings.get('maxLines');\n if (maxLines) {\n this.terminal.setMaxLines(maxLines);\n }\n\n // Update connection status in settings\n this.settings.updateConnectionStatus(this.wsClient.getStatus());\n }\n\n /**\n * Show welcome message\n */\n showWelcomeMessage() {\n this.terminal.showWelcomeMessage();\n this.terminal.writeInfo('Console ready. Type \"help\" for available commands.');\n\n const config = this.settings.getConnectionConfig();\n if (config.url && !config.autoConnect) {\n this.terminal.writeInfo(`Use \"connect\" to connect to ${config.url}`);\n }\n }\n\n /**\n * Auto-connect to server\n */\n async autoConnect() {\n const config = this.settings.getConnectionConfig();\n\n if (config.url) {\n this.terminal.writeInfo(`Auto-connecting to ${config.url}...`);\n await this.connect(config.url, config.token);\n }\n }\n\n /**\n * Connect to server\n */\n async connect(url, token = '') {\n try {\n this.updateConnectionStatus(false, true);\n await this.wsClient.connect(url, token);\n await this.wsClient.initializeSession();\n\n // Update settings with successful connection\n this.settings.set('serverUrl', url);\n if (token) {\n this.settings.set('authToken', token);\n }\n } catch (error) {\n this.updateConnectionStatus(false, false);\n this.terminal.writeError(`Connection failed: ${error.message}`);\n }\n }\n\n /**\n * Disconnect from server\n */\n disconnect() {\n this.wsClient.disconnect();\n this.updateConnectionStatus(false, false);\n }\n\n /**\n * Update connection status in UI\n */\n updateConnectionStatus(connected, connecting) {\n const status = this.wsClient.getStatus();\n\n // Update status indicator\n if (this.elements.statusIndicator) {\n this.elements.statusIndicator.className =\n 'status-indicator ' + (connected ? 'connected' : connecting ? 'connecting' : '');\n }\n\n // Update status text\n if (this.elements.statusText) {\n this.elements.statusText.textContent = connected\n ? 'Connected'\n : connecting\n ? 'Connecting...'\n : 'Disconnected';\n }\n\n // Update settings panel\n this.settings.updateConnectionStatus(status);\n }\n\n /**\n * Handle incoming messages\n */\n handleIncomingMessage(message) {\n // Handle streaming output\n if (message.method === 'output/stream') {\n this.handleStreamingOutput(message.params);\n }\n\n // Handle Claude Flow notifications\n if (message.method && message.method.startsWith('claude-flow/')) {\n this.handleClaudeFlowNotification(message);\n }\n }\n\n /**\n * Handle notifications\n */\n handleNotification(notification) {\n const { method, params } = notification;\n\n switch (method) {\n case 'agent/status':\n this.handleAgentStatus(params);\n break;\n\n case 'swarm/update':\n this.handleSwarmUpdate(params);\n break;\n\n case 'memory/update':\n this.handleMemoryUpdate(params);\n break;\n\n case 'log/message':\n this.handleLogMessage(params);\n break;\n\n case 'connection/established':\n this.handleConnectionEstablished(params);\n break;\n\n default:\n console.log('Unhandled notification:', method, params);\n }\n }\n\n /**\n * Handle streaming output\n */\n handleStreamingOutput(params) {\n if (params && params.content) {\n const type = params.type || 'output';\n\n if (params.streaming) {\n // Use streaming text effect for long outputs\n this.terminal.streamText(params.content, 10);\n } else {\n this.terminal.write(params.content, type);\n }\n }\n }\n\n /**\n * Handle Claude Flow notifications\n */\n handleClaudeFlowNotification(message) {\n const { method, params } = message;\n\n switch (method) {\n case 'claude-flow/started':\n this.terminal.writeSuccess(`Claude Flow started in ${params.mode} mode`);\n break;\n\n case 'claude-flow/stopped':\n this.terminal.writeInfo('Claude Flow stopped');\n break;\n\n case 'claude-flow/error':\n this.terminal.writeError(`Claude Flow error: ${params.message}`);\n break;\n\n default:\n this.terminal.writeInfo(`Claude Flow: ${method} - ${JSON.stringify(params)}`);\n }\n }\n\n /**\n * Handle agent status updates\n */\n handleAgentStatus(params) {\n if (params.active !== undefined) {\n this.activeAgents = params.active;\n }\n\n if (params.message) {\n this.terminal.writeInfo(`Agent: ${params.message}`);\n }\n }\n\n /**\n * Handle swarm updates\n */\n handleSwarmUpdate(params) {\n if (params.message) {\n this.terminal.writeInfo(`Swarm: ${params.message}`);\n }\n }\n\n /**\n * Handle memory updates\n */\n handleMemoryUpdate(params) {\n if (params.message) {\n this.terminal.writeInfo(`Memory: ${params.message}`);\n }\n }\n\n /**\n * Handle log messages\n */\n handleLogMessage(params) {\n if (params.level && params.message) {\n const type =\n params.level === 'error' ? 'error' : params.level === 'warn' ? 'warning' : 'info';\n this.terminal.write(`[${params.level.toUpperCase()}] ${params.message}`, type);\n }\n }\n\n /**\n * Handle connection established notification\n */\n handleConnectionEstablished(params) {\n // Log connection details without cluttering the terminal\n console.log('Connection established:', params);\n // Optionally show a brief success message\n // this.terminal.writeSuccess(`Connected to ${params.server} v${params.version}`);\n }\n\n /**\n * Handle interrupt (Ctrl+C)\n */\n handleInterrupt() {\n // Could be used to cancel running commands\n this.terminal.writeWarning('Interrupt signal sent');\n }\n\n /**\n * Handle setting changes\n */\n handleSettingChange(key, value) {\n switch (key) {\n case 'theme':\n document.documentElement.setAttribute('data-theme', value);\n break;\n\n case 'fontSize':\n document.documentElement.style.setProperty('--font-size-base', `${value}px`);\n break;\n\n case 'lineHeight':\n document.documentElement.style.setProperty('--line-height', value);\n break;\n }\n }\n\n /**\n * Start status updates\n */\n startStatusUpdates() {\n // Update status every 5 seconds\n this.statusInterval = setInterval(() => {\n this.updateStatus();\n }, 5000);\n\n // Update timestamp every second\n this.uptimeInterval = setInterval(() => {\n this.updateUptime();\n this.updateTimestamp();\n }, 1000);\n\n // Initial update\n this.updateStatus();\n this.updateUptime();\n this.updateTimestamp();\n }\n\n /**\n * Update status bar\n */\n updateStatus() {\n // Update active agents\n if (this.elements.activeAgents) {\n this.elements.activeAgents.textContent = `Agents: ${this.activeAgents}`;\n }\n\n // Update message count\n if (this.elements.messageCount) {\n this.elements.messageCount.textContent = `Messages: ${this.messageCount}`;\n }\n\n // Update memory usage (if available)\n if (this.elements.memoryUsage && performance.memory) {\n const used = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);\n this.elements.memoryUsage.textContent = `Memory: ${used}MB`;\n }\n }\n\n /**\n * Update uptime\n */\n updateUptime() {\n if (this.elements.uptime) {\n const uptime = Date.now() - this.startTime;\n const hours = Math.floor(uptime / (1000 * 60 * 60));\n const minutes = Math.floor((uptime % (1000 * 60 * 60)) / (1000 * 60));\n const seconds = Math.floor((uptime % (1000 * 60)) / 1000);\n\n this.elements.uptime.textContent = `Uptime: ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;\n }\n }\n\n /**\n * Update timestamp\n */\n updateTimestamp() {\n if (this.elements.timestamp) {\n this.elements.timestamp.textContent = new Date().toLocaleTimeString();\n }\n }\n\n /**\n * Toggle fullscreen mode\n */\n toggleFullscreen() {\n if (!document.fullscreenElement) {\n document.documentElement.requestFullscreen().catch((err) => {\n console.error('Error attempting to enable fullscreen:', err);\n });\n } else {\n document.exitFullscreen();\n }\n }\n\n /**\n * Show loading overlay\n */\n showLoading(message = 'Loading...') {\n if (this.elements.loadingOverlay) {\n const loadingText = this.elements.loadingOverlay.querySelector('.loading-text');\n if (loadingText) {\n loadingText.textContent = message;\n }\n this.elements.loadingOverlay.classList.remove('hidden');\n }\n }\n\n /**\n * Hide loading overlay\n */\n hideLoading() {\n if (this.elements.loadingOverlay) {\n this.elements.loadingOverlay.classList.add('hidden');\n }\n }\n\n /**\n * Show error message\n */\n showError(message) {\n this.hideLoading();\n\n if (this.terminal) {\n this.terminal.writeError(message);\n } else {\n // Fallback if terminal isn't initialized\n console.error(message);\n alert(message);\n }\n }\n\n /**\n * Setup global event listeners\n */\n setupEventListeners() {\n // Handle unhandled promise rejections\n window.addEventListener('unhandledrejection', (event) => {\n console.error('Unhandled promise rejection:', event.reason);\n if (this.terminal) {\n this.terminal.writeError(`Unhandled error: ${event.reason.message || event.reason}`);\n }\n });\n\n // Handle errors\n window.addEventListener('error', (event) => {\n console.error('Global error:', event.error);\n if (this.terminal) {\n this.terminal.writeError(`Application error: ${event.error.message || event.error}`);\n }\n });\n }\n\n /**\n * Cleanup on shutdown\n */\n cleanup() {\n // Clear intervals\n if (this.statusInterval) {\n clearInterval(this.statusInterval);\n }\n\n if (this.uptimeInterval) {\n clearInterval(this.uptimeInterval);\n }\n\n // Disconnect WebSocket\n if (this.wsClient) {\n this.wsClient.disconnect();\n }\n }\n\n /**\n * Get console statistics\n */\n getStats() {\n return {\n initialized: this.isInitialized,\n uptime: Date.now() - this.startTime,\n messageCount: this.messageCount,\n activeAgents: this.activeAgents,\n connection: this.wsClient.getStatus(),\n terminal: this.terminal ? this.terminal.getStats() : null,\n };\n }\n}\n\n// Initialize the console when DOM is ready\ndocument.addEventListener('DOMContentLoaded', async () => {\n const console = new ClaudeCodeConsole();\n\n // Make console globally available for debugging\n window.claudeConsole = console;\n\n // Initialize the application\n await console.init();\n});\n\n// Export for module usage\nexport { ClaudeCodeConsole };\n"],"names":["WebSocketClient","TerminalEmulator","CommandHandler","SettingsManager","ClaudeCodeConsole","wsClient","terminal","commandHandler","settings","isInitialized","startTime","Date","now","messageCount","activeAgents","elements","statusInterval","uptimeInterval","setupEventListeners","init","showLoading","getDOMElements","consoleOutput","consoleInput","setupComponentInteractions","setupUIEventHandlers","applyInitialSettings","startStatusUpdates","hideLoading","showWelcomeMessage","get","autoConnect","console","log","error","showError","message","document","getElementById","settingsPanel","loadingOverlay","connectionStatus","statusIndicator","statusText","currentMode","uptime","memoryUsage","timestamp","clearConsole","fullscreenToggle","required","elementId","Error","on","command","processCommand","handleInterrupt","updateConnectionStatus","writeSuccess","setPrompt","info","writeWarning","code","writeError","reason","writeInfo","attempt","maxReconnectAttempts","handleIncomingMessage","notification","handleNotification","config","connect","url","token","disconnect","maxLines","setMaxLines","key","value","handleSettingChange","addEventListener","clear","toggleFullscreen","focus","window","hidden","updateTimestamp","cleanup","getStatus","getConnectionConfig","initializeSession","set","connected","connecting","status","className","textContent","method","handleStreamingOutput","params","startsWith","handleClaudeFlowNotification","handleAgentStatus","handleSwarmUpdate","handleMemoryUpdate","handleLogMessage","handleConnectionEstablished","content","type","streaming","streamText","write","mode","JSON","stringify","active","undefined","level","toUpperCase","documentElement","setAttribute","style","setProperty","setInterval","updateStatus","updateUptime","performance","memory","used","Math","round","usedJSHeapSize","hours","floor","minutes","seconds","toString","padStart","toLocaleTimeString","fullscreenElement","requestFullscreen","catch","err","exitFullscreen","loadingText","querySelector","classList","remove","add","alert","event","clearInterval","getStats","initialized","connection","claudeConsole"],"mappings":"AAKA,SAASA,eAAe,QAAQ,wBAAwB;AACxD,SAASC,gBAAgB,QAAQ,yBAAyB;AAC1D,SAASC,cAAc,QAAQ,uBAAuB;AACtD,SAASC,eAAe,QAAQ,gBAAgB;AAEhD,IAAA,AAAMC,oBAAN,MAAMA;IACJ,aAAc;QAEZ,IAAI,CAACC,QAAQ,GAAG,IAAIL;QACpB,IAAI,CAACM,QAAQ,GAAG;QAChB,IAAI,CAACC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E;YAChCvH,QAAQE,KAAK,CAAC,iBAAiBqH,MAAMrH,KAAK;YAC1C,IAAI,IAAI,CAAC5B,QAAQ,EAAE;gBACjB,IAAI,CAACA,QAAQ,CAACyD,UAAU,CAAC,CAAC,mBAAmB,EAAEwF,MAAMrH,KAAK,CAACE,OAAO,IAAImH,MAAMrH,KAAK,EAAE;YACrF;QACF;IACF;IAKAsD,UAAU;QAER,IAAI,IAAI,CAACxE,cAAc,EAAE;YACvBwI,cAAc,IAAI,CAACxI,cAAc;QACnC;QAEA,IAAI,IAAI,CAACC,cAAc,EAAE;YACvBuI,cAAc,IAAI,CAACvI,cAAc;QACnC;QAGA,IAAI,IAAI,CAACZ,QAAQ,EAAE;YACjB,IAAI,CAACA,QAAQ,CAACsE,UAAU;QAC1B;IACF;IAKA8E,WAAW;QACT,OAAO;YACLC,aAAa,IAAI,CAACjJ,aAAa;YAC/BoC,QAAQlC,KAAKC,GAAG,KAAK,IAAI,CAACF,SAAS;YACnCG,cAAc,IAAI,CAACA,YAAY;YAC/BC,cAAc,IAAI,CAACA,YAAY;YAC/B6I,YAAY,IAAI,CAACtJ,QAAQ,CAACoF,SAAS;YACnCnF,UAAU,IAAI,CAACA,QAAQ,GAAG,IAAI,CAACA,QAAQ,CAACmJ,QAAQ,KAAK;QACvD;IACF;AACF;AAGApH,SAAS4C,gBAAgB,CAAC,oBAAoB;IAC5C,MAAMjD,WAAU,IAAI5B;IAGpBiF,OAAOuE,aAAa,GAAG5H;IAGvB,MAAMA,SAAQb,IAAI;AACpB;AAGA,SAASf,iBAAiB,GAAG"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/daa-tools.js b/dist-cjs/src/ui/console/js/daa-tools.js deleted file mode 100644 index ce5ec7ef1d..0000000000 --- a/dist-cjs/src/ui/console/js/daa-tools.js +++ /dev/null @@ -1,891 +0,0 @@ -let DAATools = class DAATools { - constructor(){ - this.agents = new Map(); - this.resources = new Map(); - this.communications = new Map(); - this.consensus = new Map(); - this.isInitialized = false; - this.currentTab = 'agents'; - this.metrics = { - totalAgents: 0, - activeAgents: 0, - resourceUtilization: 0, - communicationLatency: 0, - consensusTime: 0, - faultCount: 0 - }; - this.init(); - } - init() { - if (this.isInitialized) return; - this.createDAAPanel(); - this.setupEventListeners(); - this.initializeMonitoring(); - this.isInitialized = true; - console.log('DAA Tools initialized'); - } - daa_agent_create(config) { - const agentId = this.generateAgentId(); - const agent = { - id: agentId, - type: config.type || 'generic', - capabilities: config.capabilities || [], - resources: config.resources || {}, - status: 'initializing', - created: Date.now(), - lastActivity: Date.now(), - tasks: [], - metadata: config.metadata || {} - }; - this.agents.set(agentId, agent); - this.metrics.totalAgents++; - this.metrics.activeAgents++; - this.initializeAgent(agent); - this.updateAgentsList(); - this.updateMetrics(); - return { - success: true, - agentId: agentId, - agent: agent - }; - } - daa_capability_match(requirements) { - const matches = []; - for (const [agentId, agent] of this.agents){ - if (agent.status !== 'active') continue; - const score = this.calculateCapabilityScore(agent.capabilities, requirements); - if (score > 0) { - matches.push({ - agentId, - agent, - score, - availableCapabilities: agent.capabilities.filter((cap)=>requirements.some((req)=>this.matchCapability(cap, req))) - }); - } - } - matches.sort((a, b)=>b.score - a.score); - this.updateCapabilityMatches(matches); - return { - success: true, - matches: matches, - totalCandidates: matches.length - }; - } - daa_resource_alloc(allocation) { - const resourceId = this.generateResourceId(); - const resource = { - id: resourceId, - type: allocation.type, - capacity: allocation.capacity, - allocated: 0, - assignments: new Map(), - priority: allocation.priority || 'medium', - created: Date.now(), - metadata: allocation.metadata || {} - }; - this.resources.set(resourceId, resource); - const allocationResult = this.allocateResource(resource, allocation); - this.updateResourceGraphs(); - this.updateMetrics(); - return { - success: allocationResult.success, - resourceId: resourceId, - allocation: allocationResult, - utilization: this.calculateResourceUtilization() - }; - } - daa_lifecycle_manage(agentId, action, params = {}) { - const agent = this.agents.get(agentId); - if (!agent) { - return { - success: false, - error: 'Agent not found' - }; - } - let result; - switch(action){ - case 'start': - result = this.startAgent(agent, params); - break; - case 'pause': - result = this.pauseAgent(agent, params); - break; - case 'resume': - result = this.resumeAgent(agent, params); - break; - case 'stop': - result = this.stopAgent(agent, params); - break; - case 'restart': - result = this.restartAgent(agent, params); - break; - case 'destroy': - result = this.destroyAgent(agent, params); - break; - default: - return { - success: false, - error: 'Unknown action' - }; - } - this.updateLifecycleVisualization(); - this.updateMetrics(); - return result; - } - daa_communication(fromAgent, toAgent, message, options = {}) { - const commId = this.generateCommId(); - const communication = { - id: commId, - from: fromAgent, - to: toAgent, - message: message, - timestamp: Date.now(), - type: options.type || 'direct', - priority: options.priority || 'normal', - status: 'pending', - latency: 0, - metadata: options.metadata || {} - }; - this.communications.set(commId, communication); - const result = this.processCommunication(communication); - this.updateCommunicationFlow(); - return { - success: result.success, - commId: commId, - latency: result.latency, - status: result.status - }; - } - daa_consensus(proposal, agents, options = {}) { - const consensusId = this.generateConsensusId(); - const consensus = { - id: consensusId, - proposal: proposal, - participants: agents, - votes: new Map(), - status: 'voting', - algorithm: options.algorithm || 'majority', - threshold: options.threshold || 0.5, - timeout: options.timeout || 30000, - started: Date.now(), - completed: null, - result: null - }; - this.consensus.set(consensusId, consensus); - const result = this.startConsensusProcess(consensus); - this.updateConsensusInterface(); - return { - success: result.success, - consensusId: consensusId, - expectedCompletion: result.expectedCompletion - }; - } - daa_fault_tolerance(faultType, affectedAgents, recoveryOptions = {}) { - const faultId = this.generateFaultId(); - const fault = { - id: faultId, - type: faultType, - affected: affectedAgents, - detected: Date.now(), - severity: recoveryOptions.severity || 'medium', - status: 'detected', - recoveryPlan: null, - recovered: null - }; - this.metrics.faultCount++; - const recoveryPlan = this.createRecoveryPlan(fault, recoveryOptions); - fault.recoveryPlan = recoveryPlan; - const recoveryResult = this.executeRecovery(fault); - this.updateFaultDashboard(); - return { - success: recoveryResult.success, - faultId: faultId, - recoveryPlan: recoveryPlan, - estimatedRecoveryTime: recoveryResult.estimatedTime - }; - } - daa_optimization(target, options = {}) { - const optimizationId = this.generateOptimizationId(); - const optimization = { - id: optimizationId, - target: target, - baseline: this.capturePerformanceBaseline(), - options: options, - started: Date.now(), - status: 'running', - improvements: [], - completed: null - }; - const result = this.performOptimization(optimization); - this.updateOptimizationDashboard(); - return { - success: result.success, - optimizationId: optimizationId, - improvements: result.improvements, - performanceGain: result.performanceGain - }; - } - createDAAPanel() { - const panel = document.createElement('div'); - panel.id = 'daa-tools-panel'; - panel.className = 'daa-panel'; - panel.innerHTML = ` -
-

DAA Control Center

-
-
- Agents - 0 -
-
- Resources - 0% -
-
- Latency - 0ms -
-
- Faults - 0 -
-
-
- -
- - - - -
- -
- ${this.createAgentsTab()} - ${this.createResourcesTab()} - ${this.createCommunicationTab()} - ${this.createMonitoringTab()} -
- `; - const consoleContainer = document.querySelector('.console-container') || document.body; - consoleContainer.appendChild(panel); - } - createAgentsTab() { - return ` -
-
-

Agent Creation

-
- - - -
-
- -
-

Agent Lifecycle

-
- -
-
- -
-

Active Agents

-
- -
-
-
- `; - } - createResourcesTab() { - return ` -
-
-

Resource Allocation

-
- - - - -
-
- -
-

Resource Graphs

-
- -
-
- -
-

Resource Status

-
- -
-
-
- `; - } - createCommunicationTab() { - return ` -
-
-

Communication Flow

-
- -
-
- -
-

Consensus Voting

-
- - - -
-
- -
-
-
- `; - } - createMonitoringTab() { - return ` -
-
-

Real-time Dashboard

-
-
-
-
Performance Metrics
- -
-
-
System Health
-
- -
-
-
-
Fault Tolerance
-
- -
-
-
-
Optimization
-
- -
-
-
-
-
-
- `; - } - generateAgentId() { - return `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - generateResourceId() { - return `resource-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - generateCommId() { - return `comm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - generateConsensusId() { - return `consensus-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - generateFaultId() { - return `fault-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - generateOptimizationId() { - return `opt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - calculateCapabilityScore(agentCapabilities, requirements) { - let score = 0; - for (const requirement of requirements){ - for (const capability of agentCapabilities){ - if (this.matchCapability(capability, requirement)) { - score += 1; - } - } - } - return score; - } - matchCapability(capability, requirement) { - return capability.toLowerCase().includes(requirement.toLowerCase()); - } - calculateResourceUtilization() { - let totalCapacity = 0; - let totalAllocated = 0; - for (const [_, resource] of this.resources){ - totalCapacity += resource.capacity; - totalAllocated += resource.allocated; - } - return totalCapacity > 0 ? Math.round(totalAllocated / totalCapacity * 100) : 0; - } - initializeAgent(agent) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - } - startAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { - success: true, - status: 'active' - }; - } - pauseAgent(agent, params) { - agent.status = 'paused'; - return { - success: true, - status: 'paused' - }; - } - resumeAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { - success: true, - status: 'active' - }; - } - stopAgent(agent, params) { - agent.status = 'stopped'; - this.metrics.activeAgents--; - return { - success: true, - status: 'stopped' - }; - } - restartAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { - success: true, - status: 'active' - }; - } - destroyAgent(agent, params) { - this.agents.delete(agent.id); - this.metrics.totalAgents--; - this.metrics.activeAgents--; - return { - success: true, - status: 'destroyed' - }; - } - allocateResource(resource, allocation) { - const requested = allocation.amount || 0; - const available = resource.capacity - resource.allocated; - if (requested <= available) { - resource.allocated += requested; - return { - success: true, - allocated: requested, - remaining: available - requested - }; - } else { - return { - success: false, - error: 'Insufficient resources', - available: available - }; - } - } - processCommunication(communication) { - const latency = Math.random() * 100; - communication.latency = latency; - communication.status = 'completed'; - this.metrics.communicationLatency = (this.metrics.communicationLatency + latency) / 2; - return { - success: true, - latency: latency, - status: 'completed' - }; - } - startConsensusProcess(consensus) { - const expectedTime = consensus.timeout || 30000; - setTimeout(()=>{ - this.completeConsensus(consensus); - }, expectedTime); - return { - success: true, - expectedCompletion: Date.now() + expectedTime - }; - } - completeConsensus(consensus) { - consensus.status = 'completed'; - consensus.completed = Date.now(); - consensus.result = 'approved'; - this.metrics.consensusTime = consensus.completed - consensus.started; - this.updateConsensusInterface(); - } - createRecoveryPlan(fault, options) { - return { - steps: [ - 'Isolate affected agents', - 'Backup current state', - 'Restart affected components', - 'Verify system integrity', - 'Resume normal operations' - ], - estimatedTime: 60000, - priority: fault.severity - }; - } - executeRecovery(fault) { - fault.status = 'recovering'; - setTimeout(()=>{ - fault.status = 'recovered'; - fault.recovered = Date.now(); - this.updateFaultDashboard(); - }, fault.recoveryPlan.estimatedTime); - return { - success: true, - estimatedTime: fault.recoveryPlan.estimatedTime - }; - } - capturePerformanceBaseline() { - return { - timestamp: Date.now(), - metrics: { - ...this.metrics - }, - agentCount: this.agents.size, - resourceCount: this.resources.size - }; - } - performOptimization(optimization) { - const improvements = [ - { - type: 'agent_efficiency', - improvement: 15 - }, - { - type: 'resource_allocation', - improvement: 12 - }, - { - type: 'communication_latency', - improvement: 8 - } - ]; - optimization.improvements = improvements; - optimization.status = 'completed'; - optimization.completed = Date.now(); - const totalGain = improvements.reduce((sum, imp)=>sum + imp.improvement, 0) / improvements.length; - return { - success: true, - improvements: improvements, - performanceGain: totalGain - }; - } - updateAgentsList() { - const agentsList = document.getElementById('daa-agents-list'); - if (!agentsList) return; - agentsList.innerHTML = ''; - for (const [agentId, agent] of this.agents){ - const agentElement = document.createElement('div'); - agentElement.className = 'daa-agent-card'; - agentElement.innerHTML = ` -
- ${agentId} - ${agent.status} -
-
-
${agent.type}
-
${agent.capabilities.join(', ')}
-
-
- - - -
- `; - agentsList.appendChild(agentElement); - } - } - updateMetrics() { - const elements = { - 'daa-agents-count': this.metrics.activeAgents, - 'daa-resources-util': `${this.metrics.resourceUtilization}%`, - 'daa-latency': `${Math.round(this.metrics.communicationLatency)}ms`, - 'daa-faults': this.metrics.faultCount - }; - for (const [id, value] of Object.entries(elements)){ - const element = document.getElementById(id); - if (element) { - element.textContent = value; - } - } - } - updateCapabilityMatches(matches) { - console.log('Capability matches:', matches); - } - updateResourceGraphs() { - const canvas = document.getElementById('daa-resource-chart'); - if (!canvas) return; - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - const resources = Array.from(this.resources.values()); - const barWidth = canvas.width / Math.max(resources.length, 1); - resources.forEach((resource, index)=>{ - const utilization = resource.capacity > 0 ? resource.allocated / resource.capacity : 0; - const barHeight = utilization * canvas.height; - ctx.fillStyle = utilization > 0.8 ? '#ff4444' : utilization > 0.5 ? '#ffaa00' : '#44ff44'; - ctx.fillRect(index * barWidth, canvas.height - barHeight, barWidth - 2, barHeight); - ctx.fillStyle = '#000'; - ctx.font = '12px Arial'; - ctx.fillText(resource.type, index * barWidth + 5, canvas.height - 5); - }); - } - updateLifecycleVisualization() { - const visualization = document.getElementById('daa-lifecycle-visualization'); - if (!visualization) return; - const statusCounts = {}; - for (const [_, agent] of this.agents){ - statusCounts[agent.status] = (statusCounts[agent.status] || 0) + 1; - } - visualization.innerHTML = Object.entries(statusCounts).map(([status, count])=>`
- ${status} - ${count} -
`).join(''); - } - updateCommunicationFlow() { - const svg = document.getElementById('daa-comm-diagram'); - if (!svg) return; - svg.innerHTML = ''; - const agents = Array.from(this.agents.values()); - const centerX = 300; - const centerY = 200; - const radius = 150; - agents.forEach((agent, index)=>{ - const angle = index * 2 * Math.PI / agents.length; - const x = centerX + radius * Math.cos(angle); - const y = centerY + radius * Math.sin(angle); - const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); - circle.setAttribute('cx', x); - circle.setAttribute('cy', y); - circle.setAttribute('r', 20); - circle.setAttribute('fill', '#4CAF50'); - circle.setAttribute('stroke', '#333'); - circle.setAttribute('stroke-width', '2'); - svg.appendChild(circle); - const text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - text.setAttribute('x', x); - text.setAttribute('y', y + 5); - text.setAttribute('text-anchor', 'middle'); - text.setAttribute('font-size', '12'); - text.setAttribute('fill', '#fff'); - text.textContent = agent.id.split('-')[0]; - svg.appendChild(text); - }); - } - updateConsensusInterface() { - const consensusStatus = document.getElementById('daa-consensus-status'); - if (!consensusStatus) return; - consensusStatus.innerHTML = Array.from(this.consensus.values()).map((consensus)=>`
-
${consensus.proposal}
-
${consensus.status}
-
-
-
-
`).join(''); - } - updateFaultDashboard() { - const faultStatus = document.getElementById('daa-fault-status'); - if (!faultStatus) return; - faultStatus.innerHTML = ` -
- Total Faults - ${this.metrics.faultCount} -
-
- Recovery Rate - 95% -
-
- MTTR - 2.3min -
- `; - } - updateOptimizationDashboard() { - const optimizationStatus = document.getElementById('daa-optimization-status'); - if (!optimizationStatus) return; - optimizationStatus.innerHTML = ` -
- Performance Gain - +15% -
-
- Resource Efficiency - +12% -
-
- Latency Reduction - -8% -
- `; - } - setupEventListeners() { - document.addEventListener('click', (e)=>{ - if (e.target.classList.contains('daa-tab')) { - this.switchTab(e.target.dataset.tab); - } - }); - document.addEventListener('click', (e)=>{ - if (e.target.id === 'daa-create-agent') { - this.handleCreateAgent(); - } - }); - document.addEventListener('click', (e)=>{ - if (e.target.id === 'daa-allocate-resource') { - this.handleAllocateResource(); - } - }); - document.addEventListener('click', (e)=>{ - if (e.target.id === 'daa-start-consensus') { - this.handleStartConsensus(); - } - }); - } - switchTab(tabName) { - document.querySelectorAll('.daa-tab-content').forEach((tab)=>{ - tab.classList.remove('active'); - }); - document.querySelectorAll('.daa-tab').forEach((tab)=>{ - tab.classList.remove('active'); - }); - document.getElementById(`daa-${tabName}-tab`).classList.add('active'); - document.querySelector(`.daa-tab[data-tab="${tabName}"]`).classList.add('active'); - this.currentTab = tabName; - } - handleCreateAgent() { - const type = document.getElementById('daa-agent-type').value; - const capabilities = document.getElementById('daa-agent-capabilities').value.split(',').map((s)=>s.trim()); - const result = this.daa_agent_create({ - type: type, - capabilities: capabilities, - resources: { - cpu: 1, - memory: 512 - } - }); - if (result.success) { - console.log('Agent created:', result.agentId); - } - } - handleAllocateResource() { - const type = document.getElementById('daa-resource-type').value; - const capacity = parseInt(document.getElementById('daa-resource-capacity').value) || 100; - const priority = document.getElementById('daa-resource-priority').value; - const result = this.daa_resource_alloc({ - type: type, - capacity: capacity, - priority: priority, - amount: capacity * 0.5 - }); - if (result.success) { - console.log('Resource allocated:', result.resourceId); - } - } - handleStartConsensus() { - const proposal = document.getElementById('daa-consensus-proposal').value; - const algorithm = document.getElementById('daa-consensus-algorithm').value; - if (!proposal.trim()) { - alert('Please enter a proposal'); - return; - } - const agents = Array.from(this.agents.keys()); - const result = this.daa_consensus(proposal, agents, { - algorithm: algorithm, - timeout: 30000 - }); - if (result.success) { - console.log('Consensus started:', result.consensusId); - } - } - initializeMonitoring() { - setInterval(()=>{ - this.updateMetrics(); - this.updateResourceGraphs(); - this.updateLifecycleVisualization(); - }, 5000); - this.createSampleData(); - } - createSampleData() { - this.daa_agent_create({ - type: 'researcher', - capabilities: [ - 'data_analysis', - 'research', - 'documentation' - ], - resources: { - cpu: 2, - memory: 1024 - } - }); - this.daa_agent_create({ - type: 'coder', - capabilities: [ - "javascript", - 'python', - 'testing' - ], - resources: { - cpu: 4, - memory: 2048 - } - }); - this.daa_resource_alloc({ - type: 'cpu', - capacity: 100, - priority: 'high', - amount: 30 - }); - this.daa_resource_alloc({ - type: 'memory', - capacity: 8192, - priority: 'medium', - amount: 2048 - }); - } -}; -let daaTools; -if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', ()=>{ - daaTools = new DAATools(); - }); -} else { - daaTools = new DAATools(); -} -if (typeof module !== 'undefined' && module.exports) { - module.exports = DAATools; -} - -//# sourceMappingURL=daa-tools.js.map \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/daa-tools.js.map b/dist-cjs/src/ui/console/js/daa-tools.js.map deleted file mode 100644 index 5a6bf05e40..0000000000 --- a/dist-cjs/src/ui/console/js/daa-tools.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../../../src/ui/console/js/daa-tools.js"],"sourcesContent":["/**\n * Dynamic Agent Architecture (DAA) Tools\n * Implementation of 8 core DAA tools for Claude Flow\n */\n\nclass DAATools {\n constructor() {\n this.agents = new Map();\n this.resources = new Map();\n this.communications = new Map();\n this.consensus = new Map();\n this.isInitialized = false;\n this.currentTab = 'agents';\n\n // Performance metrics\n this.metrics = {\n totalAgents: 0,\n activeAgents: 0,\n resourceUtilization: 0,\n communicationLatency: 0,\n consensusTime: 0,\n faultCount: 0,\n };\n\n this.init();\n }\n\n init() {\n if (this.isInitialized) return;\n\n this.createDAAPanel();\n this.setupEventListeners();\n this.initializeMonitoring();\n this.isInitialized = true;\n\n console.log('DAA Tools initialized');\n }\n\n // Tool 1: Dynamic Agent Creation\n daa_agent_create(config) {\n const agentId = this.generateAgentId();\n const agent = {\n id: agentId,\n type: config.type || 'generic',\n capabilities: config.capabilities || [],\n resources: config.resources || {},\n status: 'initializing',\n created: Date.now(),\n lastActivity: Date.now(),\n tasks: [],\n metadata: config.metadata || {},\n };\n\n this.agents.set(agentId, agent);\n this.metrics.totalAgents++;\n this.metrics.activeAgents++;\n\n // Lifecycle management\n this.initializeAgent(agent);\n\n // Update UI\n this.updateAgentsList();\n this.updateMetrics();\n\n return {\n success: true,\n agentId: agentId,\n agent: agent,\n };\n }\n\n // Tool 2: Capability Matching System\n daa_capability_match(requirements) {\n const matches = [];\n\n for (const [agentId, agent] of this.agents) {\n if (agent.status !== 'active') continue;\n\n const score = this.calculateCapabilityScore(agent.capabilities, requirements);\n if (score > 0) {\n matches.push({\n agentId,\n agent,\n score,\n availableCapabilities: agent.capabilities.filter((cap) =>\n requirements.some((req) => this.matchCapability(cap, req)),\n ),\n });\n }\n }\n\n // Sort by score descending\n matches.sort((a, b) => b.score - a.score);\n\n this.updateCapabilityMatches(matches);\n\n return {\n success: true,\n matches: matches,\n totalCandidates: matches.length,\n };\n }\n\n // Tool 3: Resource Allocation Management\n daa_resource_alloc(allocation) {\n const resourceId = this.generateResourceId();\n const resource = {\n id: resourceId,\n type: allocation.type,\n capacity: allocation.capacity,\n allocated: 0,\n assignments: new Map(),\n priority: allocation.priority || 'medium',\n created: Date.now(),\n metadata: allocation.metadata || {},\n };\n\n this.resources.set(resourceId, resource);\n\n // Perform allocation\n const allocationResult = this.allocateResource(resource, allocation);\n\n // Update visualizations\n this.updateResourceGraphs();\n this.updateMetrics();\n\n return {\n success: allocationResult.success,\n resourceId: resourceId,\n allocation: allocationResult,\n utilization: this.calculateResourceUtilization(),\n };\n }\n\n // Tool 4: Agent Lifecycle Management\n daa_lifecycle_manage(agentId, action, params = {}) {\n const agent = this.agents.get(agentId);\n if (!agent) {\n return { success: false, error: 'Agent not found' };\n }\n\n let result;\n\n switch (action) {\n case 'start':\n result = this.startAgent(agent, params);\n break;\n case 'pause':\n result = this.pauseAgent(agent, params);\n break;\n case 'resume':\n result = this.resumeAgent(agent, params);\n break;\n case 'stop':\n result = this.stopAgent(agent, params);\n break;\n case 'restart':\n result = this.restartAgent(agent, params);\n break;\n case 'destroy':\n result = this.destroyAgent(agent, params);\n break;\n default:\n return { success: false, error: 'Unknown action' };\n }\n\n // Update lifecycle visualization\n this.updateLifecycleVisualization();\n this.updateMetrics();\n\n return result;\n }\n\n // Tool 5: Inter-agent Communication\n daa_communication(fromAgent, toAgent, message, options = {}) {\n const commId = this.generateCommId();\n const communication = {\n id: commId,\n from: fromAgent,\n to: toAgent,\n message: message,\n timestamp: Date.now(),\n type: options.type || 'direct',\n priority: options.priority || 'normal',\n status: 'pending',\n latency: 0,\n metadata: options.metadata || {},\n };\n\n this.communications.set(commId, communication);\n\n // Process communication\n const result = this.processCommunication(communication);\n\n // Update communication flow diagrams\n this.updateCommunicationFlow();\n\n return {\n success: result.success,\n commId: commId,\n latency: result.latency,\n status: result.status,\n };\n }\n\n // Tool 6: Consensus Mechanisms\n daa_consensus(proposal, agents, options = {}) {\n const consensusId = this.generateConsensusId();\n const consensus = {\n id: consensusId,\n proposal: proposal,\n participants: agents,\n votes: new Map(),\n status: 'voting',\n algorithm: options.algorithm || 'majority',\n threshold: options.threshold || 0.5,\n timeout: options.timeout || 30000,\n started: Date.now(),\n completed: null,\n result: null,\n };\n\n this.consensus.set(consensusId, consensus);\n\n // Start consensus process\n const result = this.startConsensusProcess(consensus);\n\n // Update consensus interface\n this.updateConsensusInterface();\n\n return {\n success: result.success,\n consensusId: consensusId,\n expectedCompletion: result.expectedCompletion,\n };\n }\n\n // Tool 7: Fault Tolerance and Recovery\n daa_fault_tolerance(faultType, affectedAgents, recoveryOptions = {}) {\n const faultId = this.generateFaultId();\n const fault = {\n id: faultId,\n type: faultType,\n affected: affectedAgents,\n detected: Date.now(),\n severity: recoveryOptions.severity || 'medium',\n status: 'detected',\n recoveryPlan: null,\n recovered: null,\n };\n\n this.metrics.faultCount++;\n\n // Analyze fault and create recovery plan\n const recoveryPlan = this.createRecoveryPlan(fault, recoveryOptions);\n fault.recoveryPlan = recoveryPlan;\n\n // Execute recovery\n const recoveryResult = this.executeRecovery(fault);\n\n // Update fault tolerance dashboard\n this.updateFaultDashboard();\n\n return {\n success: recoveryResult.success,\n faultId: faultId,\n recoveryPlan: recoveryPlan,\n estimatedRecoveryTime: recoveryResult.estimatedTime,\n };\n }\n\n // Tool 8: Performance Optimization\n daa_optimization(target, options = {}) {\n const optimizationId = this.generateOptimizationId();\n const optimization = {\n id: optimizationId,\n target: target,\n baseline: this.capturePerformanceBaseline(),\n options: options,\n started: Date.now(),\n status: 'running',\n improvements: [],\n completed: null,\n };\n\n // Perform optimization\n const result = this.performOptimization(optimization);\n\n // Update optimization dashboard\n this.updateOptimizationDashboard();\n\n return {\n success: result.success,\n optimizationId: optimizationId,\n improvements: result.improvements,\n performanceGain: result.performanceGain,\n };\n }\n\n // UI Creation Methods\n createDAAPanel() {\n const panel = document.createElement('div');\n panel.id = 'daa-tools-panel';\n panel.className = 'daa-panel';\n\n panel.innerHTML = `\n
\n

DAA Control Center

\n
\n
\n Agents\n 0\n
\n
\n Resources\n 0%\n
\n
\n Latency\n 0ms\n
\n
\n Faults\n 0\n
\n
\n
\n \n
\n \n \n \n \n
\n \n
\n ${this.createAgentsTab()}\n ${this.createResourcesTab()}\n ${this.createCommunicationTab()}\n ${this.createMonitoringTab()}\n
\n `;\n\n // Add to console\n const consoleContainer = document.querySelector('.console-container') || document.body;\n consoleContainer.appendChild(panel);\n }\n\n createAgentsTab() {\n return `\n
\n
\n

Agent Creation

\n
\n \n \n \n
\n
\n \n
\n

Agent Lifecycle

\n
\n \n
\n
\n \n
\n

Active Agents

\n
\n \n
\n
\n
\n `;\n }\n\n createResourcesTab() {\n return `\n
\n
\n

Resource Allocation

\n
\n \n \n \n \n
\n
\n \n
\n

Resource Graphs

\n
\n \n
\n
\n \n
\n

Resource Status

\n
\n \n
\n
\n
\n `;\n }\n\n createCommunicationTab() {\n return `\n
\n
\n

Communication Flow

\n
\n \n
\n
\n \n
\n

Consensus Voting

\n
\n \n \n \n
\n
\n \n
\n
\n
\n `;\n }\n\n createMonitoringTab() {\n return `\n
\n
\n

Real-time Dashboard

\n
\n
\n
\n
Performance Metrics
\n \n
\n
\n
System Health
\n
\n \n
\n
\n
\n
Fault Tolerance
\n
\n \n
\n
\n
\n
Optimization
\n
\n \n
\n
\n
\n
\n
\n
\n `;\n }\n\n // Helper Methods\n generateAgentId() {\n return `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n generateResourceId() {\n return `resource-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n generateCommId() {\n return `comm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n generateConsensusId() {\n return `consensus-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n generateFaultId() {\n return `fault-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n generateOptimizationId() {\n return `opt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n calculateCapabilityScore(agentCapabilities, requirements) {\n let score = 0;\n for (const requirement of requirements) {\n for (const capability of agentCapabilities) {\n if (this.matchCapability(capability, requirement)) {\n score += 1;\n }\n }\n }\n return score;\n }\n\n matchCapability(capability, requirement) {\n // Simple string matching - can be enhanced with fuzzy matching\n return capability.toLowerCase().includes(requirement.toLowerCase());\n }\n\n calculateResourceUtilization() {\n let totalCapacity = 0;\n let totalAllocated = 0;\n\n for (const [_, resource] of this.resources) {\n totalCapacity += resource.capacity;\n totalAllocated += resource.allocated;\n }\n\n return totalCapacity > 0 ? Math.round((totalAllocated / totalCapacity) * 100) : 0;\n }\n\n // Implementation methods (simplified for brevity)\n initializeAgent(agent) {\n agent.status = 'active';\n agent.lastActivity = Date.now();\n }\n\n startAgent(agent, params) {\n agent.status = 'active';\n agent.lastActivity = Date.now();\n return { success: true, status: 'active' };\n }\n\n pauseAgent(agent, params) {\n agent.status = 'paused';\n return { success: true, status: 'paused' };\n }\n\n resumeAgent(agent, params) {\n agent.status = 'active';\n agent.lastActivity = Date.now();\n return { success: true, status: 'active' };\n }\n\n stopAgent(agent, params) {\n agent.status = 'stopped';\n this.metrics.activeAgents--;\n return { success: true, status: 'stopped' };\n }\n\n restartAgent(agent, params) {\n agent.status = 'active';\n agent.lastActivity = Date.now();\n return { success: true, status: 'active' };\n }\n\n destroyAgent(agent, params) {\n this.agents.delete(agent.id);\n this.metrics.totalAgents--;\n this.metrics.activeAgents--;\n return { success: true, status: 'destroyed' };\n }\n\n allocateResource(resource, allocation) {\n // Simple allocation logic\n const requested = allocation.amount || 0;\n const available = resource.capacity - resource.allocated;\n\n if (requested <= available) {\n resource.allocated += requested;\n return { success: true, allocated: requested, remaining: available - requested };\n } else {\n return { success: false, error: 'Insufficient resources', available: available };\n }\n }\n\n processCommunication(communication) {\n // Simulate communication processing\n const latency = Math.random() * 100; // 0-100ms\n communication.latency = latency;\n communication.status = 'completed';\n\n this.metrics.communicationLatency = (this.metrics.communicationLatency + latency) / 2;\n\n return { success: true, latency: latency, status: 'completed' };\n }\n\n startConsensusProcess(consensus) {\n // Simulate consensus process\n const expectedTime = consensus.timeout || 30000;\n\n setTimeout(() => {\n this.completeConsensus(consensus);\n }, expectedTime);\n\n return { success: true, expectedCompletion: Date.now() + expectedTime };\n }\n\n completeConsensus(consensus) {\n consensus.status = 'completed';\n consensus.completed = Date.now();\n consensus.result = 'approved'; // Simplified\n\n this.metrics.consensusTime = consensus.completed - consensus.started;\n this.updateConsensusInterface();\n }\n\n createRecoveryPlan(fault, options) {\n return {\n steps: [\n 'Isolate affected agents',\n 'Backup current state',\n 'Restart affected components',\n 'Verify system integrity',\n 'Resume normal operations',\n ],\n estimatedTime: 60000, // 1 minute\n priority: fault.severity,\n };\n }\n\n executeRecovery(fault) {\n // Simulate recovery execution\n fault.status = 'recovering';\n\n setTimeout(() => {\n fault.status = 'recovered';\n fault.recovered = Date.now();\n this.updateFaultDashboard();\n }, fault.recoveryPlan.estimatedTime);\n\n return { success: true, estimatedTime: fault.recoveryPlan.estimatedTime };\n }\n\n capturePerformanceBaseline() {\n return {\n timestamp: Date.now(),\n metrics: { ...this.metrics },\n agentCount: this.agents.size,\n resourceCount: this.resources.size,\n };\n }\n\n performOptimization(optimization) {\n // Simulate optimization process\n const improvements = [\n { type: 'agent_efficiency', improvement: 15 },\n { type: 'resource_allocation', improvement: 12 },\n { type: 'communication_latency', improvement: 8 },\n ];\n\n optimization.improvements = improvements;\n optimization.status = 'completed';\n optimization.completed = Date.now();\n\n const totalGain =\n improvements.reduce((sum, imp) => sum + imp.improvement, 0) / improvements.length;\n\n return { success: true, improvements: improvements, performanceGain: totalGain };\n }\n\n // UI Update Methods\n updateAgentsList() {\n const agentsList = document.getElementById('daa-agents-list');\n if (!agentsList) return;\n\n agentsList.innerHTML = '';\n\n for (const [agentId, agent] of this.agents) {\n const agentElement = document.createElement('div');\n agentElement.className = 'daa-agent-card';\n agentElement.innerHTML = `\n
\n ${agentId}\n ${agent.status}\n
\n
\n
${agent.type}
\n
${agent.capabilities.join(', ')}
\n
\n
\n \n \n \n
\n `;\n agentsList.appendChild(agentElement);\n }\n }\n\n updateMetrics() {\n const elements = {\n 'daa-agents-count': this.metrics.activeAgents,\n 'daa-resources-util': `${this.metrics.resourceUtilization}%`,\n 'daa-latency': `${Math.round(this.metrics.communicationLatency)}ms`,\n 'daa-faults': this.metrics.faultCount,\n };\n\n for (const [id, value] of Object.entries(elements)) {\n const element = document.getElementById(id);\n if (element) {\n element.textContent = value;\n }\n }\n }\n\n updateCapabilityMatches(matches) {\n // Update capability matching visualization\n console.log('Capability matches:', matches);\n }\n\n updateResourceGraphs() {\n const canvas = document.getElementById('daa-resource-chart');\n if (!canvas) return;\n\n const ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // Draw resource utilization bars\n const resources = Array.from(this.resources.values());\n const barWidth = canvas.width / Math.max(resources.length, 1);\n\n resources.forEach((resource, index) => {\n const utilization = resource.capacity > 0 ? resource.allocated / resource.capacity : 0;\n const barHeight = utilization * canvas.height;\n\n ctx.fillStyle = utilization > 0.8 ? '#ff4444' : utilization > 0.5 ? '#ffaa00' : '#44ff44';\n ctx.fillRect(index * barWidth, canvas.height - barHeight, barWidth - 2, barHeight);\n\n // Resource label\n ctx.fillStyle = '#000';\n ctx.font = '12px Arial';\n ctx.fillText(resource.type, index * barWidth + 5, canvas.height - 5);\n });\n }\n\n updateLifecycleVisualization() {\n const visualization = document.getElementById('daa-lifecycle-visualization');\n if (!visualization) return;\n\n const statusCounts = {};\n for (const [_, agent] of this.agents) {\n statusCounts[agent.status] = (statusCounts[agent.status] || 0) + 1;\n }\n\n visualization.innerHTML = Object.entries(statusCounts)\n .map(\n ([status, count]) =>\n `
\n ${status}\n ${count}\n
`,\n )\n .join('');\n }\n\n updateCommunicationFlow() {\n const svg = document.getElementById('daa-comm-diagram');\n if (!svg) return;\n\n // Clear existing content\n svg.innerHTML = '';\n\n // Draw communication flow visualization\n const agents = Array.from(this.agents.values());\n const centerX = 300;\n const centerY = 200;\n const radius = 150;\n\n agents.forEach((agent, index) => {\n const angle = (index * 2 * Math.PI) / agents.length;\n const x = centerX + radius * Math.cos(angle);\n const y = centerY + radius * Math.sin(angle);\n\n // Draw agent node\n const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n circle.setAttribute('cx', x);\n circle.setAttribute('cy', y);\n circle.setAttribute('r', 20);\n circle.setAttribute('fill', '#4CAF50');\n circle.setAttribute('stroke', '#333');\n circle.setAttribute('stroke-width', '2');\n svg.appendChild(circle);\n\n // Draw agent label\n const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');\n text.setAttribute('x', x);\n text.setAttribute('y', y + 5);\n text.setAttribute('text-anchor', 'middle');\n text.setAttribute('font-size', '12');\n text.setAttribute('fill', '#fff');\n text.textContent = agent.id.split('-')[0];\n svg.appendChild(text);\n });\n }\n\n updateConsensusInterface() {\n const consensusStatus = document.getElementById('daa-consensus-status');\n if (!consensusStatus) return;\n\n consensusStatus.innerHTML = Array.from(this.consensus.values())\n .map(\n (consensus) =>\n `
\n
${consensus.proposal}
\n
${consensus.status}
\n
\n
\n
\n
`,\n )\n .join('');\n }\n\n updateFaultDashboard() {\n const faultStatus = document.getElementById('daa-fault-status');\n if (!faultStatus) return;\n\n faultStatus.innerHTML = `\n
\n Total Faults\n ${this.metrics.faultCount}\n
\n
\n Recovery Rate\n 95%\n
\n
\n MTTR\n 2.3min\n
\n `;\n }\n\n updateOptimizationDashboard() {\n const optimizationStatus = document.getElementById('daa-optimization-status');\n if (!optimizationStatus) return;\n\n optimizationStatus.innerHTML = `\n
\n Performance Gain\n +15%\n
\n
\n Resource Efficiency\n +12%\n
\n
\n Latency Reduction\n -8%\n
\n `;\n }\n\n setupEventListeners() {\n // Tab switching\n document.addEventListener('click', (e) => {\n if (e.target.classList.contains('daa-tab')) {\n this.switchTab(e.target.dataset.tab);\n }\n });\n\n // Agent creation\n document.addEventListener('click', (e) => {\n if (e.target.id === 'daa-create-agent') {\n this.handleCreateAgent();\n }\n });\n\n // Resource allocation\n document.addEventListener('click', (e) => {\n if (e.target.id === 'daa-allocate-resource') {\n this.handleAllocateResource();\n }\n });\n\n // Consensus voting\n document.addEventListener('click', (e) => {\n if (e.target.id === 'daa-start-consensus') {\n this.handleStartConsensus();\n }\n });\n }\n\n switchTab(tabName) {\n // Hide all tabs\n document.querySelectorAll('.daa-tab-content').forEach((tab) => {\n tab.classList.remove('active');\n });\n\n document.querySelectorAll('.daa-tab').forEach((tab) => {\n tab.classList.remove('active');\n });\n\n // Show selected tab\n document.getElementById(`daa-${tabName}-tab`).classList.add('active');\n document.querySelector(`.daa-tab[data-tab=\"${tabName}\"]`).classList.add('active');\n\n this.currentTab = tabName;\n }\n\n handleCreateAgent() {\n const type = document.getElementById('daa-agent-type').value;\n const capabilities = document\n .getElementById('daa-agent-capabilities')\n .value.split(',')\n .map((s) => s.trim());\n\n const result = this.daa_agent_create({\n type: type,\n capabilities: capabilities,\n resources: { cpu: 1, memory: 512 },\n });\n\n if (result.success) {\n console.log('Agent created:', result.agentId);\n }\n }\n\n handleAllocateResource() {\n const type = document.getElementById('daa-resource-type').value;\n const capacity = parseInt(document.getElementById('daa-resource-capacity').value) || 100;\n const priority = document.getElementById('daa-resource-priority').value;\n\n const result = this.daa_resource_alloc({\n type: type,\n capacity: capacity,\n priority: priority,\n amount: capacity * 0.5, // Allocate 50% initially\n });\n\n if (result.success) {\n console.log('Resource allocated:', result.resourceId);\n }\n }\n\n handleStartConsensus() {\n const proposal = document.getElementById('daa-consensus-proposal').value;\n const algorithm = document.getElementById('daa-consensus-algorithm').value;\n\n if (!proposal.trim()) {\n alert('Please enter a proposal');\n return;\n }\n\n const agents = Array.from(this.agents.keys());\n const result = this.daa_consensus(proposal, agents, {\n algorithm: algorithm,\n timeout: 30000,\n });\n\n if (result.success) {\n console.log('Consensus started:', result.consensusId);\n }\n }\n\n initializeMonitoring() {\n // Start monitoring intervals\n setInterval(() => {\n this.updateMetrics();\n this.updateResourceGraphs();\n this.updateLifecycleVisualization();\n }, 5000);\n\n // Initialize with some sample data\n this.createSampleData();\n }\n\n createSampleData() {\n // Create sample agents\n this.daa_agent_create({\n type: 'researcher',\n capabilities: ['data_analysis', 'research', 'documentation'],\n resources: { cpu: 2, memory: 1024 },\n });\n\n this.daa_agent_create({\n type: 'coder',\n capabilities: ['javascript', 'python', 'testing'],\n resources: { cpu: 4, memory: 2048 },\n });\n\n // Create sample resources\n this.daa_resource_alloc({\n type: 'cpu',\n capacity: 100,\n priority: 'high',\n amount: 30,\n });\n\n this.daa_resource_alloc({\n type: 'memory',\n capacity: 8192,\n priority: 'medium',\n amount: 2048,\n });\n }\n}\n\n// Initialize DAA Tools\nlet daaTools;\n\n// Initialize when DOM is ready\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n daaTools = new DAATools();\n });\n} else {\n daaTools = new DAATools();\n}\n\n// Export for use in other modules\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = DAATools;\n}\n"],"names":["DAATools","agents","Map","resources","communications","consensus","isInitialized","currentTab","metrics","totalAgents","activeAgents","resourceUtilization","communicationLatency","consensusTime","faultCount","init","createDAAPanel","setupEventListeners","initializeMonitoring","console","log","daa_agent_create","config","agentId","generateAgentId","agent","id","type","capabilities","status","created","Date","now","lastActivity","tasks","metadata","set","initializeAgent","updateAgentsList","updateMetrics","success","daa_capability_match","requirements","matches","score","calculateCapabilityScore","push","availableCapabilities","filter","cap","some","req","matchCapability","sort","a","b","updateCapabilityMatches","totalCandidates","length","daa_resource_alloc","allocation","resourceId","generateResourceId","resource","capacity","allocated","assignments","priority","allocationResult","allocateResource","updateResourceGraphs","utilization","calculateResourceUtilization","daa_lifecycle_manage","action","params","get","error","result","startAgent","pauseAgent","resumeAgent","stopAgent","restartAgent","destroyAgent","updateLifecycleVisualization","daa_communication","fromAgent","toAgent","message","options","commId","generateCommId","communication","from","to","timestamp","latency","processCommunication","updateCommunicationFlow","daa_consensus","proposal","consensusId","generateConsensusId","participants","votes","algorithm","threshold","timeout","started","completed","startConsensusProcess","updateConsensusInterface","expectedCompletion","daa_fault_tolerance","faultType","affectedAgents","recoveryOptions","faultId","generateFaultId","fault","affected","detected","severity","recoveryPlan","recovered","createRecoveryPlan","recoveryResult","executeRecovery","updateFaultDashboard","estimatedRecoveryTime","estimatedTime","daa_optimization","target","optimizationId","generateOptimizationId","optimization","baseline","capturePerformanceBaseline","improvements","performOptimization","updateOptimizationDashboard","performanceGain","panel","document","createElement","className","innerHTML","createAgentsTab","createResourcesTab","createCommunicationTab","createMonitoringTab","consoleContainer","querySelector","body","appendChild","Math","random","toString","substr","agentCapabilities","requirement","capability","toLowerCase","includes","totalCapacity","totalAllocated","_","round","delete","requested","amount","available","remaining","expectedTime","setTimeout","completeConsensus","steps","agentCount","size","resourceCount","improvement","totalGain","reduce","sum","imp","agentsList","getElementById","agentElement","join","elements","value","Object","entries","element","textContent","canvas","ctx","getContext","clearRect","width","height","Array","values","barWidth","max","forEach","index","barHeight","fillStyle","fillRect","font","fillText","visualization","statusCounts","map","count","svg","centerX","centerY","radius","angle","PI","x","cos","y","sin","circle","createElementNS","setAttribute","text","split","consensusStatus","faultStatus","optimizationStatus","addEventListener","e","classList","contains","switchTab","dataset","tab","handleCreateAgent","handleAllocateResource","handleStartConsensus","tabName","querySelectorAll","remove","add","s","trim","cpu","memory","parseInt","alert","keys","setInterval","createSampleData","daaTools","readyState","module","exports"],"mappings":"AAKA,IAAA,AAAMA,WAAN,MAAMA;IACJ,aAAc;QACZ,IAAI,CAACC,MAAM,GAAG,IAAIC;QAClB,IAAI,CAACC,SAAS,GAAG,IAAID;QACrB,IAAI,CAACE,cAAc,GAAG,IAAIF;QAC1B,IAAI,CAACG,SAAS,GAAG,IAAIH;QACrB,IAAI,CAACI,aAAa,GAAG;QACrB,IAAI,CAACC,UAAU,GAAG;QAGlB,IAAI,CAACC,OAAO,GAAG;YACbC,aAAa;YACbC,cAAc;YACdC,qBAAqB;YACrBC,sBAAsB;YACtBC,eAAe;YACfC,YAAY;QACd;QAEA,IAAI,CAACC,IAAI;IACX;IA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AAU,KAAK,WAAW;IACrCnH,SAAS2F,gBAAgB,CAAC,oBAAoB;QAC5CuB,WAAW,IAAIlQ;IACjB;AACF,OAAO;IACLkQ,WAAW,IAAIlQ;AACjB;AAGA,IAAI,OAAOoQ,WAAW,eAAeA,OAAOC,OAAO,EAAE;IACnDD,OAAOC,OAAO,GAAGrQ;AACnB"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/memory-interface.js b/dist-cjs/src/ui/console/js/memory-interface.js deleted file mode 100644 index 8f853d19f5..0000000000 --- a/dist-cjs/src/ui/console/js/memory-interface.js +++ /dev/null @@ -1,792 +0,0 @@ -let MemoryInterface = class MemoryInterface { - constructor(){ - this.container = null; - this.currentNamespace = 'global'; - this.memoryData = new Map(); - this.searchFilters = {}; - this.analytics = { - usage: new Map(), - history: [], - patterns: new Map() - }; - this.backupManager = new BackupManager(); - this.syncManager = new SyncManager(); - this.compressionManager = new CompressionManager(); - this.visualizer = new MemoryVisualizer(); - this.init(); - } - init() { - this.createInterface(); - this.setupEventListeners(); - this.startMonitoring(); - this.loadMemoryData(); - } - createInterface() { - this.container = document.createElement('div'); - this.container.className = 'memory-interface'; - this.container.innerHTML = ` -
-

Memory Management Interface

-
- - - - -
-
- -
- -
-
-

Namespace Browser

- -
-
- -
- -
-
-
- - -
-
-

Key-Value Editor

-
- - - -
-
-
- -
- -
-
-
- - -
-
-

Memory Analytics

- -
-
-
-
-

Total Keys

- 0 -
-
-

Memory Usage

- 0 KB -
-
-

Compression Rate

- 0% -
-
-

Access Frequency

- 0/min -
-
-
-
- -
-
- -
-
-
-
-
- - -
-
-

Advanced Search

- -
-
-
-
- - - - -
-
-
- -
-
- -
-
-
- - -
-
-

Backup & Restore

- -
-
-
- - - -
-
- -
-
-
- - - - `; - } - setupEventListeners() { - this.container.querySelector('.btn-refresh').addEventListener('click', ()=>this.refresh()); - this.container.querySelector('.btn-backup').addEventListener('click', ()=>this.createBackup()); - this.container.querySelector('.btn-compress').addEventListener('click', ()=>this.optimizeMemory()); - this.container.querySelector('.btn-sync').addEventListener('click', ()=>this.showSyncStatus()); - this.container.querySelector('.btn-add-namespace').addEventListener('click', ()=>this.addNamespace()); - this.container.querySelector('.namespace-search-input').addEventListener('input', (e)=>this.searchNamespaces(e.target.value)); - this.container.querySelector('.btn-add-key').addEventListener('click', ()=>this.addKey()); - this.container.querySelector('.btn-bulk-edit').addEventListener('click', ()=>this.bulkEdit()); - this.container.querySelector('.btn-export').addEventListener('click', ()=>this.exportMemory()); - this.container.querySelector('.key-search-input').addEventListener('input', (e)=>this.searchKeys(e.target.value)); - this.container.querySelector('.type-filter').addEventListener('change', (e)=>this.filterByType(e.target.value)); - this.container.querySelector('.analytics-timeframe').addEventListener('change', (e)=>this.updateAnalytics(e.target.value)); - this.container.querySelector('.btn-add-filter').addEventListener('click', ()=>this.addSearchFilter()); - this.container.querySelector('.btn-saved-searches').addEventListener('click', ()=>this.showSavedSearches()); - this.container.querySelector('.btn-create-backup').addEventListener('click', ()=>this.createBackup()); - this.container.querySelector('.btn-restore-backup').addEventListener('click', ()=>this.restoreBackup()); - this.container.querySelector('.btn-import-backup').addEventListener('click', ()=>this.importBackup()); - this.container.querySelector('.btn-close-modal').addEventListener('click', ()=>this.closeModal()); - this.container.querySelector('.modal-overlay').addEventListener('click', (e)=>{ - if (e.target === this.container.querySelector('.modal-overlay')) { - this.closeModal(); - } - }); - this.container.querySelector('#key-editor-form').addEventListener('submit', (e)=>this.saveKeyValue(e)); - } - async loadMemoryData() { - try { - const response = await fetch('/api/memory/list'); - const data = await response.json(); - this.memoryData = new Map(Object.entries(data)); - this.updateNamespaceTree(); - this.updateKeyValueList(); - this.updateAnalytics(); - } catch (error) { - console.error('Failed to load memory data:', error); - this.showError('Failed to load memory data'); - } - } - updateNamespaceTree() { - const container = this.container.querySelector('.namespace-tree-container'); - const namespaces = this.getNamespaces(); - container.innerHTML = this.renderNamespaceTree(namespaces); - container.querySelectorAll('.namespace-item').forEach((item)=>{ - item.addEventListener('click', (e)=>{ - e.stopPropagation(); - this.selectNamespace(item.dataset.namespace); - }); - }); - } - renderNamespaceTree(namespaces, parent = '', level = 0) { - let html = ''; - for (const [namespace, data] of namespaces){ - const fullPath = parent ? `${parent}.${namespace}` : namespace; - const hasChildren = data.children && data.children.size > 0; - html += ` -
-
- ${hasChildren ? '' : ''} - ${namespace} - (${data.count}) -
-
- `; - if (hasChildren) { - html += this.renderNamespaceTree(data.children, fullPath, level + 1); - } - } - return html; - } - updateKeyValueList() { - const container = this.container.querySelector('.key-value-list'); - const keys = this.getKeysForNamespace(this.currentNamespace); - container.innerHTML = keys.map((key)=>this.renderKeyValueItem(key)).join(''); - container.querySelectorAll('.key-value-item').forEach((item)=>{ - item.querySelector('.btn-edit').addEventListener('click', ()=>this.editKey(item.dataset.key)); - item.querySelector('.btn-delete').addEventListener('click', ()=>this.deleteKey(item.dataset.key)); - item.querySelector('.btn-copy').addEventListener('click', ()=>this.copyKey(item.dataset.key)); - }); - } - renderKeyValueItem(key) { - const value = this.memoryData.get(key); - const type = this.getValueType(value); - const displayValue = this.formatValueForDisplay(value, type); - return ` -
-
- ${key} - ${type} -
-
- ${displayValue} -
-
- - - -
-
- `; - } - getNamespaces() { - const namespaces = new Map(); - for (const [key, value] of this.memoryData){ - const parts = key.split('.'); - let current = namespaces; - let path = ''; - for(let i = 0; i < parts.length - 1; i++){ - const part = parts[i]; - path = path ? `${path}.${part}` : part; - if (!current.has(part)) { - current.set(part, { - count: 0, - children: new Map() - }); - } - current = current.get(part).children; - } - const finalPart = parts[parts.length - 1]; - if (!current.has(finalPart)) { - current.set(finalPart, { - count: 0, - children: new Map() - }); - } - current.get(finalPart).count++; - } - return namespaces; - } - getKeysForNamespace(namespace) { - const keys = []; - const prefix = namespace === 'global' ? '' : `${namespace}.`; - for (const [key, value] of this.memoryData){ - if (namespace === 'global' || key.startsWith(prefix)) { - keys.push(key); - } - } - return keys.sort(); - } - getValueType(value) { - if (value === null) return 'null'; - if (value === undefined) return 'undefined'; - if (Array.isArray(value)) return 'array'; - return typeof value; - } - formatValueForDisplay(value, type) { - switch(type){ - case 'string': - return value.length > 50 ? `${value.substring(0, 50)}...` : value; - case 'object': - return JSON.stringify(value).substring(0, 100) + '...'; - case 'array': - return `[${value.length} items]`; - default: - return String(value); - } - } - updateAnalytics(timeframe = '24h') { - const stats = this.calculateStats(timeframe); - this.container.querySelector('#total-keys').textContent = stats.totalKeys; - this.container.querySelector('#memory-usage').textContent = stats.memoryUsage; - this.container.querySelector('#compression-rate').textContent = stats.compressionRate; - this.container.querySelector('#access-frequency').textContent = stats.accessFrequency; - this.visualizer.updateUsageChart(stats.usageData); - this.visualizer.updatePatternChart(stats.patternData); - } - calculateStats(timeframe) { - const now = Date.now(); - const timeframes = { - '1h': 60 * 60 * 1000, - '24h': 24 * 60 * 60 * 1000, - '7d': 7 * 24 * 60 * 60 * 1000, - '30d': 30 * 24 * 60 * 60 * 1000 - }; - const cutoff = now - timeframes[timeframe]; - return { - totalKeys: this.memoryData.size, - memoryUsage: this.calculateMemoryUsage(), - compressionRate: this.compressionManager.getCompressionRate(), - accessFrequency: this.calculateAccessFrequency(cutoff), - usageData: this.getUsageData(cutoff), - patternData: this.getPatternData(cutoff) - }; - } - calculateMemoryUsage() { - let totalSize = 0; - for (const [key, value] of this.memoryData){ - totalSize += this.getObjectSize(key) + this.getObjectSize(value); - } - return this.formatBytes(totalSize); - } - getObjectSize(obj) { - let size = 0; - if (typeof obj === 'string') { - size = obj.length * 2; - } else if (typeof obj === 'number') { - size = 8; - } else if (typeof obj === 'boolean') { - size = 1; - } else if (obj === null || obj === undefined) { - size = 0; - } else { - size = JSON.stringify(obj).length * 2; - } - return size; - } - formatBytes(bytes) { - if (bytes === 0) return '0 B'; - const k = 1024; - const sizes = [ - 'B', - 'KB', - 'MB', - 'GB' - ]; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; - } - calculateAccessFrequency(cutoff) { - const recentAccess = this.analytics.history.filter((entry)=>entry.timestamp > cutoff); - const frequency = recentAccess.length / ((Date.now() - cutoff) / 60000); - return frequency.toFixed(2); - } - getUsageData(cutoff) { - return this.analytics.history.filter((entry)=>entry.timestamp > cutoff).map((entry)=>({ - timestamp: entry.timestamp, - operations: entry.operations || 0, - memory: entry.memory || 0 - })); - } - getPatternData(cutoff) { - const patterns = new Map(); - for (const [key, value] of this.analytics.patterns){ - if (value.lastAccess > cutoff) { - patterns.set(key, value); - } - } - return Array.from(patterns.entries()); - } - async selectNamespace(namespace) { - this.currentNamespace = namespace; - this.updateKeyValueList(); - this.container.querySelectorAll('.namespace-item').forEach((item)=>{ - item.classList.toggle('active', item.dataset.namespace === namespace); - }); - await this.notifyCoordination(`Selected namespace: ${namespace}`); - } - async addNamespace() { - const name = prompt('Enter namespace name:'); - if (name) { - const key = `${name}.placeholder`; - await this.setMemoryValue(key, 'Namespace placeholder'); - await this.loadMemoryData(); - await this.notifyCoordination(`Added namespace: ${name}`); - } - } - async addKey() { - this.openModal('key-editor-modal'); - this.container.querySelector('#edit-key').value = ''; - this.container.querySelector('#edit-value').value = ''; - this.container.querySelector('#edit-type').value = 'string'; - this.container.querySelector('#edit-namespace').value = this.currentNamespace; - } - async editKey(key) { - const value = this.memoryData.get(key); - const type = this.getValueType(value); - this.openModal('key-editor-modal'); - this.container.querySelector('#edit-key').value = key; - this.container.querySelector('#edit-value').value = JSON.stringify(value, null, 2); - this.container.querySelector('#edit-type').value = type; - this.container.querySelector('#edit-namespace').value = this.getNamespaceFromKey(key); - } - async deleteKey(key) { - if (confirm(`Are you sure you want to delete "${key}"?`)) { - await this.deleteMemoryValue(key); - await this.loadMemoryData(); - await this.notifyCoordination(`Deleted key: ${key}`); - } - } - async copyKey(key) { - const value = this.memoryData.get(key); - const text = JSON.stringify({ - [key]: value - }, null, 2); - try { - await navigator.clipboard.writeText(text); - this.showSuccess('Key copied to clipboard'); - } catch (error) { - console.error('Failed to copy to clipboard:', error); - this.showError('Failed to copy to clipboard'); - } - } - async saveKeyValue(e) { - e.preventDefault(); - const key = this.container.querySelector('#edit-key').value; - const type = this.container.querySelector('#edit-type').value; - const valueText = this.container.querySelector('#edit-value').value; - try { - let value; - switch(type){ - case 'string': - value = valueText; - break; - case 'number': - value = parseFloat(valueText); - break; - case 'boolean': - value = valueText.toLowerCase() === 'true'; - break; - case 'object': - case 'array': - value = JSON.parse(valueText); - break; - default: - value = valueText; - } - await this.setMemoryValue(key, value); - await this.loadMemoryData(); - this.closeModal(); - await this.notifyCoordination(`Saved key: ${key}`); - } catch (error) { - console.error('Failed to save key-value:', error); - this.showError('Failed to save key-value pair'); - } - } - async createBackup() { - try { - const backup = await this.backupManager.createBackup(this.memoryData); - this.showSuccess(`Backup created: ${backup.id}`); - await this.notifyCoordination(`Created backup: ${backup.id}`); - } catch (error) { - console.error('Failed to create backup:', error); - this.showError('Failed to create backup'); - } - } - async optimizeMemory() { - try { - const result = await this.compressionManager.optimize(this.memoryData); - this.showSuccess(`Memory optimized: ${result.savedBytes} bytes saved`); - await this.loadMemoryData(); - await this.notifyCoordination(`Optimized memory: ${result.savedBytes} bytes saved`); - } catch (error) { - console.error('Failed to optimize memory:', error); - this.showError('Failed to optimize memory'); - } - } - async refresh() { - await this.loadMemoryData(); - this.showSuccess('Memory data refreshed'); - } - openModal(modalId) { - this.container.querySelector('#modal-overlay').style.display = 'flex'; - this.container.querySelector(`#${modalId}`).style.display = 'block'; - } - closeModal() { - this.container.querySelector('#modal-overlay').style.display = 'none'; - this.container.querySelectorAll('.modal').forEach((modal)=>{ - modal.style.display = 'none'; - }); - } - getNamespaceFromKey(key) { - const parts = key.split('.'); - return parts.length > 1 ? parts.slice(0, -1).join('.') : 'global'; - } - async setMemoryValue(key, value) { - const response = await fetch('/api/memory/set', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - key, - value - }) - }); - if (!response.ok) { - throw new Error('Failed to set memory value'); - } - } - async deleteMemoryValue(key) { - const response = await fetch('/api/memory/delete', { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - key - }) - }); - if (!response.ok) { - throw new Error('Failed to delete memory value'); - } - } - showSuccess(message) { - console.log('Success:', message); - } - showError(message) { - console.error('Error:', message); - } - async notifyCoordination(message) { - try { - await fetch('/api/coordination/notify', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - message, - timestamp: Date.now() - }) - }); - } catch (error) { - console.error('Failed to notify coordination:', error); - } - } - startMonitoring() { - setInterval(()=>{ - this.updateAnalytics(); - }, 30000); - } - render() { - return this.container; - } -}; -let BackupManager = class BackupManager { - constructor(){ - this.backups = new Map(); - } - async createBackup(memoryData) { - const id = `backup_${Date.now()}`; - const backup = { - id, - timestamp: Date.now(), - data: new Map(memoryData), - size: this.calculateBackupSize(memoryData) - }; - this.backups.set(id, backup); - return backup; - } - async restoreBackup(backupId) { - const backup = this.backups.get(backupId); - if (!backup) { - throw new Error('Backup not found'); - } - return backup.data; - } - calculateBackupSize(memoryData) { - return JSON.stringify(Array.from(memoryData.entries())).length; - } -}; -let SyncManager = class SyncManager { - constructor(){ - this.syncStatus = 'idle'; - this.lastSync = null; - } - async sync() { - this.syncStatus = 'syncing'; - try { - await new Promise((resolve)=>setTimeout(resolve, 1000)); - this.lastSync = Date.now(); - this.syncStatus = 'synchronized'; - } catch (error) { - this.syncStatus = 'error'; - throw error; - } - } - getStatus() { - return { - status: this.syncStatus, - lastSync: this.lastSync - }; - } -}; -let CompressionManager = class CompressionManager { - constructor(){ - this.compressionRate = 0; - } - async optimize(memoryData) { - const originalSize = this.calculateSize(memoryData); - await new Promise((resolve)=>setTimeout(resolve, 500)); - const compressedSize = originalSize * 0.7; - const savedBytes = originalSize - compressedSize; - this.compressionRate = savedBytes / originalSize * 100; - return { - savedBytes: Math.floor(savedBytes), - compressionRate: this.compressionRate - }; - } - getCompressionRate() { - return `${this.compressionRate.toFixed(1)}%`; - } - calculateSize(memoryData) { - return JSON.stringify(Array.from(memoryData.entries())).length; - } -}; -let MemoryVisualizer = class MemoryVisualizer { - constructor(){ - this.usageChart = null; - this.patternChart = null; - } - updateUsageChart(data) { - const canvas = document.getElementById('usage-chart'); - if (!canvas) return; - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - if (data.length > 0) { - ctx.beginPath(); - ctx.strokeStyle = '#007bff'; - ctx.lineWidth = 2; - const width = canvas.width; - const height = canvas.height; - const stepX = width / (data.length - 1); - const maxValue = Math.max(...data.map((d)=>d.operations)); - data.forEach((point, index)=>{ - const x = index * stepX; - const y = height - point.operations / maxValue * height; - if (index === 0) { - ctx.moveTo(x, y); - } else { - ctx.lineTo(x, y); - } - }); - ctx.stroke(); - } - } - updatePatternChart(data) { - const canvas = document.getElementById('pattern-chart'); - if (!canvas) return; - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - if (data.length > 0) { - const width = canvas.width; - const height = canvas.height; - const barWidth = width / data.length; - const maxValue = Math.max(...data.map((d)=>d[1].count || 0)); - data.forEach((pattern, index)=>{ - const barHeight = (pattern[1].count || 0) / maxValue * height; - const x = index * barWidth; - const y = height - barHeight; - ctx.fillStyle = '#28a745'; - ctx.fillRect(x, y, barWidth - 2, barHeight); - }); - } - } -}; -window.MemoryInterface = MemoryInterface; - -//# sourceMappingURL=memory-interface.js.map \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/memory-interface.js.map b/dist-cjs/src/ui/console/js/memory-interface.js.map deleted file mode 100644 index a31103673a..0000000000 --- a/dist-cjs/src/ui/console/js/memory-interface.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../../../../../src/ui/console/js/memory-interface.js"],"sourcesContent":["/**\n * Memory Management Interface\n * Comprehensive memory management system for Claude Flow\n */\n\nclass MemoryInterface {\n constructor() {\n this.container = null;\n this.currentNamespace = 'global';\n this.memoryData = new Map();\n this.searchFilters = {};\n this.analytics = {\n usage: new Map(),\n history: [],\n patterns: new Map(),\n };\n this.backupManager = new BackupManager();\n this.syncManager = new SyncManager();\n this.compressionManager = new CompressionManager();\n this.visualizer = new MemoryVisualizer();\n\n this.init();\n }\n\n init() {\n this.createInterface();\n this.setupEventListeners();\n this.startMonitoring();\n this.loadMemoryData();\n }\n\n createInterface() {\n this.container = document.createElement('div');\n this.container.className = 'memory-interface';\n this.container.innerHTML = `\n
\n

Memory Management Interface

\n
\n \n \n \n \n
\n
\n\n
\n \n
\n
\n

Namespace Browser

\n \n
\n
\n
\n \n
\n
\n \n
\n
\n
\n\n \n
\n
\n

Key-Value Editor

\n
\n \n \n \n
\n
\n
\n
\n \n \n
\n
\n \n
\n
\n
\n\n \n
\n
\n

Memory Analytics

\n \n
\n
\n
\n
\n

Total Keys

\n 0\n
\n
\n

Memory Usage

\n 0 KB\n
\n
\n

Compression Rate

\n 0%\n
\n
\n

Access Frequency

\n 0/min\n
\n
\n
\n
\n \n
\n
\n \n
\n
\n
\n
\n
\n\n \n
\n
\n

Advanced Search

\n \n
\n
\n
\n
\n \n \n \n \n
\n
\n
\n \n
\n
\n \n
\n
\n
\n\n \n
\n
\n

Backup & Restore

\n \n
\n
\n
\n \n \n \n
\n
\n \n
\n
\n
\n\n \n
\n
\n
\n

Edit Key-Value Pair

\n \n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n
\n `;\n }\n\n setupEventListeners() {\n // Header controls\n this.container.querySelector('.btn-refresh').addEventListener('click', () => this.refresh());\n this.container\n .querySelector('.btn-backup')\n .addEventListener('click', () => this.createBackup());\n this.container\n .querySelector('.btn-compress')\n .addEventListener('click', () => this.optimizeMemory());\n this.container\n .querySelector('.btn-sync')\n .addEventListener('click', () => this.showSyncStatus());\n\n // Namespace controls\n this.container\n .querySelector('.btn-add-namespace')\n .addEventListener('click', () => this.addNamespace());\n this.container\n .querySelector('.namespace-search-input')\n .addEventListener('input', (e) => this.searchNamespaces(e.target.value));\n\n // Editor controls\n this.container.querySelector('.btn-add-key').addEventListener('click', () => this.addKey());\n this.container.querySelector('.btn-bulk-edit').addEventListener('click', () => this.bulkEdit());\n this.container\n .querySelector('.btn-export')\n .addEventListener('click', () => this.exportMemory());\n\n // Search controls\n this.container\n .querySelector('.key-search-input')\n .addEventListener('input', (e) => this.searchKeys(e.target.value));\n this.container\n .querySelector('.type-filter')\n .addEventListener('change', (e) => this.filterByType(e.target.value));\n\n // Analytics controls\n this.container\n .querySelector('.analytics-timeframe')\n .addEventListener('change', (e) => this.updateAnalytics(e.target.value));\n\n // Search interface\n this.container\n .querySelector('.btn-add-filter')\n .addEventListener('click', () => this.addSearchFilter());\n this.container\n .querySelector('.btn-saved-searches')\n .addEventListener('click', () => this.showSavedSearches());\n\n // Backup controls\n this.container\n .querySelector('.btn-create-backup')\n .addEventListener('click', () => this.createBackup());\n this.container\n .querySelector('.btn-restore-backup')\n .addEventListener('click', () => this.restoreBackup());\n this.container\n .querySelector('.btn-import-backup')\n .addEventListener('click', () => this.importBackup());\n\n // Modal controls\n this.container\n .querySelector('.btn-close-modal')\n .addEventListener('click', () => this.closeModal());\n this.container.querySelector('.modal-overlay').addEventListener('click', (e) => {\n if (e.target === this.container.querySelector('.modal-overlay')) {\n this.closeModal();\n }\n });\n\n // Form submission\n this.container\n .querySelector('#key-editor-form')\n .addEventListener('submit', (e) => this.saveKeyValue(e));\n }\n\n async loadMemoryData() {\n try {\n // Load memory data from Claude Flow's memory system\n const response = await fetch('/api/memory/list');\n const data = await response.json();\n\n this.memoryData = new Map(Object.entries(data));\n this.updateNamespaceTree();\n this.updateKeyValueList();\n this.updateAnalytics();\n } catch (error) {\n console.error('Failed to load memory data:', error);\n this.showError('Failed to load memory data');\n }\n }\n\n updateNamespaceTree() {\n const container = this.container.querySelector('.namespace-tree-container');\n const namespaces = this.getNamespaces();\n\n container.innerHTML = this.renderNamespaceTree(namespaces);\n\n // Add click handlers for namespace items\n container.querySelectorAll('.namespace-item').forEach((item) => {\n item.addEventListener('click', (e) => {\n e.stopPropagation();\n this.selectNamespace(item.dataset.namespace);\n });\n });\n }\n\n renderNamespaceTree(namespaces, parent = '', level = 0) {\n let html = '';\n\n for (const [namespace, data] of namespaces) {\n const fullPath = parent ? `${parent}.${namespace}` : namespace;\n const hasChildren = data.children && data.children.size > 0;\n\n html += `\n
\n
\n ${hasChildren ? '' : ''}\n ${namespace}\n (${data.count})\n
\n
\n `;\n\n if (hasChildren) {\n html += this.renderNamespaceTree(data.children, fullPath, level + 1);\n }\n }\n\n return html;\n }\n\n updateKeyValueList() {\n const container = this.container.querySelector('.key-value-list');\n const keys = this.getKeysForNamespace(this.currentNamespace);\n\n container.innerHTML = keys.map((key) => this.renderKeyValueItem(key)).join('');\n\n // Add event listeners for key-value items\n container.querySelectorAll('.key-value-item').forEach((item) => {\n item\n .querySelector('.btn-edit')\n .addEventListener('click', () => this.editKey(item.dataset.key));\n item\n .querySelector('.btn-delete')\n .addEventListener('click', () => this.deleteKey(item.dataset.key));\n item\n .querySelector('.btn-copy')\n .addEventListener('click', () => this.copyKey(item.dataset.key));\n });\n }\n\n renderKeyValueItem(key) {\n const value = this.memoryData.get(key);\n const type = this.getValueType(value);\n const displayValue = this.formatValueForDisplay(value, type);\n\n return `\n
\n
\n ${key}\n ${type}\n
\n
\n ${displayValue}\n
\n
\n \n \n \n
\n
\n `;\n }\n\n getNamespaces() {\n const namespaces = new Map();\n\n for (const [key, value] of this.memoryData) {\n const parts = key.split('.');\n let current = namespaces;\n let path = '';\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n path = path ? `${path}.${part}` : part;\n\n if (!current.has(part)) {\n current.set(part, {\n count: 0,\n children: new Map(),\n });\n }\n\n current = current.get(part).children;\n }\n\n // Count the final key\n const finalPart = parts[parts.length - 1];\n if (!current.has(finalPart)) {\n current.set(finalPart, { count: 0, children: new Map() });\n }\n current.get(finalPart).count++;\n }\n\n return namespaces;\n }\n\n getKeysForNamespace(namespace) {\n const keys = [];\n const prefix = namespace === 'global' ? '' : `${namespace}.`;\n\n for (const [key, value] of this.memoryData) {\n if (namespace === 'global' || key.startsWith(prefix)) {\n keys.push(key);\n }\n }\n\n return keys.sort();\n }\n\n getValueType(value) {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n }\n\n formatValueForDisplay(value, type) {\n switch (type) {\n case 'string':\n return value.length > 50 ? `${value.substring(0, 50)}...` : value;\n case 'object':\n return JSON.stringify(value).substring(0, 100) + '...';\n case 'array':\n return `[${value.length} items]`;\n default:\n return String(value);\n }\n }\n\n updateAnalytics(timeframe = '24h') {\n const stats = this.calculateStats(timeframe);\n\n // Update stat cards\n this.container.querySelector('#total-keys').textContent = stats.totalKeys;\n this.container.querySelector('#memory-usage').textContent = stats.memoryUsage;\n this.container.querySelector('#compression-rate').textContent = stats.compressionRate;\n this.container.querySelector('#access-frequency').textContent = stats.accessFrequency;\n\n // Update charts\n this.visualizer.updateUsageChart(stats.usageData);\n this.visualizer.updatePatternChart(stats.patternData);\n }\n\n calculateStats(timeframe) {\n const now = Date.now();\n const timeframes = {\n '1h': 60 * 60 * 1000,\n '24h': 24 * 60 * 60 * 1000,\n '7d': 7 * 24 * 60 * 60 * 1000,\n '30d': 30 * 24 * 60 * 60 * 1000,\n };\n\n const cutoff = now - timeframes[timeframe];\n\n return {\n totalKeys: this.memoryData.size,\n memoryUsage: this.calculateMemoryUsage(),\n compressionRate: this.compressionManager.getCompressionRate(),\n accessFrequency: this.calculateAccessFrequency(cutoff),\n usageData: this.getUsageData(cutoff),\n patternData: this.getPatternData(cutoff),\n };\n }\n\n calculateMemoryUsage() {\n let totalSize = 0;\n for (const [key, value] of this.memoryData) {\n totalSize += this.getObjectSize(key) + this.getObjectSize(value);\n }\n return this.formatBytes(totalSize);\n }\n\n getObjectSize(obj) {\n let size = 0;\n if (typeof obj === 'string') {\n size = obj.length * 2; // UTF-16\n } else if (typeof obj === 'number') {\n size = 8; // 64-bit float\n } else if (typeof obj === 'boolean') {\n size = 1;\n } else if (obj === null || obj === undefined) {\n size = 0;\n } else {\n size = JSON.stringify(obj).length * 2;\n }\n return size;\n }\n\n formatBytes(bytes) {\n if (bytes === 0) return '0 B';\n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n }\n\n calculateAccessFrequency(cutoff) {\n const recentAccess = this.analytics.history.filter((entry) => entry.timestamp > cutoff);\n const frequency = recentAccess.length / ((Date.now() - cutoff) / 60000); // per minute\n return frequency.toFixed(2);\n }\n\n getUsageData(cutoff) {\n // Return usage data for charts\n return this.analytics.history\n .filter((entry) => entry.timestamp > cutoff)\n .map((entry) => ({\n timestamp: entry.timestamp,\n operations: entry.operations || 0,\n memory: entry.memory || 0,\n }));\n }\n\n getPatternData(cutoff) {\n // Return pattern data for charts\n const patterns = new Map();\n\n for (const [key, value] of this.analytics.patterns) {\n if (value.lastAccess > cutoff) {\n patterns.set(key, value);\n }\n }\n\n return Array.from(patterns.entries());\n }\n\n // Event handlers\n async selectNamespace(namespace) {\n this.currentNamespace = namespace;\n this.updateKeyValueList();\n\n // Update active state\n this.container.querySelectorAll('.namespace-item').forEach((item) => {\n item.classList.toggle('active', item.dataset.namespace === namespace);\n });\n\n await this.notifyCoordination(`Selected namespace: ${namespace}`);\n }\n\n async addNamespace() {\n const name = prompt('Enter namespace name:');\n if (name) {\n // Create a placeholder key to establish the namespace\n const key = `${name}.placeholder`;\n await this.setMemoryValue(key, 'Namespace placeholder');\n await this.loadMemoryData();\n await this.notifyCoordination(`Added namespace: ${name}`);\n }\n }\n\n async addKey() {\n this.openModal('key-editor-modal');\n this.container.querySelector('#edit-key').value = '';\n this.container.querySelector('#edit-value').value = '';\n this.container.querySelector('#edit-type').value = 'string';\n this.container.querySelector('#edit-namespace').value = this.currentNamespace;\n }\n\n async editKey(key) {\n const value = this.memoryData.get(key);\n const type = this.getValueType(value);\n\n this.openModal('key-editor-modal');\n this.container.querySelector('#edit-key').value = key;\n this.container.querySelector('#edit-value').value = JSON.stringify(value, null, 2);\n this.container.querySelector('#edit-type').value = type;\n this.container.querySelector('#edit-namespace').value = this.getNamespaceFromKey(key);\n }\n\n async deleteKey(key) {\n if (confirm(`Are you sure you want to delete \"${key}\"?`)) {\n await this.deleteMemoryValue(key);\n await this.loadMemoryData();\n await this.notifyCoordination(`Deleted key: ${key}`);\n }\n }\n\n async copyKey(key) {\n const value = this.memoryData.get(key);\n const text = JSON.stringify({ [key]: value }, null, 2);\n\n try {\n await navigator.clipboard.writeText(text);\n this.showSuccess('Key copied to clipboard');\n } catch (error) {\n console.error('Failed to copy to clipboard:', error);\n this.showError('Failed to copy to clipboard');\n }\n }\n\n async saveKeyValue(e) {\n e.preventDefault();\n\n const key = this.container.querySelector('#edit-key').value;\n const type = this.container.querySelector('#edit-type').value;\n const valueText = this.container.querySelector('#edit-value').value;\n\n try {\n let value;\n\n switch (type) {\n case 'string':\n value = valueText;\n break;\n case 'number':\n value = parseFloat(valueText);\n break;\n case 'boolean':\n value = valueText.toLowerCase() === 'true';\n break;\n case 'object':\n case 'array':\n value = JSON.parse(valueText);\n break;\n default:\n value = valueText;\n }\n\n await this.setMemoryValue(key, value);\n await this.loadMemoryData();\n this.closeModal();\n await this.notifyCoordination(`Saved key: ${key}`);\n } catch (error) {\n console.error('Failed to save key-value:', error);\n this.showError('Failed to save key-value pair');\n }\n }\n\n async createBackup() {\n try {\n const backup = await this.backupManager.createBackup(this.memoryData);\n this.showSuccess(`Backup created: ${backup.id}`);\n await this.notifyCoordination(`Created backup: ${backup.id}`);\n } catch (error) {\n console.error('Failed to create backup:', error);\n this.showError('Failed to create backup');\n }\n }\n\n async optimizeMemory() {\n try {\n const result = await this.compressionManager.optimize(this.memoryData);\n this.showSuccess(`Memory optimized: ${result.savedBytes} bytes saved`);\n await this.loadMemoryData();\n await this.notifyCoordination(`Optimized memory: ${result.savedBytes} bytes saved`);\n } catch (error) {\n console.error('Failed to optimize memory:', error);\n this.showError('Failed to optimize memory');\n }\n }\n\n async refresh() {\n await this.loadMemoryData();\n this.showSuccess('Memory data refreshed');\n }\n\n // Helper methods\n openModal(modalId) {\n this.container.querySelector('#modal-overlay').style.display = 'flex';\n this.container.querySelector(`#${modalId}`).style.display = 'block';\n }\n\n closeModal() {\n this.container.querySelector('#modal-overlay').style.display = 'none';\n this.container.querySelectorAll('.modal').forEach((modal) => {\n modal.style.display = 'none';\n });\n }\n\n getNamespaceFromKey(key) {\n const parts = key.split('.');\n return parts.length > 1 ? parts.slice(0, -1).join('.') : 'global';\n }\n\n async setMemoryValue(key, value) {\n const response = await fetch('/api/memory/set', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key, value }),\n });\n\n if (!response.ok) {\n throw new Error('Failed to set memory value');\n }\n }\n\n async deleteMemoryValue(key) {\n const response = await fetch('/api/memory/delete', {\n method: 'DELETE',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ key }),\n });\n\n if (!response.ok) {\n throw new Error('Failed to delete memory value');\n }\n }\n\n showSuccess(message) {\n // Implementation for success notification\n console.log('Success:', message);\n }\n\n showError(message) {\n // Implementation for error notification\n console.error('Error:', message);\n }\n\n async notifyCoordination(message) {\n try {\n await fetch('/api/coordination/notify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ message, timestamp: Date.now() }),\n });\n } catch (error) {\n console.error('Failed to notify coordination:', error);\n }\n }\n\n startMonitoring() {\n // Start real-time monitoring\n setInterval(() => {\n this.updateAnalytics();\n }, 30000); // Update every 30 seconds\n }\n\n render() {\n return this.container;\n }\n}\n\n// Supporting classes\nclass BackupManager {\n constructor() {\n this.backups = new Map();\n }\n\n async createBackup(memoryData) {\n const id = `backup_${Date.now()}`;\n const backup = {\n id,\n timestamp: Date.now(),\n data: new Map(memoryData),\n size: this.calculateBackupSize(memoryData),\n };\n\n this.backups.set(id, backup);\n return backup;\n }\n\n async restoreBackup(backupId) {\n const backup = this.backups.get(backupId);\n if (!backup) {\n throw new Error('Backup not found');\n }\n\n return backup.data;\n }\n\n calculateBackupSize(memoryData) {\n return JSON.stringify(Array.from(memoryData.entries())).length;\n }\n}\n\nclass SyncManager {\n constructor() {\n this.syncStatus = 'idle';\n this.lastSync = null;\n }\n\n async sync() {\n this.syncStatus = 'syncing';\n\n try {\n // Implement sync logic here\n await new Promise((resolve) => setTimeout(resolve, 1000));\n this.lastSync = Date.now();\n this.syncStatus = 'synchronized';\n } catch (error) {\n this.syncStatus = 'error';\n throw error;\n }\n }\n\n getStatus() {\n return {\n status: this.syncStatus,\n lastSync: this.lastSync,\n };\n }\n}\n\nclass CompressionManager {\n constructor() {\n this.compressionRate = 0;\n }\n\n async optimize(memoryData) {\n // Implement compression logic\n const originalSize = this.calculateSize(memoryData);\n\n // Simulate compression\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n const compressedSize = originalSize * 0.7; // 30% compression\n const savedBytes = originalSize - compressedSize;\n\n this.compressionRate = (savedBytes / originalSize) * 100;\n\n return {\n savedBytes: Math.floor(savedBytes),\n compressionRate: this.compressionRate,\n };\n }\n\n getCompressionRate() {\n return `${this.compressionRate.toFixed(1)}%`;\n }\n\n calculateSize(memoryData) {\n return JSON.stringify(Array.from(memoryData.entries())).length;\n }\n}\n\nclass MemoryVisualizer {\n constructor() {\n this.usageChart = null;\n this.patternChart = null;\n }\n\n updateUsageChart(data) {\n const canvas = document.getElementById('usage-chart');\n if (!canvas) return;\n\n const ctx = canvas.getContext('2d');\n\n // Simple chart implementation\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // Draw usage data\n if (data.length > 0) {\n ctx.beginPath();\n ctx.strokeStyle = '#007bff';\n ctx.lineWidth = 2;\n\n const width = canvas.width;\n const height = canvas.height;\n const stepX = width / (data.length - 1);\n const maxValue = Math.max(...data.map((d) => d.operations));\n\n data.forEach((point, index) => {\n const x = index * stepX;\n const y = height - (point.operations / maxValue) * height;\n\n if (index === 0) {\n ctx.moveTo(x, y);\n } else {\n ctx.lineTo(x, y);\n }\n });\n\n ctx.stroke();\n }\n }\n\n updatePatternChart(data) {\n const canvas = document.getElementById('pattern-chart');\n if (!canvas) return;\n\n const ctx = canvas.getContext('2d');\n\n // Simple pattern chart implementation\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n // Draw pattern data as bars\n if (data.length > 0) {\n const width = canvas.width;\n const height = canvas.height;\n const barWidth = width / data.length;\n const maxValue = Math.max(...data.map((d) => d[1].count || 0));\n\n data.forEach((pattern, index) => {\n const barHeight = ((pattern[1].count || 0) / maxValue) * height;\n const x = index * barWidth;\n const y = height - barHeight;\n\n ctx.fillStyle = '#28a745';\n ctx.fillRect(x, y, barWidth - 2, barHeight);\n });\n }\n }\n}\n\n// Export for use in other modules\nwindow.MemoryInterface = MemoryInterface;\n"],"names":["MemoryInterface","container","currentNamespace","memoryData","Map","searchFilters","analytics","usage","history","patterns","backupManager","BackupManager","syncManager","SyncManager","compressionManager","CompressionManager","visualizer","MemoryVisualizer","init","createInterface","setupEventListeners","startMonitoring","loadMemoryData","document","createElement","className","innerHTML","querySelector","addEventListener","refresh","createBackup","optimizeMemory","showSyncStatus","addNamespace","e","searchNamespaces","target","value","addKey","bulkEdit","exportMemory","searchKeys","filterByType","updateAnalytics","addSearchFilter","showSavedSearches","restoreBackup","importBackup","closeModal","saveKeyValue","response","fetch","data","json","Object","entries","updateNamespaceTree","updateKeyValueList","error","console","showError","namespaces","getNamespaces","renderNamespaceTree","querySelectorAll","forEach","item","stopPropagation","selectNamespace","dataset","namespace","parent","level","html","fullPath","hasChildren","children","size","count","keys","getKeysForNamespace","map","key","renderKeyValueItem","join","editKey","deleteKey","copyKey","get","type","getValueType","displayValue","formatValueForDisplay","parts","split","current","path","i","length","part","has","set","finalPart","prefix","startsWith","push","sort","undefined","Array","isArray","substring","JSON","stringify","String","timeframe","stats","calculateStats","textContent","totalKeys","memoryUsage","compressionRate","accessFrequency","updateUsageChart","usageData","updatePatternChart","patternData","now","Date","timeframes","cutoff","calculateMemoryUsage","getCompressionRate","calculateAccessFrequency","getUsageData","getPatternData","totalSize","getObjectSize","formatBytes","obj","bytes","k","sizes","Math","floor","log","parseFloat","pow","toFixed","recentAccess","filter","entry","timestamp","frequency","operations","memory","lastAccess","from","classList","toggle","notifyCoordination","name","prompt","setMemoryValue","openModal","getNamespaceFromKey","confirm","deleteMemoryValue","text","navigator","clipboard","writeText","showSuccess","preventDefault","valueText","toLowerCase","parse","backup","id","result","optimize","savedBytes","modalId","style","display","modal","slice","method","headers","body","ok","Error","message","setInterval","render","backups","calculateBackupSize","backupId","syncStatus","lastSync","sync","Promise","resolve","setTimeout","getStatus","status","originalSize","calculateSize","compressedSize","usageChart","patternChart","canvas","getElementById","ctx","getContext","clearRect","width","height","beginPath","strokeStyle","lineWidth","stepX","maxValue","max","d","point","index","x","y","moveTo","lineTo","stroke","barWidth","pattern","barHeight","fillStyle","fillRect","window"],"mappings":"AAKA,IAAA,AAAMA,kBAAN,MAAMA;IACJ,aAAc;QACZ,IAAI,CAACC,SAAS,GAAG;QACjB,IAAI,CAACC,gBAAgB,GAAG;QACxB,IAAI,CAACC,UAAU,GAAG,IAAIC;QACtB,IAAI,CAACC,aAAa,GAAG,CAAC;QACtB,IAAI,CAACC,SAAS,GAAG;YACfC,OAAO,IAAIH;YACXI,SAAS,EAAE;YACXC,UAAU,IAAIL;QAChB;QACA,IAAI,CAACM,aAAa,GAAG,IAAIC;QACzB,IAAI,CAACC,WAAW,GAAG,IAAIC;QACvB,IAAI,CAACC,kBAAkB,GAAG,IAAIC;QAC9B,IAAI,CAACC,UAAU,GAAG,IAAIC;QAEtB,IAAI,CAACC,IAAI;IACX;IAEAA,OAAO;QACL,IAAI,CAACC,eAAe;QACpB,IAAI,CAACC,mBAAmB;QACxB,IAAI,CAACC,eAAe;QACpB,IAAI,CAACC,cAAc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AC,CAAC,EAAE,CAACjJ,KAAK,IAAI;YAE3D1B,KAAKa,OAAO,CAAC,CAACuK,SAASP;gBACrB,MAAMQ,YAAY,AAAED,CAAAA,OAAO,CAAC,EAAE,CAAC1J,KAAK,IAAI,CAAA,IAAK+I,WAAYL;gBACzD,MAAMU,IAAID,QAAQM;gBAClB,MAAMJ,IAAIX,SAASiB;gBAEnBrB,IAAIsB,SAAS,GAAG;gBAChBtB,IAAIuB,QAAQ,CAACT,GAAGC,GAAGI,WAAW,GAAGE;YACnC;QACF;IACF;AACF;AAGAG,OAAO5O,eAAe,GAAGA"} \ No newline at end of file diff --git a/dist-cjs/src/ui/console/js/memory-test.js b/dist-cjs/src/ui/console/js/memory-test.js deleted file mode 100644 index a05b3047f8..0000000000 --- a/dist-cjs/src/ui/console/js/memory-test.js +++ /dev/null @@ -1,178 +0,0 @@ -export class MemoryTest { - constructor(memoryManager, terminal){ - this.memoryManager = memoryManager; - this.terminal = terminal; - } - async runTests() { - this.terminal.writeInfo('๐Ÿงช Starting Memory Manager Tests...'); - try { - await this.testMemoryPanel(); - await this.testMemoryTools(); - await this.testNamespaceOperations(); - await this.testMemoryOperations(); - this.terminal.writeSuccess('โœ… All memory tests completed successfully!'); - } catch (error) { - this.terminal.writeError(`โŒ Memory tests failed: ${error.message}`); - } - } - async testMemoryPanel() { - this.terminal.writeInfo('Testing memory panel...'); - this.memoryManager.togglePanel(); - const panelVisible = !document.getElementById('memoryPanel')?.classList.contains('hidden'); - if (panelVisible) { - this.terminal.writeSuccess('โœ… Memory panel opens correctly'); - } else { - throw new Error('Memory panel failed to open'); - } - const requiredElements = [ - 'memoryToolsGrid', - 'namespaceSelect', - 'memoryTable', - 'memoryAnalytics', - 'memoryLog' - ]; - for (const elementId of requiredElements){ - const element = document.getElementById(elementId); - if (element) { - this.terminal.writeSuccess(`โœ… ${elementId} component found`); - } else { - throw new Error(`Required component missing: ${elementId}`); - } - } - } - async testMemoryTools() { - this.terminal.writeInfo('Testing memory tools...'); - const tools = Object.keys(this.memoryManager.memoryTools); - this.terminal.writeInfo(`Found ${tools.length} memory tools:`); - for (const tool of tools){ - const toolInfo = this.memoryManager.memoryTools[tool]; - this.terminal.writeLine(` ${toolInfo.icon} ${toolInfo.name} - ${toolInfo.description}`); - } - if (tools.length === 10) { - this.terminal.writeSuccess('โœ… All 10 memory tools are configured'); - } else { - throw new Error(`Expected 10 memory tools, found ${tools.length}`); - } - } - async testNamespaceOperations() { - this.terminal.writeInfo('Testing namespace operations...'); - const originalNamespace = this.memoryManager.currentNamespace; - await this.memoryManager.switchNamespace('test'); - if (this.memoryManager.currentNamespace === 'test') { - this.terminal.writeSuccess('โœ… Namespace switching works'); - } else { - throw new Error('Namespace switching failed'); - } - await this.memoryManager.switchNamespace(originalNamespace); - } - async testMemoryOperations() { - this.terminal.writeInfo('Testing memory operations...'); - const testData = { - size: this.memoryManager.formatSize(1024), - ttl: this.memoryManager.formatTTL(Date.now() + 3600000), - truncate: this.memoryManager.truncateValue('This is a very long test string that should be truncated'), - escape: this.memoryManager.escapeHtml(''),\n };\n\n // Validate utility functions\n if (testData.size === '1 KB') {\n this.terminal.writeSuccess('โœ… Size formatting works');\n } else {\n throw new Error(`Size formatting failed: ${testData.size}`);\n }\n\n if (testData.ttl.includes('h') && testData.ttl.includes('m')) {\n this.terminal.writeSuccess('โœ… TTL formatting works');\n } else {\n throw new Error(`TTL formatting failed: ${testData.ttl}`);\n }\n\n if (testData.truncate.length <= 103) {\n // 100 + '...'\n this.terminal.writeSuccess('โœ… Value truncation works');\n } else {\n throw new Error('Value truncation failed');\n }\n\n if (!testData.escape.includes(' - - ``` - -### Usage - -1. Navigate to `/analysis-tools.html` in your browser -2. Use the tab navigation to switch between different views -3. Click tool buttons to execute analysis functions -4. Export data using the export buttons -5. Monitor real-time updates through the WebSocket connection - -## ๐Ÿ“ˆ Data Flow - -### Real-time Metrics - -1. **Collection**: Server collects metrics from various sources -2. **Processing**: Metrics are processed and stored in memory -3. **Broadcasting**: WebSocket broadcasts updates to connected clients -4. **Visualization**: Charts update automatically with new data - -### Tool Execution - -1. **Request**: User clicks tool button in UI -2. **API Call**: Frontend makes HTTP request to analysis API -3. **Processing**: Backend processes request and generates results -4. **Response**: Results are returned and displayed in UI -5. **Notification**: Swarm coordination hooks are triggered - -## ๐Ÿ” Monitoring & Alerts - -### Health Monitoring - -- **Component Health**: CPU, Memory, Disk, Network, API, Database -- **Health Scores**: 0-100 scale with color-coded indicators -- **Alert Thresholds**: Configurable warning and critical levels - -### Performance Monitoring - -- **Response Time**: Average, min, max response times -- **Throughput**: Requests per second/minute -- **Error Rate**: Percentage of failed requests -- **Uptime**: System availability metrics - -### Alert System - -- **Real-time Alerts**: Immediate notification of issues -- **Severity Levels**: Info, Warning, Critical -- **Auto-dismiss**: Configurable auto-dismiss for info alerts -- **Alert History**: Persistent alert logging - -## ๐Ÿ“Š Export & Reporting - -### Export Formats - -- **JSON**: Complete data export with metadata -- **CSV**: Tabular data export for spreadsheet analysis - -### Report Types - -- **Performance Reports**: Comprehensive performance analysis -- **Cost Reports**: Resource cost breakdown and optimization -- **Quality Reports**: System quality assessment -- **Health Reports**: Component health status - -## ๐ŸŽจ Customization - -### Styling - -- Modify `analysis-tools.css` for custom styling -- Responsive breakpoints for different screen sizes -- Dark mode support with CSS media queries - -### Configuration - -- Adjust WebSocket update intervals -- Configure alert thresholds -- Customize chart colors and types - -### Extension - -- Add new analysis tools following the existing pattern -- Implement additional chart types using Chart.js -- Extend API endpoints for custom metrics - -## ๐Ÿ”’ Security Considerations - -### Data Protection - -- Client-side data validation -- Secure WebSocket connections (WSS in production) -- API rate limiting implementation ready - -### Error Handling - -- Graceful error handling for failed requests -- User-friendly error messages -- Automatic retry mechanisms - -## ๐Ÿš€ Performance Optimization - -### Frontend Optimization - -- Lazy loading of chart components -- Efficient data update strategies -- Memory management for long-running sessions - -### Backend Optimization - -- Efficient metrics collection -- Optimized database queries (when integrated) -- Caching strategies for frequently accessed data - -## ๐Ÿ“ฑ Responsive Design - -### Mobile Support - -- Touch-friendly interface -- Responsive chart sizing -- Optimized navigation for small screens - -### Tablet Support - -- Optimized layout for tablet devices -- Touch gestures for chart interaction -- Efficient space utilization - -## ๐Ÿ”ง Development & Testing - -### Development Setup - -1. Start the development server -2. Open `analysis-tools.html` in browser -3. Monitor console for WebSocket connection status -4. Test all tool functions and exports - -### Testing Checklist - -- [ ] All 13 tools execute without errors -- [ ] WebSocket connection establishes successfully -- [ ] Real-time updates work correctly -- [ ] Export functions generate valid files -- [ ] Responsive design works on all devices -- [ ] Charts render and update properly -- [ ] Alert system functions correctly - -## ๐Ÿ“š API Documentation - -### Endpoint Structure - -``` -GET /api/analysis/{tool-name} -``` - -### Response Format - -```json -{ - "timestamp": 1234567890, - "summary": "Tool execution summary", - "data": { ... }, - "recommendations": [...], - "alerts": [...] -} -``` - -### WebSocket Messages - -```json -{ - "type": "metrics_update", - "payload": { - "performance": { ... }, - "tokens": { ... }, - "health": { ... }, - "load": { ... } - } -} -``` - -## ๐Ÿค Contributing - -### Adding New Tools - -1. Add tool button to HTML interface -2. Implement tool logic in JavaScript -3. Create API endpoint in backend router -4. Add styling for new components -5. Update documentation - -### Code Style - -- Follow existing naming conventions -- Use ES6+ features where appropriate -- Maintain consistent error handling -- Add comprehensive comments - -## ๐Ÿ“ž Support - -For issues or questions regarding the Analysis & Monitoring Tools: - -1. Check the console for error messages -2. Verify WebSocket connection status -3. Ensure all dependencies are installed -4. Review API endpoint responses - -## ๐Ÿ”„ Future Enhancements - -### Planned Features - -- Database integration for persistent metrics -- Advanced filtering and search capabilities -- Custom dashboard creation -- Multi-tenant support -- Advanced analytics and ML insights - -### Integration Opportunities - -- External monitoring tools -- Third-party alert systems -- Business intelligence platforms -- Custom metric sources - ---- - -**Agent 2 - Analysis & Monitoring Tools Developer** -_Complete implementation of 13 analysis and monitoring tools with real-time dashboards and WebSocket integration_ diff --git a/src/ui/console/README.md b/src/ui/console/README.md deleted file mode 100644 index 3361004576..0000000000 --- a/src/ui/console/README.md +++ /dev/null @@ -1,256 +0,0 @@ -# Claude Code Web Console - -A modern web-based terminal interface for Claude Code, providing an authentic console experience with real-time communication to the backend MCP server. - -## Features - -### Terminal Emulation - -- **Authentic Terminal Experience**: Console-style dark theme with monospace fonts -- **Real-time Output**: Live streaming of command output with proper formatting -- **Command History**: Navigate through previous commands with arrow keys -- **Input Handling**: Full keyboard support including Ctrl+L (clear), Ctrl+C (interrupt), Tab (autocomplete) -- **ANSI Color Support**: Processes ANSI escape codes for colored output - -### WebSocket Communication - -- **Real-time Bidirectional Communication**: Connects to Claude Code MCP server via WebSocket -- **Auto-reconnection**: Automatic reconnection with exponential backoff -- **Message Queuing**: Queues messages when disconnected and sends when reconnected -- **Heartbeat Mechanism**: Monitors connection health with ping/pong -- **Session Management**: Handles MCP protocol initialization and session state - -### Settings Management - -- **Connection Settings**: Server URL, authentication tokens, auto-connect -- **Appearance Customization**: Multiple themes (dark, light, classic, matrix), font size, line height -- **Behavior Options**: Auto-scroll, timestamps, sound notifications, history limits -- **Claude Flow Configuration**: Default SPARC modes, swarm strategies, coordination modes -- **Persistent Storage**: Settings saved to localStorage with import/export capabilities - -### Claude Flow Integration - -- **Built-in Commands**: Support for all major Claude Flow commands -- **SPARC Mode Support**: Integration with all 17 specialized SPARC modes -- **Swarm Management**: Web interface for swarm coordination and monitoring -- **Real-time Status**: Live updates of agent status, memory usage, and system metrics - -## Architecture - -### Component Structure - -``` -src/ui/console/ -โ”œโ”€โ”€ index.html # Main HTML structure -โ”œโ”€โ”€ styles/ -โ”‚ โ”œโ”€โ”€ console.css # Core console styling -โ”‚ โ”œโ”€โ”€ settings.css # Settings panel styling -โ”‚ โ””โ”€โ”€ responsive.css # Mobile/tablet responsive design -โ””โ”€โ”€ js/ - โ”œโ”€โ”€ console.js # Main application coordinator - โ”œโ”€โ”€ websocket-client.js # WebSocket communication layer - โ”œโ”€โ”€ terminal-emulator.js # Terminal behavior and display - โ”œโ”€โ”€ command-handler.js # Command processing and execution - โ””โ”€โ”€ settings.js # Configuration management -``` - -### Integration Points - -- **HTTP Transport**: Web console served at `/console` endpoint -- **WebSocket Endpoint**: Real-time communication via `/ws` endpoint -- **MCP Protocol**: Full JSON-RPC 2.0 compliant communication -- **Static Files**: CSS, JavaScript, and assets served via Express static middleware - -## Usage - -### Starting the Web Console - -1. Start Claude Code with HTTP transport enabled: - - ```bash - claude-flow start --transport http --port 3000 - ``` - -2. Open web browser and navigate to: - - ``` - http://localhost:3000/console - ``` - -3. The console will automatically attempt to connect to the WebSocket endpoint - -### Basic Commands - -- `help` - Show all available commands -- `connect [url] [token]` - Connect to Claude Code server -- `status` - Show connection and system status -- `clear` - Clear console output (or Ctrl+L) -- `claude-flow ` - Execute Claude Flow commands -- `swarm ` - Manage swarms -- `tools` - List available tools - -### Keyboard Shortcuts - -- **Enter** - Execute command -- **Tab** - Autocomplete command -- **โ†‘/โ†“** - Navigate command history -- **Ctrl+L** - Clear console -- **Ctrl+C** - Send interrupt signal -- **ESC** - Close settings panel - -### Settings Panel - -Access via the โš™๏ธ Settings button to configure: - -- Server connection details -- Visual appearance and themes -- Console behavior preferences -- Claude Flow default settings - -## Themes - -### Available Themes - -1. **Dark** (default) - Modern dark theme with blue accents -2. **Light** - Clean light theme for bright environments -3. **Classic** - Traditional green-on-black terminal -4. **Matrix** - Matrix-inspired green glow effect - -### Custom Styling - -The console uses CSS custom properties for easy theming: - -```css -:root { - --bg-primary: #0d1117; - --text-primary: #c9d1d9; - --console-prompt: #58a6ff; - --accent-primary: #1f6feb; -} -``` - -## Mobile Support - -### Responsive Design - -- **Tablet Landscape**: Optimized layout with condensed controls -- **Tablet Portrait**: Settings panel adapts to smaller screens -- **Mobile Landscape**: Minimized header and status bar -- **Mobile Portrait**: Full-screen overlay for settings, touch-optimized controls - -### Touch Interactions - -- Minimum 44px touch targets for accessibility -- 16px font size on inputs to prevent iOS zoom -- Gesture-friendly scrolling and selection -- Swipe gestures for panel management - -## Accessibility - -### Features - -- **Semantic HTML**: Proper ARIA labels and roles -- **Keyboard Navigation**: Full keyboard accessibility -- **Screen Reader Support**: Live regions for output updates -- **High Contrast**: Support for high contrast preferences -- **Reduced Motion**: Respects prefers-reduced-motion settings -- **Focus Management**: Clear focus indicators and logical tab order - -## Browser Compatibility - -### Supported Browsers - -- **Chrome/Chromium** 88+ -- **Firefox** 85+ -- **Safari** 14+ -- **Edge** 88+ - -### Required Features - -- ES2020 modules -- WebSocket API -- CSS Custom Properties -- localStorage API -- Fetch API - -## Development - -### Local Development - -1. Ensure Claude Code backend is running with HTTP transport -2. Open `src/ui/console/index.html` in a web browser -3. Modify settings to point to your local server URL - -### Building for Production - -The console is designed to be served as static files: - -```bash -# Copy console files to web server -cp -r src/ui/console/* /var/www/claude-console/ - -# Or serve via Node.js/Express -app.use('/console', express.static('src/ui/console')); -``` - -### Customization - -- Modify CSS custom properties for theming -- Extend command handlers for new functionality -- Add new WebSocket message handlers for custom notifications -- Customize settings panel for additional configuration options - -## Security Considerations - -### Authentication - -- Bearer token authentication support -- Secure WebSocket connections (WSS) in production -- CORS configuration for cross-origin requests -- Input validation and sanitization - -### Best Practices - -- Use HTTPS in production environments -- Configure proper CORS origins -- Implement rate limiting for WebSocket connections -- Validate all user inputs before processing - -## Performance - -### Optimizations - -- **Message Queuing**: Efficient handling of high-frequency messages -- **Output Limiting**: Configurable maximum lines to prevent memory issues -- **Lazy Loading**: Components loaded only when needed -- **Debounced Updates**: Status updates batched for performance - -### Memory Management - -- Automatic cleanup of old output lines -- Proper event listener cleanup on disconnect -- Garbage collection friendly object creation -- Minimal DOM manipulation for smooth scrolling - -## Troubleshooting - -### Common Issues - -1. **Connection Failed**: Check server URL and ensure Claude Code is running with HTTP transport -2. **WebSocket Errors**: Verify firewall settings and proxy configuration -3. **Authentication Issues**: Check bearer token format and validity -4. **Mobile Display Issues**: Ensure viewport meta tag is present -5. **Theme Not Loading**: Check CSS file paths and custom property support - -### Debug Mode - -Enable debug logging in browser developer tools: - -```javascript -// Access global console instance -window.claudeConsole.wsClient.debugMode = true; -``` - -## License - -Part of the Claude Code project. See main project LICENSE for details. diff --git a/src/ui/console/WORKFLOW_DESIGNER_README.md b/src/ui/console/WORKFLOW_DESIGNER_README.md deleted file mode 100644 index 5a756bf1d6..0000000000 --- a/src/ui/console/WORKFLOW_DESIGNER_README.md +++ /dev/null @@ -1,603 +0,0 @@ -# Claude Flow - Advanced Workflow Designer - -## Overview - -The Claude Flow Workflow Designer is a comprehensive visual workflow builder that enables users to create, execute, and manage complex data processing pipelines through an intuitive drag-and-drop interface. It features real-time execution, AI integration, and advanced validation capabilities. - -## Features - -### ๐ŸŽจ Visual Interface - -- **Drag-and-Drop Canvas**: Intuitive node-based workflow construction -- **Zoom & Pan**: Navigate large workflows with ease -- **Grid Snap**: Precision alignment for professional layouts -- **Context Menus**: Right-click for quick actions -- **Responsive Design**: Works on desktop and mobile devices - -### ๐Ÿงฉ Component Library - -- **Input Components**: File Input, Text Input, URL Input, API Input -- **Processing Components**: Transform, Filter, Aggregate, Sort -- **Output Components**: File Output, Display, API Output, Notification -- **Control Flow**: Condition, Loop, Delay, Parallel execution -- **AI Operations**: AI Analyze, AI Generate, AI Classify, AI Summarize - -### ๐Ÿ”— Connection System - -- **Visual Connections**: Drag between input/output ports -- **Type Validation**: Ensures compatible connections -- **Connection Management**: Easy editing and removal -- **Flow Visualization**: Clear data flow representation - -### ๐Ÿš€ Execution Engine - -- **Real-time Execution**: Watch workflows run in real-time -- **Status Tracking**: Visual indicators for node states -- **Progress Monitoring**: Detailed execution logs -- **Error Handling**: Comprehensive error reporting - -### โœ… Validation System - -- **Workflow Validation**: Checks for errors and warnings -- **Circular Dependency Detection**: Prevents infinite loops -- **Required Property Validation**: Ensures complete configuration -- **Connection Validation**: Verifies proper data flow - -### ๐Ÿ“š Template Gallery - -- **Pre-built Workflows**: Common patterns and examples -- **Template Categories**: Organized by use case -- **Quick Start**: Load templates to get started quickly -- **Custom Templates**: Save and share your own workflows - -## File Structure - -``` -/workspaces/claude-code-flow/src/ui/console/ -โ”œโ”€โ”€ js/ -โ”‚ โ””โ”€โ”€ workflow-designer.js # Main workflow designer class -โ”œโ”€โ”€ styles/ -โ”‚ โ””โ”€โ”€ workflow-designer.css # Complete styling system -โ”œโ”€โ”€ workflow-designer-demo.html # Demo page with examples -โ””โ”€โ”€ WORKFLOW_DESIGNER_README.md # This documentation -``` - -## Getting Started - -### Basic Usage - -1. **Open the Designer** - - ```html -
- - - ``` - -2. **Add Components** - - - Drag components from the left palette - - Drop them onto the canvas - - Components automatically snap to grid - -3. **Create Connections** - - - Click and drag from output ports (blue circles) - - Connect to input ports (green circles) - - Connections validate automatically - -4. **Configure Properties** - - - Select any node to see its properties - - Edit values in the right panel - - Changes apply immediately - -5. **Validate & Execute** - - Click "Validate" to check for errors - - Click "Execute" to run the workflow - - Monitor progress in the execution log - -### Advanced Features - -#### Custom Node Types - -```javascript -// Add custom node type -designer.nodeTypes.custom = { - inputs: [{ name: 'data', type: 'any' }], - outputs: [{ name: 'result', type: 'any' }], - properties: { customProp: 'defaultValue' }, -}; -``` - -#### Event Handling - -```javascript -// Listen for workflow events -designer.addEventListener('nodeAdded', (node) => { - console.log('Node added:', node); -}); - -designer.addEventListener('executionComplete', (results) => { - console.log('Execution complete:', results); -}); -``` - -#### Save/Load Workflows - -```javascript -// Save workflow -const workflow = designer.exportWorkflow(); -localStorage.setItem('myWorkflow', JSON.stringify(workflow)); - -// Load workflow -const saved = JSON.parse(localStorage.getItem('myWorkflow')); -designer.importWorkflow(saved); -``` - -## Component Types - -### Input Components - -#### File Input - -- **Purpose**: Read data from files -- **Properties**: - - `path`: File path - - `format`: File format (auto, json, csv, txt) -- **Outputs**: File data - -#### Text Input - -- **Purpose**: Manual text input -- **Properties**: - - `value`: Text content - - `multiline`: Single or multi-line input -- **Outputs**: Text string - -#### URL Input - -- **Purpose**: Fetch data from URLs -- **Properties**: - - `url`: Target URL - - `method`: HTTP method (GET, POST, etc.) - - `headers`: HTTP headers -- **Outputs**: Response data - -#### API Input - -- **Purpose**: Connect to APIs -- **Properties**: - - `endpoint`: API endpoint - - `method`: HTTP method - - `headers`: Request headers - - `body`: Request body -- **Outputs**: API response - -### Processing Components - -#### Transform - -- **Purpose**: Transform data using custom expressions -- **Properties**: - - `expression`: JavaScript expression - - `language`: Expression language -- **Inputs**: Data to transform -- **Outputs**: Transformed data - -#### Filter - -- **Purpose**: Filter data based on conditions -- **Properties**: - - `condition`: Filter condition - - `language`: Condition language -- **Inputs**: Data to filter -- **Outputs**: Filtered data - -#### Aggregate - -- **Purpose**: Aggregate data collections -- **Properties**: - - `operation`: Aggregation operation (sum, avg, count, etc.) - - `field`: Field to aggregate -- **Inputs**: Data array -- **Outputs**: Aggregated result - -#### Sort - -- **Purpose**: Sort data collections -- **Properties**: - - `field`: Sort field - - `order`: Sort order (asc, desc) -- **Inputs**: Data array -- **Outputs**: Sorted array - -### Output Components - -#### File Output - -- **Purpose**: Write data to files -- **Properties**: - - `path`: Output file path - - `format`: Output format -- **Inputs**: Data to write - -#### Display - -- **Purpose**: Display data in UI -- **Properties**: - - `format`: Display format (table, json, text) - - `title`: Display title -- **Inputs**: Data to display - -#### API Output - -- **Purpose**: Send data to APIs -- **Properties**: - - `endpoint`: Target API endpoint - - `method`: HTTP method - - `headers`: Request headers -- **Inputs**: Data to send -- **Outputs**: API response - -#### Notification - -- **Purpose**: Show user notifications -- **Properties**: - - `type`: Notification type (info, warning, error) - - `title`: Notification title -- **Inputs**: Message content - -### Control Flow Components - -#### Condition - -- **Purpose**: Conditional data routing -- **Properties**: - - `expression`: Condition expression - - `language`: Expression language -- **Inputs**: Condition value, data -- **Outputs**: True path, false path - -#### Loop - -- **Purpose**: Iterate over data -- **Properties**: - - `type`: Loop type (forEach, while, for) - - `condition`: Loop condition -- **Inputs**: Data to iterate -- **Outputs**: Iteration results - -#### Delay - -- **Purpose**: Add delays to workflow -- **Properties**: - - `duration`: Delay duration - - `unit`: Time unit (ms, s, m) -- **Inputs**: Data to delay -- **Outputs**: Delayed data - -#### Parallel - -- **Purpose**: Parallel execution -- **Properties**: - - `maxConcurrency`: Maximum concurrent operations -- **Inputs**: Data array -- **Outputs**: Parallel results - -### AI Components - -#### AI Analyze - -- **Purpose**: Analyze data using AI -- **Properties**: - - `model`: AI model (gpt-4, claude, etc.) - - `temperature`: Response creativity -- **Inputs**: Data to analyze -- **Outputs**: Analysis results - -#### AI Generate - -- **Purpose**: Generate content using AI -- **Properties**: - - `model`: AI model - - `temperature`: Response creativity - - `maxTokens`: Maximum response length -- **Inputs**: Generation prompt -- **Outputs**: Generated content - -#### AI Classify - -- **Purpose**: Classify data using AI -- **Properties**: - - `model`: AI model - - `categories`: Classification categories -- **Inputs**: Data to classify -- **Outputs**: Classification results - -#### AI Summarize - -- **Purpose**: Summarize content using AI -- **Properties**: - - `model`: AI model - - `length`: Summary length (short, medium, long) -- **Inputs**: Content to summarize -- **Outputs**: Summary text - -## API Reference - -### WorkflowDesigner Class - -#### Constructor - -```javascript -new WorkflowDesigner(containerId, options); -``` - -#### Methods - -##### Node Management - -- `createNode(type, x, y)`: Create new node -- `deleteNode(node)`: Delete node -- `duplicateNode(node)`: Duplicate node -- `getNodeAt(x, y)`: Get node at coordinates - -##### Connection Management - -- `createConnection(start, end)`: Create connection -- `deleteConnection(connection)`: Delete connection -- `getConnectionPointAt(x, y)`: Get connection point - -##### Workflow Operations - -- `validateWorkflow()`: Validate workflow -- `executeWorkflow()`: Execute workflow -- `stopWorkflow()`: Stop execution -- `clearCanvas()`: Clear all nodes - -##### Import/Export - -- `exportWorkflow()`: Export workflow data -- `importWorkflow(data)`: Import workflow data -- `saveWorkflow()`: Save to localStorage -- `loadWorkflow()`: Load from localStorage - -##### View Management - -- `setZoom(zoom)`: Set zoom level -- `pan(x, y)`: Pan canvas -- `draw()`: Redraw canvas - -### Events - -#### Node Events - -- `nodeAdded`: Node added to canvas -- `nodeDeleted`: Node deleted from canvas -- `nodeSelected`: Node selected -- `nodePropertyChanged`: Node property changed - -#### Connection Events - -- `connectionCreated`: Connection created -- `connectionDeleted`: Connection deleted - -#### Workflow Events - -- `workflowValidated`: Workflow validation complete -- `executionStarted`: Workflow execution started -- `executionComplete`: Workflow execution complete -- `executionError`: Workflow execution error - -#### Canvas Events - -- `canvasPan`: Canvas panned -- `canvasZoom`: Canvas zoomed -- `canvasClick`: Canvas clicked - -## Styling - -### CSS Classes - -#### Layout - -- `.workflow-designer`: Main container -- `.toolbar`: Top toolbar -- `.designer-body`: Main body area -- `.node-palette`: Left component palette -- `.canvas-container`: Canvas area -- `.properties-panel`: Right properties panel -- `.bottom-panel`: Bottom panel with tabs - -#### Components - -- `.palette-item`: Draggable palette items -- `.btn`: Button styling -- `.tab-button`: Tab navigation buttons -- `.context-menu`: Right-click context menu - -#### States - -- `.selected`: Selected node state -- `.executing`: Executing node state -- `.error`: Error state -- `.completed`: Completed state - -### Customization - -#### Custom Themes - -```css -/* Dark theme example */ -.workflow-designer.dark-theme { - background: #1a1a1a; - color: #ffffff; -} - -.workflow-designer.dark-theme .node-palette { - background: #2d2d2d; - border-color: #444444; -} -``` - -#### Custom Node Styles - -```css -/* Custom node type styling */ -.palette-item[data-node-type='custom'] { - border-color: #purple; - background: #f3e5f5; -} - -.palette-item[data-node-type='custom'] i { - color: #purple; -} -``` - -## Examples - -### Basic Data Processing - -```javascript -// Create a simple data processing workflow -const fileInput = designer.createNode('file-input', 100, 150); -const transform = designer.createNode('transform', 300, 150); -const display = designer.createNode('display', 500, 150); - -// Configure properties -fileInput.properties.path = 'data.json'; -transform.properties.expression = 'data.map(item => item.value * 2)'; -display.properties.format = 'table'; - -// Connect nodes -designer.createConnection( - { node: fileInput, type: 'output', index: 0 }, - { node: transform, type: 'input', index: 0 }, -); -designer.createConnection( - { node: transform, type: 'output', index: 0 }, - { node: display, type: 'input', index: 0 }, -); -``` - -### AI Content Pipeline - -```javascript -// Create an AI content processing workflow -const textInput = designer.createNode('text-input', 100, 150); -const aiAnalyze = designer.createNode('ai-analyze', 300, 150); -const condition = designer.createNode('condition', 500, 150); -const aiGenerate = designer.createNode('ai-generate', 700, 100); -const aiSummarize = designer.createNode('ai-summarize', 700, 200); - -// Configure AI properties -aiAnalyze.properties.model = 'gpt-4'; -aiAnalyze.properties.temperature = 0.7; -condition.properties.expression = 'data.confidence > 0.8'; -aiGenerate.properties.prompt = 'Expand on: {{data}}'; -aiSummarize.properties.length = 'short'; -``` - -### API Integration - -```javascript -// Create an API integration workflow -const apiInput = designer.createNode('api-input', 100, 150); -const filter = designer.createNode('filter', 300, 150); -const aggregate = designer.createNode('aggregate', 500, 150); -const apiOutput = designer.createNode('api-output', 700, 150); - -// Configure API properties -apiInput.properties.endpoint = 'https://api.example.com/data'; -apiInput.properties.method = 'GET'; -filter.properties.condition = 'item.status === "active"'; -aggregate.properties.operation = 'sum'; -aggregate.properties.field = 'value'; -apiOutput.properties.endpoint = 'https://api.example.com/results'; -``` - -## Best Practices - -### Workflow Design - -1. **Start Simple**: Begin with basic workflows and add complexity gradually -2. **Use Templates**: Leverage pre-built templates for common patterns -3. **Validate Early**: Validate workflows before execution -4. **Handle Errors**: Always include error handling in workflows -5. **Document**: Use descriptive names and comments - -### Performance - -1. **Minimize Connections**: Reduce unnecessary data passing -2. **Use Parallel**: Leverage parallel processing where possible -3. **Cache Results**: Cache expensive operations -4. **Optimize AI**: Use appropriate AI models for tasks -5. **Monitor Resources**: Watch memory and CPU usage - -### Security - -1. **Validate Inputs**: Always validate external data -2. **Sanitize**: Clean user inputs before processing -3. **Secure APIs**: Use proper authentication -4. **Limit Access**: Restrict file system access -5. **Audit Logs**: Keep execution logs for security - -## Troubleshooting - -### Common Issues - -#### Nodes Not Connecting - -- Check port compatibility -- Ensure proper drag direction -- Verify node positions - -#### Execution Errors - -- Validate workflow first -- Check node properties -- Review execution logs - -#### Performance Issues - -- Reduce workflow complexity -- Use parallel processing -- Optimize AI calls - -#### UI Problems - -- Clear browser cache -- Check browser compatibility -- Verify CSS/JS loading - -### Debug Mode - -```javascript -// Enable debug mode -designer.debug = true; - -// View debug information -console.log(designer.getDebugInfo()); -``` - -## Browser Support - -- Chrome 80+ -- Firefox 75+ -- Safari 13+ -- Edge 80+ - -## License - -This component is part of the Claude Flow system and follows the project's licensing terms. - -## Contributing - -Contributions are welcome! Please follow the project's contribution guidelines and ensure all tests pass before submitting pull requests. - -## Support - -For support, please create an issue in the project repository or contact the development team. diff --git a/src/ui/console/analysis-tools.html b/src/ui/console/analysis-tools.html deleted file mode 100644 index 50daa8e160..0000000000 --- a/src/ui/console/analysis-tools.html +++ /dev/null @@ -1,316 +0,0 @@ - - - - - - Claude Flow - Analysis & Monitoring Tools - - - - - - - -
- -
-

Analysis & Monitoring Tools

-
Disconnected
-
- - - - - -
- -
-
- -
-

๐Ÿ“Š Performance Metrics

-
-
-
Response Time
-
--
-
-
-
Throughput
-
--
-
-
-
Error Rate
-
--
-
-
-
Uptime
-
--
-
-
-
-
Performance Over Time
-
- -
-
-
- - -
-

๐ŸŽฏ Token Usage

-
-
-
Total Tokens
-
--
-
-
-
Input Tokens
-
--
-
-
-
Output Tokens
-
--
-
-
-
Cache Hit Rate
-
--
-
-
-
-
Token Distribution
-
- -
-
-
-
- - -
-

๐Ÿ”ง Metrics Tools

-
- - - - -
-
- - - -
-
-
- - -
-
-

๐Ÿ“‹ Report Generation

-
- - - - -
-
- - - -
-
- - -
-

๐Ÿ“Š Report Output

-
- Click on a report tool above to generate reports... -
-
-
- - -
-
-

๐Ÿ” Analysis Tools

-
- - - - -
-
- - - -
-
- - -
-

๐Ÿ” Analysis Results

-
- Click on an analysis tool above to view results... -
-
- -
-

๐Ÿ“ˆ Trend Analysis

- -
- -
-

โŒ Error Analysis

-
- Error analysis results will appear here... -
-
- -
-

๐Ÿ“ Capacity Planning

-
- Capacity planning results will appear here... -
-
-
- - -
-
-

๐Ÿฅ System Health

-
-
-
--
-
Overall Health
-
-
-
- CPU - --% -
-
- Memory - --% -
-
- Disk - --% -
-
- Network - --% -
-
- API - --% -
-
- Database - --% -
-
-
-
-
System Health Overview
-
- -
-
-
- -
-

โšก Load Monitoring

-
-
Load Over Time
-
- -
-
-
- -
-

๐Ÿฅ Health Tools

-
- - -
-
- - - -
-
- - -
-

๐Ÿฅ Health Check Results

-
- Click on a health tool above to view results... -
-
- -
-

โšก Load Monitor Results

-
- Load monitoring results will appear here... -
-
- - -
-

๐Ÿšจ System Alerts

-
-
-
- System Started - 12:00:00 -
-
- Analysis & Monitoring Tools initialized successfully -
- -
-
-
-
-
-
- - -
-
-
-
-
-
-
-
- - - - diff --git a/src/ui/console/analytics.html b/src/ui/console/analytics.html deleted file mode 100644 index 84d1ce6016..0000000000 --- a/src/ui/console/analytics.html +++ /dev/null @@ -1,376 +0,0 @@ - - - - - - - ๐Ÿ“Š Claude Flow Analytics Dashboard - - - - - - - - - - - -
-
-

- ๐Ÿ“Š - Claude Flow Analytics -

-
- - Connecting... -
-
-
- - - - -
-
- - -
- -
-
-
โšก
-
-
--
-
Performance Score
-
--
-
-
- -
-
๐Ÿช™
-
-
--
-
Tokens Used
-
--
-
-
- -
-
๐Ÿ’š
-
-
--
-
System Health
-
--
-
-
- -
-
๐Ÿ’ฐ
-
-
--
-
Estimated Cost
-
--
-
-
-
- - -
- -
-
-

๐Ÿ“ˆPerformance Monitoring

-
- - -
-
-
-
- -
-
- -
-
-
- - -
-
-

๐Ÿช™Token Usage Analytics

-
- - -
-
-
-
- -
-
- -
-
-
- - -
-
-

๐ŸฅSystem Health Monitor

-
- - -
-
-
-
-
- - CPU - -- -
-
- - Memory - -- -
-
- - Swarm - -- -
-
- - Network - -- -
-
-
- -
-
-
- - -
-
-

๐Ÿ”Error Analysis

-
- - -
-
-
-
-
- 0 - Total Errors -
-
- 0% - Error Rate -
-
-
- -
-
-
- - -
-
-

โœ…Quality Assessment

-
- - -
-
-
-
-
- -- - Overall Quality -
-
-
- Code Quality -
-
-
- -- -
-
- Response Quality -
-
-
- -- -
-
- Coordination Quality -
-
-
- -- -
-
-
-
-
- - -
-
-

๐Ÿ“ŠUsage Statistics

-
- - -
-
-
-
-
- Commands Executed - -- -
-
- Files Processed - -- -
-
- Swarms Created - -- -
-
- Avg Response Time - -- -
-
-
- -
-
-
-
- - -
-
-

๐Ÿ“Real-time Activity Log

-
- - - -
-
-
- -
-
-
- - - - - -
-
-
-
Loading analytics data...
-
-
- - - - - - - - diff --git a/src/ui/console/index.html b/src/ui/console/index.html deleted file mode 100644 index 42cfd4326b..0000000000 --- a/src/ui/console/index.html +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - ๐ŸŒŠ Claude Flow v2 - - - - - - - - - - -
-
-

- ๐ŸŒŠ - Claude Flow v2 -

-
- - Connecting... -
-
-
- - - -
-
- - -
- - - - -
- -
-
-
- ๐ŸŒŠ Claude Flow v2.0.0 Welcome to the web-based swarm orchestration console Type 'help' - for available commands Use Ctrl+L to clear console -
-
-
- - -
-
- claude-flow> - -
- -
-
-
- - -
-
- Mode: Standalone - Agents: 0 - Uptime: 00:00:00 -
-
- Memory: -- - Messages: 0 - -
-
- - -
-
-
-
Connecting to Claude Code...
-
-
- - - - - - - - - - - - diff --git a/src/ui/console/js/analysis-tools.js b/src/ui/console/js/analysis-tools.js deleted file mode 100644 index b81d2dda1d..0000000000 --- a/src/ui/console/js/analysis-tools.js +++ /dev/null @@ -1,1054 +0,0 @@ -/** - * Analysis & Monitoring Tools for Claude Flow Web UI - * Agent 2 - Analysis & Monitoring Tools Developer - * - * Features: - * - 13 analysis and monitoring tools - * - Real-time dashboards and visualizations - * - WebSocket integration for live data - * - Export functionality for reports - * - 4 main tabs: Metrics, Reports, Analysis, Health - */ - -class AnalysisTools { - constructor() { - this.ws = null; - this.charts = {}; - this.currentTab = 'metrics'; - this.isConnected = false; - this.metricsCache = new Map(); - this.updateInterval = null; - this.init(); - } - - init() { - this.setupWebSocket(); - this.setupEventListeners(); - this.initializeCharts(); - this.startRealTimeUpdates(); - } - - setupWebSocket() { - try { - this.ws = new WebSocket('ws://localhost:3000/analysis'); - - this.ws.onopen = () => { - this.isConnected = true; - console.log('Analysis WebSocket connected'); - this.updateConnectionStatus('connected'); - }; - - this.ws.onmessage = (event) => { - const data = JSON.parse(event.data); - this.handleWebSocketData(data); - }; - - this.ws.onclose = () => { - this.isConnected = false; - console.log('Analysis WebSocket disconnected'); - this.updateConnectionStatus('disconnected'); - setTimeout(() => this.setupWebSocket(), 5000); - }; - - this.ws.onerror = (error) => { - console.error('Analysis WebSocket error:', error); - this.updateConnectionStatus('error'); - }; - } catch (error) { - console.error('Failed to setup WebSocket:', error); - this.updateConnectionStatus('error'); - } - } - - setupEventListeners() { - // Tab switching - document.querySelectorAll('.analysis-tab').forEach((tab) => { - tab.addEventListener('click', (e) => { - this.switchTab(e.target.dataset.tab); - }); - }); - - // Export buttons - document.querySelectorAll('.export-btn').forEach((btn) => { - btn.addEventListener('click', (e) => { - const format = e.target.dataset.format; - const type = e.target.dataset.type; - this.exportData(type, format); - }); - }); - - // Tool buttons - document.querySelectorAll('.tool-btn').forEach((btn) => { - btn.addEventListener('click', (e) => { - const tool = e.target.dataset.tool; - this.executeTool(tool); - }); - }); - - // Refresh buttons - document.querySelectorAll('.refresh-btn').forEach((btn) => { - btn.addEventListener('click', (e) => { - const section = e.target.dataset.section; - this.refreshSection(section); - }); - }); - } - - initializeCharts() { - // Performance metrics chart - this.charts.performance = new Chart(document.getElementById('performance-chart'), { - type: 'line', - data: { - labels: [], - datasets: [ - { - label: 'Response Time (ms)', - data: [], - borderColor: '#3b82f6', - backgroundColor: 'rgba(59, 130, 246, 0.1)', - tension: 0.4, - }, - { - label: 'Throughput (req/s)', - data: [], - borderColor: '#10b981', - backgroundColor: 'rgba(16, 185, 129, 0.1)', - tension: 0.4, - }, - ], - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'top', - }, - }, - scales: { - x: { - display: true, - title: { - display: true, - text: 'Time', - }, - }, - y: { - display: true, - title: { - display: true, - text: 'Value', - }, - }, - }, - }, - }); - - // Token usage chart - this.charts.tokenUsage = new Chart(document.getElementById('token-usage-chart'), { - type: 'doughnut', - data: { - labels: ['Input Tokens', 'Output Tokens', 'Cached Tokens'], - datasets: [ - { - data: [0, 0, 0], - backgroundColor: ['#3b82f6', '#10b981', '#f59e0b'], - borderWidth: 2, - }, - ], - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'bottom', - }, - }, - }, - }); - - // System health chart - this.charts.systemHealth = new Chart(document.getElementById('system-health-chart'), { - type: 'radar', - data: { - labels: ['CPU', 'Memory', 'Disk', 'Network', 'API', 'Database'], - datasets: [ - { - label: 'Health Score', - data: [100, 100, 100, 100, 100, 100], - borderColor: '#10b981', - backgroundColor: 'rgba(16, 185, 129, 0.2)', - pointBackgroundColor: '#10b981', - pointBorderColor: '#fff', - pointHoverBackgroundColor: '#fff', - pointHoverBorderColor: '#10b981', - }, - ], - }, - options: { - responsive: true, - maintainAspectRatio: false, - scales: { - r: { - beginAtZero: true, - max: 100, - }, - }, - }, - }); - - // Load monitoring chart - this.charts.loadMonitor = new Chart(document.getElementById('load-monitor-chart'), { - type: 'bar', - data: { - labels: ['1m', '5m', '15m', '30m', '1h', '24h'], - datasets: [ - { - label: 'Average Load', - data: [0, 0, 0, 0, 0, 0], - backgroundColor: 'rgba(59, 130, 246, 0.7)', - borderColor: '#3b82f6', - borderWidth: 1, - }, - ], - }, - options: { - responsive: true, - maintainAspectRatio: false, - plugins: { - legend: { - position: 'top', - }, - }, - scales: { - y: { - beginAtZero: true, - }, - }, - }, - }); - } - - startRealTimeUpdates() { - this.updateInterval = setInterval(() => { - if (this.isConnected) { - this.requestMetricsUpdate(); - } - }, 5000); - } - - requestMetricsUpdate() { - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send( - JSON.stringify({ - type: 'request_metrics', - timestamp: Date.now(), - }), - ); - } - } - - handleWebSocketData(data) { - switch (data.type) { - case 'metrics_update': - this.updateMetrics(data.payload); - break; - case 'alert': - this.handleAlert(data.payload); - break; - case 'health_status': - this.updateHealthStatus(data.payload); - break; - default: - console.log('Unknown WebSocket message type:', data.type); - } - } - - updateMetrics(metrics) { - this.metricsCache.set('latest', metrics); - - // Update performance chart - if (this.charts.performance && metrics.performance) { - const chart = this.charts.performance; - const now = new Date().toLocaleTimeString(); - - chart.data.labels.push(now); - chart.data.datasets[0].data.push(metrics.performance.responseTime); - chart.data.datasets[1].data.push(metrics.performance.throughput); - - // Keep only last 20 data points - if (chart.data.labels.length > 20) { - chart.data.labels.shift(); - chart.data.datasets[0].data.shift(); - chart.data.datasets[1].data.shift(); - } - - chart.update('none'); - } - - // Update token usage chart - if (this.charts.tokenUsage && metrics.tokens) { - const chart = this.charts.tokenUsage; - chart.data.datasets[0].data = [ - metrics.tokens.input, - metrics.tokens.output, - metrics.tokens.cached, - ]; - chart.update('none'); - } - - // Update system health chart - if (this.charts.systemHealth && metrics.health) { - const chart = this.charts.systemHealth; - chart.data.datasets[0].data = [ - metrics.health.cpu, - metrics.health.memory, - metrics.health.disk, - metrics.health.network, - metrics.health.api, - metrics.health.database, - ]; - chart.update('none'); - } - - // Update load monitor chart - if (this.charts.loadMonitor && metrics.load) { - const chart = this.charts.loadMonitor; - chart.data.datasets[0].data = [ - metrics.load.oneMin, - metrics.load.fiveMin, - metrics.load.fifteenMin, - metrics.load.thirtyMin, - metrics.load.oneHour, - metrics.load.twentyFourHour, - ]; - chart.update('none'); - } - - // Update metric displays - this.updateMetricDisplays(metrics); - } - - updateMetricDisplays(metrics) { - // Performance metrics - const perfSection = document.getElementById('performance-metrics'); - if (perfSection && metrics.performance) { - perfSection.innerHTML = ` -
-
Response Time
-
${metrics.performance.responseTime}ms
-
-
-
Throughput
-
${metrics.performance.throughput} req/s
-
-
-
Error Rate
-
${metrics.performance.errorRate}%
-
-
-
Uptime
-
${metrics.performance.uptime}
-
- `; - } - - // Token usage metrics - const tokenSection = document.getElementById('token-metrics'); - if (tokenSection && metrics.tokens) { - const total = metrics.tokens.input + metrics.tokens.output + metrics.tokens.cached; - tokenSection.innerHTML = ` -
-
Total Tokens
-
${total.toLocaleString()}
-
-
-
Input Tokens
-
${metrics.tokens.input.toLocaleString()}
-
-
-
Output Tokens
-
${metrics.tokens.output.toLocaleString()}
-
-
-
Cache Hit Rate
-
${((metrics.tokens.cached / total) * 100).toFixed(1)}%
-
- `; - } - - // System health status - const healthSection = document.getElementById('health-status'); - if (healthSection && metrics.health) { - const overallHealth = Math.round( - (metrics.health.cpu + - metrics.health.memory + - metrics.health.disk + - metrics.health.network + - metrics.health.api + - metrics.health.database) / - 6, - ); - - healthSection.innerHTML = ` -
-
- ${overallHealth}% -
-
Overall Health
-
-
-
- CPU - ${metrics.health.cpu}% -
-
- Memory - ${metrics.health.memory}% -
-
- Disk - ${metrics.health.disk}% -
-
- Network - ${metrics.health.network}% -
-
- API - ${metrics.health.api}% -
-
- Database - ${metrics.health.database}% -
-
- `; - } - } - - getHealthClass(score) { - if (score >= 90) return 'health-excellent'; - if (score >= 70) return 'health-good'; - if (score >= 50) return 'health-warning'; - return 'health-critical'; - } - - handleAlert(alert) { - const alertsContainer = document.getElementById('alerts-container'); - if (alertsContainer) { - const alertElement = document.createElement('div'); - alertElement.className = `alert alert-${alert.severity}`; - alertElement.innerHTML = ` -
- ${alert.title} - ${new Date(alert.timestamp).toLocaleTimeString()} -
-
${alert.message}
- - `; - alertsContainer.insertBefore(alertElement, alertsContainer.firstChild); - - // Auto-dismiss after 10 seconds for info alerts - if (alert.severity === 'info') { - setTimeout(() => { - if (alertElement.parentElement) { - alertElement.remove(); - } - }, 10000); - } - } - } - - switchTab(tabName) { - this.currentTab = tabName; - - // Update tab buttons - document.querySelectorAll('.analysis-tab').forEach((tab) => { - tab.classList.remove('active'); - }); - document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); - - // Update content panels - document.querySelectorAll('.analysis-panel').forEach((panel) => { - panel.classList.remove('active'); - }); - document.getElementById(`${tabName}-panel`).classList.add('active'); - - // Refresh charts when switching tabs - setTimeout(() => { - Object.values(this.charts).forEach((chart) => { - if (chart && chart.resize) { - chart.resize(); - } - }); - }, 100); - } - - // Tool execution methods - async executeTool(toolName) { - const button = document.querySelector(`[data-tool="${toolName}"]`); - if (button) { - button.classList.add('loading'); - button.disabled = true; - } - - try { - switch (toolName) { - case 'performance_report': - await this.performanceReport(); - break; - case 'bottleneck_analyze': - await this.bottleneckAnalyze(); - break; - case 'token_usage': - await this.tokenUsage(); - break; - case 'benchmark_run': - await this.benchmarkRun(); - break; - case 'metrics_collect': - await this.metricsCollect(); - break; - case 'trend_analysis': - await this.trendAnalysis(); - break; - case 'cost_analysis': - await this.costAnalysis(); - break; - case 'quality_assess': - await this.qualityAssess(); - break; - case 'error_analysis': - await this.errorAnalysis(); - break; - case 'usage_stats': - await this.usageStats(); - break; - case 'health_check': - await this.healthCheck(); - break; - case 'load_monitor': - await this.loadMonitor(); - break; - case 'capacity_plan': - await this.capacityPlan(); - break; - default: - console.warn('Unknown tool:', toolName); - } - } catch (error) { - console.error(`Error executing tool ${toolName}:`, error); - this.showError(`Failed to execute ${toolName}: ${error.message}`); - } finally { - if (button) { - button.classList.remove('loading'); - button.disabled = false; - } - } - } - - // Tool implementations - async performanceReport() { - try { - const report = await this.fetchAnalysisData('/api/analysis/performance-report'); - this.displayReport('performance-report-output', report); - await this.notifyToolCompletion('performance_report'); - } catch (error) { - this.displayError( - 'performance-report-output', - 'Unable to fetch performance report. Please ensure the analysis service is running.', - ); - } - } - - async bottleneckAnalyze() { - try { - const analysis = await this.fetchAnalysisData('/api/analysis/bottleneck-analyze'); - this.displayAnalysis('bottleneck-analysis-output', analysis); - await this.notifyToolCompletion('bottleneck_analyze'); - } catch (error) { - this.displayError( - 'bottleneck-analysis-output', - 'Unable to fetch bottleneck analysis. Please ensure the analysis service is running.', - ); - } - } - - async tokenUsage() { - try { - const usage = await this.fetchAnalysisData('/api/analysis/token-usage'); - this.displayUsage('token-usage-output', usage); - await this.notifyToolCompletion('token_usage'); - } catch (error) { - this.displayError( - 'token-usage-output', - 'Unable to fetch token usage data. Please ensure the analysis service is running.', - ); - } - } - - async benchmarkRun() { - try { - const benchmark = await this.fetchAnalysisData('/api/analysis/benchmark-run'); - this.displayBenchmark('benchmark-output', benchmark); - await this.notifyToolCompletion('benchmark_run'); - } catch (error) { - this.displayError( - 'benchmark-output', - 'Unable to run benchmark. Please ensure the analysis service is running.', - ); - } - } - - async metricsCollect() { - try { - const metrics = await this.fetchAnalysisData('/api/analysis/metrics-collect'); - this.displayMetrics('metrics-output', metrics); - await this.notifyToolCompletion('metrics_collect'); - } catch (error) { - this.displayError( - 'metrics-output', - 'Unable to collect metrics. Please ensure the analysis service is running.', - ); - } - } - - async trendAnalysis() { - try { - const trends = await this.fetchAnalysisData('/api/analysis/trend-analysis'); - this.displayTrends('trends-output', trends); - await this.notifyToolCompletion('trend_analysis'); - } catch (error) { - this.displayError( - 'trends-output', - 'Unable to fetch trend analysis. Please ensure the analysis service is running.', - ); - } - } - - async costAnalysis() { - try { - const costs = await this.fetchAnalysisData('/api/analysis/cost-analysis'); - this.displayCosts('costs-output', costs); - await this.notifyToolCompletion('cost_analysis'); - } catch (error) { - this.displayError( - 'costs-output', - 'Unable to fetch cost analysis. Please ensure the analysis service is running.', - ); - } - } - - async qualityAssess() { - try { - const quality = await this.fetchAnalysisData('/api/analysis/quality-assess'); - this.displayQuality('quality-output', quality); - await this.notifyToolCompletion('quality_assess'); - } catch (error) { - this.displayError( - 'quality-output', - 'Unable to assess quality. Please ensure the analysis service is running.', - ); - } - } - - async errorAnalysis() { - try { - const errors = await this.fetchAnalysisData('/api/analysis/error-analysis'); - this.displayErrors('errors-output', errors); - await this.notifyToolCompletion('error_analysis'); - } catch (error) { - this.displayError( - 'errors-output', - 'Unable to fetch error analysis. Please ensure the analysis service is running.', - ); - } - } - - async usageStats() { - try { - const stats = await this.fetchAnalysisData('/api/analysis/usage-stats'); - this.displayStats('stats-output', stats); - await this.notifyToolCompletion('usage_stats'); - } catch (error) { - this.displayError( - 'stats-output', - 'Unable to fetch usage statistics. Please ensure the analysis service is running.', - ); - } - } - - async healthCheck() { - try { - const health = await this.fetchAnalysisData('/api/analysis/health-check'); - this.displayHealth('health-output', health); - await this.notifyToolCompletion('health_check'); - } catch (error) { - this.displayError( - 'health-output', - 'Unable to perform health check. Please ensure the analysis service is running.', - ); - } - } - - async loadMonitor() { - try { - const load = await this.fetchAnalysisData('/api/analysis/load-monitor'); - this.displayLoad('load-output', load); - await this.notifyToolCompletion('load_monitor'); - } catch (error) { - this.displayError( - 'load-output', - 'Unable to monitor load. Please ensure the analysis service is running.', - ); - } - } - - async capacityPlan() { - try { - const capacity = await this.fetchAnalysisData('/api/analysis/capacity-plan'); - this.displayCapacity('capacity-output', capacity); - await this.notifyToolCompletion('capacity_plan'); - } catch (error) { - this.displayError( - 'capacity-output', - 'Unable to fetch capacity plan. Please ensure the analysis service is running.', - ); - } - } - - async fetchAnalysisData(endpoint) { - try { - const response = await fetch(endpoint); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - return await response.json(); - } catch (error) { - console.error('Fetch error:', error); - // Show error message instead of falling back to mock data - this.showError(`Failed to fetch data from ${endpoint}: ${error.message}`); - throw error; // Re-throw to let calling functions handle the error - } - } - - getMockData(endpoint) { - const mockData = { - '/api/analysis/performance-report': { - summary: 'System performance is within acceptable ranges', - metrics: { - averageResponseTime: 245, - throughput: 1250, - errorRate: 0.02, - uptime: '99.8%', - }, - recommendations: [ - 'Consider caching frequently accessed data', - 'Optimize database queries for better performance', - 'Monitor memory usage during peak hours', - ], - }, - '/api/analysis/bottleneck-analyze': { - bottlenecks: [ - { component: 'Database', severity: 'medium', impact: 'Response time +15%' }, - { component: 'API Gateway', severity: 'low', impact: 'Throughput -5%' }, - ], - recommendations: [ - 'Add database read replicas', - 'Implement connection pooling', - 'Optimize slow queries', - ], - }, - '/api/analysis/token-usage': { - totalTokens: 2450000, - inputTokens: 1200000, - outputTokens: 950000, - cachedTokens: 300000, - cost: 245.5, - efficiency: 85.2, - }, - }; - return mockData[endpoint] || { message: 'No data available' }; - } - - displayReport(containerId, report) { - const container = document.getElementById(containerId); - if (!container) return; - - container.innerHTML = ` -
-

Performance Report

-

${report.summary}

-
-
-
-
- - ${report.metrics.averageResponseTime}ms -
-
- - ${report.metrics.throughput} req/s -
-
- - ${(report.metrics.errorRate * 100).toFixed(2)}% -
-
- - ${report.metrics.uptime} -
-
-
-
-

Recommendations

-
    - ${report.recommendations.map((rec) => `
  • ${rec}
  • `).join('')} -
-
- `; - } - - displayAnalysis(containerId, analysis) { - const container = document.getElementById(containerId); - if (!container) return; - - container.innerHTML = ` -
-

Bottleneck Analysis

-
- ${analysis.bottlenecks - .map( - (bottleneck) => ` -
-
${bottleneck.component}
-
${bottleneck.severity}
-
${bottleneck.impact}
-
- `, - ) - .join('')} -
-
-

Recommendations

-
    - ${analysis.recommendations.map((rec) => `
  • ${rec}
  • `).join('')} -
-
-
- `; - } - - displayUsage(containerId, usage) { - const container = document.getElementById(containerId); - if (!container) return; - - container.innerHTML = ` -
-

Token Usage Analysis

-
-
- - ${usage.totalTokens.toLocaleString()} -
-
- - ${usage.inputTokens.toLocaleString()} -
-
- - ${usage.outputTokens.toLocaleString()} -
-
- - ${usage.cachedTokens.toLocaleString()} -
-
- - $${usage.cost.toFixed(2)} -
-
- - ${usage.efficiency.toFixed(1)}% -
-
-
- `; - } - - exportData(type, format) { - const data = this.metricsCache.get('latest') || {}; - const timestamp = new Date().toISOString().split('T')[0]; - const filename = `${type}_${timestamp}.${format}`; - - if (format === 'json') { - this.downloadJSON(data, filename); - } else if (format === 'csv') { - this.downloadCSV(data, filename); - } - } - - downloadJSON(data, filename) { - const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); - URL.revokeObjectURL(url); - } - - downloadCSV(data, filename) { - const csv = this.jsonToCSV(data); - const blob = new Blob([csv], { type: 'text/csv' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - a.click(); - URL.revokeObjectURL(url); - } - - jsonToCSV(json) { - const flatten = (obj, prefix = '') => { - const flattened = {}; - for (const key in obj) { - if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) { - Object.assign(flattened, flatten(obj[key], prefix + key + '.')); - } else { - // Convert arrays to JSON strings for CSV - flattened[prefix + key] = Array.isArray(obj[key]) ? JSON.stringify(obj[key]) : obj[key]; - } - } - return flattened; - }; - - const flattened = flatten(json); - const headers = Object.keys(flattened); - const valueRow = headers - .map((header) => { - const value = flattened[header]; - if (value === null || value === undefined) { - return ''; - } - let strValue = String(value); - // Escape CSV values that contain commas, quotes, or newlines - if (strValue.includes(',') || strValue.includes('"') || strValue.includes('\n')) { - strValue = '"' + strValue.replace(/"/g, '""') + '"'; - } - return strValue; - }) - .join(','); - - return [headers.join(','), valueRow].join('\n'); - } - - refreshSection(section) { - switch (section) { - case 'metrics': - this.requestMetricsUpdate(); - break; - case 'charts': - Object.values(this.charts).forEach((chart) => { - if (chart && chart.update) { - chart.update(); - } - }); - break; - case 'alerts': - document.getElementById('alerts-container').innerHTML = ''; - break; - default: - console.warn('Unknown section:', section); - } - } - - updateConnectionStatus(status) { - const statusElement = document.getElementById('connection-status'); - if (statusElement) { - statusElement.className = `connection-status ${status}`; - statusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1); - } - } - - showError(message) { - const errorElement = document.createElement('div'); - errorElement.className = 'error-message'; - errorElement.textContent = message; - document.body.appendChild(errorElement); - - setTimeout(() => { - errorElement.remove(); - }, 5000); - } - - displayError(containerId, message) { - const container = document.getElementById(containerId); - if (!container) return; - - container.innerHTML = ` -
-
โŒ
-
-

Error

-

${message}

-
-
- - -
-
- `; - } - - async notifyToolCompletion(toolName) { - try { - // Notify swarm of tool completion - const response = await fetch('/api/swarm/notify', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - message: `${toolName} completed`, - timestamp: Date.now(), - agent: 'analysis-tools', - }), - }); - - if (!response.ok) { - console.warn('Failed to notify swarm'); - } - } catch (error) { - console.error('Error notifying swarm:', error); - } - } - - destroy() { - if (this.updateInterval) { - clearInterval(this.updateInterval); - } - - if (this.ws) { - this.ws.close(); - } - - Object.values(this.charts).forEach((chart) => { - if (chart && chart.destroy) { - chart.destroy(); - } - }); - } -} - -// Initialize when DOM is ready -document.addEventListener('DOMContentLoaded', () => { - window.analysisTools = new AnalysisTools(); -}); - -// Export for module use -if (typeof module !== 'undefined' && module.exports) { - module.exports = AnalysisTools; -} diff --git a/src/ui/console/js/command-handler.js b/src/ui/console/js/command-handler.js deleted file mode 100644 index bf09cc3244..0000000000 --- a/src/ui/console/js/command-handler.js +++ /dev/null @@ -1,853 +0,0 @@ -/** - * Command Handler for Claude Code Console - * Processes and executes console commands - */ - -export class CommandHandler { - constructor(terminal, wsClient) { - this.terminal = terminal; - this.wsClient = wsClient; - this.isProcessing = false; - - // Built-in commands - this.builtinCommands = { - help: this.showHelp.bind(this), - clear: this.clearConsole.bind(this), - status: this.showStatus.bind(this), - connect: this.connectToServer.bind(this), - disconnect: this.disconnectFromServer.bind(this), - tools: this.listTools.bind(this), - health: this.checkHealth.bind(this), - history: this.showHistory.bind(this), - export: this.exportSession.bind(this), - theme: this.changeTheme.bind(this), - version: this.showVersion.bind(this), - }; - - // Claude Flow commands - this.claudeFlowCommands = { - 'claude-flow': this.executeClaudeFlow.bind(this), - swarm: this.executeSwarm.bind(this), - init: this.initializeProject.bind(this), - config: this.manageConfig.bind(this), - memory: this.manageMemory.bind(this), - agents: this.manageAgents.bind(this), - benchmark: this.runBenchmark.bind(this), - sparc: this.executeSparc.bind(this), - }; - - // Direct SPARC mode commands - this.sparcModeCommands = { - coder: this.executeSparcMode.bind(this, 'coder'), - architect: this.executeSparcMode.bind(this, 'architect'), - analyst: this.executeSparcMode.bind(this, 'analyst'), - researcher: this.executeSparcMode.bind(this, 'researcher'), - reviewer: this.executeSparcMode.bind(this, 'reviewer'), - tester: this.executeSparcMode.bind(this, 'tester'), - debugger: this.executeSparcMode.bind(this, 'debugger'), - documenter: this.executeSparcMode.bind(this, 'documenter'), - optimizer: this.executeSparcMode.bind(this, 'optimizer'), - designer: this.executeSparcMode.bind(this, 'designer'), - }; - - this.allCommands = { - ...this.builtinCommands, - ...this.claudeFlowCommands, - ...this.sparcModeCommands, - }; - } - - /** - * Process a command - */ - async processCommand(command) { - if (this.isProcessing) { - this.terminal.writeWarning('Another command is still processing. Please wait...'); - return; - } - - this.isProcessing = true; - this.terminal.setLocked(true); - - try { - const { cmd, args } = this.parseCommand(command); - - if (this.allCommands[cmd]) { - await this.allCommands[cmd](args); - } else { - await this.executeRemoteCommand(cmd, args); - } - } catch (error) { - this.terminal.writeError(error.message); - console.error('Command execution error:', error); - } finally { - this.isProcessing = false; - this.terminal.setLocked(false); - } - } - - /** - * Parse command string into command and arguments - */ - parseCommand(commandString) { - const parts = commandString.trim().split(/\s+/); - const cmd = parts[0].toLowerCase(); - const args = parts.slice(1); - - return { cmd, args }; - } - - /** - * Show help information - */ - async showHelp(args) { - if (args.length > 0) { - const command = args[0].toLowerCase(); - if (this.allCommands[command]) { - this.showCommandHelp(command); - } else { - this.terminal.writeError(`Unknown command: ${command}`); - } - return; - } - - this.terminal.writeInfo('Claude Flow Console Commands:'); - this.terminal.writeLine(''); - - this.terminal.writeInfo('Built-in Commands:'); - Object.keys(this.builtinCommands).forEach((cmd) => { - this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`); - }); - - this.terminal.writeLine(''); - this.terminal.writeInfo('Claude Flow Commands:'); - Object.keys(this.claudeFlowCommands).forEach((cmd) => { - this.terminal.writeLine(` ${cmd.padEnd(12)} - ${this.getCommandDescription(cmd)}`); - }); - - this.terminal.writeLine(''); - this.terminal.writeInfo('Tool Commands (from tools list):'); - this.terminal.writeLine(' system/health - Get system health status'); - this.terminal.writeLine( - ' memory/manage - Manage memory (list, store , retrieve )', - ); - this.terminal.writeLine( - ' agents/manage - Manage agents (list, create , status )', - ); - this.terminal.writeLine( - ' swarm/orchestrate - Swarm operations (status, create, start, stop)', - ); - this.terminal.writeLine( - ' sparc/execute - Execute SPARC modes (coder, architect, etc.)', - ); - this.terminal.writeLine( - ' benchmark/run - Run benchmarks (default, memory, cpu, network)', - ); - this.terminal.writeLine(' claude-flow/execute - Execute Claude Flow commands'); - - this.terminal.writeLine(''); - this.terminal.writeInfo( - 'Use "help " for detailed information about a specific command.', - ); - this.terminal.writeInfo( - 'Use Ctrl+L to clear console, Ctrl+C to interrupt, Tab for autocomplete.', - ); - } - - /** - * Get command description - */ - getCommandDescription(command) { - const descriptions = { - help: 'Show help information', - clear: 'Clear console output', - status: 'Show connection and system status', - connect: 'Connect to Claude Code server', - disconnect: 'Disconnect from server', - tools: 'List available tools', - health: 'Check server health', - history: 'Show command history', - export: 'Export session data', - theme: 'Change console theme', - version: 'Show version information', - 'claude-flow': 'Execute Claude Flow commands', - swarm: 'Manage and execute swarms', - init: 'Initialize new project', - config: 'Manage configuration', - memory: 'Manage memory and data', - agents: 'Manage agents', - benchmark: 'Run benchmarks', - sparc: 'Execute SPARC mode commands', - }; - - return descriptions[command] || 'No description available'; - } - - /** - * Show detailed command help - */ - showCommandHelp(command) { - const helpText = { - help: ` -Usage: help [command] -Show help information for all commands or a specific command. - -Examples: - help - Show all commands - help claude-flow - Show help for claude-flow command`, - - clear: ` -Usage: clear -Clear the console output. You can also use Ctrl+L.`, - - connect: ` -Usage: connect [url] [token] -Connect to Claude Code server. - -Arguments: - url - WebSocket URL (default: ws://localhost:3000/ws) - token - Authentication token (optional) - -Examples: - connect - connect ws://localhost:3000/ws - connect ws://localhost:3000/ws my-auth-token`, - - 'claude-flow': ` -Usage: claude-flow [options] -Execute Claude Flow commands. - -Subcommands: - start [mode] - Start Claude Flow in specified mode - stop - Stop Claude Flow - status - Show Claude Flow status - modes - List available SPARC modes - -Examples: - claude-flow start coder - claude-flow status - claude-flow modes`, - - swarm: ` -Usage: swarm [options] -Manage and execute swarms. - -Actions: - create - Create new swarm - start - Start existing swarm - stop - Stop running swarm - list - List all swarms - status - Show swarm status - -Examples: - swarm create my-swarm - swarm start my-swarm - swarm list`, - }; - - if (helpText[command]) { - this.terminal.writeInfo(helpText[command].trim()); - } else { - this.terminal.writeInfo(`No detailed help available for: ${command}`); - } - } - - /** - * Clear console - */ - async clearConsole() { - this.terminal.clear(); - this.terminal.writeSuccess('Console cleared'); - } - - /** - * Show status - */ - async showStatus() { - const wsStatus = this.wsClient.getStatus(); - const terminalStats = this.terminal.getStats(); - - this.terminal.writeInfo('System Status:'); - this.terminal.writeLine(''); - - this.terminal.writeInfo('Connection:'); - this.terminal.writeLine(` Status: ${wsStatus.connected ? 'Connected' : 'Disconnected'}`); - this.terminal.writeLine(` URL: ${wsStatus.url || 'Not set'}`); - this.terminal.writeLine(` Reconnect attempts: ${wsStatus.reconnectAttempts}`); - this.terminal.writeLine(` Queued messages: ${wsStatus.queuedMessages}`); - this.terminal.writeLine(` Pending requests: ${wsStatus.pendingRequests}`); - - this.terminal.writeLine(''); - this.terminal.writeInfo('Terminal:'); - this.terminal.writeLine(` Total lines: ${terminalStats.totalLines}`); - this.terminal.writeLine(` History size: ${terminalStats.historySize}`); - this.terminal.writeLine(` Input locked: ${terminalStats.isLocked}`); - this.terminal.writeLine(` Current prompt: ${terminalStats.currentPrompt}`); - - if (wsStatus.connected) { - try { - const healthStatus = await this.wsClient.getHealthStatus(); - this.terminal.writeLine(''); - this.terminal.writeInfo('Server Health:'); - this.terminal.writeLine(` Status: ${healthStatus.healthy ? 'Healthy' : 'Unhealthy'}`); - - if (healthStatus.metrics) { - Object.entries(healthStatus.metrics).forEach(([key, value]) => { - this.terminal.writeLine(` ${key}: ${value}`); - }); - } - } catch (error) { - this.terminal.writeWarning('Failed to get server health status'); - } - } - } - - /** - * Connect to server - */ - async connectToServer(args) { - const url = args[0] || 'ws://localhost:3000/ws'; - const token = args[1] || ''; - - this.terminal.writeInfo(`Connecting to ${url}...`); - - try { - await this.wsClient.connect(url, token); - - // Initialize session - await this.wsClient.initializeSession(); - - this.terminal.writeSuccess('Connected successfully'); - this.terminal.setPrompt('claude-flow>'); - } catch (error) { - this.terminal.writeError(`Connection failed: ${error.message}`); - } - } - - /** - * Disconnect from server - */ - async disconnectFromServer() { - this.wsClient.disconnect(); - this.terminal.writeSuccess('Disconnected from server'); - this.terminal.setPrompt('offline>'); - } - - /** - * List available tools - */ - async listTools() { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const tools = await this.wsClient.getAvailableTools(); - - this.terminal.writeInfo('Available Tools:'); - this.terminal.writeLine(''); - - if (tools && tools.length > 0) { - tools.forEach((tool) => { - this.terminal.writeLine( - ` ${tool.name.padEnd(20)} - ${tool.description || 'No description'}`, - ); - }); - } else { - this.terminal.writeWarning('No tools available'); - } - } catch (error) { - this.terminal.writeError(`Failed to list tools: ${error.message}`); - } - } - - /** - * Check server health - */ - async checkHealth() { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const health = await this.wsClient.getHealthStatus(); - - if (health.healthy) { - this.terminal.writeSuccess('Server is healthy'); - } else { - this.terminal.writeError(`Server is unhealthy: ${health.error || 'Unknown error'}`); - } - - if (health.metrics) { - this.terminal.writeLine(''); - this.terminal.writeInfo('Metrics:'); - Object.entries(health.metrics).forEach(([key, value]) => { - this.terminal.writeLine(` ${key}: ${value}`); - }); - } - } catch (error) { - this.terminal.writeError(`Health check failed: ${error.message}`); - } - } - - /** - * Show command history - */ - async showHistory() { - const history = this.terminal.history; - - if (history.length === 0) { - this.terminal.writeInfo('No command history'); - return; - } - - this.terminal.writeInfo('Command History:'); - history.forEach((cmd, index) => { - this.terminal.writeLine(` ${(index + 1).toString().padStart(3)}: ${cmd}`); - }); - } - - /** - * Export session data - */ - async exportSession(args) { - const format = args[0] || 'json'; - - const sessionData = { - timestamp: new Date().toISOString(), - terminal: this.terminal.exportHistory(), - history: this.terminal.history, - status: this.wsClient.getStatus(), - }; - - if (format === 'json') { - const blob = new Blob([JSON.stringify(sessionData, null, 2)], { type: 'application/json' }); - this.downloadFile(blob, `console-session-${Date.now()}.json`); - this.terminal.writeSuccess('Session exported as JSON'); - } else { - this.terminal.writeError(`Unsupported export format: ${format}`); - } - } - - /** - * Change theme - */ - async changeTheme(args) { - const theme = args[0]; - const validThemes = ['dark', 'light', 'classic', 'matrix']; - - if (!theme) { - this.terminal.writeInfo(`Available themes: ${validThemes.join(', ')}`); - return; - } - - if (!validThemes.includes(theme)) { - this.terminal.writeError(`Invalid theme: ${theme}`); - return; - } - - document.documentElement.setAttribute('data-theme', theme); - localStorage.setItem('console_theme', theme); - this.terminal.writeSuccess(`Theme changed to: ${theme}`); - } - - /** - * Show version information - */ - async showVersion() { - this.terminal.writeInfo('๐ŸŒŠ Claude Flow v2.0.0'); - this.terminal.writeLine('Advanced swarm orchestration platform'); - this.terminal.writeLine('Built with modern web technologies'); - } - - /** - * Execute Claude Flow command - */ - async executeClaudeFlow(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - if (args.length === 0) { - this.terminal.writeError('Usage: claude-flow [options]'); - return; - } - - const subcommand = args[0]; - const subArgs = args.slice(1); - - try { - const result = await this.wsClient.executeCommand('claude-flow', { - subcommand, - args: subArgs, - }); - - this.terminal.writeSuccess(`Claude Flow ${subcommand} executed successfully`); - if (result && result.output) { - this.terminal.writeLine(result.output); - } - } catch (error) { - this.terminal.writeError(`Claude Flow command failed: ${error.message}`); - } - } - - /** - * Execute swarm command - */ - async executeSwarm(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const action = args[0] || 'status'; - this.terminal.writeInfo(`Executing swarm ${action}...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'swarm/status', - arguments: { action, args: args.slice(1) }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Swarm command executed successfully'); - } - } catch (error) { - this.terminal.writeError(`Swarm command failed: ${error.message}`); - } - } - - /** - * Initialize project - */ - async initializeProject(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - this.terminal.writeWarning('Project initialization not yet implemented in web console'); - } - - /** - * Manage configuration - */ - async manageConfig(args) { - this.terminal.writeInfo('Use the Settings panel (โš™๏ธ button) to manage configuration'); - } - - /** - * Manage memory - */ - async manageMemory(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const operation = args[0] || 'list'; - const key = args[1]; - const value = args.slice(2).join(' '); - - this.terminal.writeInfo(`Executing memory ${operation}...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'memory/manage', - arguments: { operation, key, value }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Memory operation completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Memory command failed: ${error.message}`); - } - } - - /** - * Manage agents - */ - async manageAgents(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const action = args[0] || 'list'; - const agentType = args[1]; - const agentId = args[1]; - - this.terminal.writeInfo(`Executing agents ${action}...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'agents/manage', - arguments: { action, agentType, agentId }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Agent operation completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Agent command failed: ${error.message}`); - } - } - - /** - * Run benchmark - */ - async runBenchmark(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const suite = args[0] || 'default'; - const iterations = parseInt(args[1]) || 10; - - this.terminal.writeInfo(`Running benchmark suite: ${suite}...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'benchmark/run', - arguments: { suite, iterations }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess('Benchmark completed successfully'); - } - } catch (error) { - this.terminal.writeError(`Benchmark failed: ${error.message}`); - } - } - - /** - * Execute SPARC mode - */ - async executeSparc(args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - if (args.length === 0) { - this.terminal.writeInfo('Available SPARC modes:'); - const modes = [ - 'coder', - 'architect', - 'analyst', - 'researcher', - 'reviewer', - 'tester', - 'debugger', - 'documenter', - 'optimizer', - 'designer', - ]; - modes.forEach((mode) => { - this.terminal.writeLine(` ${mode}`); - }); - return; - } - - try { - const mode = args[0]; - const task = args.slice(1).join(' ') || 'General task execution'; - const options = {}; - - this.terminal.writeInfo(`Executing SPARC mode: ${mode}...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'sparc/execute', - arguments: { mode, task, options }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`); - } - } catch (error) { - this.terminal.writeError(`SPARC execution failed: ${error.message}`); - } - } - - /** - * Execute specific SPARC mode - */ - async executeSparcMode(mode, args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server'); - return; - } - - try { - const task = args.join(' ') || `Execute ${mode} mode tasks`; - const options = {}; - - this.terminal.writeInfo(`Executing SPARC ${mode} mode...`); - - const result = await this.wsClient.sendRequest('tools/call', { - name: 'sparc/execute', - arguments: { mode, task, options }, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`SPARC ${mode} mode executed successfully`); - } - } catch (error) { - this.terminal.writeError(`SPARC ${mode} execution failed: ${error.message}`); - } - } - - /** - * Execute remote command via WebSocket - */ - async executeRemoteCommand(command, args) { - if (!this.wsClient.isConnected) { - this.terminal.writeError('Not connected to server. Use "connect" command first.'); - return; - } - - try { - // Check if this is a tool name (contains slash) - if (command.includes('/')) { - return await this.executeToolDirect(command, args); - } - - this.terminal.writeInfo(`Executing remote command: ${command}`); - - const result = await this.wsClient.executeCommand(command, { args }); - - if (result && result.output) { - this.terminal.writeLine(result.output); - } else { - this.terminal.writeSuccess('Command executed successfully'); - } - } catch (error) { - this.terminal.writeError(`Remote command failed: ${error.message}`); - } - } - - /** - * Execute tool directly by name - */ - async executeToolDirect(toolName, args) { - try { - this.terminal.writeInfo(`Executing tool: ${toolName}...`); - - // Prepare arguments based on tool - let toolArgs = {}; - - switch (toolName) { - case 'system/health': - toolArgs = { detailed: args.includes('--detailed') }; - break; - - case 'memory/manage': - toolArgs = { - operation: args[0] || 'list', - key: args[1], - value: args.slice(2).join(' '), - }; - break; - - case 'agents/manage': - toolArgs = { - action: args[0] || 'list', - agentType: args[1], - agentId: args[1], - }; - break; - - case 'swarm/orchestrate': - toolArgs = { - action: args[0] || 'status', - args: args.slice(1), - }; - break; - - case 'sparc/execute': - toolArgs = { - mode: args[0] || 'coder', - task: args.slice(1).join(' ') || 'General task execution', - options: {}, - }; - break; - - case 'benchmark/run': - toolArgs = { - suite: args[0] || 'default', - iterations: parseInt(args[1]) || 10, - }; - break; - - case 'claude-flow/execute': - toolArgs = { - command: args[0] || 'status', - args: args.slice(1), - }; - break; - - default: - toolArgs = { args }; - } - - const result = await this.wsClient.sendRequest('tools/call', { - name: toolName, - arguments: toolArgs, - }); - - if (result && result.content && result.content[0]) { - this.terminal.writeSuccess(result.content[0].text); - } else { - this.terminal.writeSuccess(`Tool ${toolName} executed successfully`); - } - } catch (error) { - this.terminal.writeError(`Tool execution failed: ${error.message}`); - } - } - - /** - * Download file helper - */ - downloadFile(blob, filename) { - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = filename; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - URL.revokeObjectURL(url); - } - - /** - * Get command suggestions - */ - getCommandSuggestions(input) { - const allCommands = Object.keys(this.allCommands); - return allCommands.filter((cmd) => cmd.startsWith(input.toLowerCase())); - } - - /** - * Check if command exists - */ - hasCommand(command) { - return this.allCommands.hasOwnProperty(command.toLowerCase()); - } -} diff --git a/src/ui/console/js/console.js b/src/ui/console/js/console.js deleted file mode 100644 index 9f5dc9b388..0000000000 --- a/src/ui/console/js/console.js +++ /dev/null @@ -1,669 +0,0 @@ -/** - * Main Console Application - * Coordinates all components of the Claude Code Console - */ - -import { WebSocketClient } from './websocket-client.js'; -import { TerminalEmulator } from './terminal-emulator.js'; -import { CommandHandler } from './command-handler.js'; -import { SettingsManager } from './settings.js'; - -class ClaudeCodeConsole { - constructor() { - // Initialize components - this.wsClient = new WebSocketClient(); - this.terminal = null; - this.commandHandler = null; - this.settings = new SettingsManager(); - - // State management - this.isInitialized = false; - this.startTime = Date.now(); - this.messageCount = 0; - this.activeAgents = 0; - - // DOM elements - this.elements = {}; - - // Status update intervals - this.statusInterval = null; - this.uptimeInterval = null; - - this.setupEventListeners(); - } - - /** - * Initialize the console application - */ - async init() { - if (this.isInitialized) return; - - try { - // Show loading overlay - this.showLoading('Initializing Claude Code Console...'); - - // Get DOM elements - this.getDOMElements(); - - // Initialize terminal emulator - this.terminal = new TerminalEmulator(this.elements.consoleOutput, this.elements.consoleInput); - - // Initialize command handler - this.commandHandler = new CommandHandler(this.terminal, this.wsClient); - - // Initialize settings - this.settings.init(); - - // Setup component interactions - this.setupComponentInteractions(); - - // Setup UI event handlers - this.setupUIEventHandlers(); - - // Apply initial settings - this.applyInitialSettings(); - - // Start status updates - this.startStatusUpdates(); - - // Hide loading overlay - this.hideLoading(); - - // Show welcome message - this.showWelcomeMessage(); - - // Auto-connect if enabled - if (this.settings.get('autoConnect')) { - await this.autoConnect(); - } - - this.isInitialized = true; - console.log('Claude Code Console initialized successfully'); - } catch (error) { - console.error('Failed to initialize console:', error); - this.showError('Failed to initialize console: ' + error.message); - } - } - - /** - * Get DOM elements - */ - getDOMElements() { - this.elements = { - consoleOutput: document.getElementById('consoleOutput'), - consoleInput: document.getElementById('consoleInput'), - settingsPanel: document.getElementById('settingsPanel'), - loadingOverlay: document.getElementById('loadingOverlay'), - connectionStatus: document.getElementById('connectionStatus'), - statusIndicator: document.getElementById('statusIndicator'), - statusText: document.getElementById('statusText'), - currentMode: document.getElementById('currentMode'), - activeAgents: document.getElementById('activeAgents'), - uptime: document.getElementById('uptime'), - memoryUsage: document.getElementById('memoryUsage'), - messageCount: document.getElementById('messageCount'), - timestamp: document.getElementById('timestamp'), - clearConsole: document.getElementById('clearConsole'), - fullscreenToggle: document.getElementById('fullscreenToggle'), - }; - - // Validate required elements - const required = ['consoleOutput', 'consoleInput', 'loadingOverlay']; - for (const elementId of required) { - if (!this.elements[elementId]) { - throw new Error(`Required element not found: ${elementId}`); - } - } - } - - /** - * Setup component interactions - */ - setupComponentInteractions() { - // Terminal -> Command Handler - this.terminal.on('command', (command) => { - this.commandHandler.processCommand(command); - }); - - this.terminal.on('interrupt', () => { - this.handleInterrupt(); - }); - - // WebSocket -> Terminal - this.wsClient.on('connected', () => { - this.updateConnectionStatus(true, false); - this.terminal.writeSuccess('Connected to Claude Code server'); - this.terminal.setPrompt('claude-flow>'); - }); - - this.wsClient.on('disconnected', (info) => { - this.updateConnectionStatus(false, false); - this.terminal.writeWarning('Disconnected from server'); - this.terminal.setPrompt('offline>'); - - if (info && info.code !== 1000) { - this.terminal.writeError(`Connection lost: ${info.reason || 'Unknown reason'}`); - } - }); - - this.wsClient.on('reconnecting', (info) => { - this.updateConnectionStatus(false, true); - this.terminal.writeInfo( - `Reconnecting... (${info.attempt}/${this.wsClient.maxReconnectAttempts})`, - ); - }); - - this.wsClient.on('error', (error) => { - this.terminal.writeError(`WebSocket error: ${error.message || 'Unknown error'}`); - }); - - this.wsClient.on('message_received', (message) => { - this.messageCount++; - this.handleIncomingMessage(message); - }); - - this.wsClient.on('notification', (notification) => { - this.handleNotification(notification); - }); - - // Settings -> Application - this.settings.on('connect_requested', async (config) => { - await this.connect(config.url, config.token); - }); - - this.settings.on('disconnect_requested', () => { - this.disconnect(); - }); - - this.settings.on('max_lines_changed', (maxLines) => { - this.terminal.setMaxLines(maxLines); - }); - - this.settings.on('setting_changed', ({ key, value }) => { - this.handleSettingChange(key, value); - }); - } - - /** - * Setup UI event handlers - */ - setupUIEventHandlers() { - // Clear console button - if (this.elements.clearConsole) { - this.elements.clearConsole.addEventListener('click', () => { - this.terminal.clear(); - }); - } - - // Fullscreen toggle - if (this.elements.fullscreenToggle) { - this.elements.fullscreenToggle.addEventListener('click', () => { - this.toggleFullscreen(); - }); - } - - // Focus input when clicking on output area - if (this.elements.consoleOutput) { - this.elements.consoleOutput.addEventListener('click', () => { - this.terminal.focus(); - }); - } - - // Handle window focus - window.addEventListener('focus', () => { - this.terminal.focus(); - }); - - // Handle visibility change - document.addEventListener('visibilitychange', () => { - if (!document.hidden) { - this.updateTimestamp(); - } - }); - - // Handle page unload - window.addEventListener('beforeunload', () => { - this.cleanup(); - }); - } - - /** - * Apply initial settings - */ - applyInitialSettings() { - const maxLines = this.settings.get('maxLines'); - if (maxLines) { - this.terminal.setMaxLines(maxLines); - } - - // Update connection status in settings - this.settings.updateConnectionStatus(this.wsClient.getStatus()); - } - - /** - * Show welcome message - */ - showWelcomeMessage() { - this.terminal.showWelcomeMessage(); - this.terminal.writeInfo('Console ready. Type "help" for available commands.'); - - const config = this.settings.getConnectionConfig(); - if (config.url && !config.autoConnect) { - this.terminal.writeInfo(`Use "connect" to connect to ${config.url}`); - } - } - - /** - * Auto-connect to server - */ - async autoConnect() { - const config = this.settings.getConnectionConfig(); - - if (config.url) { - this.terminal.writeInfo(`Auto-connecting to ${config.url}...`); - await this.connect(config.url, config.token); - } - } - - /** - * Connect to server - */ - async connect(url, token = '') { - try { - this.updateConnectionStatus(false, true); - await this.wsClient.connect(url, token); - await this.wsClient.initializeSession(); - - // Update settings with successful connection - this.settings.set('serverUrl', url); - if (token) { - this.settings.set('authToken', token); - } - } catch (error) { - this.updateConnectionStatus(false, false); - this.terminal.writeError(`Connection failed: ${error.message}`); - } - } - - /** - * Disconnect from server - */ - disconnect() { - this.wsClient.disconnect(); - this.updateConnectionStatus(false, false); - } - - /** - * Update connection status in UI - */ - updateConnectionStatus(connected, connecting) { - const status = this.wsClient.getStatus(); - - // Update status indicator - if (this.elements.statusIndicator) { - this.elements.statusIndicator.className = - 'status-indicator ' + (connected ? 'connected' : connecting ? 'connecting' : ''); - } - - // Update status text - if (this.elements.statusText) { - this.elements.statusText.textContent = connected - ? 'Connected' - : connecting - ? 'Connecting...' - : 'Disconnected'; - } - - // Update settings panel - this.settings.updateConnectionStatus(status); - } - - /** - * Handle incoming messages - */ - handleIncomingMessage(message) { - // Handle streaming output - if (message.method === 'output/stream') { - this.handleStreamingOutput(message.params); - } - - // Handle Claude Flow notifications - if (message.method && message.method.startsWith('claude-flow/')) { - this.handleClaudeFlowNotification(message); - } - } - - /** - * Handle notifications - */ - handleNotification(notification) { - const { method, params } = notification; - - switch (method) { - case 'agent/status': - this.handleAgentStatus(params); - break; - - case 'swarm/update': - this.handleSwarmUpdate(params); - break; - - case 'memory/update': - this.handleMemoryUpdate(params); - break; - - case 'log/message': - this.handleLogMessage(params); - break; - - case 'connection/established': - this.handleConnectionEstablished(params); - break; - - default: - console.log('Unhandled notification:', method, params); - } - } - - /** - * Handle streaming output - */ - handleStreamingOutput(params) { - if (params && params.content) { - const type = params.type || 'output'; - - if (params.streaming) { - // Use streaming text effect for long outputs - this.terminal.streamText(params.content, 10); - } else { - this.terminal.write(params.content, type); - } - } - } - - /** - * Handle Claude Flow notifications - */ - handleClaudeFlowNotification(message) { - const { method, params } = message; - - switch (method) { - case 'claude-flow/started': - this.terminal.writeSuccess(`Claude Flow started in ${params.mode} mode`); - break; - - case 'claude-flow/stopped': - this.terminal.writeInfo('Claude Flow stopped'); - break; - - case 'claude-flow/error': - this.terminal.writeError(`Claude Flow error: ${params.message}`); - break; - - default: - this.terminal.writeInfo(`Claude Flow: ${method} - ${JSON.stringify(params)}`); - } - } - - /** - * Handle agent status updates - */ - handleAgentStatus(params) { - if (params.active !== undefined) { - this.activeAgents = params.active; - } - - if (params.message) { - this.terminal.writeInfo(`Agent: ${params.message}`); - } - } - - /** - * Handle swarm updates - */ - handleSwarmUpdate(params) { - if (params.message) { - this.terminal.writeInfo(`Swarm: ${params.message}`); - } - } - - /** - * Handle memory updates - */ - handleMemoryUpdate(params) { - if (params.message) { - this.terminal.writeInfo(`Memory: ${params.message}`); - } - } - - /** - * Handle log messages - */ - handleLogMessage(params) { - if (params.level && params.message) { - const type = - params.level === 'error' ? 'error' : params.level === 'warn' ? 'warning' : 'info'; - this.terminal.write(`[${params.level.toUpperCase()}] ${params.message}`, type); - } - } - - /** - * Handle connection established notification - */ - handleConnectionEstablished(params) { - // Log connection details without cluttering the terminal - console.log('Connection established:', params); - // Optionally show a brief success message - // this.terminal.writeSuccess(`Connected to ${params.server} v${params.version}`); - } - - /** - * Handle interrupt (Ctrl+C) - */ - handleInterrupt() { - // Could be used to cancel running commands - this.terminal.writeWarning('Interrupt signal sent'); - } - - /** - * Handle setting changes - */ - handleSettingChange(key, value) { - switch (key) { - case 'theme': - document.documentElement.setAttribute('data-theme', value); - break; - - case 'fontSize': - document.documentElement.style.setProperty('--font-size-base', `${value}px`); - break; - - case 'lineHeight': - document.documentElement.style.setProperty('--line-height', value); - break; - } - } - - /** - * Start status updates - */ - startStatusUpdates() { - // Update status every 5 seconds - this.statusInterval = setInterval(() => { - this.updateStatus(); - }, 5000); - - // Update timestamp every second - this.uptimeInterval = setInterval(() => { - this.updateUptime(); - this.updateTimestamp(); - }, 1000); - - // Initial update - this.updateStatus(); - this.updateUptime(); - this.updateTimestamp(); - } - - /** - * Update status bar - */ - updateStatus() { - // Update active agents - if (this.elements.activeAgents) { - this.elements.activeAgents.textContent = `Agents: ${this.activeAgents}`; - } - - // Update message count - if (this.elements.messageCount) { - this.elements.messageCount.textContent = `Messages: ${this.messageCount}`; - } - - // Update memory usage (if available) - if (this.elements.memoryUsage && performance.memory) { - const used = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024); - this.elements.memoryUsage.textContent = `Memory: ${used}MB`; - } - } - - /** - * Update uptime - */ - updateUptime() { - if (this.elements.uptime) { - const uptime = Date.now() - this.startTime; - const hours = Math.floor(uptime / (1000 * 60 * 60)); - const minutes = Math.floor((uptime % (1000 * 60 * 60)) / (1000 * 60)); - const seconds = Math.floor((uptime % (1000 * 60)) / 1000); - - this.elements.uptime.textContent = `Uptime: ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; - } - } - - /** - * Update timestamp - */ - updateTimestamp() { - if (this.elements.timestamp) { - this.elements.timestamp.textContent = new Date().toLocaleTimeString(); - } - } - - /** - * Toggle fullscreen mode - */ - toggleFullscreen() { - if (!document.fullscreenElement) { - document.documentElement.requestFullscreen().catch((err) => { - console.error('Error attempting to enable fullscreen:', err); - }); - } else { - document.exitFullscreen(); - } - } - - /** - * Show loading overlay - */ - showLoading(message = 'Loading...') { - if (this.elements.loadingOverlay) { - const loadingText = this.elements.loadingOverlay.querySelector('.loading-text'); - if (loadingText) { - loadingText.textContent = message; - } - this.elements.loadingOverlay.classList.remove('hidden'); - } - } - - /** - * Hide loading overlay - */ - hideLoading() { - if (this.elements.loadingOverlay) { - this.elements.loadingOverlay.classList.add('hidden'); - } - } - - /** - * Show error message - */ - showError(message) { - this.hideLoading(); - - if (this.terminal) { - this.terminal.writeError(message); - } else { - // Fallback if terminal isn't initialized - console.error(message); - alert(message); - } - } - - /** - * Setup global event listeners - */ - setupEventListeners() { - // Handle unhandled promise rejections - window.addEventListener('unhandledrejection', (event) => { - console.error('Unhandled promise rejection:', event.reason); - if (this.terminal) { - this.terminal.writeError(`Unhandled error: ${event.reason.message || event.reason}`); - } - }); - - // Handle errors - window.addEventListener('error', (event) => { - console.error('Global error:', event.error); - if (this.terminal) { - this.terminal.writeError(`Application error: ${event.error.message || event.error}`); - } - }); - } - - /** - * Cleanup on shutdown - */ - cleanup() { - // Clear intervals - if (this.statusInterval) { - clearInterval(this.statusInterval); - } - - if (this.uptimeInterval) { - clearInterval(this.uptimeInterval); - } - - // Disconnect WebSocket - if (this.wsClient) { - this.wsClient.disconnect(); - } - } - - /** - * Get console statistics - */ - getStats() { - return { - initialized: this.isInitialized, - uptime: Date.now() - this.startTime, - messageCount: this.messageCount, - activeAgents: this.activeAgents, - connection: this.wsClient.getStatus(), - terminal: this.terminal ? this.terminal.getStats() : null, - }; - } -} - -// Initialize the console when DOM is ready -document.addEventListener('DOMContentLoaded', async () => { - const console = new ClaudeCodeConsole(); - - // Make console globally available for debugging - window.claudeConsole = console; - - // Initialize the application - await console.init(); -}); - -// Export for module usage -export { ClaudeCodeConsole }; diff --git a/src/ui/console/js/daa-tools.js b/src/ui/console/js/daa-tools.js deleted file mode 100644 index aae91f06ef..0000000000 --- a/src/ui/console/js/daa-tools.js +++ /dev/null @@ -1,1035 +0,0 @@ -/** - * Dynamic Agent Architecture (DAA) Tools - * Implementation of 8 core DAA tools for Claude Flow - */ - -class DAATools { - constructor() { - this.agents = new Map(); - this.resources = new Map(); - this.communications = new Map(); - this.consensus = new Map(); - this.isInitialized = false; - this.currentTab = 'agents'; - - // Performance metrics - this.metrics = { - totalAgents: 0, - activeAgents: 0, - resourceUtilization: 0, - communicationLatency: 0, - consensusTime: 0, - faultCount: 0, - }; - - this.init(); - } - - init() { - if (this.isInitialized) return; - - this.createDAAPanel(); - this.setupEventListeners(); - this.initializeMonitoring(); - this.isInitialized = true; - - console.log('DAA Tools initialized'); - } - - // Tool 1: Dynamic Agent Creation - daa_agent_create(config) { - const agentId = this.generateAgentId(); - const agent = { - id: agentId, - type: config.type || 'generic', - capabilities: config.capabilities || [], - resources: config.resources || {}, - status: 'initializing', - created: Date.now(), - lastActivity: Date.now(), - tasks: [], - metadata: config.metadata || {}, - }; - - this.agents.set(agentId, agent); - this.metrics.totalAgents++; - this.metrics.activeAgents++; - - // Lifecycle management - this.initializeAgent(agent); - - // Update UI - this.updateAgentsList(); - this.updateMetrics(); - - return { - success: true, - agentId: agentId, - agent: agent, - }; - } - - // Tool 2: Capability Matching System - daa_capability_match(requirements) { - const matches = []; - - for (const [agentId, agent] of this.agents) { - if (agent.status !== 'active') continue; - - const score = this.calculateCapabilityScore(agent.capabilities, requirements); - if (score > 0) { - matches.push({ - agentId, - agent, - score, - availableCapabilities: agent.capabilities.filter((cap) => - requirements.some((req) => this.matchCapability(cap, req)), - ), - }); - } - } - - // Sort by score descending - matches.sort((a, b) => b.score - a.score); - - this.updateCapabilityMatches(matches); - - return { - success: true, - matches: matches, - totalCandidates: matches.length, - }; - } - - // Tool 3: Resource Allocation Management - daa_resource_alloc(allocation) { - const resourceId = this.generateResourceId(); - const resource = { - id: resourceId, - type: allocation.type, - capacity: allocation.capacity, - allocated: 0, - assignments: new Map(), - priority: allocation.priority || 'medium', - created: Date.now(), - metadata: allocation.metadata || {}, - }; - - this.resources.set(resourceId, resource); - - // Perform allocation - const allocationResult = this.allocateResource(resource, allocation); - - // Update visualizations - this.updateResourceGraphs(); - this.updateMetrics(); - - return { - success: allocationResult.success, - resourceId: resourceId, - allocation: allocationResult, - utilization: this.calculateResourceUtilization(), - }; - } - - // Tool 4: Agent Lifecycle Management - daa_lifecycle_manage(agentId, action, params = {}) { - const agent = this.agents.get(agentId); - if (!agent) { - return { success: false, error: 'Agent not found' }; - } - - let result; - - switch (action) { - case 'start': - result = this.startAgent(agent, params); - break; - case 'pause': - result = this.pauseAgent(agent, params); - break; - case 'resume': - result = this.resumeAgent(agent, params); - break; - case 'stop': - result = this.stopAgent(agent, params); - break; - case 'restart': - result = this.restartAgent(agent, params); - break; - case 'destroy': - result = this.destroyAgent(agent, params); - break; - default: - return { success: false, error: 'Unknown action' }; - } - - // Update lifecycle visualization - this.updateLifecycleVisualization(); - this.updateMetrics(); - - return result; - } - - // Tool 5: Inter-agent Communication - daa_communication(fromAgent, toAgent, message, options = {}) { - const commId = this.generateCommId(); - const communication = { - id: commId, - from: fromAgent, - to: toAgent, - message: message, - timestamp: Date.now(), - type: options.type || 'direct', - priority: options.priority || 'normal', - status: 'pending', - latency: 0, - metadata: options.metadata || {}, - }; - - this.communications.set(commId, communication); - - // Process communication - const result = this.processCommunication(communication); - - // Update communication flow diagrams - this.updateCommunicationFlow(); - - return { - success: result.success, - commId: commId, - latency: result.latency, - status: result.status, - }; - } - - // Tool 6: Consensus Mechanisms - daa_consensus(proposal, agents, options = {}) { - const consensusId = this.generateConsensusId(); - const consensus = { - id: consensusId, - proposal: proposal, - participants: agents, - votes: new Map(), - status: 'voting', - algorithm: options.algorithm || 'majority', - threshold: options.threshold || 0.5, - timeout: options.timeout || 30000, - started: Date.now(), - completed: null, - result: null, - }; - - this.consensus.set(consensusId, consensus); - - // Start consensus process - const result = this.startConsensusProcess(consensus); - - // Update consensus interface - this.updateConsensusInterface(); - - return { - success: result.success, - consensusId: consensusId, - expectedCompletion: result.expectedCompletion, - }; - } - - // Tool 7: Fault Tolerance and Recovery - daa_fault_tolerance(faultType, affectedAgents, recoveryOptions = {}) { - const faultId = this.generateFaultId(); - const fault = { - id: faultId, - type: faultType, - affected: affectedAgents, - detected: Date.now(), - severity: recoveryOptions.severity || 'medium', - status: 'detected', - recoveryPlan: null, - recovered: null, - }; - - this.metrics.faultCount++; - - // Analyze fault and create recovery plan - const recoveryPlan = this.createRecoveryPlan(fault, recoveryOptions); - fault.recoveryPlan = recoveryPlan; - - // Execute recovery - const recoveryResult = this.executeRecovery(fault); - - // Update fault tolerance dashboard - this.updateFaultDashboard(); - - return { - success: recoveryResult.success, - faultId: faultId, - recoveryPlan: recoveryPlan, - estimatedRecoveryTime: recoveryResult.estimatedTime, - }; - } - - // Tool 8: Performance Optimization - daa_optimization(target, options = {}) { - const optimizationId = this.generateOptimizationId(); - const optimization = { - id: optimizationId, - target: target, - baseline: this.capturePerformanceBaseline(), - options: options, - started: Date.now(), - status: 'running', - improvements: [], - completed: null, - }; - - // Perform optimization - const result = this.performOptimization(optimization); - - // Update optimization dashboard - this.updateOptimizationDashboard(); - - return { - success: result.success, - optimizationId: optimizationId, - improvements: result.improvements, - performanceGain: result.performanceGain, - }; - } - - // UI Creation Methods - createDAAPanel() { - const panel = document.createElement('div'); - panel.id = 'daa-tools-panel'; - panel.className = 'daa-panel'; - - panel.innerHTML = ` -
-

DAA Control Center

-
-
- Agents - 0 -
-
- Resources - 0% -
-
- Latency - 0ms -
-
- Faults - 0 -
-
-
- -
- - - - -
- -
- ${this.createAgentsTab()} - ${this.createResourcesTab()} - ${this.createCommunicationTab()} - ${this.createMonitoringTab()} -
- `; - - // Add to console - const consoleContainer = document.querySelector('.console-container') || document.body; - consoleContainer.appendChild(panel); - } - - createAgentsTab() { - return ` -
-
-

Agent Creation

-
- - - -
-
- -
-

Agent Lifecycle

-
- -
-
- -
-

Active Agents

-
- -
-
-
- `; - } - - createResourcesTab() { - return ` -
-
-

Resource Allocation

-
- - - - -
-
- -
-

Resource Graphs

-
- -
-
- -
-

Resource Status

-
- -
-
-
- `; - } - - createCommunicationTab() { - return ` -
-
-

Communication Flow

-
- -
-
- -
-

Consensus Voting

-
- - - -
-
- -
-
-
- `; - } - - createMonitoringTab() { - return ` -
-
-

Real-time Dashboard

-
-
-
-
Performance Metrics
- -
-
-
System Health
-
- -
-
-
-
Fault Tolerance
-
- -
-
-
-
Optimization
-
- -
-
-
-
-
-
- `; - } - - // Helper Methods - generateAgentId() { - return `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - generateResourceId() { - return `resource-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - generateCommId() { - return `comm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - generateConsensusId() { - return `consensus-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - generateFaultId() { - return `fault-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - generateOptimizationId() { - return `opt-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; - } - - calculateCapabilityScore(agentCapabilities, requirements) { - let score = 0; - for (const requirement of requirements) { - for (const capability of agentCapabilities) { - if (this.matchCapability(capability, requirement)) { - score += 1; - } - } - } - return score; - } - - matchCapability(capability, requirement) { - // Simple string matching - can be enhanced with fuzzy matching - return capability.toLowerCase().includes(requirement.toLowerCase()); - } - - calculateResourceUtilization() { - let totalCapacity = 0; - let totalAllocated = 0; - - for (const [_, resource] of this.resources) { - totalCapacity += resource.capacity; - totalAllocated += resource.allocated; - } - - return totalCapacity > 0 ? Math.round((totalAllocated / totalCapacity) * 100) : 0; - } - - // Implementation methods (simplified for brevity) - initializeAgent(agent) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - } - - startAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { success: true, status: 'active' }; - } - - pauseAgent(agent, params) { - agent.status = 'paused'; - return { success: true, status: 'paused' }; - } - - resumeAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { success: true, status: 'active' }; - } - - stopAgent(agent, params) { - agent.status = 'stopped'; - this.metrics.activeAgents--; - return { success: true, status: 'stopped' }; - } - - restartAgent(agent, params) { - agent.status = 'active'; - agent.lastActivity = Date.now(); - return { success: true, status: 'active' }; - } - - destroyAgent(agent, params) { - this.agents.delete(agent.id); - this.metrics.totalAgents--; - this.metrics.activeAgents--; - return { success: true, status: 'destroyed' }; - } - - allocateResource(resource, allocation) { - // Simple allocation logic - const requested = allocation.amount || 0; - const available = resource.capacity - resource.allocated; - - if (requested <= available) { - resource.allocated += requested; - return { success: true, allocated: requested, remaining: available - requested }; - } else { - return { success: false, error: 'Insufficient resources', available: available }; - } - } - - processCommunication(communication) { - // Simulate communication processing - const latency = Math.random() * 100; // 0-100ms - communication.latency = latency; - communication.status = 'completed'; - - this.metrics.communicationLatency = (this.metrics.communicationLatency + latency) / 2; - - return { success: true, latency: latency, status: 'completed' }; - } - - startConsensusProcess(consensus) { - // Simulate consensus process - const expectedTime = consensus.timeout || 30000; - - setTimeout(() => { - this.completeConsensus(consensus); - }, expectedTime); - - return { success: true, expectedCompletion: Date.now() + expectedTime }; - } - - completeConsensus(consensus) { - consensus.status = 'completed'; - consensus.completed = Date.now(); - consensus.result = 'approved'; // Simplified - - this.metrics.consensusTime = consensus.completed - consensus.started; - this.updateConsensusInterface(); - } - - createRecoveryPlan(fault, options) { - return { - steps: [ - 'Isolate affected agents', - 'Backup current state', - 'Restart affected components', - 'Verify system integrity', - 'Resume normal operations', - ], - estimatedTime: 60000, // 1 minute - priority: fault.severity, - }; - } - - executeRecovery(fault) { - // Simulate recovery execution - fault.status = 'recovering'; - - setTimeout(() => { - fault.status = 'recovered'; - fault.recovered = Date.now(); - this.updateFaultDashboard(); - }, fault.recoveryPlan.estimatedTime); - - return { success: true, estimatedTime: fault.recoveryPlan.estimatedTime }; - } - - capturePerformanceBaseline() { - return { - timestamp: Date.now(), - metrics: { ...this.metrics }, - agentCount: this.agents.size, - resourceCount: this.resources.size, - }; - } - - performOptimization(optimization) { - // Simulate optimization process - const improvements = [ - { type: 'agent_efficiency', improvement: 15 }, - { type: 'resource_allocation', improvement: 12 }, - { type: 'communication_latency', improvement: 8 }, - ]; - - optimization.improvements = improvements; - optimization.status = 'completed'; - optimization.completed = Date.now(); - - const totalGain = - improvements.reduce((sum, imp) => sum + imp.improvement, 0) / improvements.length; - - return { success: true, improvements: improvements, performanceGain: totalGain }; - } - - // UI Update Methods - updateAgentsList() { - const agentsList = document.getElementById('daa-agents-list'); - if (!agentsList) return; - - agentsList.innerHTML = ''; - - for (const [agentId, agent] of this.agents) { - const agentElement = document.createElement('div'); - agentElement.className = 'daa-agent-card'; - agentElement.innerHTML = ` -
- ${agentId} - ${agent.status} -
-
-
${agent.type}
-
${agent.capabilities.join(', ')}
-
-
- - - -
- `; - agentsList.appendChild(agentElement); - } - } - - updateMetrics() { - const elements = { - 'daa-agents-count': this.metrics.activeAgents, - 'daa-resources-util': `${this.metrics.resourceUtilization}%`, - 'daa-latency': `${Math.round(this.metrics.communicationLatency)}ms`, - 'daa-faults': this.metrics.faultCount, - }; - - for (const [id, value] of Object.entries(elements)) { - const element = document.getElementById(id); - if (element) { - element.textContent = value; - } - } - } - - updateCapabilityMatches(matches) { - // Update capability matching visualization - console.log('Capability matches:', matches); - } - - updateResourceGraphs() { - const canvas = document.getElementById('daa-resource-chart'); - if (!canvas) return; - - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - - // Draw resource utilization bars - const resources = Array.from(this.resources.values()); - const barWidth = canvas.width / Math.max(resources.length, 1); - - resources.forEach((resource, index) => { - const utilization = resource.capacity > 0 ? resource.allocated / resource.capacity : 0; - const barHeight = utilization * canvas.height; - - ctx.fillStyle = utilization > 0.8 ? '#ff4444' : utilization > 0.5 ? '#ffaa00' : '#44ff44'; - ctx.fillRect(index * barWidth, canvas.height - barHeight, barWidth - 2, barHeight); - - // Resource label - ctx.fillStyle = '#000'; - ctx.font = '12px Arial'; - ctx.fillText(resource.type, index * barWidth + 5, canvas.height - 5); - }); - } - - updateLifecycleVisualization() { - const visualization = document.getElementById('daa-lifecycle-visualization'); - if (!visualization) return; - - const statusCounts = {}; - for (const [_, agent] of this.agents) { - statusCounts[agent.status] = (statusCounts[agent.status] || 0) + 1; - } - - visualization.innerHTML = Object.entries(statusCounts) - .map( - ([status, count]) => - `
- ${status} - ${count} -
`, - ) - .join(''); - } - - updateCommunicationFlow() { - const svg = document.getElementById('daa-comm-diagram'); - if (!svg) return; - - // Clear existing content - svg.innerHTML = ''; - - // Draw communication flow visualization - const agents = Array.from(this.agents.values()); - const centerX = 300; - const centerY = 200; - const radius = 150; - - agents.forEach((agent, index) => { - const angle = (index * 2 * Math.PI) / agents.length; - const x = centerX + radius * Math.cos(angle); - const y = centerY + radius * Math.sin(angle); - - // Draw agent node - const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); - circle.setAttribute('cx', x); - circle.setAttribute('cy', y); - circle.setAttribute('r', 20); - circle.setAttribute('fill', '#4CAF50'); - circle.setAttribute('stroke', '#333'); - circle.setAttribute('stroke-width', '2'); - svg.appendChild(circle); - - // Draw agent label - const text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); - text.setAttribute('x', x); - text.setAttribute('y', y + 5); - text.setAttribute('text-anchor', 'middle'); - text.setAttribute('font-size', '12'); - text.setAttribute('fill', '#fff'); - text.textContent = agent.id.split('-')[0]; - svg.appendChild(text); - }); - } - - updateConsensusInterface() { - const consensusStatus = document.getElementById('daa-consensus-status'); - if (!consensusStatus) return; - - consensusStatus.innerHTML = Array.from(this.consensus.values()) - .map( - (consensus) => - `
-
${consensus.proposal}
-
${consensus.status}
-
-
-
-
`, - ) - .join(''); - } - - updateFaultDashboard() { - const faultStatus = document.getElementById('daa-fault-status'); - if (!faultStatus) return; - - faultStatus.innerHTML = ` -
- Total Faults - ${this.metrics.faultCount} -
-
- Recovery Rate - 95% -
-
- MTTR - 2.3min -
- `; - } - - updateOptimizationDashboard() { - const optimizationStatus = document.getElementById('daa-optimization-status'); - if (!optimizationStatus) return; - - optimizationStatus.innerHTML = ` -
- Performance Gain - +15% -
-
- Resource Efficiency - +12% -
-
- Latency Reduction - -8% -
- `; - } - - setupEventListeners() { - // Tab switching - document.addEventListener('click', (e) => { - if (e.target.classList.contains('daa-tab')) { - this.switchTab(e.target.dataset.tab); - } - }); - - // Agent creation - document.addEventListener('click', (e) => { - if (e.target.id === 'daa-create-agent') { - this.handleCreateAgent(); - } - }); - - // Resource allocation - document.addEventListener('click', (e) => { - if (e.target.id === 'daa-allocate-resource') { - this.handleAllocateResource(); - } - }); - - // Consensus voting - document.addEventListener('click', (e) => { - if (e.target.id === 'daa-start-consensus') { - this.handleStartConsensus(); - } - }); - } - - switchTab(tabName) { - // Hide all tabs - document.querySelectorAll('.daa-tab-content').forEach((tab) => { - tab.classList.remove('active'); - }); - - document.querySelectorAll('.daa-tab').forEach((tab) => { - tab.classList.remove('active'); - }); - - // Show selected tab - document.getElementById(`daa-${tabName}-tab`).classList.add('active'); - document.querySelector(`.daa-tab[data-tab="${tabName}"]`).classList.add('active'); - - this.currentTab = tabName; - } - - handleCreateAgent() { - const type = document.getElementById('daa-agent-type').value; - const capabilities = document - .getElementById('daa-agent-capabilities') - .value.split(',') - .map((s) => s.trim()); - - const result = this.daa_agent_create({ - type: type, - capabilities: capabilities, - resources: { cpu: 1, memory: 512 }, - }); - - if (result.success) { - console.log('Agent created:', result.agentId); - } - } - - handleAllocateResource() { - const type = document.getElementById('daa-resource-type').value; - const capacity = parseInt(document.getElementById('daa-resource-capacity').value) || 100; - const priority = document.getElementById('daa-resource-priority').value; - - const result = this.daa_resource_alloc({ - type: type, - capacity: capacity, - priority: priority, - amount: capacity * 0.5, // Allocate 50% initially - }); - - if (result.success) { - console.log('Resource allocated:', result.resourceId); - } - } - - handleStartConsensus() { - const proposal = document.getElementById('daa-consensus-proposal').value; - const algorithm = document.getElementById('daa-consensus-algorithm').value; - - if (!proposal.trim()) { - alert('Please enter a proposal'); - return; - } - - const agents = Array.from(this.agents.keys()); - const result = this.daa_consensus(proposal, agents, { - algorithm: algorithm, - timeout: 30000, - }); - - if (result.success) { - console.log('Consensus started:', result.consensusId); - } - } - - initializeMonitoring() { - // Start monitoring intervals - setInterval(() => { - this.updateMetrics(); - this.updateResourceGraphs(); - this.updateLifecycleVisualization(); - }, 5000); - - // Initialize with some sample data - this.createSampleData(); - } - - createSampleData() { - // Create sample agents - this.daa_agent_create({ - type: 'researcher', - capabilities: ['data_analysis', 'research', 'documentation'], - resources: { cpu: 2, memory: 1024 }, - }); - - this.daa_agent_create({ - type: 'coder', - capabilities: ['javascript', 'python', 'testing'], - resources: { cpu: 4, memory: 2048 }, - }); - - // Create sample resources - this.daa_resource_alloc({ - type: 'cpu', - capacity: 100, - priority: 'high', - amount: 30, - }); - - this.daa_resource_alloc({ - type: 'memory', - capacity: 8192, - priority: 'medium', - amount: 2048, - }); - } -} - -// Initialize DAA Tools -let daaTools; - -// Initialize when DOM is ready -if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', () => { - daaTools = new DAATools(); - }); -} else { - daaTools = new DAATools(); -} - -// Export for use in other modules -if (typeof module !== 'undefined' && module.exports) { - module.exports = DAATools; -} diff --git a/src/ui/console/js/memory-interface.js b/src/ui/console/js/memory-interface.js deleted file mode 100644 index db040da72b..0000000000 --- a/src/ui/console/js/memory-interface.js +++ /dev/null @@ -1,961 +0,0 @@ -/** - * Memory Management Interface - * Comprehensive memory management system for Claude Flow - */ - -class MemoryInterface { - constructor() { - this.container = null; - this.currentNamespace = 'global'; - this.memoryData = new Map(); - this.searchFilters = {}; - this.analytics = { - usage: new Map(), - history: [], - patterns: new Map(), - }; - this.backupManager = new BackupManager(); - this.syncManager = new SyncManager(); - this.compressionManager = new CompressionManager(); - this.visualizer = new MemoryVisualizer(); - - this.init(); - } - - init() { - this.createInterface(); - this.setupEventListeners(); - this.startMonitoring(); - this.loadMemoryData(); - } - - createInterface() { - this.container = document.createElement('div'); - this.container.className = 'memory-interface'; - this.container.innerHTML = ` -
-

Memory Management Interface

-
- - - - -
-
- -
- -
-
-

Namespace Browser

- -
-
- -
- -
-
-
- - -
-
-

Key-Value Editor

-
- - - -
-
-
- -
- -
-
-
- - -
-
-

Memory Analytics

- -
-
-
-
-

Total Keys

- 0 -
-
-

Memory Usage

- 0 KB -
-
-

Compression Rate

- 0% -
-
-

Access Frequency

- 0/min -
-
-
-
- -
-
- -
-
-
-
-
- - -
-
-

Advanced Search

- -
-
-
-
- - - - -
-
-
- -
-
- -
-
-
- - -
-
-

Backup & Restore

- -
-
-
- - - -
-
- -
-
-
- - - - `; - } - - setupEventListeners() { - // Header controls - this.container.querySelector('.btn-refresh').addEventListener('click', () => this.refresh()); - this.container - .querySelector('.btn-backup') - .addEventListener('click', () => this.createBackup()); - this.container - .querySelector('.btn-compress') - .addEventListener('click', () => this.optimizeMemory()); - this.container - .querySelector('.btn-sync') - .addEventListener('click', () => this.showSyncStatus()); - - // Namespace controls - this.container - .querySelector('.btn-add-namespace') - .addEventListener('click', () => this.addNamespace()); - this.container - .querySelector('.namespace-search-input') - .addEventListener('input', (e) => this.searchNamespaces(e.target.value)); - - // Editor controls - this.container.querySelector('.btn-add-key').addEventListener('click', () => this.addKey()); - this.container.querySelector('.btn-bulk-edit').addEventListener('click', () => this.bulkEdit()); - this.container - .querySelector('.btn-export') - .addEventListener('click', () => this.exportMemory()); - - // Search controls - this.container - .querySelector('.key-search-input') - .addEventListener('input', (e) => this.searchKeys(e.target.value)); - this.container - .querySelector('.type-filter') - .addEventListener('change', (e) => this.filterByType(e.target.value)); - - // Analytics controls - this.container - .querySelector('.analytics-timeframe') - .addEventListener('change', (e) => this.updateAnalytics(e.target.value)); - - // Search interface - this.container - .querySelector('.btn-add-filter') - .addEventListener('click', () => this.addSearchFilter()); - this.container - .querySelector('.btn-saved-searches') - .addEventListener('click', () => this.showSavedSearches()); - - // Backup controls - this.container - .querySelector('.btn-create-backup') - .addEventListener('click', () => this.createBackup()); - this.container - .querySelector('.btn-restore-backup') - .addEventListener('click', () => this.restoreBackup()); - this.container - .querySelector('.btn-import-backup') - .addEventListener('click', () => this.importBackup()); - - // Modal controls - this.container - .querySelector('.btn-close-modal') - .addEventListener('click', () => this.closeModal()); - this.container.querySelector('.modal-overlay').addEventListener('click', (e) => { - if (e.target === this.container.querySelector('.modal-overlay')) { - this.closeModal(); - } - }); - - // Form submission - this.container - .querySelector('#key-editor-form') - .addEventListener('submit', (e) => this.saveKeyValue(e)); - } - - async loadMemoryData() { - try { - // Load memory data from Claude Flow's memory system - const response = await fetch('/api/memory/list'); - const data = await response.json(); - - this.memoryData = new Map(Object.entries(data)); - this.updateNamespaceTree(); - this.updateKeyValueList(); - this.updateAnalytics(); - } catch (error) { - console.error('Failed to load memory data:', error); - this.showError('Failed to load memory data'); - } - } - - updateNamespaceTree() { - const container = this.container.querySelector('.namespace-tree-container'); - const namespaces = this.getNamespaces(); - - container.innerHTML = this.renderNamespaceTree(namespaces); - - // Add click handlers for namespace items - container.querySelectorAll('.namespace-item').forEach((item) => { - item.addEventListener('click', (e) => { - e.stopPropagation(); - this.selectNamespace(item.dataset.namespace); - }); - }); - } - - renderNamespaceTree(namespaces, parent = '', level = 0) { - let html = ''; - - for (const [namespace, data] of namespaces) { - const fullPath = parent ? `${parent}.${namespace}` : namespace; - const hasChildren = data.children && data.children.size > 0; - - html += ` -
-
- ${hasChildren ? '' : ''} - ${namespace} - (${data.count}) -
-
- `; - - if (hasChildren) { - html += this.renderNamespaceTree(data.children, fullPath, level + 1); - } - } - - return html; - } - - updateKeyValueList() { - const container = this.container.querySelector('.key-value-list'); - const keys = this.getKeysForNamespace(this.currentNamespace); - - container.innerHTML = keys.map((key) => this.renderKeyValueItem(key)).join(''); - - // Add event listeners for key-value items - container.querySelectorAll('.key-value-item').forEach((item) => { - item - .querySelector('.btn-edit') - .addEventListener('click', () => this.editKey(item.dataset.key)); - item - .querySelector('.btn-delete') - .addEventListener('click', () => this.deleteKey(item.dataset.key)); - item - .querySelector('.btn-copy') - .addEventListener('click', () => this.copyKey(item.dataset.key)); - }); - } - - renderKeyValueItem(key) { - const value = this.memoryData.get(key); - const type = this.getValueType(value); - const displayValue = this.formatValueForDisplay(value, type); - - return ` -
-
- ${key} - ${type} -
-
- ${displayValue} -
-
- - - -
-
- `; - } - - getNamespaces() { - const namespaces = new Map(); - - for (const [key, value] of this.memoryData) { - const parts = key.split('.'); - let current = namespaces; - let path = ''; - - for (let i = 0; i < parts.length - 1; i++) { - const part = parts[i]; - path = path ? `${path}.${part}` : part; - - if (!current.has(part)) { - current.set(part, { - count: 0, - children: new Map(), - }); - } - - current = current.get(part).children; - } - - // Count the final key - const finalPart = parts[parts.length - 1]; - if (!current.has(finalPart)) { - current.set(finalPart, { count: 0, children: new Map() }); - } - current.get(finalPart).count++; - } - - return namespaces; - } - - getKeysForNamespace(namespace) { - const keys = []; - const prefix = namespace === 'global' ? '' : `${namespace}.`; - - for (const [key, value] of this.memoryData) { - if (namespace === 'global' || key.startsWith(prefix)) { - keys.push(key); - } - } - - return keys.sort(); - } - - getValueType(value) { - if (value === null) return 'null'; - if (value === undefined) return 'undefined'; - if (Array.isArray(value)) return 'array'; - return typeof value; - } - - formatValueForDisplay(value, type) { - switch (type) { - case 'string': - return value.length > 50 ? `${value.substring(0, 50)}...` : value; - case 'object': - return JSON.stringify(value).substring(0, 100) + '...'; - case 'array': - return `[${value.length} items]`; - default: - return String(value); - } - } - - updateAnalytics(timeframe = '24h') { - const stats = this.calculateStats(timeframe); - - // Update stat cards - this.container.querySelector('#total-keys').textContent = stats.totalKeys; - this.container.querySelector('#memory-usage').textContent = stats.memoryUsage; - this.container.querySelector('#compression-rate').textContent = stats.compressionRate; - this.container.querySelector('#access-frequency').textContent = stats.accessFrequency; - - // Update charts - this.visualizer.updateUsageChart(stats.usageData); - this.visualizer.updatePatternChart(stats.patternData); - } - - calculateStats(timeframe) { - const now = Date.now(); - const timeframes = { - '1h': 60 * 60 * 1000, - '24h': 24 * 60 * 60 * 1000, - '7d': 7 * 24 * 60 * 60 * 1000, - '30d': 30 * 24 * 60 * 60 * 1000, - }; - - const cutoff = now - timeframes[timeframe]; - - return { - totalKeys: this.memoryData.size, - memoryUsage: this.calculateMemoryUsage(), - compressionRate: this.compressionManager.getCompressionRate(), - accessFrequency: this.calculateAccessFrequency(cutoff), - usageData: this.getUsageData(cutoff), - patternData: this.getPatternData(cutoff), - }; - } - - calculateMemoryUsage() { - let totalSize = 0; - for (const [key, value] of this.memoryData) { - totalSize += this.getObjectSize(key) + this.getObjectSize(value); - } - return this.formatBytes(totalSize); - } - - getObjectSize(obj) { - let size = 0; - if (typeof obj === 'string') { - size = obj.length * 2; // UTF-16 - } else if (typeof obj === 'number') { - size = 8; // 64-bit float - } else if (typeof obj === 'boolean') { - size = 1; - } else if (obj === null || obj === undefined) { - size = 0; - } else { - size = JSON.stringify(obj).length * 2; - } - return size; - } - - formatBytes(bytes) { - if (bytes === 0) return '0 B'; - const k = 1024; - const sizes = ['B', 'KB', 'MB', 'GB']; - const i = Math.floor(Math.log(bytes) / Math.log(k)); - return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; - } - - calculateAccessFrequency(cutoff) { - const recentAccess = this.analytics.history.filter((entry) => entry.timestamp > cutoff); - const frequency = recentAccess.length / ((Date.now() - cutoff) / 60000); // per minute - return frequency.toFixed(2); - } - - getUsageData(cutoff) { - // Return usage data for charts - return this.analytics.history - .filter((entry) => entry.timestamp > cutoff) - .map((entry) => ({ - timestamp: entry.timestamp, - operations: entry.operations || 0, - memory: entry.memory || 0, - })); - } - - getPatternData(cutoff) { - // Return pattern data for charts - const patterns = new Map(); - - for (const [key, value] of this.analytics.patterns) { - if (value.lastAccess > cutoff) { - patterns.set(key, value); - } - } - - return Array.from(patterns.entries()); - } - - // Event handlers - async selectNamespace(namespace) { - this.currentNamespace = namespace; - this.updateKeyValueList(); - - // Update active state - this.container.querySelectorAll('.namespace-item').forEach((item) => { - item.classList.toggle('active', item.dataset.namespace === namespace); - }); - - await this.notifyCoordination(`Selected namespace: ${namespace}`); - } - - async addNamespace() { - const name = prompt('Enter namespace name:'); - if (name) { - // Create a placeholder key to establish the namespace - const key = `${name}.placeholder`; - await this.setMemoryValue(key, 'Namespace placeholder'); - await this.loadMemoryData(); - await this.notifyCoordination(`Added namespace: ${name}`); - } - } - - async addKey() { - this.openModal('key-editor-modal'); - this.container.querySelector('#edit-key').value = ''; - this.container.querySelector('#edit-value').value = ''; - this.container.querySelector('#edit-type').value = 'string'; - this.container.querySelector('#edit-namespace').value = this.currentNamespace; - } - - async editKey(key) { - const value = this.memoryData.get(key); - const type = this.getValueType(value); - - this.openModal('key-editor-modal'); - this.container.querySelector('#edit-key').value = key; - this.container.querySelector('#edit-value').value = JSON.stringify(value, null, 2); - this.container.querySelector('#edit-type').value = type; - this.container.querySelector('#edit-namespace').value = this.getNamespaceFromKey(key); - } - - async deleteKey(key) { - if (confirm(`Are you sure you want to delete "${key}"?`)) { - await this.deleteMemoryValue(key); - await this.loadMemoryData(); - await this.notifyCoordination(`Deleted key: ${key}`); - } - } - - async copyKey(key) { - const value = this.memoryData.get(key); - const text = JSON.stringify({ [key]: value }, null, 2); - - try { - await navigator.clipboard.writeText(text); - this.showSuccess('Key copied to clipboard'); - } catch (error) { - console.error('Failed to copy to clipboard:', error); - this.showError('Failed to copy to clipboard'); - } - } - - async saveKeyValue(e) { - e.preventDefault(); - - const key = this.container.querySelector('#edit-key').value; - const type = this.container.querySelector('#edit-type').value; - const valueText = this.container.querySelector('#edit-value').value; - - try { - let value; - - switch (type) { - case 'string': - value = valueText; - break; - case 'number': - value = parseFloat(valueText); - break; - case 'boolean': - value = valueText.toLowerCase() === 'true'; - break; - case 'object': - case 'array': - value = JSON.parse(valueText); - break; - default: - value = valueText; - } - - await this.setMemoryValue(key, value); - await this.loadMemoryData(); - this.closeModal(); - await this.notifyCoordination(`Saved key: ${key}`); - } catch (error) { - console.error('Failed to save key-value:', error); - this.showError('Failed to save key-value pair'); - } - } - - async createBackup() { - try { - const backup = await this.backupManager.createBackup(this.memoryData); - this.showSuccess(`Backup created: ${backup.id}`); - await this.notifyCoordination(`Created backup: ${backup.id}`); - } catch (error) { - console.error('Failed to create backup:', error); - this.showError('Failed to create backup'); - } - } - - async optimizeMemory() { - try { - const result = await this.compressionManager.optimize(this.memoryData); - this.showSuccess(`Memory optimized: ${result.savedBytes} bytes saved`); - await this.loadMemoryData(); - await this.notifyCoordination(`Optimized memory: ${result.savedBytes} bytes saved`); - } catch (error) { - console.error('Failed to optimize memory:', error); - this.showError('Failed to optimize memory'); - } - } - - async refresh() { - await this.loadMemoryData(); - this.showSuccess('Memory data refreshed'); - } - - // Helper methods - openModal(modalId) { - this.container.querySelector('#modal-overlay').style.display = 'flex'; - this.container.querySelector(`#${modalId}`).style.display = 'block'; - } - - closeModal() { - this.container.querySelector('#modal-overlay').style.display = 'none'; - this.container.querySelectorAll('.modal').forEach((modal) => { - modal.style.display = 'none'; - }); - } - - getNamespaceFromKey(key) { - const parts = key.split('.'); - return parts.length > 1 ? parts.slice(0, -1).join('.') : 'global'; - } - - async setMemoryValue(key, value) { - const response = await fetch('/api/memory/set', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ key, value }), - }); - - if (!response.ok) { - throw new Error('Failed to set memory value'); - } - } - - async deleteMemoryValue(key) { - const response = await fetch('/api/memory/delete', { - method: 'DELETE', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ key }), - }); - - if (!response.ok) { - throw new Error('Failed to delete memory value'); - } - } - - showSuccess(message) { - // Implementation for success notification - console.log('Success:', message); - } - - showError(message) { - // Implementation for error notification - console.error('Error:', message); - } - - async notifyCoordination(message) { - try { - await fetch('/api/coordination/notify', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message, timestamp: Date.now() }), - }); - } catch (error) { - console.error('Failed to notify coordination:', error); - } - } - - startMonitoring() { - // Start real-time monitoring - setInterval(() => { - this.updateAnalytics(); - }, 30000); // Update every 30 seconds - } - - render() { - return this.container; - } -} - -// Supporting classes -class BackupManager { - constructor() { - this.backups = new Map(); - } - - async createBackup(memoryData) { - const id = `backup_${Date.now()}`; - const backup = { - id, - timestamp: Date.now(), - data: new Map(memoryData), - size: this.calculateBackupSize(memoryData), - }; - - this.backups.set(id, backup); - return backup; - } - - async restoreBackup(backupId) { - const backup = this.backups.get(backupId); - if (!backup) { - throw new Error('Backup not found'); - } - - return backup.data; - } - - calculateBackupSize(memoryData) { - return JSON.stringify(Array.from(memoryData.entries())).length; - } -} - -class SyncManager { - constructor() { - this.syncStatus = 'idle'; - this.lastSync = null; - } - - async sync() { - this.syncStatus = 'syncing'; - - try { - // Implement sync logic here - await new Promise((resolve) => setTimeout(resolve, 1000)); - this.lastSync = Date.now(); - this.syncStatus = 'synchronized'; - } catch (error) { - this.syncStatus = 'error'; - throw error; - } - } - - getStatus() { - return { - status: this.syncStatus, - lastSync: this.lastSync, - }; - } -} - -class CompressionManager { - constructor() { - this.compressionRate = 0; - } - - async optimize(memoryData) { - // Implement compression logic - const originalSize = this.calculateSize(memoryData); - - // Simulate compression - await new Promise((resolve) => setTimeout(resolve, 500)); - - const compressedSize = originalSize * 0.7; // 30% compression - const savedBytes = originalSize - compressedSize; - - this.compressionRate = (savedBytes / originalSize) * 100; - - return { - savedBytes: Math.floor(savedBytes), - compressionRate: this.compressionRate, - }; - } - - getCompressionRate() { - return `${this.compressionRate.toFixed(1)}%`; - } - - calculateSize(memoryData) { - return JSON.stringify(Array.from(memoryData.entries())).length; - } -} - -class MemoryVisualizer { - constructor() { - this.usageChart = null; - this.patternChart = null; - } - - updateUsageChart(data) { - const canvas = document.getElementById('usage-chart'); - if (!canvas) return; - - const ctx = canvas.getContext('2d'); - - // Simple chart implementation - ctx.clearRect(0, 0, canvas.width, canvas.height); - - // Draw usage data - if (data.length > 0) { - ctx.beginPath(); - ctx.strokeStyle = '#007bff'; - ctx.lineWidth = 2; - - const width = canvas.width; - const height = canvas.height; - const stepX = width / (data.length - 1); - const maxValue = Math.max(...data.map((d) => d.operations)); - - data.forEach((point, index) => { - const x = index * stepX; - const y = height - (point.operations / maxValue) * height; - - if (index === 0) { - ctx.moveTo(x, y); - } else { - ctx.lineTo(x, y); - } - }); - - ctx.stroke(); - } - } - - updatePatternChart(data) { - const canvas = document.getElementById('pattern-chart'); - if (!canvas) return; - - const ctx = canvas.getContext('2d'); - - // Simple pattern chart implementation - ctx.clearRect(0, 0, canvas.width, canvas.height); - - // Draw pattern data as bars - if (data.length > 0) { - const width = canvas.width; - const height = canvas.height; - const barWidth = width / data.length; - const maxValue = Math.max(...data.map((d) => d[1].count || 0)); - - data.forEach((pattern, index) => { - const barHeight = ((pattern[1].count || 0) / maxValue) * height; - const x = index * barWidth; - const y = height - barHeight; - - ctx.fillStyle = '#28a745'; - ctx.fillRect(x, y, barWidth - 2, barHeight); - }); - } - } -} - -// Export for use in other modules -window.MemoryInterface = MemoryInterface; diff --git a/src/ui/console/js/memory-test.js b/src/ui/console/js/memory-test.js deleted file mode 100644 index 089ef7e972..0000000000 --- a/src/ui/console/js/memory-test.js +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Memory Manager Test Module - * Tests the memory management functionality - */ - -export class MemoryTest { - constructor(memoryManager, terminal) { - this.memoryManager = memoryManager; - this.terminal = terminal; - } - - /** - * Run comprehensive memory tests - */ - async runTests() { - this.terminal.writeInfo('๐Ÿงช Starting Memory Manager Tests...'); - - try { - await this.testMemoryPanel(); - await this.testMemoryTools(); - await this.testNamespaceOperations(); - await this.testMemoryOperations(); - - this.terminal.writeSuccess('โœ… All memory tests completed successfully!'); - } catch (error) { - this.terminal.writeError(`โŒ Memory tests failed: ${error.message}`); - } - } - - /** - * Test memory panel functionality - */ - async testMemoryPanel() { - this.terminal.writeInfo('Testing memory panel...'); - - // Test panel toggle - this.memoryManager.togglePanel(); - const panelVisible = !document.getElementById('memoryPanel')?.classList.contains('hidden'); - - if (panelVisible) { - this.terminal.writeSuccess('โœ… Memory panel opens correctly'); - } else { - throw new Error('Memory panel failed to open'); - } - - // Test panel components - const requiredElements = [ - 'memoryToolsGrid', - 'namespaceSelect', - 'memoryTable', - 'memoryAnalytics', - 'memoryLog', - ]; - - for (const elementId of requiredElements) { - const element = document.getElementById(elementId); - if (element) { - this.terminal.writeSuccess(`โœ… ${elementId} component found`); - } else { - throw new Error(`Required component missing: ${elementId}`); - } - } - } - - /** - * Test memory tools - */ - async testMemoryTools() { - this.terminal.writeInfo('Testing memory tools...'); - - const tools = Object.keys(this.memoryManager.memoryTools); - this.terminal.writeInfo(`Found ${tools.length} memory tools:`); - - for (const tool of tools) { - const toolInfo = this.memoryManager.memoryTools[tool]; - this.terminal.writeLine(` ${toolInfo.icon} ${toolInfo.name} - ${toolInfo.description}`); - } - - if (tools.length === 10) { - this.terminal.writeSuccess('โœ… All 10 memory tools are configured'); - } else { - throw new Error(`Expected 10 memory tools, found ${tools.length}`); - } - } - - /** - * Test namespace operations - */ - async testNamespaceOperations() { - this.terminal.writeInfo('Testing namespace operations...'); - - // Test namespace switching - const originalNamespace = this.memoryManager.currentNamespace; - - // Switch to test namespace - await this.memoryManager.switchNamespace('test'); - - if (this.memoryManager.currentNamespace === 'test') { - this.terminal.writeSuccess('โœ… Namespace switching works'); - } else { - throw new Error('Namespace switching failed'); - } - - // Switch back to original namespace - await this.memoryManager.switchNamespace(originalNamespace); - } - - /** - * Test memory operations - */ - async testMemoryOperations() { - this.terminal.writeInfo('Testing memory operations...'); - - // Test utility functions - const testData = { - size: this.memoryManager.formatSize(1024), - ttl: this.memoryManager.formatTTL(Date.now() + 3600000), - truncate: this.memoryManager.truncateValue( - 'This is a very long test string that should be truncated', - ), - escape: this.memoryManager.escapeHtml(''), - }; - - // Validate utility functions - if (testData.size === '1 KB') { - this.terminal.writeSuccess('โœ… Size formatting works'); - } else { - throw new Error(`Size formatting failed: ${testData.size}`); - } - - if (testData.ttl.includes('h') && testData.ttl.includes('m')) { - this.terminal.writeSuccess('โœ… TTL formatting works'); - } else { - throw new Error(`TTL formatting failed: ${testData.ttl}`); - } - - if (testData.truncate.length <= 103) { - // 100 + '...' - this.terminal.writeSuccess('โœ… Value truncation works'); - } else { - throw new Error('Value truncation failed'); - } - - if (!testData.escape.includes(' - - - - - - - diff --git a/src/ui/console/workflow-designer-demo.html b/src/ui/console/workflow-designer-demo.html deleted file mode 100644 index 4b21867b3e..0000000000 --- a/src/ui/console/workflow-designer-demo.html +++ /dev/null @@ -1,530 +0,0 @@ - - - - - - Claude Flow - Advanced Workflow Designer - - - - - - - - - - -
-

Claude Flow Workflow Designer

-

Advanced Visual Workflow Builder with AI Integration

-
-
- - Drag & Drop -
-
- - AI Operations -
-
- - Real-time Execution -
-
- - Validation -
-
-
- -
-
- - - Designer Ready - - - - Drag components from the palette to build workflows - - - - Use templates to get started quickly - -
-
- - -
-
- - -
- - -
- -

Quick Start

-
    -
  • Drag components from the left palette
  • -
  • Drop them onto the canvas
  • -
  • Connect nodes by dragging between ports
  • -
  • Configure properties in the right panel
  • -
  • Validate your workflow
  • -
  • Execute to see results
  • -
-
- - - - - - - - diff --git a/src/ui/hive-dashboard.ts b/src/ui/hive-dashboard.ts deleted file mode 100644 index 0a5a166a85..0000000000 --- a/src/ui/hive-dashboard.ts +++ /dev/null @@ -1,395 +0,0 @@ -/** - * Hive Mind Monitoring Dashboard - * Real-time visualization of swarm activity and consensus - */ - -import { HiveOrchestrator } from '../coordination/hive-orchestrator.js'; -import { HiveCommunicationProtocol } from '../coordination/hive-protocol.js'; - -export interface HiveDashboardData { - swarmId: string; - status: 'initializing' | 'active' | 'voting' | 'executing' | 'completed'; - agents: AgentStatus[]; - tasks: TaskProgress[]; - consensus: ConsensusMetrics; - communication: CommunicationStats; - performance: PerformanceMetrics; - timestamp: number; -} - -export interface AgentStatus { - id: string; - name: string; - type: string; - status: 'idle' | 'thinking' | 'voting' | 'executing' | 'communicating'; - currentTask?: string; - workload: number; // 0-100 - votes: number; - contributions: number; -} - -export interface TaskProgress { - id: string; - type: string; - description: string; - status: string; - assignedTo?: string; - progress: number; // 0-100 - dependencies: string[]; - votes?: { approve: number; reject: number }; -} - -export interface ConsensusMetrics { - totalDecisions: number; - approvedDecisions: number; - rejectedDecisions: number; - averageConsensus: number; - currentVotes: VoteStatus[]; -} - -export interface VoteStatus { - topic: string; - votes: { for: number; against: number; pending: number }; - deadline?: number; -} - -export interface CommunicationStats { - totalMessages: number; - messageRate: number; // messages per minute - channelActivity: Map; - knowledgeShared: number; -} - -export interface PerformanceMetrics { - tasksCompleted: number; - tasksPending: number; - avgExecutionTime: number; - successRate: number; - qualityScore: number; -} - -export class HiveDashboard { - private orchestrator: HiveOrchestrator; - private protocol: HiveCommunicationProtocol; - private refreshInterval: number = 1000; // 1 second - private updateCallback?: (data: HiveDashboardData) => void; - - constructor(orchestrator: HiveOrchestrator, protocol: HiveCommunicationProtocol) { - this.orchestrator = orchestrator; - this.protocol = protocol; - } - - /** - * Start monitoring with callback for updates - */ - startMonitoring(callback: (data: HiveDashboardData) => void) { - this.updateCallback = callback; - this.update(); - - // Set up periodic updates - const interval = setInterval(() => { - this.update(); - }, this.refreshInterval); - - return () => clearInterval(interval); - } - - /** - * Get current dashboard data - */ - private update() { - const data = this.collectDashboardData(); - if (this.updateCallback) { - this.updateCallback(data); - } - } - - /** - * Collect all dashboard data - */ - private collectDashboardData(): HiveDashboardData { - const perfMetrics = this.orchestrator.getPerformanceMetrics(); - const commStats = this.protocol.getStatistics(); - - return { - swarmId: 'current-swarm', - status: this.determineSwarmStatus(perfMetrics), - agents: this.getAgentStatuses(), - tasks: this.getTaskProgress(), - consensus: this.getConsensusMetrics(), - communication: this.getCommunicationStats(commStats), - performance: this.getPerformanceMetrics(perfMetrics), - timestamp: Date.now(), - }; - } - - /** - * Determine overall swarm status - */ - private determineSwarmStatus(metrics: any): HiveDashboardData['status'] { - if (metrics.executingTasks > 0) return 'executing'; - if (metrics.pendingTasks > 0) return 'active'; - if (metrics.completedTasks === metrics.totalTasks) return 'completed'; - return 'initializing'; - } - - /** - * Get status of all agents - */ - private getAgentStatuses(): AgentStatus[] { - // This would be populated from actual agent data - return [ - { - id: 'queen-1', - name: 'Queen-Genesis', - type: 'queen', - status: 'thinking', - workload: 85, - votes: 15, - contributions: 42, - }, - { - id: 'architect-1', - name: 'Architect-1', - type: 'architect', - status: 'executing', - currentTask: 'Design system architecture', - workload: 70, - votes: 8, - contributions: 23, - }, - { - id: 'worker-1', - name: 'Worker-1', - type: 'worker', - status: 'voting', - workload: 45, - votes: 12, - contributions: 31, - }, - ]; - } - - /** - * Get task progress information - */ - private getTaskProgress(): TaskProgress[] { - const taskGraph = this.orchestrator.getTaskGraph(); - return taskGraph.nodes.map((node) => ({ - id: node.id, - type: node.type, - description: `${node.type} task`, - status: node.status, - assignedTo: node.assignedTo, - progress: this.calculateTaskProgress(node.status), - dependencies: [], - })); - } - - /** - * Calculate task progress based on status - */ - private calculateTaskProgress(status: string): number { - switch (status) { - case 'completed': - return 100; - case 'executing': - return 50; - case 'assigned': - return 25; - case 'voting': - return 10; - case 'pending': - return 0; - default: - return 0; - } - } - - /** - * Get consensus metrics - */ - private getConsensusMetrics(): ConsensusMetrics { - const metrics = this.orchestrator.getPerformanceMetrics(); - return { - totalDecisions: metrics.totalDecisions, - approvedDecisions: metrics.approvedDecisions, - rejectedDecisions: metrics.totalDecisions - metrics.approvedDecisions, - averageConsensus: metrics.consensusRate, - currentVotes: [], // Would be populated from active votes - }; - } - - /** - * Get communication statistics - */ - private getCommunicationStats(stats: any): CommunicationStats { - return { - totalMessages: stats.totalMessages, - messageRate: stats.totalMessages / 10, // Approximate rate - channelActivity: stats.messagesByType, - knowledgeShared: stats.knowledgeEntries, - }; - } - - /** - * Get performance metrics - */ - private getPerformanceMetrics(metrics: any): PerformanceMetrics { - return { - tasksCompleted: metrics.completedTasks, - tasksPending: metrics.pendingTasks, - avgExecutionTime: metrics.avgExecutionTime, - successRate: metrics.totalTasks > 0 ? metrics.completedTasks / metrics.totalTasks : 0, - qualityScore: 0.85, // Would be calculated from quality reports - }; - } - - /** - * Format dashboard for console output - */ - static formatConsoleOutput(data: HiveDashboardData): string { - const output = []; - - // Header - output.push('๐Ÿ Hive Mind Dashboard'); - output.push('โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•'); - output.push( - `Status: ${data.status.toUpperCase()} | Time: ${new Date(data.timestamp).toLocaleTimeString()}`, - ); - output.push(''); - - // Agents Section - output.push('๐Ÿ‘ฅ Agent Status'); - output.push('โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€'); - for (const agent of data.agents) { - const statusIcon = this.getStatusIcon(agent.status); - const workloadBar = this.createProgressBar(agent.workload); - output.push(`${statusIcon} ${agent.name} (${agent.type})`); - output.push(` Status: ${agent.status} | Workload: ${workloadBar} ${agent.workload}%`); - if (agent.currentTask) { - output.push(` Task: ${agent.currentTask}`); - } - output.push(` Votes: ${agent.votes} | Contributions: ${agent.contributions}`); - output.push(''); - } - - // Tasks Section - output.push('๐Ÿ“‹ Task Progress'); - output.push('โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€'); - for (const task of data.tasks) { - const progressBar = this.createProgressBar(task.progress); - const statusIcon = this.getTaskStatusIcon(task.status); - output.push(`${statusIcon} ${task.type}: ${task.description}`); - output.push(` Progress: ${progressBar} ${task.progress}%`); - if (task.assignedTo) { - output.push(` Assigned to: ${task.assignedTo}`); - } - output.push(''); - } - - // Consensus Section - output.push('๐Ÿ—ณ๏ธ Consensus Metrics'); - output.push('โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€'); - output.push(`Total Decisions: ${data.consensus.totalDecisions}`); - output.push( - `Approved: ${data.consensus.approvedDecisions} | Rejected: ${data.consensus.rejectedDecisions}`, - ); - output.push(`Average Consensus: ${(data.consensus.averageConsensus * 100).toFixed(1)}%`); - output.push(''); - - // Performance Section - output.push('๐Ÿ“Š Performance'); - output.push('โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€'); - output.push( - `Tasks: ${data.performance.tasksCompleted}/${data.performance.tasksCompleted + data.performance.tasksPending} completed`, - ); - output.push(`Success Rate: ${(data.performance.successRate * 100).toFixed(1)}%`); - output.push(`Quality Score: ${(data.performance.qualityScore * 100).toFixed(1)}%`); - output.push(`Avg Execution Time: ${(data.performance.avgExecutionTime / 1000).toFixed(1)}s`); - output.push(''); - - // Communication Section - output.push('๐Ÿ’ฌ Communication'); - output.push('โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€'); - output.push(`Total Messages: ${data.communication.totalMessages}`); - output.push(`Message Rate: ${data.communication.messageRate.toFixed(1)}/min`); - output.push(`Knowledge Shared: ${data.communication.knowledgeShared} entries`); - - return output.join('\\n'); - } - - /** - * Get status icon for agent - */ - private static getStatusIcon(status: AgentStatus['status']): string { - switch (status) { - case 'idle': - return '๐Ÿ˜ด'; - case 'thinking': - return '๐Ÿค”'; - case 'voting': - return '๐Ÿ—ณ๏ธ'; - case 'executing': - return 'โšก'; - case 'communicating': - return '๐Ÿ’ฌ'; - default: - return 'โ“'; - } - } - - /** - * Get status icon for task - */ - private static getTaskStatusIcon(status: string): string { - switch (status) { - case 'pending': - return 'โญ•'; - case 'voting': - return '๐Ÿ—ณ๏ธ'; - case 'assigned': - return '๐Ÿ“Œ'; - case 'executing': - return '๐Ÿ”„'; - case 'reviewing': - return '๐Ÿ”'; - case 'completed': - return 'โœ…'; - case 'failed': - return 'โŒ'; - default: - return 'โ“'; - } - } - - /** - * Create ASCII progress bar - */ - private static createProgressBar(percentage: number, width: number = 20): string { - const filled = Math.round((percentage / 100) * width); - const empty = width - filled; - return `[${'โ–ˆ'.repeat(filled)}${' '.repeat(empty)}]`; - } - - /** - * Export dashboard data as JSON - */ - exportData(): string { - const data = this.collectDashboardData(); - return JSON.stringify(data, null, 2); - } - - /** - * Get real-time event stream - */ - getEventStream(): AsyncGenerator { - // This would return a stream of dashboard events - return (async function* () { - while (true) { - yield { type: 'update', timestamp: Date.now() }; - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - })(); - } -} diff --git a/src/ui/web-ui/EnhancedProcessUI.js b/src/ui/web-ui/EnhancedProcessUI.js deleted file mode 100644 index 31dd6812a1..0000000000 --- a/src/ui/web-ui/EnhancedProcessUI.js +++ /dev/null @@ -1,1772 +0,0 @@ -/** - * Enhanced Process UI - Upgraded version with modular architecture integration - * Combines existing process management with 71+ MCP tools and advanced features - */ - -import { printSuccess, printError, printWarning, printInfo } from '../../cli/utils.js'; -import { compat } from '../../cli/runtime-detector.js'; -import SwarmWebUIIntegration from '../../cli/simple-commands/swarm-webui-integration.js'; -import EnhancedWebUI from './EnhancedWebUI.js'; - -// Enhanced color utilities with more options -const colors = { - cyan: (text) => `\x1b[36m${text}\x1b[0m`, - gray: (text) => `\x1b[90m${text}\x1b[0m`, - white: (text) => `\x1b[37m${text}\x1b[0m`, - yellow: (text) => `\x1b[33m${text}\x1b[0m`, - green: (text) => `\x1b[32m${text}\x1b[0m`, - red: (text) => `\x1b[31m${text}\x1b[0m`, - blue: (text) => `\x1b[34m${text}\x1b[0m`, - magenta: (text) => `\x1b[35m${text}\x1b[0m`, - bold: (text) => `\x1b[1m${text}\x1b[0m`, - dim: (text) => `\x1b[2m${text}\x1b[0m`, - bright: (text) => `\x1b[97m${text}\x1b[0m`, - orange: (text) => `\x1b[38;5;208m${text}\x1b[0m`, - purple: (text) => `\x1b[35m${text}\x1b[0m`, -}; - -const PROCESSES = [ - { id: 'event-bus', name: 'Event Bus', description: 'Central event distribution system' }, - { id: 'orchestrator', name: 'Orchestrator', description: 'Main coordination engine' }, - { id: 'memory-manager', name: 'Memory Manager', description: 'Persistent memory system' }, - { id: 'terminal-pool', name: 'Terminal Pool', description: 'Terminal session management' }, - { id: 'mcp-server', name: 'MCP Server', description: 'Model Context Protocol server' }, - { id: 'coordinator', name: 'Coordinator', description: 'Task coordination service' }, - { id: 'enhanced-ui', name: 'Enhanced UI', description: 'Advanced web interface system' }, - { id: 'neural-engine', name: 'Neural Engine', description: 'AI neural network processor' }, -]; - -// Enhanced view modes with new categories -const VIEWS = { - OVERVIEW: 'overview', - PROCESSES: 'processes', - STATUS: 'status', - ORCHESTRATION: 'orchestration', - MEMORY: 'memory', - NEURAL: 'neural', - MONITORING: 'monitoring', - WORKFLOW: 'workflow', - GITHUB: 'github', - DAA: 'daa', - SYSTEM: 'system', - CLI: 'cli', - LOGS: 'logs', - HELP: 'help', -}; - -// Tool category information -const TOOL_CATEGORIES = { - neural: { icon: '๐Ÿง ', name: 'Neural Network', count: 15, color: colors.cyan }, - memory: { icon: '๐Ÿ’พ', name: 'Memory Management', count: 10, color: colors.green }, - monitoring: { icon: '๐Ÿ“Š', name: 'Monitoring & Analysis', count: 13, color: colors.yellow }, - workflow: { icon: '๐Ÿ”„', name: 'Workflow & Automation', count: 11, color: colors.blue }, - github: { icon: '๐Ÿ™', name: 'GitHub Integration', count: 8, color: colors.magenta }, - daa: { icon: '๐Ÿค–', name: 'Dynamic Agents', count: 8, color: colors.purple }, - system: { icon: '๐Ÿ› ๏ธ', name: 'System Utilities', count: 6, color: colors.orange }, - cli: { icon: 'โŒจ๏ธ', name: 'CLI Commands', count: 9, color: colors.white }, -}; - -export class EnhancedProcessUI { - constructor() { - this.processes = new Map(); - this.running = true; - this.selectedIndex = 0; - this.currentView = VIEWS.OVERVIEW; - this.agents = []; - this.tasks = []; - this.memoryStats = { - totalEntries: 0, - totalSize: 0, - namespaces: [], - }; - this.logs = []; - this.systemStats = { - uptime: 0, - totalTasks: 0, - completedTasks: 0, - activeAgents: 0, - memoryUsage: 0, - cpuUsage: 0, - toolsAvailable: 71, - enhancedMode: false, - }; - - // Enhanced UI integration - this.enhancedWebUI = null; - this.toolExecutions = new Map(); - this.recentTools = []; - this.toolStats = new Map(); - - // Initialize integrations - this.swarmIntegration = new SwarmWebUIIntegration(this); - - // Initialize process states - PROCESSES.forEach((p) => { - this.processes.set(p.id, { - ...p, - status: 'stopped', - pid: null, - uptime: 0, - cpu: Math.random() * 5, - memory: Math.random() * 100, - }); - }); - - // Start system uptime counter - setInterval(() => { - this.systemStats.uptime++; - }, 1000); - - // Initialize enhanced features - this.initializeEnhancedFeatures(); - } - - /** - * Initialize enhanced features - */ - async initializeEnhancedFeatures() { - try { - // Initialize enhanced web UI - this.enhancedWebUI = new EnhancedWebUI(); - await this.enhancedWebUI.initialize(this); - - this.systemStats.enhancedMode = true; - this.addLog('success', 'Enhanced UI features initialized'); - - // Set enhanced UI process as running - const enhancedUIProcess = this.processes.get('enhanced-ui'); - if (enhancedUIProcess) { - enhancedUIProcess.status = 'running'; - enhancedUIProcess.pid = Math.floor(Math.random() * 10000) + 1000; - } - } catch (error) { - this.addLog('warning', 'Enhanced UI fallback mode enabled'); - console.warn('Enhanced UI initialization warning:', error); - } - - // Initialize swarm (this will create mock data) - await this.initializeSwarm(); - - // Initialize tool statistics - this.initializeToolStats(); - } - - /** - * Initialize tool statistics - */ - initializeToolStats() { - Object.keys(TOOL_CATEGORIES).forEach((category) => { - this.toolStats.set(category, { - executions: 0, - lastUsed: null, - avgDuration: 0, - successRate: 100, - }); - }); - } - - async initializeSwarm() { - // Initialize swarm with mock data - await this.swarmIntegration.initializeSwarm('hierarchical', 8); - - // Enhanced memory namespaces - this.memoryStats = { - totalEntries: 156, - totalSize: '2.4 MB', - namespaces: [ - { name: 'neural', entries: 45, size: '678 KB' }, - { name: 'sparc', entries: 32, size: '512 KB' }, - { name: 'agents', entries: 28, size: '389 KB' }, - { name: 'tasks', entries: 24, size: '334 KB' }, - { name: 'workflows', entries: 18, size: '267 KB' }, - { name: 'monitoring', entries: 9, size: '245 KB' }, - ], - }; - - // Enhanced initial logs - this.logs = [ - { time: new Date(), level: 'info', message: 'System initialized with enhanced features' }, - { time: new Date(), level: 'success', message: 'All 71+ tools loaded successfully' }, - { time: new Date(), level: 'success', message: 'Enhanced UI architecture active' }, - { time: new Date(), level: 'info', message: 'Swarm orchestration ready' }, - { time: new Date(), level: 'success', message: 'Neural engine online' }, - ]; - } - - async start() { - // Clear screen - console.clear(); - - // Show enhanced welcome - printSuccess('๐Ÿง  Claude-Flow Enhanced UI v2.0.0'); - console.log(colors.dim('Enhanced with 71+ MCP tools and advanced features')); - console.log('โ”€'.repeat(80)); - console.log(); - - // Initial render - this.render(); - - // Main UI loop - while (this.running) { - await this.handleInput(); - if (this.running) { - this.render(); - } - } - } - - render() { - // Clear screen and move cursor to top - console.log('\x1b[2J\x1b[H'); - - // Header with enhanced navigation - this.renderEnhancedHeader(); - - // Main content based on current view - switch (this.currentView) { - case VIEWS.OVERVIEW: - this.renderOverviewView(); - break; - case VIEWS.PROCESSES: - this.renderProcessView(); - break; - case VIEWS.STATUS: - this.renderStatusView(); - break; - case VIEWS.ORCHESTRATION: - this.renderOrchestrationView(); - break; - case VIEWS.MEMORY: - this.renderMemoryView(); - break; - case VIEWS.NEURAL: - this.renderNeuralView(); - break; - case VIEWS.MONITORING: - this.renderMonitoringView(); - break; - case VIEWS.WORKFLOW: - this.renderWorkflowView(); - break; - case VIEWS.GITHUB: - this.renderGitHubView(); - break; - case VIEWS.DAA: - this.renderDAAView(); - break; - case VIEWS.SYSTEM: - this.renderSystemView(); - break; - case VIEWS.CLI: - this.renderCLIView(); - break; - case VIEWS.LOGS: - this.renderLogsView(); - break; - case VIEWS.HELP: - this.renderEnhancedHelpView(); - break; - } - - // Enhanced footer with tool information - this.renderEnhancedFooter(); - } - - renderEnhancedHeader() { - const enhancedStatus = this.systemStats.enhancedMode - ? colors.green('ENHANCED') - : colors.yellow('FALLBACK'); - - console.log(colors.cyan(colors.bold('๐Ÿง  Claude-Flow Enhanced Process Manager'))); - console.log( - colors.dim( - `Mode: ${enhancedStatus} | Tools: ${this.systemStats.toolsAvailable}+ | Uptime: ${this.formatUptime(this.systemStats.uptime)}`, - ), - ); - console.log(colors.gray('โ”€'.repeat(80))); - - // Enhanced navigation tabs with tool counts - const tabs = [ - { key: '0', view: VIEWS.OVERVIEW, label: 'Overview', icon: '๐Ÿ ' }, - { key: '1', view: VIEWS.PROCESSES, label: 'Processes', icon: 'โš™๏ธ' }, - { key: '2', view: VIEWS.STATUS, label: 'Status', icon: '๐Ÿ“Š' }, - { key: '3', view: VIEWS.ORCHESTRATION, label: 'Orchestration', icon: '๐Ÿ' }, - { key: '4', view: VIEWS.MEMORY, label: 'Memory', icon: '๐Ÿ’พ' }, - { key: '5', view: VIEWS.NEURAL, label: 'Neural (15)', icon: '๐Ÿง ' }, - { key: '6', view: VIEWS.MONITORING, label: 'Monitor (13)', icon: '๐Ÿ“Š' }, - { key: '7', view: VIEWS.WORKFLOW, label: 'Workflow (11)', icon: '๐Ÿ”„' }, - { key: '8', view: VIEWS.GITHUB, label: 'GitHub (8)', icon: '๐Ÿ™' }, - { key: '9', view: VIEWS.LOGS, label: 'Logs', icon: '๐Ÿ“œ' }, - { key: '?', view: VIEWS.HELP, label: 'Help', icon: 'โ“' }, - ]; - - let tabLine = ''; - tabs.forEach((tab, index) => { - const isActive = this.currentView === tab.view; - const label = isActive - ? colors.yellow(`[${tab.icon} ${tab.label}]`) - : colors.gray(`${tab.icon} ${tab.label}`); - tabLine += ` ${colors.bold(tab.key)}:${label}`; - - // Add line break every 4 tabs for better layout - if ((index + 1) % 4 === 0 && index < tabs.length - 1) { - tabLine += '\n'; - } - }); - - console.log(tabLine); - console.log(colors.gray('โ”€'.repeat(80))); - console.log(); - } - - renderOverviewView() { - console.log(colors.white(colors.bold('๐Ÿ  System Overview'))); - console.log(); - - // Quick stats grid - const stats = [ - { - label: 'Tools Available', - value: this.systemStats.toolsAvailable + '+', - icon: '๐Ÿ”ง', - color: colors.cyan, - }, - { - label: 'Active Agents', - value: this.agents.filter((a) => a.status === 'working').length, - icon: '๐Ÿค–', - color: colors.green, - }, - { - label: 'Running Processes', - value: Array.from(this.processes.values()).filter((p) => p.status === 'running').length, - icon: 'โš™๏ธ', - color: colors.blue, - }, - { - label: 'Memory Namespaces', - value: this.memoryStats.namespaces.length, - icon: '๐Ÿ’พ', - color: colors.magenta, - }, - ]; - - const statsLine1 = stats - .slice(0, 2) - .map((stat) => `${stat.icon} ${stat.color(stat.value)} ${colors.gray(stat.label)}`) - .join(' | '); - - const statsLine2 = stats - .slice(2, 4) - .map((stat) => `${stat.icon} ${stat.color(stat.value)} ${colors.gray(stat.label)}`) - .join(' | '); - - console.log(` ${statsLine1}`); - console.log(` ${statsLine2}`); - console.log(); - - // Tool categories overview - console.log(colors.cyan('๐Ÿ”ง Tool Categories')); - console.log(); - - const categories = Object.entries(TOOL_CATEGORIES); - categories.forEach(([id, category], index) => { - const stats = this.toolStats.get(id); - const usageInfo = - stats && stats.executions > 0 - ? colors.dim(` (${stats.executions} uses)`) - : colors.dim(' (unused)'); - - console.log( - ` ${category.icon} ${category.color(category.name)}: ${colors.yellow(category.count)} tools${usageInfo}`, - ); - }); - - console.log(); - - // Recent activity - console.log(colors.cyan('๐Ÿ”” Recent Activity')); - this.logs.slice(-5).forEach((log) => { - const time = log.time.toLocaleTimeString(); - const icon = log.level === 'success' ? 'โœ“' : log.level === 'warning' ? 'โš ' : 'โ„น'; - const color = - log.level === 'success' - ? colors.green - : log.level === 'warning' - ? colors.yellow - : colors.blue; - console.log(` ${colors.gray(time)} ${color(icon)} ${log.message}`); - }); - - console.log(); - - // Quick actions - console.log(colors.cyan('โšก Quick Actions')); - console.log( - ` ${colors.yellow('N')} Neural Tools ${colors.yellow('M')} Memory Tools ${colors.yellow('W')} Workflows ${colors.yellow('G')} GitHub`, - ); - console.log( - ` ${colors.yellow('D')} Diagnostics ${colors.yellow('S')} Swarm Control ${colors.yellow('T')} Train Model ${colors.yellow('A')} Analytics`, - ); - } - - renderNeuralView() { - console.log(colors.white(colors.bold('๐Ÿง  Neural Network Operations'))); - console.log(); - - const neuralTools = [ - { key: 'T', name: 'neural_train', desc: 'Train neural patterns with WASM SIMD' }, - { key: 'P', name: 'neural_predict', desc: 'Make AI predictions' }, - { key: 'S', name: 'neural_status', desc: 'Check neural network status' }, - { key: 'A', name: 'neural_patterns', desc: 'Analyze cognitive patterns' }, - { key: 'L', name: 'model_load', desc: 'Load pre-trained models' }, - { key: 'V', name: 'model_save', desc: 'Save trained models' }, - { key: 'R', name: 'pattern_recognize', desc: 'Pattern recognition' }, - { key: 'C', name: 'cognitive_analyze', desc: 'Cognitive behavior analysis' }, - { key: 'D', name: 'learning_adapt', desc: 'Adaptive learning' }, - { key: 'Z', name: 'neural_compress', desc: 'Compress neural models' }, - { key: 'E', name: 'ensemble_create', desc: 'Create model ensembles' }, - { key: 'F', name: 'transfer_learn', desc: 'Transfer learning' }, - { key: 'X', name: 'neural_explain', desc: 'AI explainability' }, - { key: 'W', name: 'wasm_optimize', desc: 'WASM SIMD optimization' }, - { key: 'I', name: 'inference_run', desc: 'Run neural inference' }, - ]; - - console.log(colors.cyan('Available Neural Tools (15):')); - neuralTools.forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐ŸŽฏ Recent Neural Operations:')); - const recentNeural = this.recentTools.filter( - (t) => t.startsWith('neural_') || t.includes('model_'), - ); - if (recentNeural.length > 0) { - recentNeural.slice(-3).forEach((tool) => { - console.log(` โœ“ ${colors.green(tool)}`); - }); - } else { - console.log(` ${colors.gray('No recent neural operations')}`); - } - } - - renderMonitoringView() { - console.log(colors.white(colors.bold('๐Ÿ“Š Monitoring & Analysis'))); - console.log(); - - const monitoringTools = [ - { key: 'P', name: 'performance_report', desc: 'Generate performance reports' }, - { key: 'B', name: 'bottleneck_analyze', desc: 'Identify performance bottlenecks' }, - { key: 'T', name: 'token_usage', desc: 'Analyze token consumption' }, - { key: 'M', name: 'metrics_collect', desc: 'Collect system metrics' }, - { key: 'H', name: 'health_check', desc: 'System health monitoring' }, - { key: 'E', name: 'error_analysis', desc: 'Error pattern analysis' }, - { key: 'U', name: 'usage_stats', desc: 'Usage statistics' }, - { key: 'Q', name: 'quality_assess', desc: 'Quality assessment' }, - { key: 'C', name: 'cost_analysis', desc: 'Cost and resource analysis' }, - { key: 'R', name: 'trend_analysis', desc: 'Analyze performance trends' }, - { key: 'K', name: 'benchmark_run', desc: 'Performance benchmarks' }, - { key: 'S', name: 'swarm_monitor', desc: 'Real-time swarm monitoring' }, - { key: 'A', name: 'agent_metrics', desc: 'Agent performance metrics' }, - ]; - - console.log(colors.cyan('Available Monitoring Tools (13):')); - monitoringTools.slice(0, 7).forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(' ' + colors.gray('... and 6 more tools')); - - // Live system metrics - console.log(); - console.log(colors.cyan('๐Ÿ“ˆ Live System Metrics:')); - console.log( - ` CPU: ${this.getUsageBar(this.systemStats.cpuUsage, 100)} ${this.systemStats.cpuUsage.toFixed(1)}%`, - ); - console.log( - ` Memory: ${this.getUsageBar(this.systemStats.memoryUsage, 100)} ${this.systemStats.memoryUsage.toFixed(1)}%`, - ); - console.log( - ` Agents: ${colors.green(this.agents.filter((a) => a.status === 'working').length)}/${this.agents.length} active`, - ); - console.log( - ` Tasks: ${colors.yellow(this.tasks.filter((t) => t.status === 'in_progress').length)} in progress`, - ); - } - - renderWorkflowView() { - console.log(colors.white(colors.bold('๐Ÿ”„ Workflow & Automation'))); - console.log(); - - const workflowTools = [ - { key: 'C', name: 'workflow_create', desc: 'Create custom workflows' }, - { key: 'E', name: 'workflow_execute', desc: 'Execute predefined workflows' }, - { key: 'A', name: 'automation_setup', desc: 'Setup automation rules' }, - { key: 'P', name: 'pipeline_create', desc: 'Create CI/CD pipelines' }, - { key: 'S', name: 'scheduler_manage', desc: 'Manage task scheduling' }, - { key: 'T', name: 'trigger_setup', desc: 'Setup event triggers' }, - { key: 'W', name: 'workflow_template', desc: 'Manage workflow templates' }, - { key: 'B', name: 'batch_process', desc: 'Batch processing' }, - { key: 'L', name: 'parallel_execute', desc: 'Execute tasks in parallel' }, - { key: 'R', name: 'sparc_mode', desc: 'Run SPARC development modes' }, - { key: 'O', name: 'task_orchestrate', desc: 'Orchestrate complex workflows' }, - ]; - - console.log(colors.cyan('Available Workflow Tools (11):')); - workflowTools.forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐ŸŽฏ Active Workflows:')); - // Show active workflows/automations - const activeWorkflows = this.tasks.filter( - (t) => t.description.includes('workflow') || t.description.includes('automation'), - ); - if (activeWorkflows.length > 0) { - activeWorkflows.slice(-3).forEach((workflow) => { - const status = - workflow.status === 'completed' - ? colors.green('โœ“') - : workflow.status === 'in_progress' - ? colors.yellow('โ—') - : colors.gray('โ—‹'); - console.log(` ${status} ${workflow.description}`); - }); - } else { - console.log(` ${colors.gray('No active workflows')}`); - } - } - - renderGitHubView() { - console.log(colors.white(colors.bold('๐Ÿ™ GitHub Integration'))); - console.log(); - - const githubTools = [ - { key: 'A', name: 'github_repo_analyze', desc: 'Repository analysis' }, - { key: 'P', name: 'github_pr_manage', desc: 'Pull request management' }, - { key: 'I', name: 'github_issue_track', desc: 'Issue tracking & triage' }, - { key: 'R', name: 'github_release_coord', desc: 'Release coordination' }, - { key: 'W', name: 'github_workflow_auto', desc: 'Workflow automation' }, - { key: 'C', name: 'github_code_review', desc: 'Automated code review' }, - { key: 'S', name: 'github_sync_coord', desc: 'Multi-repo sync coordination' }, - { key: 'M', name: 'github_metrics', desc: 'Repository metrics' }, - ]; - - console.log(colors.cyan('Available GitHub Tools (8):')); - githubTools.forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐Ÿ“Š GitHub Integration Status:')); - console.log(` Repository: ${colors.green('claude-code-flow')}`); - console.log(` Branch: ${colors.yellow('claude-flow-v2.0.0')}`); - console.log(` Status: ${colors.green('Connected')}`); - console.log(` Last Sync: ${colors.gray('Recently')}`); - } - - renderDAAView() { - console.log(colors.white(colors.bold('๐Ÿค– Dynamic Agent Architecture'))); - console.log(); - - const daaTools = [ - { key: 'C', name: 'daa_agent_create', desc: 'Create dynamic agents' }, - { key: 'M', name: 'daa_capability_match', desc: 'Match capabilities to tasks' }, - { key: 'R', name: 'daa_resource_alloc', desc: 'Resource allocation' }, - { key: 'L', name: 'daa_lifecycle_manage', desc: 'Agent lifecycle management' }, - { key: 'O', name: 'daa_communication', desc: 'Inter-agent communication' }, - { key: 'N', name: 'daa_consensus', desc: 'Consensus mechanisms' }, - { key: 'F', name: 'daa_fault_tolerance', desc: 'Fault tolerance & recovery' }, - { key: 'P', name: 'daa_optimization', desc: 'Performance optimization' }, - ]; - - console.log(colors.cyan('Available DAA Tools (8):')); - daaTools.forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐Ÿ”— Agent Network Status:')); - console.log(` Total Agents: ${colors.green(this.agents.length)}`); - console.log( - ` Active: ${colors.yellow(this.agents.filter((a) => a.status === 'working').length)}`, - ); - console.log(` Idle: ${colors.gray(this.agents.filter((a) => a.status === 'idle').length)}`); - console.log(` Consensus: ${colors.green('Healthy')}`); - } - - renderSystemView() { - console.log(colors.white(colors.bold('๐Ÿ› ๏ธ System Utilities'))); - console.log(); - - const systemTools = [ - { key: 'S', name: 'security_scan', desc: 'Security scanning' }, - { key: 'B', name: 'backup_create', desc: 'Create system backups' }, - { key: 'R', name: 'restore_system', desc: 'System restoration' }, - { key: 'L', name: 'log_analysis', desc: 'Log analysis & insights' }, - { key: 'D', name: 'diagnostic_run', desc: 'System diagnostics' }, - { key: 'C', name: 'config_manage', desc: 'Configuration management' }, - ]; - - console.log(colors.cyan('Available System Tools (6):')); - systemTools.forEach((tool) => { - const stats = this.getToolStats(tool.name); - const usage = stats ? colors.dim(` (${stats.executions} uses)`) : ''; - console.log( - ` ${colors.yellow(tool.key)}: ${colors.white(tool.name)} - ${colors.gray(tool.desc)}${usage}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐Ÿ”ง System Health:')); - console.log(` Overall Status: ${colors.green('Healthy')}`); - console.log(` Security Score: ${colors.green('A-')}`); - console.log(` Last Backup: ${colors.gray('2 hours ago')}`); - console.log(` Disk Usage: ${this.getUsageBar(65, 100)} 65%`); - } - - renderCLIView() { - console.log(colors.white(colors.bold('โŒจ๏ธ CLI Command Bridge'))); - console.log(); - - const cliCommands = [ - { key: 'H', name: 'hive-mind', desc: 'Hive mind orchestration wizard' }, - { key: 'G', name: 'github', desc: 'GitHub operations' }, - { key: 'T', name: 'training', desc: 'Neural training commands' }, - { key: 'A', name: 'analysis', desc: 'Analysis operations' }, - { key: 'U', name: 'automation', desc: 'Automation setup' }, - { key: 'C', name: 'coordination', desc: 'Swarm coordination' }, - { key: 'K', name: 'hooks', desc: 'Hook management' }, - { key: 'M', name: 'mcp', desc: 'MCP server control' }, - { key: 'F', name: 'config', desc: 'Configuration management' }, - ]; - - console.log(colors.cyan('Available CLI Commands (9):')); - cliCommands.forEach((cmd) => { - console.log( - ` ${colors.yellow(cmd.key)}: ${colors.white(cmd.name)} - ${colors.gray(cmd.desc)}`, - ); - }); - - console.log(); - console.log(colors.cyan('๐ŸŽฏ CLI Integration Status:')); - console.log(` Bridge Mode: ${colors.green('Active')}`); - console.log(` Commands Available: ${colors.yellow('All')}`); - console.log(` Last Command: ${colors.gray('N/A')}`); - } - - // Keep existing methods but add enhanced functionality - renderProcessView() { - console.log(colors.white(colors.bold('โš™๏ธ Process Management'))); - console.log(); - - let index = 0; - for (const [id, process] of this.processes) { - const selected = index === this.selectedIndex; - const prefix = selected ? colors.yellow('โ–ถ ') : ' '; - const status = this.getStatusIcon(process.status); - const name = selected ? colors.yellow(process.name) : colors.white(process.name); - - console.log(`${prefix}${status} ${name}`); - console.log(` ${colors.gray(process.description)}`); - - if (process.status === 'running') { - const stats = colors.dim( - `PID: ${process.pid} | Uptime: ${this.formatUptime(process.uptime)} | CPU: ${process.cpu.toFixed(1)}% | Mem: ${process.memory.toFixed(0)}MB`, - ); - console.log(` ${stats}`); - } - console.log(); - - index++; - } - - // Enhanced stats - const running = Array.from(this.processes.values()).filter( - (p) => p.status === 'running', - ).length; - console.log(colors.gray('โ”€'.repeat(80))); - console.log( - colors.white( - `Total: ${this.processes.size} | Running: ${colors.green(running)} | Stopped: ${colors.gray(this.processes.size - running)} | Enhanced: ${this.systemStats.enhancedMode ? colors.green('Yes') : colors.yellow('Fallback')}`, - ), - ); - } - - // Enhanced status view - renderStatusView() { - console.log(colors.white(colors.bold('๐Ÿ“Š Enhanced System Status'))); - console.log(); - - // System overview - console.log(colors.cyan('๐Ÿ“Š System Overview')); - console.log(` Uptime: ${colors.green(this.formatUptime(this.systemStats.uptime))}`); - console.log( - ` Mode: ${this.systemStats.enhancedMode ? colors.green('Enhanced') : colors.yellow('Fallback')}`, - ); - console.log(` Process Health: ${this.getHealthBar()}`); - console.log(` Tools Available: ${colors.cyan(this.systemStats.toolsAvailable + '+')}`); - console.log(); - - // Resource usage - console.log(colors.cyan('๐Ÿ’ป Resource Usage')); - console.log( - ` CPU Usage: ${this.getUsageBar(this.systemStats.cpuUsage, 100)} ${this.systemStats.cpuUsage.toFixed(1)}%`, - ); - console.log( - ` Memory: ${this.getUsageBar(this.systemStats.memoryUsage, 100)} ${this.systemStats.memoryUsage.toFixed(1)}%`, - ); - console.log( - ` Memory Bank: ${colors.green(this.memoryStats.totalSize)} (${this.memoryStats.totalEntries} entries)`, - ); - console.log(); - - // Enhanced metrics - console.log(colors.cyan('๐Ÿ”ง Tool Usage')); - let totalToolUsage = 0; - this.toolStats.forEach((stats) => (totalToolUsage += stats.executions)); - console.log(` Total Executions: ${colors.yellow(totalToolUsage)}`); - - const topCategories = Array.from(this.toolStats.entries()) - .sort((a, b) => b[1].executions - a[1].executions) - .slice(0, 3); - - topCategories.forEach(([category, stats]) => { - const info = TOOL_CATEGORIES[category]; - if (info && stats.executions > 0) { - console.log(` ${info.icon} ${info.name}: ${colors.green(stats.executions)} uses`); - } - }); - - console.log(); - - // Activity metrics (existing code continues...) - console.log(colors.cyan('๐Ÿ“ˆ Activity Metrics')); - console.log( - ` Active Agents: ${colors.yellow(this.agents.filter((a) => a.status === 'working').length)}/${this.agents.length}`, - ); - console.log(` Total Tasks: ${this.tasks.length}`); - console.log( - ` Completed: ${colors.green(this.tasks.filter((t) => t.status === 'completed').length)}`, - ); - console.log( - ` In Progress: ${colors.yellow(this.tasks.filter((t) => t.status === 'in_progress').length)}`, - ); - console.log( - ` Pending: ${colors.gray(this.tasks.filter((t) => t.status === 'pending').length)}`, - ); - console.log(); - - // Recent events - console.log(colors.cyan('๐Ÿ”” Recent Events')); - this.logs.slice(-3).forEach((log) => { - const time = log.time.toLocaleTimeString(); - const icon = log.level === 'success' ? 'โœ“' : log.level === 'warning' ? 'โš ' : 'โ„น'; - const color = - log.level === 'success' - ? colors.green - : log.level === 'warning' - ? colors.yellow - : colors.blue; - console.log(` ${colors.gray(time)} ${color(icon)} ${log.message}`); - }); - } - - // Keep existing methods... - renderOrchestrationView() { - console.log(colors.white(colors.bold('๐Ÿ Enhanced Swarm Orchestration'))); - console.log(); - - // Swarm metrics - const metrics = this.swarmIntegration.getSwarmMetrics(); - if (metrics) { - console.log(colors.cyan('๐Ÿ Swarm Status')); - console.log(` Swarm ID: ${colors.yellow(metrics.swarmId)}`); - console.log( - ` Agents: ${colors.green(metrics.agents.active)}/${metrics.agents.total} active`, - ); - console.log( - ` Tasks: ${colors.yellow(metrics.tasks.inProgress)} in progress, ${colors.green(metrics.tasks.completed)} completed`, - ); - console.log(` Efficiency: ${colors.cyan(metrics.efficiency + '%')}`); - console.log( - ` Enhanced Mode: ${this.systemStats.enhancedMode ? colors.green('Active') : colors.yellow('Fallback')}`, - ); - console.log(); - } - - // Rest of orchestration view... - // (Continue with existing orchestration code) - - // Agents section - console.log(colors.cyan('๐Ÿค– Active Agents')); - console.log(); - this.agents.slice(0, 5).forEach((agent, index) => { - const selected = this.currentView === VIEWS.ORCHESTRATION && index === this.selectedIndex; - const prefix = selected ? colors.yellow('โ–ถ ') : ' '; - const statusIcon = agent.status === 'working' ? colors.green('โ—') : colors.gray('โ—‹'); - const name = selected ? colors.yellow(agent.name) : colors.white(agent.name); - - console.log(`${prefix}${statusIcon} ${name} (${agent.type})`); - console.log(` ID: ${agent.id} | Tasks: ${agent.tasks} | Status: ${agent.status}`); - if (agent.capabilities && agent.capabilities.length > 0) { - console.log(` Capabilities: ${colors.dim(agent.capabilities.join(', '))}`); - } - console.log(); - }); - - if (this.agents.length > 5) { - console.log(colors.gray(` ... and ${this.agents.length - 5} more agents`)); - } - - console.log(colors.gray('โ”€'.repeat(40))); - - // Tasks section - console.log(colors.cyan('๐Ÿ“‹ Task Queue')); - console.log(); - this.tasks.slice(0, 5).forEach((task) => { - const statusColor = - task.status === 'completed' - ? colors.green - : task.status === 'in_progress' - ? colors.yellow - : colors.gray; - const status = statusColor(`[${task.status}]`); - const priority = - task.priority === 'high' - ? colors.red(`[${task.priority}]`) - : task.priority === 'medium' - ? colors.yellow(`[${task.priority}]`) - : colors.gray(`[${task.priority}]`); - console.log(` ${status} ${priority} ${task.description}`); - if (task.assignedTo) { - const agent = this.agents.find((a) => a.id === task.assignedTo); - console.log(` Assigned to: ${agent ? agent.name : task.assignedTo}`); - } - }); - - if (this.tasks.length > 5) { - console.log(colors.gray(` ... and ${this.tasks.length - 5} more tasks`)); - } - } - - // Enhanced memory view - renderMemoryView() { - console.log(colors.white(colors.bold('๐Ÿ’พ Enhanced Memory Bank Management'))); - console.log(); - - // Overview - console.log(colors.cyan('๐Ÿ’พ Memory Overview')); - console.log(` Total Entries: ${colors.yellow(this.memoryStats.totalEntries)}`); - console.log(` Total Size: ${colors.yellow(this.memoryStats.totalSize)}`); - console.log(` Namespaces: ${colors.cyan(this.memoryStats.namespaces.length)}`); - console.log(); - - // Enhanced namespaces - console.log(colors.cyan('๐Ÿ“ Enhanced Namespaces')); - console.log(); - this.memoryStats.namespaces.forEach((ns, index) => { - const selected = this.currentView === VIEWS.MEMORY && index === this.selectedIndex; - const prefix = selected ? colors.yellow('โ–ถ ') : ' '; - const name = selected ? colors.yellow(ns.name) : colors.white(ns.name); - const typeIcon = this.getNamespaceIcon(ns.name); - - console.log(`${prefix}${typeIcon} ${name}`); - console.log(` Entries: ${colors.cyan(ns.entries)} | Size: ${colors.green(ns.size)}`); - console.log(); - }); - - // Enhanced operations - console.log(colors.gray('โ”€'.repeat(40))); - console.log(colors.cyan('๐Ÿ”„ Available Operations')); - console.log( - ` ${colors.yellow('S')} Store Data | ${colors.yellow('G')} Get Data | ${colors.yellow('B')} Backup | ${colors.yellow('R')} Restore`, - ); - console.log( - ` ${colors.yellow('C')} Compress | ${colors.yellow('Y')} Sync | ${colors.yellow('A')} Analytics | ${colors.yellow('N')} Manage Namespaces`, - ); - } - - renderLogsView() { - console.log(colors.white(colors.bold('๐Ÿ“œ Enhanced System Logs'))); - console.log(); - - // Enhanced log filters - console.log( - colors.cyan('๐Ÿ” Filters: ') + colors.gray('[A]ll [I]nfo [S]uccess [W]arning [E]rror [T]ools'), - ); - console.log(colors.gray('โ”€'.repeat(80))); - console.log(); - - // Display logs with enhanced formatting - const displayLogs = this.logs.slice(-15); - displayLogs.forEach((log) => { - const time = log.time.toLocaleTimeString(); - let icon, color; - - switch (log.level) { - case 'success': - icon = 'โœ“'; - color = colors.green; - break; - case 'warning': - icon = 'โš '; - color = colors.yellow; - break; - case 'error': - icon = 'โœ—'; - color = colors.red; - break; - case 'tool': - icon = '๐Ÿ”ง'; - color = colors.cyan; - break; - default: - icon = 'โ„น'; - color = colors.blue; - } - - console.log(`${colors.gray(time)} ${color(icon)} ${log.message}`); - }); - - if (this.logs.length > 15) { - console.log(); - console.log(colors.gray(`Showing last 15 of ${this.logs.length} logs`)); - } - } - - renderEnhancedHelpView() { - console.log(colors.white(colors.bold('โ“ Enhanced Help & Documentation'))); - console.log(); - - console.log(colors.cyan('๐ŸŽฏ Enhanced Navigation')); - console.log(` ${colors.yellow('0')} Overview Dashboard`); - console.log( - ` ${colors.yellow('1-4')} Core views (Processes, Status, Orchestration, Memory)`, - ); - console.log(` ${colors.yellow('5')} Neural Network Tools (15 tools)`); - console.log(` ${colors.yellow('6')} Monitoring & Analysis (13 tools)`); - console.log(` ${colors.yellow('7')} Workflow & Automation (11 tools)`); - console.log(` ${colors.yellow('8')} GitHub Integration (8 tools)`); - console.log(` ${colors.yellow('9')} System Logs`); - console.log(` ${colors.yellow('Tab')} Cycle through views`); - console.log(` ${colors.yellow('โ†‘/โ†“')} Navigate items (when available)`); - console.log(); - - console.log(colors.cyan('๐Ÿ”ง Enhanced Tool Categories')); - Object.entries(TOOL_CATEGORIES).forEach(([id, category]) => { - console.log( - ` ${category.icon} ${category.color(category.name)}: ${colors.yellow(category.count)} tools`, - ); - }); - console.log(); - - console.log(colors.cyan('โšก Process Controls')); - console.log(` ${colors.yellow('Space')} Toggle selected process`); - console.log(` ${colors.yellow('A')} Start all processes`); - console.log(` ${colors.yellow('Z')} Stop all processes`); - console.log(` ${colors.yellow('R')} Restart all processes`); - console.log(); - - console.log(colors.cyan('๐Ÿง  Neural Network Quick Actions')); - console.log(` ${colors.yellow('N')} Open Neural Tools`); - console.log(` ${colors.yellow('T')} Train Model`); - console.log(` ${colors.yellow('P')} Make Prediction`); - console.log(); - - console.log(colors.cyan('๐Ÿ”„ Workflow & Automation')); - console.log(` ${colors.yellow('W')} Open Workflow Tools`); - console.log(` ${colors.yellow('C')} Create Workflow`); - console.log(` ${colors.yellow('E')} Execute Workflow`); - console.log(); - - console.log(colors.cyan('๐Ÿ”ง Other Enhanced Features')); - console.log(` ${colors.yellow('M')} Memory Analytics`); - console.log(` ${colors.yellow('D')} System Diagnostics`); - console.log(` ${colors.yellow('G')} GitHub Operations`); - console.log(` ${colors.yellow('L')} Clear logs`); - console.log(` ${colors.yellow('H/?')} Show this help`); - console.log(` ${colors.yellow('Q')} Quit`); - console.log(); - - console.log(colors.cyan('๐Ÿ’ก Tips')); - console.log(` โ€ข ${colors.gray('Enhanced mode provides 71+ MCP tools')}`); - console.log(` โ€ข ${colors.gray('Use keyboard shortcuts for quick access')}`); - console.log(` โ€ข ${colors.gray('Tool statistics track usage and performance')}`); - console.log(` โ€ข ${colors.gray('Memory bank supports multiple namespaces')}`); - } - - renderEnhancedFooter() { - console.log(); - console.log(colors.gray('โ”€'.repeat(80))); - - // Context-sensitive controls with enhanced options - let controls = ''; - switch (this.currentView) { - case VIEWS.OVERVIEW: - controls = `${colors.yellow('N')} Neural | ${colors.yellow('M')} Memory | ${colors.yellow('W')} Workflow | ${colors.yellow('G')} GitHub`; - break; - case VIEWS.PROCESSES: - controls = `${colors.yellow('Space')} Toggle | ${colors.yellow('A')} Start All | ${colors.yellow('Z')} Stop All | ${colors.yellow('R')} Restart`; - break; - case VIEWS.NEURAL: - controls = `${colors.yellow('T')} Train | ${colors.yellow('P')} Predict | ${colors.yellow('S')} Status | ${colors.yellow('A')} Analyze`; - break; - case VIEWS.MONITORING: - controls = `${colors.yellow('P')} Performance | ${colors.yellow('B')} Bottlenecks | ${colors.yellow('H')} Health | ${colors.yellow('M')} Metrics`; - break; - case VIEWS.WORKFLOW: - controls = `${colors.yellow('C')} Create | ${colors.yellow('E')} Execute | ${colors.yellow('A')} Automate | ${colors.yellow('S')} Schedule`; - break; - case VIEWS.GITHUB: - controls = `${colors.yellow('A')} Analyze | ${colors.yellow('P')} PR Mgmt | ${colors.yellow('I')} Issues | ${colors.yellow('M')} Metrics`; - break; - case VIEWS.ORCHESTRATION: - controls = `${colors.yellow('N')} New Agent | ${colors.yellow('T')} New Task | ${colors.yellow('D')} Complete | ${colors.yellow('S')} Metrics`; - break; - case VIEWS.MEMORY: - controls = `${colors.yellow('S')} Store | ${colors.yellow('G')} Get | ${colors.yellow('B')} Backup | ${colors.yellow('A')} Analytics`; - break; - case VIEWS.LOGS: - controls = `${colors.yellow('L')} Clear | ${colors.yellow('F')} Filter | ${colors.yellow('E')} Export`; - break; - default: - controls = `${colors.yellow('Tab')} Next View | ${colors.yellow('0')} Overview | ${colors.yellow('?')} Help`; - } - - const enhancedStatus = this.systemStats.enhancedMode - ? colors.green('Enhanced') - : colors.yellow('Fallback'); - - console.log(`${controls} | ${colors.yellow('Q')} Quit | Mode: ${enhancedStatus}`); - console.log(colors.gray('โ”€'.repeat(80))); - } - - // Enhanced input handling - async handleInput() { - const terminal = compat.terminal; - - await terminal.write('\nCommand: '); - - const buf = new Uint8Array(1024); - const n = await terminal.read(buf); - if (n === null) return; - - const rawInput = terminal.decoder.decode(buf.subarray(0, n)).trim(); - const input = rawInput.split('\n')[0].toLowerCase(); - - // Enhanced global commands - switch (input) { - case 'q': - case 'quit': - await this.shutdown(); - return; - - case '0': - this.currentView = VIEWS.OVERVIEW; - this.selectedIndex = 0; - break; - - case '1': - this.currentView = VIEWS.PROCESSES; - this.selectedIndex = 0; - break; - - case '2': - this.currentView = VIEWS.STATUS; - this.selectedIndex = 0; - break; - - case '3': - this.currentView = VIEWS.ORCHESTRATION; - this.selectedIndex = 0; - break; - - case '4': - this.currentView = VIEWS.MEMORY; - this.selectedIndex = 0; - break; - - case '5': - this.currentView = VIEWS.NEURAL; - this.selectedIndex = 0; - break; - - case '6': - this.currentView = VIEWS.MONITORING; - this.selectedIndex = 0; - break; - - case '7': - this.currentView = VIEWS.WORKFLOW; - this.selectedIndex = 0; - break; - - case '8': - this.currentView = VIEWS.GITHUB; - this.selectedIndex = 0; - break; - - case '9': - this.currentView = VIEWS.LOGS; - this.selectedIndex = 0; - break; - - case '?': - case 'h': - case 'help': - this.currentView = VIEWS.HELP; - break; - - case 'tab': - case '\t': - // Enhanced view cycling - const viewKeys = Object.values(VIEWS); - const currentIndex = viewKeys.indexOf(this.currentView); - this.currentView = viewKeys[(currentIndex + 1) % viewKeys.length]; - this.selectedIndex = 0; - break; - - // Quick action shortcuts - case 'n': - if (this.currentView === VIEWS.OVERVIEW) { - this.currentView = VIEWS.NEURAL; - } else { - await this.handleViewSpecificInput(input); - } - break; - - case 'm': - if (this.currentView === VIEWS.OVERVIEW) { - this.currentView = VIEWS.MEMORY; - } else { - await this.handleViewSpecificInput(input); - } - break; - - case 'w': - if (this.currentView === VIEWS.OVERVIEW) { - this.currentView = VIEWS.WORKFLOW; - } else { - await this.handleViewSpecificInput(input); - } - break; - - case 'g': - if (this.currentView === VIEWS.OVERVIEW) { - this.currentView = VIEWS.GITHUB; - } else { - await this.handleViewSpecificInput(input); - } - break; - - default: - // View-specific commands - await this.handleViewSpecificInput(input); - } - - // Update system stats - this.updateSystemStats(); - } - - // Enhanced view-specific input handling - async handleViewSpecificInput(input) { - switch (this.currentView) { - case VIEWS.PROCESSES: - await this.handleProcessInput(input); - break; - case VIEWS.ORCHESTRATION: - await this.handleOrchestrationInput(input); - break; - case VIEWS.MEMORY: - await this.handleEnhancedMemoryInput(input); - break; - case VIEWS.NEURAL: - await this.handleNeuralInput(input); - break; - case VIEWS.MONITORING: - await this.handleMonitoringInput(input); - break; - case VIEWS.WORKFLOW: - await this.handleWorkflowInput(input); - break; - case VIEWS.GITHUB: - await this.handleGitHubInput(input); - break; - case VIEWS.DAA: - await this.handleDAAInput(input); - break; - case VIEWS.SYSTEM: - await this.handleSystemInput(input); - break; - case VIEWS.CLI: - await this.handleCLIInput(input); - break; - case VIEWS.LOGS: - await this.handleLogsInput(input); - break; - } - } - - // Enhanced tool execution with statistics - async executeEnhancedTool(toolName, params = {}) { - try { - const startTime = Date.now(); - - // Execute through enhanced UI if available - let result; - if (this.enhancedWebUI) { - result = await this.enhancedWebUI.executeTool(toolName, params); - } else { - // Fallback execution - result = await this.mockToolExecution(toolName, params); - } - - const duration = Date.now() - startTime; - - // Update statistics - this.updateToolStats(toolName, duration, true); - - // Add to recent tools - this.recentTools.push(toolName); - if (this.recentTools.length > 20) { - this.recentTools = this.recentTools.slice(-20); - } - - // Log execution - this.addLog('tool', `Executed ${toolName} (${duration}ms)`); - - return result; - } catch (error) { - this.updateToolStats(toolName, 0, false); - this.addLog('error', `Failed to execute ${toolName}: ${error.message}`); - throw error; - } - } - - // Mock tool execution for fallback - async mockToolExecution(toolName, params) { - // Simulate execution delay - await new Promise((resolve) => setTimeout(resolve, 100 + Math.random() * 500)); - - return { - success: true, - tool: toolName, - params, - result: `Mock result for ${toolName}`, - timestamp: Date.now(), - }; - } - - // Update tool statistics - updateToolStats(toolName, duration, success) { - const category = this.getToolCategory(toolName); - if (!category) return; - - const stats = this.toolStats.get(category) || { - executions: 0, - lastUsed: null, - avgDuration: 0, - successRate: 100, - }; - - stats.executions++; - stats.lastUsed = Date.now(); - - if (success) { - stats.avgDuration = - (stats.avgDuration * (stats.executions - 1) + duration) / stats.executions; - } else { - stats.successRate = (stats.successRate * (stats.executions - 1) + 0) / stats.executions; - } - - this.toolStats.set(category, stats); - } - - // Get tool category - getToolCategory(toolName) { - for (const [category, info] of Object.entries(TOOL_CATEGORIES)) { - // Simple pattern matching - in real implementation would be more sophisticated - if ( - toolName.includes(category) || - (category === 'neural' && (toolName.includes('neural_') || toolName.includes('model_'))) || - (category === 'memory' && toolName.includes('memory_')) || - (category === 'monitoring' && - (toolName.includes('performance_') || toolName.includes('health_'))) || - (category === 'workflow' && - (toolName.includes('workflow_') || toolName.includes('automation_'))) || - (category === 'github' && toolName.includes('github_')) || - (category === 'daa' && toolName.includes('daa_')) || - (category === 'system' && (toolName.includes('security_') || toolName.includes('backup_'))) - ) { - return category; - } - } - return null; - } - - // Get tool statistics - getToolStats(toolName) { - const category = this.getToolCategory(toolName); - return category ? this.toolStats.get(category) : null; - } - - // Enhanced input handlers for new views - async handleNeuralInput(input) { - const actions = { - t: () => this.executeEnhancedTool('neural_train'), - p: () => this.executeEnhancedTool('neural_predict'), - s: () => this.executeEnhancedTool('neural_status'), - a: () => this.executeEnhancedTool('neural_patterns'), - l: () => this.executeEnhancedTool('model_load'), - v: () => this.executeEnhancedTool('model_save'), - r: () => this.executeEnhancedTool('pattern_recognize'), - c: () => this.executeEnhancedTool('cognitive_analyze'), - d: () => this.executeEnhancedTool('learning_adapt'), - z: () => this.executeEnhancedTool('neural_compress'), - e: () => this.executeEnhancedTool('ensemble_create'), - f: () => this.executeEnhancedTool('transfer_learn'), - x: () => this.executeEnhancedTool('neural_explain'), - w: () => this.executeEnhancedTool('wasm_optimize'), - i: () => this.executeEnhancedTool('inference_run'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleMonitoringInput(input) { - const actions = { - p: () => this.executeEnhancedTool('performance_report'), - b: () => this.executeEnhancedTool('bottleneck_analyze'), - t: () => this.executeEnhancedTool('token_usage'), - m: () => this.executeEnhancedTool('metrics_collect'), - h: () => this.executeEnhancedTool('health_check'), - e: () => this.executeEnhancedTool('error_analysis'), - u: () => this.executeEnhancedTool('usage_stats'), - q: () => this.executeEnhancedTool('quality_assess'), - c: () => this.executeEnhancedTool('cost_analysis'), - r: () => this.executeEnhancedTool('trend_analysis'), - k: () => this.executeEnhancedTool('benchmark_run'), - s: () => this.executeEnhancedTool('swarm_monitor'), - a: () => this.executeEnhancedTool('agent_metrics'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleWorkflowInput(input) { - const actions = { - c: () => this.executeEnhancedTool('workflow_create'), - e: () => this.executeEnhancedTool('workflow_execute'), - a: () => this.executeEnhancedTool('automation_setup'), - p: () => this.executeEnhancedTool('pipeline_create'), - s: () => this.executeEnhancedTool('scheduler_manage'), - t: () => this.executeEnhancedTool('trigger_setup'), - w: () => this.executeEnhancedTool('workflow_template'), - b: () => this.executeEnhancedTool('batch_process'), - l: () => this.executeEnhancedTool('parallel_execute'), - r: () => this.executeEnhancedTool('sparc_mode'), - o: () => this.executeEnhancedTool('task_orchestrate'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleGitHubInput(input) { - const actions = { - a: () => this.executeEnhancedTool('github_repo_analyze'), - p: () => this.executeEnhancedTool('github_pr_manage'), - i: () => this.executeEnhancedTool('github_issue_track'), - r: () => this.executeEnhancedTool('github_release_coord'), - w: () => this.executeEnhancedTool('github_workflow_auto'), - c: () => this.executeEnhancedTool('github_code_review'), - s: () => this.executeEnhancedTool('github_sync_coord'), - m: () => this.executeEnhancedTool('github_metrics'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleDAAInput(input) { - const actions = { - c: () => this.executeEnhancedTool('daa_agent_create'), - m: () => this.executeEnhancedTool('daa_capability_match'), - r: () => this.executeEnhancedTool('daa_resource_alloc'), - l: () => this.executeEnhancedTool('daa_lifecycle_manage'), - o: () => this.executeEnhancedTool('daa_communication'), - n: () => this.executeEnhancedTool('daa_consensus'), - f: () => this.executeEnhancedTool('daa_fault_tolerance'), - p: () => this.executeEnhancedTool('daa_optimization'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleSystemInput(input) { - const actions = { - s: () => this.executeEnhancedTool('security_scan'), - b: () => this.executeEnhancedTool('backup_create'), - r: () => this.executeEnhancedTool('restore_system'), - l: () => this.executeEnhancedTool('log_analysis'), - d: () => this.executeEnhancedTool('diagnostic_run'), - c: () => this.executeEnhancedTool('config_manage'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - async handleCLIInput(input) { - const commands = { - h: 'hive-mind', - g: 'github', - t: 'training', - a: 'analysis', - u: 'automation', - c: 'coordination', - k: 'hooks', - m: 'mcp', - f: 'config', - }; - - if (commands[input]) { - this.addLog('info', `Executing CLI command: ${commands[input]}`); - // In real implementation, would bridge to actual CLI commands - console.log(`\n๐Ÿ”ง CLI Command: ${commands[input]}`); - console.log('Command execution would be bridged to actual CLI...'); - } - } - - // Enhanced memory input handling - async handleEnhancedMemoryInput(input) { - const actions = { - s: () => this.executeEnhancedTool('memory_usage', { action: 'store' }), - g: () => this.executeEnhancedTool('memory_usage', { action: 'retrieve' }), - b: () => this.executeEnhancedTool('memory_backup'), - r: () => this.executeEnhancedTool('memory_restore'), - c: () => this.executeEnhancedTool('memory_compress'), - y: () => this.executeEnhancedTool('memory_sync'), - a: () => this.executeEnhancedTool('memory_analytics'), - n: () => this.executeEnhancedTool('memory_namespace'), - }; - - if (actions[input]) { - await actions[input](); - } - } - - // Helper methods - getNamespaceIcon(name) { - const icons = { - neural: '๐Ÿง ', - sparc: 'โšก', - agents: '๐Ÿค–', - tasks: '๐Ÿ“‹', - workflows: '๐Ÿ”„', - monitoring: '๐Ÿ“Š', - }; - return icons[name] || '๐Ÿ“'; - } - - // Enhanced system stats update - updateSystemStats() { - // Update random stats for demo - this.systemStats.cpuUsage = Math.min( - 100, - Math.max(0, this.systemStats.cpuUsage + (Math.random() - 0.5) * 10), - ); - this.systemStats.memoryUsage = Math.min( - 100, - Math.max(0, this.systemStats.memoryUsage + (Math.random() - 0.5) * 5), - ); - - // Update process stats - for (const [id, process] of this.processes) { - if (process.status === 'running') { - process.uptime++; - process.cpu = Math.min(100, Math.max(0, process.cpu + (Math.random() - 0.5) * 2)); - process.memory = Math.min(200, Math.max(10, process.memory + (Math.random() - 0.5) * 5)); - } - } - - // Update enhanced stats - this.systemStats.activeAgents = this.agents.filter((a) => a.status === 'working').length; - this.systemStats.totalTasks = this.tasks.length; - this.systemStats.completedTasks = this.tasks.filter((t) => t.status === 'completed').length; - } - - // Enhanced shutdown - async shutdown() { - this.running = false; - console.clear(); - - if (this.enhancedWebUI) { - await this.enhancedWebUI.shutdown(); - } - - printSuccess('Enhanced UI shutdown complete. Goodbye!'); - compat.terminal.exit(0); - } - - // Keep all existing methods from original class... - // (getStatusIcon, getHealthBar, getUsageBar, formatUptime, etc.) - - getStatusIcon(status) { - switch (status) { - case 'running': - return colors.green('โ—'); - case 'stopped': - return colors.gray('โ—‹'); - case 'error': - return colors.red('โœ—'); - case 'starting': - return colors.yellow('โ—'); - default: - return colors.gray('?'); - } - } - - getHealthBar() { - const running = Array.from(this.processes.values()).filter( - (p) => p.status === 'running', - ).length; - const total = this.processes.size; - const percentage = (running / total) * 100; - const filled = Math.round(percentage / 10); - const bar = 'โ–ˆ'.repeat(filled) + 'โ–‘'.repeat(10 - filled); - const color = percentage >= 80 ? colors.green : percentage >= 50 ? colors.yellow : colors.red; - return color(bar) + ` ${percentage.toFixed(0)}%`; - } - - getUsageBar(value, max) { - const percentage = (value / max) * 100; - const filled = Math.round(percentage / 10); - const bar = 'โ–“'.repeat(filled) + 'โ–‘'.repeat(10 - filled); - const color = percentage >= 80 ? colors.red : percentage >= 50 ? colors.yellow : colors.green; - return color(bar); - } - - formatUptime(seconds) { - if (seconds < 60) return `${seconds}s`; - if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`; - const hours = Math.floor(seconds / 3600); - const minutes = Math.floor((seconds % 3600) / 60); - return `${hours}h ${minutes}m`; - } - - addLog(level, message) { - this.logs.push({ - time: new Date(), - level, - message, - }); - - // Keep logs manageable - if (this.logs.length > 100) { - this.logs = this.logs.slice(-100); - } - } - - // Continue with existing methods... - async handleProcessInput(input) { - switch (input) { - case 'a': - await this.startAll(); - break; - - case 'z': - await this.stopAll(); - break; - - case 'r': - await this.restartAll(); - break; - - case ' ': - case 'space': - case 'enter': - case '': - await this.toggleSelected(); - break; - - case 'up': - case 'k': - this.selectedIndex = Math.max(0, this.selectedIndex - 1); - break; - - case 'down': - case 'j': - this.selectedIndex = Math.min(this.processes.size - 1, this.selectedIndex + 1); - break; - } - } - - async handleOrchestrationInput(input) { - switch (input) { - case 'n': - // Spawn new agent - const agentTypes = ['researcher', 'coder', 'analyst', 'coordinator', 'tester']; - const randomType = agentTypes[Math.floor(Math.random() * agentTypes.length)]; - await this.swarmIntegration.spawnAgent(randomType); - break; - - case 't': - // Create new task - const sampleTasks = [ - 'Implement neural network optimization', - 'Analyze performance bottlenecks', - 'Create workflow automation', - 'Review GitHub integration', - 'Test DAA consensus mechanism', - ]; - const randomTask = sampleTasks[Math.floor(Math.random() * sampleTasks.length)]; - await this.swarmIntegration.createTask(randomTask, 'medium'); - break; - - case 'd': - // Complete selected task (simulate) - if (this.tasks.length > 0) { - const pendingTasks = this.tasks.filter((t) => t.status === 'in_progress'); - if (pendingTasks.length > 0) { - const taskToComplete = pendingTasks[0]; - await this.swarmIntegration.completeTask(taskToComplete.id); - } else { - this.addLog('info', 'No in-progress tasks to complete'); - } - } - break; - - case 's': - // Show swarm metrics - const metrics = this.swarmIntegration.getSwarmMetrics(); - if (metrics) { - this.addLog( - 'info', - `Swarm efficiency: ${metrics.efficiency}% (${metrics.tasks.completed}/${metrics.tasks.total} tasks completed)`, - ); - } - break; - } - } - - async handleLogsInput(input) { - switch (input) { - case 'l': - this.logs = []; - this.addLog('info', 'Logs cleared'); - break; - - case 'f': - this.addLog('info', 'Log filtering not yet implemented'); - break; - - case 'e': - this.addLog('info', 'Log export feature available in enhanced mode'); - break; - } - } - - async toggleSelected() { - const process = Array.from(this.processes.values())[this.selectedIndex]; - if (process.status === 'stopped') { - await this.startProcess(process.id); - } else { - await this.stopProcess(process.id); - } - } - - async startProcess(id) { - const process = this.processes.get(id); - if (!process) return; - - this.addLog('info', `Starting ${process.name}...`); - process.status = 'starting'; - - await new Promise((resolve) => setTimeout(resolve, 500)); - - process.status = 'running'; - process.pid = Math.floor(Math.random() * 10000) + 1000; - process.uptime = 0; - - this.addLog('success', `${process.name} started successfully`); - } - - async stopProcess(id) { - const process = this.processes.get(id); - if (!process) return; - - this.addLog('info', `Stopping ${process.name}...`); - process.status = 'stopped'; - process.pid = null; - process.uptime = 0; - - await new Promise((resolve) => setTimeout(resolve, 300)); - this.addLog('success', `${process.name} stopped`); - } - - async startAll() { - this.addLog('info', 'Starting all processes...'); - for (const [id, process] of this.processes) { - if (process.status === 'stopped') { - await this.startProcess(id); - } - } - this.addLog('success', 'All processes started'); - } - - async stopAll() { - this.addLog('info', 'Stopping all processes...'); - for (const [id, process] of this.processes) { - if (process.status === 'running') { - await this.stopProcess(id); - } - } - this.addLog('success', 'All processes stopped'); - } - - async restartAll() { - await this.stopAll(); - await new Promise((resolve) => setTimeout(resolve, 500)); - await this.startAll(); - } -} - -export async function launchEnhancedUI() { - const ui = new EnhancedProcessUI(); - await ui.start(); -} - -export default EnhancedProcessUI; diff --git a/src/ui/web-ui/EnhancedWebUI.js b/src/ui/web-ui/EnhancedWebUI.js deleted file mode 100644 index dace4a6db0..0000000000 --- a/src/ui/web-ui/EnhancedWebUI.js +++ /dev/null @@ -1,566 +0,0 @@ -/** - * Enhanced Web UI - Main controller integrating modular architecture - * Provides comprehensive interface for all 71+ MCP tools and CLI commands - */ - -import UIManager from './core/UIManager.js'; -import { VIEW_CATEGORIES } from './core/UIManager.js'; - -export class EnhancedWebUI { - constructor() { - this.uiManager = null; - this.isInitialized = false; - this.fallbackMode = false; - this.originalProcessUI = null; - } - - /** - * Initialize enhanced web UI - */ - async initialize(existingProcessUI = null) { - try { - console.log('๐Ÿš€ Initializing Enhanced Web UI...'); - - // Store reference to existing process UI - this.originalProcessUI = existingProcessUI; - - // Try to initialize full UI manager - try { - this.uiManager = new UIManager(); - await this.uiManager.initialize(); - - console.log('โœ… Enhanced Web UI initialized successfully'); - this.isInitialized = true; - } catch (error) { - console.warn('โš ๏ธ Full UI initialization failed, using fallback mode:', error); - this.fallbackMode = true; - await this.initializeFallbackMode(); - } - - // Setup integration with existing UI if provided - if (this.originalProcessUI) { - this.integrateWithExistingUI(); - } - - return this.isInitialized || this.fallbackMode; - } catch (error) { - console.error('โŒ Failed to initialize Enhanced Web UI:', error); - throw error; - } - } - - /** - * Initialize fallback mode for minimal functionality - */ - async initializeFallbackMode() { - console.log('๐Ÿ”„ Initializing fallback mode...'); - - // Create minimal UI structure - this.createFallbackUI(); - - this.fallbackMode = true; - console.log('โœ… Fallback mode initialized'); - } - - /** - * Create fallback UI structure - */ - createFallbackUI() { - // Add enhanced views to existing process UI - if (this.originalProcessUI) { - this.addEnhancedViewsToProcessUI(); - } else { - this.createStandaloneUI(); - } - } - - /** - * Add enhanced views to existing process UI - */ - addEnhancedViewsToProcessUI() { - // Extend the VIEWS enum - const enhancedViews = { - NEURAL: 'neural', - MEMORY_MGMT: 'memory_mgmt', - MONITORING_ADV: 'monitoring_adv', - WORKFLOW_MGMT: 'workflow_mgmt', - GITHUB_INT: 'github_int', - DAA_CONTROL: 'daa_control', - SYSTEM_UTILS: 'system_utils', - CLI_BRIDGE: 'cli_bridge', - }; - - // Add to original UI's VIEWS if possible - if (this.originalProcessUI.constructor.VIEWS) { - Object.assign(this.originalProcessUI.constructor.VIEWS, enhancedViews); - } - - // Extend render method to handle new views - const originalRender = this.originalProcessUI.render.bind(this.originalProcessUI); - this.originalProcessUI.render = () => { - // Call original render first - originalRender(); - - // Add enhanced view handling - this.handleEnhancedViews(); - }; - - // Extend input handling - const originalHandleInput = this.originalProcessUI.handleViewSpecificInput.bind( - this.originalProcessUI, - ); - this.originalProcessUI.handleViewSpecificInput = async (input) => { - // Try enhanced views first - if (await this.handleEnhancedInput(input)) { - return; // Handled by enhanced UI - } - - // Fall back to original handling - return originalHandleInput(input); - }; - } - - /** - * Handle enhanced views in fallback mode - */ - handleEnhancedViews() { - if (!this.originalProcessUI.currentView) return; - - switch (this.originalProcessUI.currentView) { - case 'neural': - this.renderNeuralView(); - break; - case 'memory_mgmt': - this.renderMemoryManagementView(); - break; - case 'monitoring_adv': - this.renderAdvancedMonitoringView(); - break; - case 'workflow_mgmt': - this.renderWorkflowManagementView(); - break; - case 'github_int': - this.renderGitHubIntegrationView(); - break; - case 'daa_control': - this.renderDAAControlView(); - break; - case 'system_utils': - this.renderSystemUtilitiesView(); - break; - case 'cli_bridge': - this.renderCLIBridgeView(); - break; - } - } - - /** - * Handle enhanced input in fallback mode - */ - async handleEnhancedInput(input) { - const currentView = this.originalProcessUI.currentView; - - // Enhanced view shortcuts - const enhancedShortcuts = { - 7: () => (this.originalProcessUI.currentView = 'neural'), - 8: () => (this.originalProcessUI.currentView = 'memory_mgmt'), - 9: () => (this.originalProcessUI.currentView = 'monitoring_adv'), - 0: () => (this.originalProcessUI.currentView = 'workflow_mgmt'), - }; - - if (enhancedShortcuts[input]) { - enhancedShortcuts[input](); - return true; - } - - // View-specific enhanced input handling - switch (currentView) { - case 'neural': - return this.handleNeuralInput(input); - case 'memory_mgmt': - return this.handleMemoryInput(input); - case 'monitoring_adv': - return this.handleMonitoringInput(input); - case 'workflow_mgmt': - return this.handleWorkflowInput(input); - default: - return false; - } - } - - /** - * Create standalone UI for when no existing UI is available - */ - createStandaloneUI() { - console.log('๐Ÿ”ง Creating standalone enhanced UI...'); - - // This would create a complete standalone interface - // For now, just log the available functionality - console.log('\n๐ŸŽจ Enhanced Web UI - Standalone Mode'); - console.log('โ•'.repeat(60)); - console.log('๐Ÿ“Š Available Tool Categories:'); - console.log(' ๐Ÿง  Neural Network Tools (15 tools)'); - console.log(' ๐Ÿ’พ Memory Management Tools (10 tools)'); - console.log(' ๐Ÿ“Š Monitoring & Analysis Tools (13 tools)'); - console.log(' ๐Ÿ”„ Workflow & Automation Tools (11 tools)'); - console.log(' ๐Ÿ™ GitHub Integration Tools (8 tools)'); - console.log(' ๐Ÿค– Dynamic Agent Architecture Tools (8 tools)'); - console.log(' ๐Ÿ› ๏ธ System & Utilities Tools (6 tools)'); - console.log(' โŒจ๏ธ CLI Bridge Commands (9 commands)'); - console.log('โ•'.repeat(60)); - console.log('Total: 71+ tools and commands available'); - console.log('Use the enhanced UI manager for full functionality.'); - } - - /** - * Navigate to enhanced view - */ - async navigateToView(viewId, params = {}) { - if (this.uiManager && !this.fallbackMode) { - return await this.uiManager.navigateToView(viewId, params); - } else { - // Fallback navigation - if (this.originalProcessUI) { - this.originalProcessUI.currentView = viewId; - this.originalProcessUI.selectedIndex = 0; - } else { - console.log(`๐Ÿ“„ Navigating to view: ${viewId}`, params); - } - } - } - - /** - * Execute MCP tool - */ - async executeTool(toolName, params = {}) { - if (this.uiManager && !this.fallbackMode) { - return await this.uiManager.executeMCPTool(toolName, params); - } else { - // Fallback tool execution - console.log(`๐Ÿ”ง Executing tool: ${toolName}`, params); - - // Simulate tool execution - await new Promise((resolve) => setTimeout(resolve, 500)); - - const mockResult = { - success: true, - tool: toolName, - params, - result: `Mock result for ${toolName}`, - timestamp: Date.now(), - }; - - console.log(`โœ… Tool ${toolName} completed:`, mockResult.result); - return mockResult; - } - } - - /** - * Get system status - */ - async getSystemStatus() { - if (this.uiManager && !this.fallbackMode) { - return await this.uiManager.getSystemStatus(); - } else { - // Fallback status - return { - mode: 'fallback', - toolsAvailable: 71, - uiManager: false, - enhancedFeatures: false, - originalProcessUI: !!this.originalProcessUI, - }; - } - } - - /** - * Integration with existing process UI - */ - integrateWithExistingUI() { - console.log('๐Ÿ”— Integrating with existing process UI...'); - - // Add enhanced views to the header navigation - this.addEnhancedNavigation(); - - // Add tool palette - this.addToolPalette(); - - // Add quick actions - this.addQuickActions(); - } - - /** - * Add enhanced navigation to existing UI - */ - addEnhancedNavigation() { - // This would extend the existing navigation tabs - console.log('๐Ÿ“Š Added enhanced navigation tabs'); - } - - /** - * Add tool palette to existing UI - */ - addToolPalette() { - // This would add a tool palette overlay - console.log('๐ŸŽจ Added tool palette overlay'); - } - - /** - * Add quick actions to existing UI - */ - addQuickActions() { - // This would add quick action buttons - console.log('โšก Added quick action buttons'); - } - - /** - * Render enhanced views (fallback mode) - */ - renderNeuralView() { - console.clear(); - console.log('๐Ÿง  Neural Network Operations'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [T] Train Neural Network'); - console.log(' [P] Make Prediction'); - console.log(' [S] Check Status'); - console.log(' [A] Analyze Patterns'); - console.log(' [M] Manage Models'); - console.log(' [O] Optimize WASM'); - console.log('\nPress a key to execute tool...'); - } - - renderMemoryManagementView() { - console.clear(); - console.log('๐Ÿ’พ Memory Management'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [S] Store Data'); - console.log(' [R] Retrieve Data'); - console.log(' [B] Backup Memory'); - console.log(' [C] Compress Data'); - console.log(' [Y] Sync Instances'); - console.log(' [A] Analytics'); - console.log('\nPress a key to execute tool...'); - } - - renderAdvancedMonitoringView() { - console.clear(); - console.log('๐Ÿ“Š Advanced Monitoring'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [P] Performance Report'); - console.log(' [B] Bottleneck Analysis'); - console.log(' [T] Token Usage'); - console.log(' [M] Metrics Collection'); - console.log(' [H] Health Check'); - console.log(' [E] Error Analysis'); - console.log('\nPress a key to execute tool...'); - } - - renderWorkflowManagementView() { - console.clear(); - console.log('๐Ÿ”„ Workflow & Automation Management'); - console.log('โ•'.repeat(50)); - console.log('Available Tools (11):'); - console.log(' [C] Create Workflow'); - console.log(' [E] Execute Workflow'); - console.log(' [A] Setup Automation'); - console.log(' [P] Create Pipeline'); - console.log(' [S] Manage Scheduler'); - console.log(' [T] Setup Triggers'); - console.log(' [W] Workflow Templates'); - console.log(' [B] Batch Processing'); - console.log(' [L] Parallel Execution'); - console.log(' [M] SPARC Modes'); - console.log(' [O] Task Orchestration'); - console.log('\nPress a key to execute tool...'); - } - - renderGitHubIntegrationView() { - console.clear(); - console.log('๐Ÿ™ GitHub Integration'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [A] Analyze Repository'); - console.log(' [P] Manage Pull Requests'); - console.log(' [I] Track Issues'); - console.log(' [R] Release Coordination'); - console.log(' [W] Workflow Automation'); - console.log(' [M] Repository Metrics'); - console.log('\nPress a key to execute tool...'); - } - - renderDAAControlView() { - console.clear(); - console.log('๐Ÿค– Dynamic Agent Architecture'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [C] Create Agent'); - console.log(' [M] Match Capabilities'); - console.log(' [R] Resource Allocation'); - console.log(' [L] Lifecycle Management'); - console.log(' [O] Communication'); - console.log(' [F] Fault Tolerance'); - console.log('\nPress a key to execute tool...'); - } - - renderSystemUtilitiesView() { - console.clear(); - console.log('๐Ÿ› ๏ธ System Utilities'); - console.log('โ•'.repeat(50)); - console.log('Available Tools:'); - console.log(' [S] Security Scan'); - console.log(' [B] Create Backup'); - console.log(' [R] Restore System'); - console.log(' [L] Log Analysis'); - console.log(' [D] Run Diagnostics'); - console.log(' [C] Manage Config'); - console.log('\nPress a key to execute tool...'); - } - - renderCLIBridgeView() { - console.clear(); - console.log('โŒจ๏ธ CLI Command Bridge'); - console.log('โ•'.repeat(50)); - console.log('Available Commands:'); - console.log(' [H] Hive Mind Wizard'); - console.log(' [G] GitHub Operations'); - console.log(' [T] Training Commands'); - console.log(' [A] Analysis Operations'); - console.log(' [U] Automation Setup'); - console.log(' [C] Coordination Tools'); - console.log('\nPress a key to execute command...'); - } - - /** - * Handle input for enhanced views (fallback mode) - */ - async handleNeuralInput(input) { - const actions = { - t: () => this.executeTool('neural_train'), - p: () => this.executeTool('neural_predict'), - s: () => this.executeTool('neural_status'), - a: () => this.executeTool('neural_patterns'), - m: () => this.executeTool('model_load'), - o: () => this.executeTool('wasm_optimize'), - }; - - if (actions[input]) { - await actions[input](); - return true; - } - return false; - } - - async handleMemoryInput(input) { - const actions = { - s: () => this.executeTool('memory_usage', { action: 'store' }), - r: () => this.executeTool('memory_usage', { action: 'retrieve' }), - b: () => this.executeTool('memory_backup'), - c: () => this.executeTool('memory_compress'), - y: () => this.executeTool('memory_sync'), - a: () => this.executeTool('memory_analytics'), - }; - - if (actions[input]) { - await actions[input](); - return true; - } - return false; - } - - async handleMonitoringInput(input) { - const actions = { - p: () => this.executeTool('performance_report'), - b: () => this.executeTool('bottleneck_analyze'), - t: () => this.executeTool('token_usage'), - m: () => this.executeTool('metrics_collect'), - h: () => this.executeTool('health_check'), - e: () => this.executeTool('error_analysis'), - }; - - if (actions[input]) { - await actions[input](); - return true; - } - return false; - } - - async handleWorkflowInput(input) { - const actions = { - c: () => this.executeTool('workflow_create'), - e: () => this.executeTool('workflow_execute'), - a: () => this.executeTool('automation_setup'), - p: () => this.executeTool('pipeline_create'), - s: () => this.executeTool('scheduler_manage'), - t: () => this.executeTool('trigger_setup'), - w: () => this.executeTool('workflow_template'), - b: () => this.executeTool('batch_process'), - l: () => this.executeTool('parallel_execute'), - m: () => this.executeTool('sparc_mode'), - o: () => this.executeTool('task_orchestrate'), - }; - - if (actions[input]) { - await actions[input](); - return true; - } - return false; - } - - /** - * Show help for enhanced UI - */ - showHelp() { - console.log('\n๐ŸŽจ Enhanced Web UI Help'); - console.log('โ•'.repeat(60)); - console.log('Navigation:'); - console.log(' 1-6: Original views'); - console.log(' 7: Neural Network Tools'); - console.log(' 8: Memory Management'); - console.log(' 9: Advanced Monitoring'); - console.log(' 0: Workflow Management'); - console.log('\nTool Categories:'); - console.log(' ๐Ÿง  Neural (15 tools): Training, prediction, patterns'); - console.log(' ๐Ÿ’พ Memory (10 tools): Storage, backup, analytics'); - console.log(' ๐Ÿ“Š Monitor (13 tools): Performance, bottlenecks, health'); - console.log(' ๐Ÿ”„ Workflow (11 tools): Automation, pipelines, scheduling'); - console.log(' ๐Ÿ™ GitHub (8 tools): Repository analysis, PR management'); - console.log(' ๐Ÿค– DAA (8 tools): Dynamic agents, consensus, fault tolerance'); - console.log(' ๐Ÿ› ๏ธ System (6 tools): Security, backup, diagnostics'); - console.log(' โŒจ๏ธ CLI (9 commands): Bridge to command-line tools'); - console.log('โ•'.repeat(60)); - } - - /** - * Shutdown enhanced UI - */ - async shutdown() { - console.log('๐Ÿ”„ Shutting down Enhanced Web UI...'); - - if (this.uiManager && !this.fallbackMode) { - await this.uiManager.shutdown(); - } - - this.isInitialized = false; - this.fallbackMode = false; - - console.log('โœ… Enhanced Web UI shutdown complete'); - } -} - -export default EnhancedWebUI; - -// Auto-detect and enhance existing process UI if available -if (typeof window !== 'undefined') { - window.addEventListener('load', async () => { - // Check if there's an existing process UI to enhance - if (window.claudeFlowProcessUI) { - console.log('๐Ÿ”— Enhancing existing process UI...'); - const enhancedUI = new EnhancedWebUI(); - await enhancedUI.initialize(window.claudeFlowProcessUI); - window.claudeFlowEnhancedUI = enhancedUI; - } - }); -} diff --git a/src/ui/web-ui/README.md b/src/ui/web-ui/README.md deleted file mode 100644 index 38a9aa39e1..0000000000 --- a/src/ui/web-ui/README.md +++ /dev/null @@ -1,308 +0,0 @@ -# Enhanced Web UI Architecture - -## ๐ŸŽฏ Overview - -This is the modular UI architecture designed to support **71+ MCP tools and CLI commands** for Claude Flow. The architecture provides a comprehensive interface that can run in multiple modes: full browser UI, enhanced terminal interface, or fallback mode. - -## ๐Ÿ—๏ธ Architecture Components - -### Core System (`/core/`) - -- **`UIManager.js`** - Central UI controller that coordinates all views and manages global state -- **`MCPIntegrationLayer.js`** - Bridge between UI and Claude Flow MCP tools with caching and error handling -- **`EventBus.js`** - Central event communication system for loose coupling between components -- **`ViewManager.js`** - Dynamic view loading and state management with transitions -- **`StateManager.js`** - Global state persistence and user preferences - -### Component Library (`/components/`) - -- **`ComponentLibrary.js`** - Reusable UI components (charts, forms, panels, etc.) with consistent theming - -### Views (`/views/`) - -- **`NeuralNetworkView.js`** - Example view implementation for neural network tools -- **More views** - Each tool category gets its own specialized view - -### Main Controllers - -- **`EnhancedWebUI.js`** - Main enhanced UI controller with fallback support -- **`EnhancedProcessUI.js`** - Enhanced version of the original process UI with 71+ tools -- **`index.js`** - Main entry point and auto-initialization - -## ๐Ÿ”ง Tool Categories Supported - -| Category | Tools | Description | -| ---------------------------- | ----- | --------------------------------------------------------- | -| ๐Ÿง  **Neural Network** | 15 | Training, prediction, patterns, models, WASM optimization | -| ๐Ÿ’พ **Memory Management** | 10 | Storage, backup, sync, analytics, namespaces | -| ๐Ÿ“Š **Monitoring & Analysis** | 13 | Performance, bottlenecks, health, metrics, trends | -| ๐Ÿ”„ **Workflow & Automation** | 11 | Workflows, pipelines, scheduling, triggers, SPARC modes | -| ๐Ÿ™ **GitHub Integration** | 8 | Repository analysis, PR management, release coordination | -| ๐Ÿค– **Dynamic Agents (DAA)** | 8 | Agent creation, consensus, fault tolerance, optimization | -| ๐Ÿ› ๏ธ **System Utilities** | 6 | Security, backup, diagnostics, configuration | -| โŒจ๏ธ **CLI Commands** | 9 | Bridge to command-line tools and operations | - -**Total: 71+ tools and commands** - -## ๐Ÿš€ Usage - -### Browser Environment - -```javascript -import { initializeEnhancedUI } from './ui/web-ui/index.js'; - -// Full UI manager mode -const ui = await initializeEnhancedUI({ mode: 'full' }); -await ui.navigateToView('neural'); -await ui.executeMCPTool('neural_train', { epochs: 100 }); -``` - -### Terminal Environment - -```javascript -import { launchTerminalUI } from './ui/web-ui/index.js'; - -// Launch enhanced terminal interface -await launchTerminalUI(); -``` - -### Enhance Existing UI - -```javascript -import { initializeEnhancedUI } from './ui/web-ui/index.js'; - -// Enhance existing process UI -const enhanced = await initializeEnhancedUI({ - mode: 'enhanced', - existingUI: existingProcessUI, -}); -``` - -### Auto-Initialization - -The system automatically detects the environment and initializes appropriately: - -- **Browser**: Creates full UI manager with DOM integration -- **Node.js with existing UI**: Enhances existing interface -- **Terminal**: Provides enhanced terminal interface -- **Fallback**: Always provides basic functionality - -## ๐ŸŽจ Views and Navigation - -### View Structure - -Each view follows a consistent pattern: - -```javascript -export default class ExampleView { - constructor(container, eventBus, viewConfig) { - this.container = container; - this.eventBus = eventBus; - this.viewConfig = viewConfig; - } - - async render(params = {}) { - // Create UI based on environment (DOM or terminal) - } - - async destroy() { - // Cleanup resources - } -} -``` - -### Navigation System - -- **Keyboard Shortcuts**: 0-9, Tab, Arrow keys -- **View Categories**: Overview, Processes, Tools by category -- **Quick Actions**: Direct tool execution shortcuts -- **Command Palette**: Ctrl+K for command search - -## ๐Ÿ”Œ MCP Tool Integration - -### Tool Execution - -```javascript -// Execute any MCP tool through the integration layer -const result = await ui.executeMCPTool('neural_train', { - pattern_type: 'coordination', - training_data: 'sample_data', - epochs: 50, -}); -``` - -### Real-time Updates - -- **Event-driven**: Tools emit events on completion -- **Caching**: Intelligent caching with TTL -- **Statistics**: Usage tracking and performance metrics -- **Error Handling**: Graceful degradation and retry logic - -## ๐Ÿ’พ State Management - -### Persistence - -- **Local Storage**: Browser environment -- **File System**: Node.js environment -- **Auto-save**: Configurable intervals -- **Import/Export**: State backup and restore - -### State Structure - -```javascript -{ - preferences: { theme: 'dark', autoSave: true }, - viewStates: { neural: { lastModel: 'model_123' } }, - toolResults: { neural_train: { result: {...}, timestamp: 123 } }, - sessionData: { currentSwarm: 'swarm_456' } -} -``` - -## ๐ŸŽฏ Event System - -### Event Categories - -- **`ui:*`** - UI lifecycle and interactions -- **`tool:*`** - MCP tool execution and results -- **`view:*`** - View navigation and state changes -- **`state:*`** - State persistence and updates - -### Event Usage - -```javascript -// Listen for tool results -eventBus.on('tool:executed', (data) => { - console.log(`Tool ${data.tool} completed:`, data.result); -}); - -// Emit navigation events -eventBus.emit('view:navigate', { viewId: 'neural', params: {} }); -``` - -## ๐ŸŽจ Component Library - -### Available Components - -- **ToolPanel**: Reusable tool interface panel -- **MetricsChart**: Real-time charts and graphs -- **CommandPalette**: VS Code-style command interface -- **ProgressBar**: Operation progress indicators -- **StatusBadge**: Status indicators with color coding -- **FormBuilder**: Dynamic form generation -- **TabContainer**: Tabbed content organization - -### Usage Example - -```javascript -const toolPanel = componentLibrary.getComponent('ToolPanel')({ - title: 'Neural Network Tools', - description: 'AI model training and optimization', -}); - -toolPanel.append(someContent); -``` - -## ๐Ÿ”ง Customization - -### Adding New Views - -1. **Create view class** in `/views/NewView.js` -2. **Register in UIManager** view configurations -3. **Add navigation** shortcuts and menu items -4. **Implement tool handlers** for view-specific tools - -### Adding New Tools - -1. **Register in MCPIntegrationLayer** tool definitions -2. **Add to tool categories** in UIManager -3. **Create view handlers** for tool-specific UI -4. **Update help system** with tool documentation - -### Theming - -```javascript -// Update theme -eventBus.emit('ui:theme:changed', 'light'); - -// Component library automatically updates styles -``` - -## ๐Ÿ” Debugging - -### Debug Information - -```javascript -// Get system status -const status = await ui.getSystemStatus(); - -// View event history -eventBus.getEventHistory(50); - -// Tool execution statistics -const stats = mcpIntegration.getToolUsageStats(); -``` - -### Logging - -- **Event Bus**: All events logged with timestamps -- **Tool Execution**: Detailed execution logs with performance metrics -- **Error Tracking**: Comprehensive error handling and reporting - -## ๐Ÿงช Testing - -### Component Testing - -Each component includes test interfaces: - -```javascript -// Test tool execution -await ui.executeTool('neural_train', { test: true }); - -// Mock data generation -const mockData = mcpIntegration.generateMockData('neural_status'); -``` - -### Integration Testing - -- **Cross-platform**: Browser, Node.js, terminal environments -- **Fallback modes**: Graceful degradation testing -- **Performance**: Load testing with multiple tools - -## ๐Ÿš€ Performance - -### Optimizations - -- **Lazy Loading**: Views loaded on demand -- **Caching**: Intelligent tool result caching -- **Event Batching**: Efficient event processing -- **Memory Management**: Automatic cleanup and limits - -### Metrics - -- **Tool Execution**: Average response times -- **Memory Usage**: State and cache size monitoring -- **Event Throughput**: Events processed per second -- **View Performance**: Render and transition times - -## ๐Ÿ”ฎ Future Enhancements - -### Planned Features - -- **Web Components**: Native web component versions -- **Real-time Collaboration**: Multi-user support -- **Plugin System**: Third-party view and tool plugins -- **Advanced Theming**: Custom CSS and layout options -- **Offline Support**: Progressive Web App features - -### Extensibility - -The architecture is designed for easy extension: - -- **Modular Views**: Add new tool categories -- **Component Library**: Extend with new UI components -- **Event System**: Custom event handlers and workflows -- **State Management**: Additional persistence backends - -## ๐Ÿ“ License - -Part of the Claude Flow project. See main project license. diff --git a/src/ui/web-ui/components/ComponentLibrary.js b/src/ui/web-ui/components/ComponentLibrary.js deleted file mode 100644 index e8145fd26f..0000000000 --- a/src/ui/web-ui/components/ComponentLibrary.js +++ /dev/null @@ -1,1054 +0,0 @@ -/** - * ComponentLibrary - Reusable UI components for Claude Flow Web UI - * Provides consistent, themeable components across all views - */ - -export class ComponentLibrary { - constructor() { - this.components = new Map(); - this.theme = 'dark'; - this.isInitialized = false; - } - - /** - * Initialize component library - */ - initialize() { - this.registerComponents(); - this.addComponentStyles(); - this.isInitialized = true; - console.log('๐ŸŽจ Component Library initialized'); - } - - /** - * Register all reusable components - */ - registerComponents() { - this.components.set('ToolPanel', this.createToolPanel); - this.components.set('MetricsChart', this.createMetricsChart); - this.components.set('CommandPalette', this.createCommandPalette); - this.components.set('ProgressBar', this.createProgressBar); - this.components.set('StatusBadge', this.createStatusBadge); - this.components.set('LoadingSpinner', this.createLoadingSpinner); - this.components.set('ErrorMessage', this.createErrorMessage); - this.components.set('SuccessMessage', this.createSuccessMessage); - this.components.set('InfoPanel', this.createInfoPanel); - this.components.set('ActionButton', this.createActionButton); - this.components.set('ToolGrid', this.createToolGrid); - this.components.set('StatsCard', this.createStatsCard); - this.components.set('LogViewer', this.createLogViewer); - this.components.set('FormBuilder', this.createFormBuilder); - this.components.set('TabContainer', this.createTabContainer); - } - - /** - * Get component by name - */ - getComponent(name) { - const component = this.components.get(name); - if (!component) { - throw new Error(`Component not found: ${name}`); - } - return component; - } - - /** - * Create tool panel component - */ - createToolPanel(config) { - const panel = document.createElement('div'); - panel.className = 'claude-tool-panel'; - - const header = document.createElement('div'); - header.className = 'claude-tool-panel-header'; - - const title = document.createElement('h3'); - title.textContent = config.title; - title.className = 'claude-tool-panel-title'; - - const subtitle = document.createElement('p'); - subtitle.textContent = config.description; - subtitle.className = 'claude-tool-panel-subtitle'; - - header.appendChild(title); - header.appendChild(subtitle); - - const content = document.createElement('div'); - content.className = 'claude-tool-panel-content'; - - panel.appendChild(header); - panel.appendChild(content); - - return { - element: panel, - content, - setTitle: (newTitle) => { - title.textContent = newTitle; - }, - setDescription: (newDesc) => { - subtitle.textContent = newDesc; - }, - clear: () => { - content.innerHTML = ''; - }, - append: (element) => { - content.appendChild(element); - }, - }; - } - - /** - * Create metrics chart component - */ - createMetricsChart(config) { - const container = document.createElement('div'); - container.className = 'claude-metrics-chart'; - - const title = document.createElement('h4'); - title.textContent = config.title; - title.className = 'claude-chart-title'; - - const canvas = document.createElement('canvas'); - canvas.width = config.width || 400; - canvas.height = config.height || 200; - canvas.className = 'claude-chart-canvas'; - - const legend = document.createElement('div'); - legend.className = 'claude-chart-legend'; - - container.appendChild(title); - container.appendChild(canvas); - container.appendChild(legend); - - return { - element: container, - canvas, - updateData: (data) => this.updateChart(canvas, data, config), - setTitle: (newTitle) => { - title.textContent = newTitle; - }, - addLegendItem: (label, color) => this.addLegendItem(legend, label, color), - }; - } - - /** - * Create command palette component - */ - createCommandPalette(config) { - const overlay = document.createElement('div'); - overlay.className = 'claude-command-palette-overlay'; - overlay.style.display = 'none'; - - const palette = document.createElement('div'); - palette.className = 'claude-command-palette'; - - const input = document.createElement('input'); - input.type = 'text'; - input.placeholder = 'Type a command...'; - input.className = 'claude-command-input'; - - const results = document.createElement('div'); - results.className = 'claude-command-results'; - - palette.appendChild(input); - palette.appendChild(results); - overlay.appendChild(palette); - - return { - element: overlay, - input, - results, - show: () => { - overlay.style.display = 'flex'; - input.focus(); - }, - hide: () => { - overlay.style.display = 'none'; - }, - updateResults: (commands) => this.updateCommandResults(results, commands), - onCommand: null, // Set by user - }; - } - - /** - * Create progress bar component - */ - createProgressBar(config) { - const container = document.createElement('div'); - container.className = 'claude-progress-container'; - - const label = document.createElement('div'); - label.className = 'claude-progress-label'; - label.textContent = config.label || 'Progress'; - - const bar = document.createElement('div'); - bar.className = 'claude-progress-bar'; - - const fill = document.createElement('div'); - fill.className = 'claude-progress-fill'; - fill.style.width = '0%'; - - const text = document.createElement('div'); - text.className = 'claude-progress-text'; - text.textContent = '0%'; - - bar.appendChild(fill); - bar.appendChild(text); - container.appendChild(label); - container.appendChild(bar); - - return { - element: container, - setProgress: (percent) => { - fill.style.width = `${percent}%`; - text.textContent = `${Math.round(percent)}%`; - }, - setLabel: (newLabel) => { - label.textContent = newLabel; - }, - }; - } - - /** - * Create status badge component - */ - createStatusBadge(status, text) { - const badge = document.createElement('span'); - badge.className = `claude-status-badge claude-status-${status}`; - badge.textContent = text || status; - - return { - element: badge, - setStatus: (newStatus) => { - badge.className = `claude-status-badge claude-status-${newStatus}`; - }, - setText: (newText) => { - badge.textContent = newText; - }, - }; - } - - /** - * Create loading spinner component - */ - createLoadingSpinner(config = {}) { - const container = document.createElement('div'); - container.className = 'claude-loading-container'; - - const spinner = document.createElement('div'); - spinner.className = 'claude-loading-spinner'; - - const message = document.createElement('div'); - message.className = 'claude-loading-message'; - message.textContent = config.message || 'Loading...'; - - container.appendChild(spinner); - container.appendChild(message); - - return { - element: container, - setMessage: (newMessage) => { - message.textContent = newMessage; - }, - show: () => { - container.style.display = 'flex'; - }, - hide: () => { - container.style.display = 'none'; - }, - }; - } - - /** - * Create error message component - */ - createErrorMessage(message, details = null) { - const container = document.createElement('div'); - container.className = 'claude-error-message'; - - const icon = document.createElement('span'); - icon.textContent = 'โŒ'; - icon.className = 'claude-error-icon'; - - const text = document.createElement('div'); - text.className = 'claude-error-text'; - text.textContent = message; - - container.appendChild(icon); - container.appendChild(text); - - if (details) { - const detailsEl = document.createElement('div'); - detailsEl.className = 'claude-error-details'; - detailsEl.textContent = details; - container.appendChild(detailsEl); - } - - return { - element: container, - setMessage: (newMessage) => { - text.textContent = newMessage; - }, - setDetails: (newDetails) => { - if (newDetails) { - if (!container.querySelector('.claude-error-details')) { - const detailsEl = document.createElement('div'); - detailsEl.className = 'claude-error-details'; - container.appendChild(detailsEl); - } - container.querySelector('.claude-error-details').textContent = newDetails; - } - }, - }; - } - - /** - * Create success message component - */ - createSuccessMessage(message) { - const container = document.createElement('div'); - container.className = 'claude-success-message'; - - const icon = document.createElement('span'); - icon.textContent = 'โœ…'; - icon.className = 'claude-success-icon'; - - const text = document.createElement('div'); - text.className = 'claude-success-text'; - text.textContent = message; - - container.appendChild(icon); - container.appendChild(text); - - return { - element: container, - setMessage: (newMessage) => { - text.textContent = newMessage; - }, - }; - } - - /** - * Create info panel component - */ - createInfoPanel(config) { - const panel = document.createElement('div'); - panel.className = 'claude-info-panel'; - - const header = document.createElement('div'); - header.className = 'claude-info-header'; - header.textContent = config.title; - - const content = document.createElement('div'); - content.className = 'claude-info-content'; - - panel.appendChild(header); - panel.appendChild(content); - - return { - element: panel, - content, - setTitle: (title) => { - header.textContent = title; - }, - setContent: (html) => { - content.innerHTML = html; - }, - append: (element) => { - content.appendChild(element); - }, - clear: () => { - content.innerHTML = ''; - }, - }; - } - - /** - * Create action button component - */ - createActionButton(config) { - const button = document.createElement('button'); - button.className = `claude-action-button claude-button-${config.type || 'primary'}`; - button.textContent = config.text; - - if (config.icon) { - const icon = document.createElement('span'); - icon.textContent = config.icon; - icon.className = 'claude-button-icon'; - button.insertBefore(icon, button.firstChild); - } - - if (config.onclick) { - button.addEventListener('click', config.onclick); - } - - return { - element: button, - setText: (text) => { - button.textContent = text; - if (config.icon) { - const icon = document.createElement('span'); - icon.textContent = config.icon; - icon.className = 'claude-button-icon'; - button.insertBefore(icon, button.firstChild); - } - }, - setDisabled: (disabled) => { - button.disabled = disabled; - }, - setLoading: (loading) => { - if (loading) { - button.classList.add('claude-button-loading'); - button.disabled = true; - } else { - button.classList.remove('claude-button-loading'); - button.disabled = false; - } - }, - }; - } - - /** - * Create tool grid component - */ - createToolGrid(tools, onToolClick) { - const grid = document.createElement('div'); - grid.className = 'claude-tool-grid'; - - tools.forEach((tool) => { - const card = document.createElement('div'); - card.className = 'claude-tool-card'; - - const icon = document.createElement('div'); - icon.className = 'claude-tool-icon'; - icon.textContent = tool.icon || '๐Ÿ”ง'; - - const name = document.createElement('div'); - name.className = 'claude-tool-name'; - name.textContent = tool.name; - - const desc = document.createElement('div'); - desc.className = 'claude-tool-description'; - desc.textContent = tool.description; - - card.appendChild(icon); - card.appendChild(name); - card.appendChild(desc); - - card.addEventListener('click', () => onToolClick(tool)); - - grid.appendChild(card); - }); - - return { - element: grid, - updateTools: (newTools) => { - grid.innerHTML = ''; - newTools.forEach((tool) => { - // Recreate cards with new tools - const card = this.createToolCard(tool, onToolClick); - grid.appendChild(card); - }); - }, - }; - } - - /** - * Create stats card component - */ - createStatsCard(config) { - const card = document.createElement('div'); - card.className = 'claude-stats-card'; - - const icon = document.createElement('div'); - icon.className = 'claude-stats-icon'; - icon.textContent = config.icon; - - const content = document.createElement('div'); - content.className = 'claude-stats-content'; - - const value = document.createElement('div'); - value.className = 'claude-stats-value'; - value.textContent = config.value; - - const label = document.createElement('div'); - label.className = 'claude-stats-label'; - label.textContent = config.label; - - content.appendChild(value); - content.appendChild(label); - card.appendChild(icon); - card.appendChild(content); - - return { - element: card, - setValue: (newValue) => { - value.textContent = newValue; - }, - setLabel: (newLabel) => { - label.textContent = newLabel; - }, - setIcon: (newIcon) => { - icon.textContent = newIcon; - }, - }; - } - - /** - * Create tab container component - */ - createTabContainer(tabs) { - const container = document.createElement('div'); - container.className = 'claude-tab-container'; - - const tabList = document.createElement('div'); - tabList.className = 'claude-tab-list'; - - const tabContent = document.createElement('div'); - tabContent.className = 'claude-tab-content'; - - let activeTab = 0; - - tabs.forEach((tab, index) => { - const tabButton = document.createElement('button'); - tabButton.className = `claude-tab-button ${index === 0 ? 'active' : ''}`; - tabButton.textContent = tab.label; - - const tabPane = document.createElement('div'); - tabPane.className = `claude-tab-pane ${index === 0 ? 'active' : ''}`; - tabPane.innerHTML = tab.content; - - tabButton.addEventListener('click', () => { - // Remove active class from all tabs - tabList - .querySelectorAll('.claude-tab-button') - .forEach((btn) => btn.classList.remove('active')); - tabContent - .querySelectorAll('.claude-tab-pane') - .forEach((pane) => pane.classList.remove('active')); - - // Add active class to clicked tab - tabButton.classList.add('active'); - tabPane.classList.add('active'); - activeTab = index; - }); - - tabList.appendChild(tabButton); - tabContent.appendChild(tabPane); - }); - - container.appendChild(tabList); - container.appendChild(tabContent); - - return { - element: container, - setActiveTab: (index) => { - if (index >= 0 && index < tabs.length) { - tabList.children[index].click(); - } - }, - getActiveTab: () => activeTab, - addTab: (tab) => { - // Implementation for adding new tabs dynamically - }, - }; - } - - /** - * Add component styles to document - */ - addComponentStyles() { - if (document.getElementById('claude-component-styles')) return; - - const styles = document.createElement('style'); - styles.id = 'claude-component-styles'; - styles.textContent = ` - /* Tool Panel Styles */ - .claude-tool-panel { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - margin: 8px 0; - } - - .claude-tool-panel-header { - margin-bottom: 12px; - } - - .claude-tool-panel-title { - margin: 0 0 4px 0; - color: #00d4ff; - font-size: 18px; - } - - .claude-tool-panel-subtitle { - margin: 0; - color: #888; - font-size: 14px; - } - - .claude-tool-panel-content { - color: #fff; - } - - /* Metrics Chart Styles */ - .claude-metrics-chart { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - margin: 8px 0; - } - - .claude-chart-title { - margin: 0 0 12px 0; - color: #00d4ff; - font-size: 16px; - } - - .claude-chart-canvas { - display: block; - margin: 0 auto; - background: #1a1a1a; - border-radius: 4px; - } - - .claude-chart-legend { - display: flex; - flex-wrap: wrap; - gap: 12px; - margin-top: 8px; - justify-content: center; - } - - /* Command Palette Styles */ - .claude-command-palette-overlay { - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: rgba(0, 0, 0, 0.8); - display: flex; - justify-content: center; - align-items: flex-start; - padding-top: 20vh; - z-index: 9999; - } - - .claude-command-palette { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - width: 600px; - max-width: 90vw; - max-height: 60vh; - overflow: hidden; - } - - .claude-command-input { - width: 100%; - padding: 16px; - background: transparent; - border: none; - color: #fff; - font-size: 18px; - outline: none; - border-bottom: 1px solid #444; - } - - .claude-command-results { - max-height: 400px; - overflow-y: auto; - } - - /* Progress Bar Styles */ - .claude-progress-container { - margin: 8px 0; - } - - .claude-progress-label { - color: #fff; - margin-bottom: 4px; - font-size: 14px; - } - - .claude-progress-bar { - position: relative; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - height: 24px; - overflow: hidden; - } - - .claude-progress-fill { - height: 100%; - background: linear-gradient(90deg, #00d4ff, #0099cc); - transition: width 0.3s ease; - } - - .claude-progress-text { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - color: #fff; - font-size: 12px; - font-weight: bold; - } - - /* Status Badge Styles */ - .claude-status-badge { - display: inline-block; - padding: 4px 8px; - border-radius: 4px; - font-size: 12px; - font-weight: bold; - text-transform: uppercase; - } - - .claude-status-success { - background: #22c55e; - color: white; - } - - .claude-status-error { - background: #ef4444; - color: white; - } - - .claude-status-warning { - background: #f59e0b; - color: white; - } - - .claude-status-info { - background: #3b82f6; - color: white; - } - - .claude-status-idle { - background: #6b7280; - color: white; - } - - /* Loading Spinner Styles */ - .claude-loading-container { - display: flex; - flex-direction: column; - align-items: center; - padding: 32px; - } - - .claude-loading-spinner { - width: 32px; - height: 32px; - border: 3px solid #444; - border-top: 3px solid #00d4ff; - border-radius: 50%; - animation: spin 1s linear infinite; - } - - .claude-loading-message { - margin-top: 12px; - color: #888; - font-size: 14px; - } - - @keyframes spin { - 0% { transform: rotate(0deg); } - 100% { transform: rotate(360deg); } - } - - /* Message Styles */ - .claude-error-message, - .claude-success-message { - display: flex; - align-items: center; - padding: 12px 16px; - border-radius: 6px; - margin: 8px 0; - } - - .claude-error-message { - background: #fef2f2; - border: 1px solid #fecaca; - color: #991b1b; - } - - .claude-success-message { - background: #f0fdf4; - border: 1px solid #bbf7d0; - color: #166534; - } - - .claude-error-icon, - .claude-success-icon { - margin-right: 8px; - font-size: 16px; - } - - /* Tool Grid Styles */ - .claude-tool-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); - gap: 16px; - margin: 16px 0; - } - - .claude-tool-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - cursor: pointer; - transition: all 0.2s ease; - } - - .claude-tool-card:hover { - border-color: #00d4ff; - transform: translateY(-2px); - } - - .claude-tool-icon { - font-size: 32px; - margin-bottom: 8px; - } - - .claude-tool-name { - font-weight: bold; - color: #fff; - margin-bottom: 4px; - } - - .claude-tool-description { - color: #888; - font-size: 14px; - } - - /* Stats Card Styles */ - .claude-stats-card { - display: flex; - align-items: center; - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - margin: 8px 0; - } - - .claude-stats-icon { - font-size: 24px; - margin-right: 12px; - } - - .claude-stats-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .claude-stats-label { - color: #888; - font-size: 14px; - } - - /* Tab Styles */ - .claude-tab-container { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - overflow: hidden; - } - - .claude-tab-list { - display: flex; - background: #1a1a1a; - border-bottom: 1px solid #444; - } - - .claude-tab-button { - background: transparent; - border: none; - color: #888; - padding: 12px 16px; - cursor: pointer; - border-bottom: 2px solid transparent; - transition: all 0.2s ease; - } - - .claude-tab-button:hover { - color: #fff; - } - - .claude-tab-button.active { - color: #00d4ff; - border-bottom-color: #00d4ff; - } - - .claude-tab-content { - position: relative; - } - - .claude-tab-pane { - display: none; - padding: 16px; - } - - .claude-tab-pane.active { - display: block; - } - - /* Button Styles */ - .claude-action-button { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 8px 16px; - border: none; - border-radius: 6px; - cursor: pointer; - font-size: 14px; - font-weight: 500; - transition: all 0.2s ease; - } - - .claude-button-primary { - background: #00d4ff; - color: #000; - } - - .claude-button-primary:hover { - background: #00b8e6; - } - - .claude-button-secondary { - background: #444; - color: #fff; - } - - .claude-button-secondary:hover { - background: #555; - } - - .claude-button-danger { - background: #ef4444; - color: #fff; - } - - .claude-button-danger:hover { - background: #dc2626; - } - - .claude-button-loading { - opacity: 0.7; - pointer-events: none; - } - - /* Info Panel Styles */ - .claude-info-panel { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - margin: 8px 0; - overflow: hidden; - } - - .claude-info-header { - background: #1a1a1a; - padding: 12px 16px; - font-weight: bold; - color: #00d4ff; - border-bottom: 1px solid #444; - } - - .claude-info-content { - padding: 16px; - color: #fff; - } - `; - - document.head.appendChild(styles); - } - - /** - * Update chart with new data - */ - updateChart(canvas, data, config) { - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - - // Simple chart implementation - // In a real implementation, you'd use Chart.js or similar - const padding = 40; - const chartWidth = canvas.width - padding * 2; - const chartHeight = canvas.height - padding * 2; - - if (config.type === 'line') { - this.drawLineChart(ctx, data, padding, chartWidth, chartHeight); - } else if (config.type === 'bar') { - this.drawBarChart(ctx, data, padding, chartWidth, chartHeight); - } - } - - /** - * Draw line chart - */ - drawLineChart(ctx, data, padding, width, height) { - if (!data || data.length === 0) return; - - const maxValue = Math.max(...data.map((d) => d.value)); - const stepX = width / (data.length - 1); - - ctx.strokeStyle = '#00d4ff'; - ctx.lineWidth = 2; - ctx.beginPath(); - - data.forEach((point, index) => { - const x = padding + index * stepX; - const y = padding + height - (point.value / maxValue) * height; - - if (index === 0) { - ctx.moveTo(x, y); - } else { - ctx.lineTo(x, y); - } - }); - - ctx.stroke(); - } - - /** - * Draw bar chart - */ - drawBarChart(ctx, data, padding, width, height) { - if (!data || data.length === 0) return; - - const maxValue = Math.max(...data.map((d) => d.value)); - const barWidth = (width / data.length) * 0.8; - const barSpacing = (width / data.length) * 0.2; - - ctx.fillStyle = '#00d4ff'; - - data.forEach((point, index) => { - const x = padding + index * (barWidth + barSpacing); - const barHeight = (point.value / maxValue) * height; - const y = padding + height - barHeight; - - ctx.fillRect(x, y, barWidth, barHeight); - }); - } - - /** - * Set theme - */ - setTheme(theme) { - this.theme = theme; - // Update component styles based on theme - // This would be more comprehensive in a real implementation - } -} - -export default ComponentLibrary; diff --git a/src/ui/web-ui/core/EventBus.js b/src/ui/web-ui/core/EventBus.js deleted file mode 100644 index adc21a8b64..0000000000 --- a/src/ui/web-ui/core/EventBus.js +++ /dev/null @@ -1,514 +0,0 @@ -/** - * EventBus - Central event communication system for the Web UI - * Enables loose coupling between components and real-time updates - */ - -export class EventBus { - constructor() { - this.events = new Map(); - this.onceEvents = new Map(); - this.wildcardHandlers = new Map(); - this.eventHistory = []; - this.maxHistorySize = 1000; - this.isLogging = true; - } - - /** - * Subscribe to an event - */ - on(event, handler, context = null) { - if (typeof handler !== 'function') { - throw new Error('Event handler must be a function'); - } - - if (!this.events.has(event)) { - this.events.set(event, []); - } - - const handlerInfo = { - handler, - context, - id: this.generateHandlerId(), - }; - - this.events.get(event).push(handlerInfo); - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Subscribed to '${event}'`); - } - - // Return unsubscribe function - return () => this.off(event, handler); - } - - /** - * Subscribe to an event (once only) - */ - once(event, handler, context = null) { - if (typeof handler !== 'function') { - throw new Error('Event handler must be a function'); - } - - if (!this.onceEvents.has(event)) { - this.onceEvents.set(event, []); - } - - const handlerInfo = { - handler, - context, - id: this.generateHandlerId(), - }; - - this.onceEvents.get(event).push(handlerInfo); - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Subscribed once to '${event}'`); - } - - // Return unsubscribe function - return () => this.offOnce(event, handler); - } - - /** - * Subscribe to events with wildcard patterns - */ - onWildcard(pattern, handler, context = null) { - if (typeof handler !== 'function') { - throw new Error('Event handler must be a function'); - } - - if (!this.wildcardHandlers.has(pattern)) { - this.wildcardHandlers.set(pattern, []); - } - - const handlerInfo = { - handler, - context, - id: this.generateHandlerId(), - regex: this.createWildcardRegex(pattern), - }; - - this.wildcardHandlers.get(pattern).push(handlerInfo); - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Subscribed to wildcard pattern '${pattern}'`); - } - - // Return unsubscribe function - return () => this.offWildcard(pattern, handler); - } - - /** - * Unsubscribe from an event - */ - off(event, handler) { - const handlers = this.events.get(event); - if (!handlers) return false; - - const index = handlers.findIndex((h) => h.handler === handler); - if (index === -1) return false; - - handlers.splice(index, 1); - - if (handlers.length === 0) { - this.events.delete(event); - } - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Unsubscribed from '${event}'`); - } - - return true; - } - - /** - * Unsubscribe from a once event - */ - offOnce(event, handler) { - const handlers = this.onceEvents.get(event); - if (!handlers) return false; - - const index = handlers.findIndex((h) => h.handler === handler); - if (index === -1) return false; - - handlers.splice(index, 1); - - if (handlers.length === 0) { - this.onceEvents.delete(event); - } - - return true; - } - - /** - * Unsubscribe from wildcard pattern - */ - offWildcard(pattern, handler) { - const handlers = this.wildcardHandlers.get(pattern); - if (!handlers) return false; - - const index = handlers.findIndex((h) => h.handler === handler); - if (index === -1) return false; - - handlers.splice(index, 1); - - if (handlers.length === 0) { - this.wildcardHandlers.delete(pattern); - } - - return true; - } - - /** - * Emit an event - */ - emit(event, data = null) { - const eventInfo = { - event, - data, - timestamp: Date.now(), - id: this.generateEventId(), - }; - - // Add to history - this.addToHistory(eventInfo); - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Emitting '${event}'`, data); - } - - let handlersExecuted = 0; - - // Execute regular event handlers - const handlers = this.events.get(event); - if (handlers) { - for (const handlerInfo of [...handlers]) { - try { - if (handlerInfo.context) { - handlerInfo.handler.call(handlerInfo.context, data, eventInfo); - } else { - handlerInfo.handler(data, eventInfo); - } - handlersExecuted++; - } catch (error) { - console.error(`๐Ÿ“ก EventBus: Error in handler for '${event}':`, error); - this.emit('error', { event, error, handlerInfo }); - } - } - } - - // Execute once event handlers - const onceHandlers = this.onceEvents.get(event); - if (onceHandlers) { - for (const handlerInfo of [...onceHandlers]) { - try { - if (handlerInfo.context) { - handlerInfo.handler.call(handlerInfo.context, data, eventInfo); - } else { - handlerInfo.handler(data, eventInfo); - } - handlersExecuted++; - } catch (error) { - console.error(`๐Ÿ“ก EventBus: Error in once handler for '${event}':`, error); - this.emit('error', { event, error, handlerInfo }); - } - } - // Clear once handlers after execution - this.onceEvents.delete(event); - } - - // Execute wildcard handlers - for (const [pattern, handlers] of this.wildcardHandlers) { - for (const handlerInfo of handlers) { - if (handlerInfo.regex.test(event)) { - try { - if (handlerInfo.context) { - handlerInfo.handler.call(handlerInfo.context, data, eventInfo); - } else { - handlerInfo.handler(data, eventInfo); - } - handlersExecuted++; - } catch (error) { - console.error(`๐Ÿ“ก EventBus: Error in wildcard handler for '${pattern}':`, error); - this.emit('error', { event, error, handlerInfo, pattern }); - } - } - } - } - - return handlersExecuted; - } - - /** - * Emit event asynchronously - */ - async emitAsync(event, data = null) { - const eventInfo = { - event, - data, - timestamp: Date.now(), - id: this.generateEventId(), - }; - - // Add to history - this.addToHistory(eventInfo); - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Emitting async '${event}'`, data); - } - - const promises = []; - - // Execute regular event handlers - const handlers = this.events.get(event); - if (handlers) { - for (const handlerInfo of [...handlers]) { - const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo); - promises.push(promise); - } - } - - // Execute once event handlers - const onceHandlers = this.onceEvents.get(event); - if (onceHandlers) { - for (const handlerInfo of [...onceHandlers]) { - const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo); - promises.push(promise); - } - // Clear once handlers after execution - this.onceEvents.delete(event); - } - - // Execute wildcard handlers - for (const [pattern, handlers] of this.wildcardHandlers) { - for (const handlerInfo of handlers) { - if (handlerInfo.regex.test(event)) { - const promise = this.executeHandlerAsync(handlerInfo, data, eventInfo); - promises.push(promise); - } - } - } - - const results = await Promise.allSettled(promises); - - // Handle any rejections - const failures = results.filter((r) => r.status === 'rejected'); - if (failures.length > 0) { - console.error(`๐Ÿ“ก EventBus: ${failures.length} handlers failed for '${event}'`); - failures.forEach((failure) => { - this.emit('error', { event, error: failure.reason }); - }); - } - - return results.length; - } - - /** - * Execute handler asynchronously - */ - async executeHandlerAsync(handlerInfo, data, eventInfo) { - try { - let result; - if (handlerInfo.context) { - result = handlerInfo.handler.call(handlerInfo.context, data, eventInfo); - } else { - result = handlerInfo.handler(data, eventInfo); - } - - // If handler returns a promise, await it - if (result && typeof result.then === 'function') { - return await result; - } - - return result; - } catch (error) { - console.error(`๐Ÿ“ก EventBus: Error in async handler:`, error); - throw error; - } - } - - /** - * Wait for an event to be emitted - */ - waitFor(event, timeout = 5000) { - return new Promise((resolve, reject) => { - let timeoutId; - - const unsubscribe = this.once(event, (data) => { - if (timeoutId) { - clearTimeout(timeoutId); - } - resolve(data); - }); - - if (timeout > 0) { - timeoutId = setTimeout(() => { - unsubscribe(); - reject(new Error(`Timeout waiting for event '${event}' after ${timeout}ms`)); - }, timeout); - } - }); - } - - /** - * Remove all event listeners - */ - removeAllListeners(event = null) { - if (event) { - this.events.delete(event); - this.onceEvents.delete(event); - - // Remove matching wildcard handlers - for (const [pattern, handlers] of this.wildcardHandlers) { - if (pattern === event) { - this.wildcardHandlers.delete(pattern); - } - } - } else { - this.events.clear(); - this.onceEvents.clear(); - this.wildcardHandlers.clear(); - } - - if (this.isLogging) { - console.debug(`๐Ÿ“ก EventBus: Removed all listeners${event ? ` for '${event}'` : ''}`); - } - } - - /** - * Get event listeners count - */ - listenerCount(event) { - const regular = this.events.get(event)?.length || 0; - const once = this.onceEvents.get(event)?.length || 0; - - let wildcard = 0; - for (const [pattern, handlers] of this.wildcardHandlers) { - const regex = this.createWildcardRegex(pattern); - if (regex.test(event)) { - wildcard += handlers.length; - } - } - - return regular + once + wildcard; - } - - /** - * Get all event names - */ - eventNames() { - const names = new Set(); - - for (const event of this.events.keys()) { - names.add(event); - } - - for (const event of this.onceEvents.keys()) { - names.add(event); - } - - return Array.from(names); - } - - /** - * Get event history - */ - getEventHistory(limit = 100) { - return this.eventHistory.slice(-limit); - } - - /** - * Get events by pattern - */ - getEventsByPattern(pattern, limit = 100) { - const regex = this.createWildcardRegex(pattern); - return this.eventHistory.filter((event) => regex.test(event.event)).slice(-limit); - } - - /** - * Clear event history - */ - clearHistory() { - this.eventHistory = []; - } - - /** - * Enable/disable logging - */ - setLogging(enabled) { - this.isLogging = enabled; - } - - /** - * Create wildcard regex - */ - createWildcardRegex(pattern) { - const escaped = pattern - .replace(/[.+^${}()|[\]\\]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/\?/g, '.'); - - return new RegExp(`^${escaped}$`); - } - - /** - * Generate unique handler ID - */ - generateHandlerId() { - return `handler_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; - } - - /** - * Generate unique event ID - */ - generateEventId() { - return `event_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; - } - - /** - * Add event to history - */ - addToHistory(eventInfo) { - this.eventHistory.push(eventInfo); - - // Keep history size under control - if (this.eventHistory.length > this.maxHistorySize) { - this.eventHistory = this.eventHistory.slice(-this.maxHistorySize); - } - } - - /** - * Get statistics - */ - getStats() { - return { - regularEvents: this.events.size, - onceEvents: this.onceEvents.size, - wildcardPatterns: this.wildcardHandlers.size, - historySize: this.eventHistory.length, - totalHandlers: - Array.from(this.events.values()).reduce((sum, handlers) => sum + handlers.length, 0) + - Array.from(this.onceEvents.values()).reduce((sum, handlers) => sum + handlers.length, 0) + - Array.from(this.wildcardHandlers.values()).reduce( - (sum, handlers) => sum + handlers.length, - 0, - ), - }; - } - - /** - * Debug information - */ - debug() { - const stats = this.getStats(); - console.group('๐Ÿ“ก EventBus Debug Info'); - console.log('Statistics:', stats); - console.log('Regular Events:', Array.from(this.events.keys())); - console.log('Once Events:', Array.from(this.onceEvents.keys())); - console.log('Wildcard Patterns:', Array.from(this.wildcardHandlers.keys())); - console.log('Recent History:', this.getEventHistory(10)); - console.groupEnd(); - } -} - -export default EventBus; diff --git a/src/ui/web-ui/core/MCPIntegrationLayer.js b/src/ui/web-ui/core/MCPIntegrationLayer.js deleted file mode 100644 index 49366122bb..0000000000 --- a/src/ui/web-ui/core/MCPIntegrationLayer.js +++ /dev/null @@ -1,715 +0,0 @@ -/** - * MCP Integration Layer - Bridge between UI and Claude Flow MCP Tools - * Handles all MCP tool execution, caching, and result processing - */ - -import { EventBus } from './EventBus.js'; - -export class MCPIntegrationLayer { - constructor(eventBus) { - this.eventBus = eventBus; - this.mcpTools = new Map(); - this.toolResults = new Map(); - this.activeExecutions = new Map(); - this.cache = new Map(); - this.isInitialized = false; - this.mcpServerStatus = 'unknown'; - this.toolCategories = { - neural: [], - memory: [], - monitoring: [], - workflow: [], - github: [], - daa: [], - system: [], - }; - } - - /** - * Initialize MCP integration layer - */ - async initialize() { - try { - // Check if MCP server is available - this.mcpServerStatus = await this.checkMCPServerStatus(); - - // Discover available tools - await this.discoverTools(); - - // Setup tool execution handlers - this.setupToolHandlers(); - - // Initialize caching system - this.initializeCache(); - - this.isInitialized = true; - this.eventBus.emit('mcp:initialized', { status: this.mcpServerStatus }); - - console.log('๐Ÿ”Œ MCP Integration Layer initialized'); - } catch (error) { - console.error('โŒ Failed to initialize MCP Integration Layer:', error); - this.mcpServerStatus = 'error'; - throw error; - } - } - - /** - * Check MCP server status - */ - async checkMCPServerStatus() { - try { - // Try to detect available MCP tools - // This would normally check for actual MCP server connection - if (typeof window !== 'undefined' && window.claudeFlowMCP) { - return 'connected'; - } - - // Check for Node.js environment with MCP tools - if (typeof process !== 'undefined' && process.env.CLAUDE_FLOW_MCP_ENABLED === 'true') { - return 'connected'; - } - - return 'mock'; // Use mock mode for development - } catch (error) { - console.warn('MCP Server connection check failed:', error); - return 'offline'; - } - } - - /** - * Discover available MCP tools - */ - async discoverTools() { - const availableTools = { - // Neural Network Tools - neural: [ - { - name: 'neural_train', - description: 'Train neural patterns with WASM SIMD', - params: ['pattern_type', 'training_data', 'epochs'], - }, - { - name: 'neural_predict', - description: 'Make AI predictions', - params: ['modelId', 'input'], - }, - { name: 'neural_status', description: 'Check neural network status', params: ['modelId'] }, - { - name: 'neural_patterns', - description: 'Analyze cognitive patterns', - params: ['action', 'operation', 'outcome'], - }, - { name: 'model_load', description: 'Load pre-trained models', params: ['modelPath'] }, - { name: 'model_save', description: 'Save trained models', params: ['modelId', 'path'] }, - { - name: 'pattern_recognize', - description: 'Pattern recognition', - params: ['data', 'patterns'], - }, - { - name: 'cognitive_analyze', - description: 'Cognitive behavior analysis', - params: ['behavior'], - }, - { name: 'learning_adapt', description: 'Adaptive learning', params: ['experience'] }, - { - name: 'neural_compress', - description: 'Compress neural models', - params: ['modelId', 'ratio'], - }, - { - name: 'ensemble_create', - description: 'Create model ensembles', - params: ['models', 'strategy'], - }, - { - name: 'transfer_learn', - description: 'Transfer learning', - params: ['sourceModel', 'targetDomain'], - }, - { - name: 'neural_explain', - description: 'AI explainability', - params: ['modelId', 'prediction'], - }, - { name: 'wasm_optimize', description: 'WASM SIMD optimization', params: ['operation'] }, - { name: 'inference_run', description: 'Run neural inference', params: ['modelId', 'data'] }, - ], - - // Memory & Persistence Tools - memory: [ - { - name: 'memory_usage', - description: 'Store/retrieve persistent memory', - params: ['action', 'key', 'value', 'namespace', 'ttl'], - }, - { name: 'memory_backup', description: 'Backup memory stores', params: ['path'] }, - { name: 'memory_restore', description: 'Restore from backups', params: ['backupPath'] }, - { name: 'memory_compress', description: 'Compress memory data', params: ['namespace'] }, - { name: 'memory_sync', description: 'Sync across instances', params: ['target'] }, - { - name: 'cache_manage', - description: 'Manage coordination cache', - params: ['action', 'key'], - }, - { name: 'state_snapshot', description: 'Create state snapshots', params: ['name'] }, - { - name: 'context_restore', - description: 'Restore execution context', - params: ['snapshotId'], - }, - { name: 'memory_analytics', description: 'Analyze memory usage', params: ['timeframe'] }, - { name: 'memory_persist', description: 'Cross-session persistence', params: ['sessionId'] }, - { - name: 'memory_namespace', - description: 'Namespace management', - params: ['namespace', 'action'], - }, - ], - - // Monitoring & Analysis Tools - monitoring: [ - { - name: 'performance_report', - description: 'Generate performance reports', - params: ['format', 'timeframe'], - }, - { - name: 'bottleneck_analyze', - description: 'Identify performance bottlenecks', - params: ['component', 'metrics'], - }, - { - name: 'token_usage', - description: 'Analyze token consumption', - params: ['operation', 'timeframe'], - }, - { name: 'benchmark_run', description: 'Performance benchmarks', params: ['suite'] }, - { name: 'metrics_collect', description: 'Collect system metrics', params: ['components'] }, - { - name: 'trend_analysis', - description: 'Analyze performance trends', - params: ['metric', 'period'], - }, - { name: 'cost_analysis', description: 'Cost and resource analysis', params: ['timeframe'] }, - { - name: 'quality_assess', - description: 'Quality assessment', - params: ['target', 'criteria'], - }, - { name: 'error_analysis', description: 'Error pattern analysis', params: ['logs'] }, - { name: 'usage_stats', description: 'Usage statistics', params: ['component'] }, - { name: 'health_check', description: 'System health monitoring', params: ['components'] }, - { - name: 'swarm_monitor', - description: 'Real-time swarm monitoring', - params: ['swarmId', 'interval'], - }, - { name: 'agent_metrics', description: 'Agent performance metrics', params: ['agentId'] }, - ], - - // Workflow & Automation Tools - workflow: [ - { - name: 'workflow_create', - description: 'Create custom workflows', - params: ['name', 'steps', 'triggers'], - }, - { - name: 'workflow_execute', - description: 'Execute predefined workflows', - params: ['workflowId', 'params'], - }, - { name: 'automation_setup', description: 'Setup automation rules', params: ['rules'] }, - { name: 'pipeline_create', description: 'Create CI/CD pipelines', params: ['config'] }, - { - name: 'scheduler_manage', - description: 'Manage task scheduling', - params: ['action', 'schedule'], - }, - { - name: 'trigger_setup', - description: 'Setup event triggers', - params: ['events', 'actions'], - }, - { - name: 'workflow_template', - description: 'Manage workflow templates', - params: ['action', 'template'], - }, - { name: 'batch_process', description: 'Batch processing', params: ['items', 'operation'] }, - { name: 'parallel_execute', description: 'Execute tasks in parallel', params: ['tasks'] }, - { - name: 'sparc_mode', - description: 'Run SPARC development modes', - params: ['mode', 'task_description', 'options'], - }, - { - name: 'task_orchestrate', - description: 'Orchestrate complex task workflows', - params: ['task', 'strategy', 'priority', 'dependencies'], - }, - ], - - // GitHub Integration Tools - github: [ - { - name: 'github_repo_analyze', - description: 'Repository analysis', - params: ['repo', 'analysis_type'], - }, - { - name: 'github_pr_manage', - description: 'Pull request management', - params: ['repo', 'action', 'pr_number'], - }, - { - name: 'github_issue_track', - description: 'Issue tracking & triage', - params: ['repo', 'action'], - }, - { - name: 'github_release_coord', - description: 'Release coordination', - params: ['repo', 'version'], - }, - { - name: 'github_workflow_auto', - description: 'Workflow automation', - params: ['repo', 'workflow'], - }, - { - name: 'github_code_review', - description: 'Automated code review', - params: ['repo', 'pr'], - }, - { - name: 'github_sync_coord', - description: 'Multi-repo sync coordination', - params: ['repos'], - }, - { name: 'github_metrics', description: 'Repository metrics', params: ['repo'] }, - ], - - // DAA Tools - daa: [ - { - name: 'daa_agent_create', - description: 'Create dynamic agents', - params: ['agent_type', 'capabilities', 'resources'], - }, - { - name: 'daa_capability_match', - description: 'Match capabilities to tasks', - params: ['task_requirements', 'available_agents'], - }, - { - name: 'daa_resource_alloc', - description: 'Resource allocation', - params: ['resources', 'agents'], - }, - { - name: 'daa_lifecycle_manage', - description: 'Agent lifecycle management', - params: ['agentId', 'action'], - }, - { - name: 'daa_communication', - description: 'Inter-agent communication', - params: ['from', 'to', 'message'], - }, - { - name: 'daa_consensus', - description: 'Consensus mechanisms', - params: ['agents', 'proposal'], - }, - { - name: 'daa_fault_tolerance', - description: 'Fault tolerance & recovery', - params: ['agentId', 'strategy'], - }, - { - name: 'daa_optimization', - description: 'Performance optimization', - params: ['target', 'metrics'], - }, - ], - - // System & Utilities - system: [ - { name: 'security_scan', description: 'Security scanning', params: ['target', 'depth'] }, - { - name: 'backup_create', - description: 'Create system backups', - params: ['components', 'destination'], - }, - { name: 'restore_system', description: 'System restoration', params: ['backupId'] }, - { - name: 'log_analysis', - description: 'Log analysis & insights', - params: ['logFile', 'patterns'], - }, - { name: 'diagnostic_run', description: 'System diagnostics', params: ['components'] }, - { - name: 'config_manage', - description: 'Configuration management', - params: ['action', 'config'], - }, - { name: 'features_detect', description: 'Feature detection', params: ['component'] }, - { - name: 'terminal_execute', - description: 'Execute terminal commands', - params: ['command', 'args'], - }, - ], - }; - - // Register tools - for (const [category, tools] of Object.entries(availableTools)) { - this.toolCategories[category] = tools; - tools.forEach((tool) => { - this.mcpTools.set(tool.name, { - ...tool, - category, - lastUsed: null, - usageCount: 0, - }); - }); - } - - console.log( - `๐Ÿ”ง Discovered ${this.mcpTools.size} MCP tools across ${Object.keys(this.toolCategories).length} categories`, - ); - } - - /** - * Execute MCP tool - */ - async executeTool(toolName, params = {}) { - if (!this.isInitialized) { - throw new Error('MCP Integration Layer not initialized'); - } - - const tool = this.mcpTools.get(toolName); - if (!tool) { - throw new Error(`Tool not found: ${toolName}`); - } - - // Check if execution is already in progress - if (this.activeExecutions.has(toolName)) { - throw new Error(`Tool ${toolName} is already executing`); - } - - // Check cache first - const cacheKey = this.getCacheKey(toolName, params); - const cached = this.cache.get(cacheKey); - if (cached && !this.isCacheExpired(cached)) { - return cached.result; - } - - try { - // Mark as executing - this.activeExecutions.set(toolName, { - startTime: Date.now(), - params, - }); - - // Execute based on MCP server status - let result; - if (this.mcpServerStatus === 'connected') { - result = await this.executeRealTool(toolName, params); - } else { - result = await this.executeMockTool(toolName, params); - } - - // Update tool usage stats - tool.lastUsed = Date.now(); - tool.usageCount++; - - // Cache result - this.cacheResult(cacheKey, result); - - // Store in results map - this.toolResults.set(toolName, { - result, - timestamp: Date.now(), - params, - }); - - // Emit success event - this.eventBus.emit('tool:executed', { - tool: toolName, - result, - params, - duration: Date.now() - this.activeExecutions.get(toolName).startTime, - }); - - return result; - } catch (error) { - this.eventBus.emit('tool:error', { - tool: toolName, - error: error.message, - params, - }); - throw error; - } finally { - // Remove from active executions - this.activeExecutions.delete(toolName); - } - } - - /** - * Execute real MCP tool (when server is connected) - */ - async executeRealTool(toolName, params) { - // This would call the actual MCP tool - // For now, we'll simulate the call - const mcpToolName = `mcp__claude-flow__${toolName}`; - - if (typeof window !== 'undefined' && window.claudeFlowMCP) { - return await window.claudeFlowMCP.execute(mcpToolName, params); - } - - // Node.js environment - if (typeof process !== 'undefined') { - // This would import and execute the actual MCP tool - // For now, return mock data - return this.executeMockTool(toolName, params); - } - - throw new Error('MCP server not available'); - } - - /** - * Execute mock tool (for development/testing) - */ - async executeMockTool(toolName, params) { - // Simulate execution delay - await new Promise((resolve) => setTimeout(resolve, 100 + Math.random() * 500)); - - const mockResults = { - // Neural tools - neural_train: { success: true, epochs: params.epochs || 50, accuracy: 0.95, loss: 0.05 }, - neural_predict: { prediction: 'sample_prediction', confidence: 0.87 }, - neural_status: { modelId: params.modelId, status: 'ready', accuracy: 0.92 }, - neural_patterns: { patterns: ['pattern1', 'pattern2'], insights: 'analysis complete' }, - - // Memory tools - memory_usage: { - action: params.action, - key: params.key, - success: true, - result: params.action === 'retrieve' ? 'sample_value' : 'stored', - }, - memory_backup: { backupId: 'backup_' + Date.now(), size: '1.2MB', success: true }, - memory_analytics: { entries: 42, size: '156KB', namespaces: 4 }, - - // Monitoring tools - performance_report: { - cpu: 45, - memory: 67, - uptime: 3600, - efficiency: 92, - bottlenecks: ['network_io', 'memory_allocation'], - }, - bottleneck_analyze: { - component: params.component, - issues: ['high_cpu_usage', 'memory_leaks'], - recommendations: ['optimize_queries', 'increase_cache'], - }, - - // Workflow tools - workflow_create: { workflowId: 'wf_' + Date.now(), status: 'created' }, - workflow_execute: { workflowId: params.workflowId, status: 'completed', duration: 1500 }, - task_orchestrate: { taskId: 'task_' + Date.now(), status: 'orchestrated', agents: 3 }, - - // GitHub tools - github_repo_analyze: { - repo: params.repo, - score: 85, - issues: 12, - complexity: 'medium', - recommendations: ['add_tests', 'update_dependencies'], - }, - - // DAA tools - daa_agent_create: { - agentId: 'agent_' + Date.now(), - type: params.agent_type, - status: 'created', - }, - daa_capability_match: { matches: ['agent1', 'agent2'], confidence: 0.89 }, - - // System tools - security_scan: { - target: params.target, - vulnerabilities: 2, - score: 'A-', - issues: ['outdated_dependencies', 'weak_encryption'], - }, - health_check: { status: 'healthy', components: { all: 'ok' }, uptime: 3600 }, - }; - - return mockResults[toolName] || { success: true, message: 'Mock execution completed' }; - } - - /** - * Get cache key for tool and params - */ - getCacheKey(toolName, params) { - return `${toolName}_${JSON.stringify(params)}`; - } - - /** - * Cache tool result - */ - cacheResult(cacheKey, result) { - this.cache.set(cacheKey, { - result, - timestamp: Date.now(), - ttl: 5 * 60 * 1000, // 5 minutes - }); - } - - /** - * Check if cache entry is expired - */ - isCacheExpired(cacheEntry) { - return Date.now() - cacheEntry.timestamp > cacheEntry.ttl; - } - - /** - * Setup tool execution handlers - */ - setupToolHandlers() { - this.eventBus.on('tool:execute', async (data) => { - try { - const result = await this.executeTool(data.tool, data.params); - this.eventBus.emit('tool:result', { tool: data.tool, result }); - } catch (error) { - this.eventBus.emit('tool:error', { tool: data.tool, error }); - } - }); - } - - /** - * Initialize caching system - */ - initializeCache() { - // Clean expired cache entries every 5 minutes - setInterval( - () => { - for (const [key, entry] of this.cache.entries()) { - if (this.isCacheExpired(entry)) { - this.cache.delete(key); - } - } - }, - 5 * 60 * 1000, - ); - } - - /** - * Get all available tools - */ - getAvailableTools() { - return Array.from(this.mcpTools.values()); - } - - /** - * Get tools by category - */ - getToolsByCategory(category) { - return this.toolCategories[category] || []; - } - - /** - * Get tool usage statistics - */ - getToolUsageStats() { - const stats = {}; - for (const [name, tool] of this.mcpTools) { - stats[name] = { - usageCount: tool.usageCount, - lastUsed: tool.lastUsed, - category: tool.category, - }; - } - return stats; - } - - /** - * Get system status - */ - async getSystemStatus() { - return { - mcpServerStatus: this.mcpServerStatus, - toolsAvailable: this.mcpTools.size, - activeExecutions: this.activeExecutions.size, - cacheSize: this.cache.size, - isInitialized: this.isInitialized, - }; - } - - /** - * Get system uptime - */ - async getSystemUptime() { - if (typeof process !== 'undefined') { - return process.uptime(); - } - return Date.now() - (window.claudeFlowStartTime || Date.now()); - } - - /** - * Get active tools - */ - async getActiveTools() { - return Array.from(this.activeExecutions.keys()); - } - - /** - * Get memory usage - */ - async getMemoryUsage() { - if (typeof process !== 'undefined') { - const usage = process.memoryUsage(); - return { - used: usage.heapUsed, - total: usage.heapTotal, - external: usage.external, - }; - } - return { used: 0, total: 0, external: 0 }; - } - - /** - * Get swarm status - */ - async getSwarmStatus() { - try { - const result = await this.executeTool('swarm_status'); - return result; - } catch (error) { - return { status: 'offline', error: error.message }; - } - } - - /** - * Shutdown MCP integration - */ - async shutdown() { - // Cancel all active executions - this.activeExecutions.clear(); - - // Clear cache - this.cache.clear(); - - // Clear tool results - this.toolResults.clear(); - - this.eventBus.emit('mcp:shutdown'); - } -} - -export default MCPIntegrationLayer; diff --git a/src/ui/web-ui/core/StateManager.js b/src/ui/web-ui/core/StateManager.js deleted file mode 100644 index 066947f31c..0000000000 --- a/src/ui/web-ui/core/StateManager.js +++ /dev/null @@ -1,515 +0,0 @@ -/** - * StateManager - Global state persistence and management - * Handles UI state, user preferences, and data persistence - */ - -import { EventBus } from './EventBus.js'; - -export class StateManager { - constructor(eventBus) { - this.eventBus = eventBus; - this.state = new Map(); - this.preferences = new Map(); - this.toolResults = new Map(); - this.viewStates = new Map(); - this.sessionData = new Map(); - this.storageKey = 'claude-flow-ui-state'; - this.isInitialized = false; - this.autoSaveInterval = 30000; // 30 seconds - this.autoSaveTimer = null; - } - - /** - * Initialize state manager - */ - async initialize() { - try { - // Load persisted state - await this.loadPersistedState(); - - // Setup auto-save - this.setupAutoSave(); - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - this.eventBus.emit('state-manager:initialized'); - - console.log('๐Ÿ’พ State Manager initialized'); - } catch (error) { - console.error('โŒ Failed to initialize State Manager:', error); - throw error; - } - } - - /** - * Load persisted state from storage - */ - async loadPersistedState() { - try { - let persistedData = null; - - // Try to load from localStorage in browser - if (typeof window !== 'undefined' && window.localStorage) { - const stored = localStorage.getItem(this.storageKey); - if (stored) { - persistedData = JSON.parse(stored); - } - } - - // Try to load from file system in Node.js - if (!persistedData && typeof process !== 'undefined') { - try { - const fs = await import('fs'); - const path = await import('path'); - const stateFile = path.join(process.cwd(), '.claude-flow-state.json'); - - if (fs.existsSync(stateFile)) { - const data = fs.readFileSync(stateFile, 'utf8'); - persistedData = JSON.parse(data); - } - } catch (error) { - console.warn('Could not load state from file system:', error.message); - } - } - - if (persistedData) { - this.restoreFromData(persistedData); - console.log('๐Ÿ’พ Loaded persisted state'); - } else { - this.initializeDefaultState(); - } - } catch (error) { - console.warn('Could not load persisted state:', error); - this.initializeDefaultState(); - } - } - - /** - * Restore state from persisted data - */ - restoreFromData(data) { - if (data.preferences) { - this.preferences = new Map(Object.entries(data.preferences)); - } - - if (data.viewStates) { - this.viewStates = new Map(Object.entries(data.viewStates)); - } - - if (data.toolResults) { - this.toolResults = new Map(Object.entries(data.toolResults)); - } - - if (data.sessionData) { - this.sessionData = new Map(Object.entries(data.sessionData)); - } - - if (data.state) { - this.state = new Map(Object.entries(data.state)); - } - } - - /** - * Initialize default state - */ - initializeDefaultState() { - this.preferences.set('theme', 'dark'); - this.preferences.set('autoSave', true); - this.preferences.set('showTooltips', true); - this.preferences.set('animationSpeed', 'normal'); - this.preferences.set('defaultView', 'overview'); - this.preferences.set('keyboardShortcuts', true); - this.preferences.set('realTimeUpdates', true); - this.preferences.set('logLevel', 'info'); - - this.state.set('initialized', true); - this.state.set('version', '2.0.0'); - this.state.set('installDate', Date.now()); - - console.log('๐Ÿ’พ Initialized default state'); - } - - /** - * Setup auto-save functionality - */ - setupAutoSave() { - if (!this.getPreference('autoSave', true)) { - return; - } - - this.autoSaveTimer = setInterval(() => { - this.persistState(); - }, this.autoSaveInterval); - } - - /** - * Persist current state - */ - async persistState() { - try { - const stateData = { - timestamp: Date.now(), - version: '2.0.0', - preferences: Object.fromEntries(this.preferences), - viewStates: Object.fromEntries(this.viewStates), - toolResults: Object.fromEntries(this.toolResults), - sessionData: Object.fromEntries(this.sessionData), - state: Object.fromEntries(this.state), - }; - - // Save to localStorage in browser - if (typeof window !== 'undefined' && window.localStorage) { - localStorage.setItem(this.storageKey, JSON.stringify(stateData)); - } - - // Save to file system in Node.js - if (typeof process !== 'undefined') { - try { - const fs = await import('fs'); - const path = await import('path'); - const stateFile = path.join(process.cwd(), '.claude-flow-state.json'); - - fs.writeFileSync(stateFile, JSON.stringify(stateData, null, 2)); - } catch (error) { - console.warn('Could not save state to file system:', error.message); - } - } - - this.eventBus.emit('state:persisted', { timestamp: Date.now() }); - } catch (error) { - console.error('Failed to persist state:', error); - this.eventBus.emit('state:error', { error: error.message }); - } - } - - /** - * Get preference value - */ - getPreference(key, defaultValue = null) { - return this.preferences.get(key) ?? defaultValue; - } - - /** - * Set preference value - */ - setPreference(key, value) { - this.preferences.set(key, value); - this.eventBus.emit('preference:changed', { key, value }); - - // Auto-save if enabled - if (this.getPreference('autoSave', true)) { - this.debouncedSave(); - } - } - - /** - * Get multiple preferences - */ - getPreferences(keys) { - const result = {}; - for (const key of keys) { - result[key] = this.preferences.get(key); - } - return result; - } - - /** - * Set multiple preferences - */ - setPreferences(preferences) { - for (const [key, value] of Object.entries(preferences)) { - this.preferences.set(key, value); - } - - this.eventBus.emit('preferences:changed', preferences); - - if (this.getPreference('autoSave', true)) { - this.debouncedSave(); - } - } - - /** - * Get all user preferences - */ - getUserPreferences() { - return Object.fromEntries(this.preferences); - } - - /** - * Get state value - */ - getState(key, defaultValue = null) { - return this.state.get(key) ?? defaultValue; - } - - /** - * Set state value - */ - setState(key, value) { - this.state.set(key, value); - this.eventBus.emit('state:changed', { key, value }); - - if (this.getPreference('autoSave', true)) { - this.debouncedSave(); - } - } - - /** - * Get view state - */ - getViewState(viewId) { - return this.viewStates.get(viewId); - } - - /** - * Set view state - */ - setViewState(viewId, state) { - const existing = this.viewStates.get(viewId) || {}; - const newState = { ...existing, ...state, lastUpdate: Date.now() }; - - this.viewStates.set(viewId, newState); - this.eventBus.emit('view-state:changed', { viewId, state: newState }); - - if (this.getPreference('autoSave', true)) { - this.debouncedSave(); - } - } - - /** - * Clear view state - */ - clearViewState(viewId) { - this.viewStates.delete(viewId); - this.eventBus.emit('view-state:cleared', { viewId }); - } - - /** - * Get tool result - */ - getToolResult(toolName) { - return this.toolResults.get(toolName); - } - - /** - * Set tool result - */ - setToolResult(toolName, result) { - const resultData = { - result, - timestamp: Date.now(), - tool: toolName, - }; - - this.toolResults.set(toolName, resultData); - this.eventBus.emit('tool-result:stored', { toolName, result }); - - // Keep only last 100 results to manage memory - if (this.toolResults.size > 100) { - const entries = Array.from(this.toolResults.entries()); - entries.sort((a, b) => b[1].timestamp - a[1].timestamp); - - this.toolResults.clear(); - for (const [key, value] of entries.slice(0, 100)) { - this.toolResults.set(key, value); - } - } - - if (this.getPreference('autoSave', true)) { - this.debouncedSave(); - } - } - - /** - * Get recent tool results - */ - getRecentToolResults(limit = 10) { - const results = Array.from(this.toolResults.entries()) - .sort((a, b) => b[1].timestamp - a[1].timestamp) - .slice(0, limit); - - return results.map(([tool, data]) => ({ - tool, - ...data, - })); - } - - /** - * Get session data - */ - getSessionData(key) { - return this.sessionData.get(key); - } - - /** - * Set session data - */ - setSessionData(key, value) { - this.sessionData.set(key, value); - this.eventBus.emit('session-data:changed', { key, value }); - } - - /** - * Clear session data - */ - clearSessionData() { - this.sessionData.clear(); - this.eventBus.emit('session-data:cleared'); - } - - /** - * Export state data - */ - exportState() { - return { - timestamp: Date.now(), - version: '2.0.0', - preferences: Object.fromEntries(this.preferences), - viewStates: Object.fromEntries(this.viewStates), - toolResults: Object.fromEntries(this.toolResults), - sessionData: Object.fromEntries(this.sessionData), - state: Object.fromEntries(this.state), - }; - } - - /** - * Import state data - */ - importState(stateData) { - try { - this.restoreFromData(stateData); - this.eventBus.emit('state:imported', { timestamp: Date.now() }); - console.log('๐Ÿ’พ State imported successfully'); - } catch (error) { - console.error('Failed to import state:', error); - throw error; - } - } - - /** - * Reset to default state - */ - resetState() { - this.state.clear(); - this.preferences.clear(); - this.viewStates.clear(); - this.toolResults.clear(); - this.sessionData.clear(); - - this.initializeDefaultState(); - this.persistState(); - - this.eventBus.emit('state:reset', { timestamp: Date.now() }); - console.log('๐Ÿ’พ State reset to defaults'); - } - - /** - * Clear specific data types - */ - clearData(types = []) { - if (types.includes('preferences') || types.length === 0) { - this.preferences.clear(); - } - - if (types.includes('viewStates') || types.length === 0) { - this.viewStates.clear(); - } - - if (types.includes('toolResults') || types.length === 0) { - this.toolResults.clear(); - } - - if (types.includes('sessionData') || types.length === 0) { - this.sessionData.clear(); - } - - this.eventBus.emit('data:cleared', { types, timestamp: Date.now() }); - } - - /** - * Get state statistics - */ - getStateStats() { - return { - preferences: this.preferences.size, - viewStates: this.viewStates.size, - toolResults: this.toolResults.size, - sessionData: this.sessionData.size, - generalState: this.state.size, - lastSave: this.state.get('lastSave'), - autoSaveEnabled: this.getPreference('autoSave', true), - }; - } - - /** - * Setup debounced save to avoid excessive writes - */ - debouncedSave() { - if (this.saveTimeout) { - clearTimeout(this.saveTimeout); - } - - this.saveTimeout = setTimeout(() => { - this.persistState(); - }, 1000); // Save after 1 second of inactivity - } - - /** - * Persist all state immediately - */ - async persistAllState() { - if (this.saveTimeout) { - clearTimeout(this.saveTimeout); - } - - await this.persistState(); - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - // Listen for shutdown events - this.eventBus.on('ui:shutdown', async () => { - await this.persistAllState(); - }); - - // Listen for preference changes from UI - this.eventBus.on('ui:preference:set', (data) => { - this.setPreference(data.key, data.value); - }); - - // Listen for state changes from UI - this.eventBus.on('ui:state:set', (data) => { - this.setState(data.key, data.value); - }); - - // Listen for tool results - this.eventBus.on('tool:executed', (data) => { - this.setToolResult(data.tool, data.result); - }); - } - - /** - * Cleanup and shutdown - */ - async shutdown() { - // Clear auto-save timer - if (this.autoSaveTimer) { - clearInterval(this.autoSaveTimer); - } - - if (this.saveTimeout) { - clearTimeout(this.saveTimeout); - } - - // Final save - await this.persistAllState(); - - this.eventBus.emit('state-manager:shutdown'); - } -} - -export default StateManager; diff --git a/src/ui/web-ui/core/UIManager.js b/src/ui/web-ui/core/UIManager.js deleted file mode 100644 index 87b8a77f8d..0000000000 --- a/src/ui/web-ui/core/UIManager.js +++ /dev/null @@ -1,540 +0,0 @@ -/** - * UIManager - Central UI Controller for Claude Flow Web UI - * Coordinates all views, handles navigation, and manages global state - */ - -import { EventBus } from './EventBus.js'; -import { MCPIntegrationLayer } from './MCPIntegrationLayer.js'; -import { ViewManager } from './ViewManager.js'; -import { StateManager } from './StateManager.js'; -import { ComponentLibrary } from '../components/ComponentLibrary.js'; - -// View category definitions -export const VIEW_CATEGORIES = { - OVERVIEW: 'overview', - PROCESSES: 'processes', - NEURAL: 'neural', - MEMORY: 'memory', - MONITORING: 'monitoring', - WORKFLOW: 'workflow', - GITHUB: 'github', - DAA: 'daa', - SYSTEM: 'system', - CLI: 'cli', - HELP: 'help', -}; - -// MCP Tool Categories mapping -export const MCP_TOOL_CATEGORIES = { - NEURAL: [ - 'neural_train', - 'neural_predict', - 'neural_status', - 'neural_patterns', - 'model_load', - 'model_save', - 'pattern_recognize', - 'cognitive_analyze', - 'learning_adapt', - 'neural_compress', - 'ensemble_create', - 'transfer_learn', - 'neural_explain', - 'wasm_optimize', - 'inference_run', - ], - MEMORY: [ - 'memory_usage', - 'memory_backup', - 'memory_restore', - 'memory_compress', - 'memory_sync', - 'cache_manage', - 'state_snapshot', - 'context_restore', - 'memory_analytics', - 'memory_persist', - 'memory_namespace', - ], - MONITORING: [ - 'performance_report', - 'bottleneck_analyze', - 'token_usage', - 'benchmark_run', - 'metrics_collect', - 'trend_analysis', - 'cost_analysis', - 'quality_assess', - 'error_analysis', - 'usage_stats', - 'health_check', - 'swarm_monitor', - 'agent_metrics', - ], - WORKFLOW: [ - 'workflow_create', - 'workflow_execute', - 'automation_setup', - 'pipeline_create', - 'scheduler_manage', - 'trigger_setup', - 'workflow_template', - 'batch_process', - 'parallel_execute', - 'sparc_mode', - 'task_orchestrate', - ], - GITHUB: [ - 'github_repo_analyze', - 'github_pr_manage', - 'github_issue_track', - 'github_release_coord', - 'github_workflow_auto', - 'github_code_review', - 'github_sync_coord', - 'github_metrics', - ], - DAA: [ - 'daa_agent_create', - 'daa_capability_match', - 'daa_resource_alloc', - 'daa_lifecycle_manage', - 'daa_communication', - 'daa_consensus', - 'daa_fault_tolerance', - 'daa_optimization', - ], - SYSTEM: [ - 'security_scan', - 'backup_create', - 'restore_system', - 'log_analysis', - 'diagnostic_run', - 'config_manage', - 'features_detect', - 'terminal_execute', - ], -}; - -export class UIManager { - constructor() { - this.eventBus = new EventBus(); - this.mcpIntegration = new MCPIntegrationLayer(this.eventBus); - this.viewManager = new ViewManager(this.eventBus); - this.stateManager = new StateManager(this.eventBus); - this.componentLibrary = new ComponentLibrary(); - - this.currentView = VIEW_CATEGORIES.OVERVIEW; - this.viewHistory = []; - this.shortcuts = new Map(); - this.theme = 'dark'; - this.isResponsive = true; - - this.initializeEventHandlers(); - this.setupKeyboardShortcuts(); - } - - /** - * Initialize the complete UI system - */ - async initialize() { - try { - // Initialize core systems - await this.stateManager.initialize(); - await this.mcpIntegration.initialize(); - await this.viewManager.initialize(); - - // Load user preferences - await this.loadUserPreferences(); - - // Register all views - await this.registerAllViews(); - - // Set up real-time updates - this.setupRealTimeUpdates(); - - // Initialize component library - this.componentLibrary.initialize(); - - this.eventBus.emit('ui:initialized'); - console.log('๐ŸŽจ UI Manager initialized successfully'); - } catch (error) { - console.error('โŒ Failed to initialize UI Manager:', error); - throw error; - } - } - - /** - * Register all available views - */ - async registerAllViews() { - const viewConfigs = [ - { - id: VIEW_CATEGORIES.OVERVIEW, - name: 'Overview', - icon: '๐Ÿ ', - description: 'System overview and quick actions', - component: 'OverviewView', - shortcut: '1', - }, - { - id: VIEW_CATEGORIES.PROCESSES, - name: 'Processes', - icon: 'โš™๏ธ', - description: 'Process management and monitoring', - component: 'ProcessView', - shortcut: '2', - }, - { - id: VIEW_CATEGORIES.NEURAL, - name: 'Neural Network', - icon: '๐Ÿง ', - description: 'AI model training and neural operations', - component: 'NeuralNetworkView', - shortcut: '3', - toolCount: MCP_TOOL_CATEGORIES.NEURAL.length, - }, - { - id: VIEW_CATEGORIES.MEMORY, - name: 'Memory Bank', - icon: '๐Ÿ’พ', - description: 'Memory management and persistence', - component: 'MemoryManagementView', - shortcut: '4', - toolCount: MCP_TOOL_CATEGORIES.MEMORY.length, - }, - { - id: VIEW_CATEGORIES.MONITORING, - name: 'Monitoring', - icon: '๐Ÿ“Š', - description: 'Performance monitoring and analysis', - component: 'MonitoringView', - shortcut: '5', - toolCount: MCP_TOOL_CATEGORIES.MONITORING.length, - }, - { - id: VIEW_CATEGORIES.WORKFLOW, - name: 'Workflows', - icon: '๐Ÿ”„', - description: 'Automation and workflow management', - component: 'WorkflowAutomationView', - shortcut: '6', - toolCount: MCP_TOOL_CATEGORIES.WORKFLOW.length, - }, - { - id: VIEW_CATEGORIES.GITHUB, - name: 'GitHub', - icon: '๐Ÿ™', - description: 'GitHub integration and operations', - component: 'GitHubIntegrationView', - shortcut: '7', - toolCount: MCP_TOOL_CATEGORIES.GITHUB.length, - }, - { - id: VIEW_CATEGORIES.DAA, - name: 'Dynamic Agents', - icon: '๐Ÿค–', - description: 'Dynamic agent architecture', - component: 'DAAView', - shortcut: '8', - toolCount: MCP_TOOL_CATEGORIES.DAA.length, - }, - { - id: VIEW_CATEGORIES.SYSTEM, - name: 'System', - icon: '๐Ÿ› ๏ธ', - description: 'System utilities and diagnostics', - component: 'SystemUtilitiesView', - shortcut: '9', - toolCount: MCP_TOOL_CATEGORIES.SYSTEM.length, - }, - { - id: VIEW_CATEGORIES.CLI, - name: 'CLI Bridge', - icon: 'โŒจ๏ธ', - description: 'Command-line interface bridge', - component: 'CLICommandView', - shortcut: '0', - }, - { - id: VIEW_CATEGORIES.HELP, - name: 'Help', - icon: 'โ“', - description: 'Documentation and help', - component: 'HelpView', - shortcut: '?', - }, - ]; - - for (const config of viewConfigs) { - await this.viewManager.registerView(config); - } - } - - /** - * Navigate to a specific view - */ - async navigateToView(viewId, params = {}) { - if (!this.viewManager.hasView(viewId)) { - throw new Error(`View not found: ${viewId}`); - } - - // Store current view in history - if (this.currentView && this.currentView !== viewId) { - this.viewHistory.push({ - viewId: this.currentView, - timestamp: Date.now(), - params: this.stateManager.getViewState(this.currentView), - }); - } - - // Update current view - this.currentView = viewId; - - // Load view with parameters - await this.viewManager.loadView(viewId, params); - - // Update browser history if available - if (typeof window !== 'undefined' && window.history) { - window.history.pushState({ viewId, params }, '', `#${viewId}`); - } - - // Update state - await this.stateManager.setViewState(viewId, params); - - // Emit navigation event - this.eventBus.emit('ui:navigation', { viewId, params }); - } - - /** - * Go back to previous view - */ - async goBack() { - if (this.viewHistory.length === 0) return; - - const previousView = this.viewHistory.pop(); - await this.navigateToView(previousView.viewId, previousView.params); - } - - /** - * Execute MCP tool with UI integration - */ - async executeMCPTool(toolName, params = {}) { - try { - // Show loading indicator - this.eventBus.emit('ui:loading', { tool: toolName, params }); - - // Execute tool through MCP integration layer - const result = await this.mcpIntegration.executeTool(toolName, params); - - // Handle result based on tool type - await this.handleToolResult(toolName, result, params); - - // Hide loading indicator - this.eventBus.emit('ui:loading:complete', { tool: toolName, result }); - - return result; - } catch (error) { - this.eventBus.emit('ui:error', { tool: toolName, error, params }); - throw error; - } - } - - /** - * Handle tool execution results - */ - async handleToolResult(toolName, result, originalParams) { - // Update relevant views with new data - const category = this.getToolCategory(toolName); - - if (category) { - this.eventBus.emit(`view:${category}:update`, { - tool: toolName, - result, - params: originalParams, - }); - } - - // Store result in state for persistence - await this.stateManager.setToolResult(toolName, result); - - // Log execution - this.eventBus.emit('ui:log', { - level: 'info', - message: `Executed ${toolName}`, - data: { result, params: originalParams }, - }); - } - - /** - * Get tool category for a given tool name - */ - getToolCategory(toolName) { - for (const [category, tools] of Object.entries(MCP_TOOL_CATEGORIES)) { - if (tools.includes(toolName)) { - return category.toLowerCase(); - } - } - return null; - } - - /** - * Setup keyboard shortcuts - */ - setupKeyboardShortcuts() { - // View navigation shortcuts - Object.values(VIEW_CATEGORIES).forEach((viewId, index) => { - const key = (index + 1).toString(); - this.shortcuts.set(key, () => this.navigateToView(viewId)); - }); - - // Global shortcuts - this.shortcuts.set('ctrl+k', () => this.showCommandPalette()); - this.shortcuts.set('ctrl+/', () => this.navigateToView(VIEW_CATEGORIES.HELP)); - this.shortcuts.set('ctrl+1', () => this.navigateToView(VIEW_CATEGORIES.OVERVIEW)); - this.shortcuts.set('escape', () => this.hideAllOverlays()); - this.shortcuts.set('ctrl+shift+p', () => this.showCommandPalette()); - this.shortcuts.set('ctrl+b', () => this.goBack()); - this.shortcuts.set('ctrl+r', () => this.refreshCurrentView()); - this.shortcuts.set('ctrl+t', () => this.toggleTheme()); - - // Setup event listener for keyboard events - if (typeof window !== 'undefined') { - window.addEventListener('keydown', (event) => { - const key = this.getKeyString(event); - const handler = this.shortcuts.get(key); - if (handler) { - event.preventDefault(); - handler(); - } - }); - } - } - - /** - * Get key string from keyboard event - */ - getKeyString(event) { - const parts = []; - if (event.ctrlKey) parts.push('ctrl'); - if (event.shiftKey) parts.push('shift'); - if (event.altKey) parts.push('alt'); - if (event.metaKey) parts.push('meta'); - - if (event.key.length === 1) { - parts.push(event.key.toLowerCase()); - } else { - parts.push(event.key.toLowerCase()); - } - - return parts.join('+'); - } - - /** - * Show command palette - */ - showCommandPalette() { - this.eventBus.emit('ui:command-palette:show'); - } - - /** - * Hide all overlays - */ - hideAllOverlays() { - this.eventBus.emit('ui:overlays:hide'); - } - - /** - * Refresh current view - */ - async refreshCurrentView() { - await this.viewManager.refreshView(this.currentView); - } - - /** - * Toggle theme - */ - toggleTheme() { - this.theme = this.theme === 'dark' ? 'light' : 'dark'; - this.eventBus.emit('ui:theme:changed', this.theme); - } - - /** - * Setup real-time updates - */ - setupRealTimeUpdates() { - // Update every 5 seconds for live data - setInterval(() => { - this.eventBus.emit('ui:real-time:update'); - }, 5000); - - // Setup MCP tool result streaming - this.mcpIntegration.on('tool:result', (result) => { - this.eventBus.emit('ui:real-time:tool-result', result); - }); - } - - /** - * Initialize event handlers - */ - initializeEventHandlers() { - // Handle tool execution requests - this.eventBus.on('tool:execute', async (data) => { - await this.executeMCPTool(data.tool, data.params); - }); - - // Handle view navigation requests - this.eventBus.on('view:navigate', async (data) => { - await this.navigateToView(data.viewId, data.params); - }); - - // Handle state persistence - this.eventBus.on('state:persist', async (data) => { - await this.stateManager.persistState(data); - }); - - // Handle errors - this.eventBus.on('ui:error', (error) => { - console.error('UI Error:', error); - // Could show error toast/notification here - }); - } - - /** - * Load user preferences - */ - async loadUserPreferences() { - const preferences = await this.stateManager.getUserPreferences(); - if (preferences) { - this.theme = preferences.theme || 'dark'; - this.isResponsive = preferences.responsive !== false; - } - } - - /** - * Get system status for overview - */ - async getSystemStatus() { - const status = { - uptime: await this.mcpIntegration.getSystemUptime(), - activeTools: await this.mcpIntegration.getActiveTools(), - memoryUsage: await this.mcpIntegration.getMemoryUsage(), - swarmStatus: await this.mcpIntegration.getSwarmStatus(), - toolsAvailable: Object.values(MCP_TOOL_CATEGORIES).flat().length, - viewsRegistered: this.viewManager.getViewCount(), - }; - - return status; - } - - /** - * Shutdown UI Manager - */ - async shutdown() { - await this.stateManager.persistAllState(); - await this.mcpIntegration.shutdown(); - this.eventBus.emit('ui:shutdown'); - } -} - -export default UIManager; diff --git a/src/ui/web-ui/core/ViewManager.js b/src/ui/web-ui/core/ViewManager.js deleted file mode 100644 index d81f639ebd..0000000000 --- a/src/ui/web-ui/core/ViewManager.js +++ /dev/null @@ -1,617 +0,0 @@ -/** - * ViewManager - Dynamic view loading and state management - * Handles all UI views, transitions, and state persistence - */ - -import { EventBus } from './EventBus.js'; - -export class ViewManager { - constructor(eventBus) { - this.eventBus = eventBus; - this.registeredViews = new Map(); - this.loadedViews = new Map(); - this.currentView = null; - this.viewStack = []; - this.viewStates = new Map(); - this.isInitialized = false; - this.containerElement = null; - this.transitionDuration = 300; - } - - /** - * Initialize view manager - */ - async initialize() { - try { - // Create main view container if in browser - if (typeof document !== 'undefined') { - this.setupDOMContainer(); - } - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - this.eventBus.emit('view-manager:initialized'); - - console.log('๐Ÿ–ผ๏ธ View Manager initialized'); - } catch (error) { - console.error('โŒ Failed to initialize View Manager:', error); - throw error; - } - } - - /** - * Setup DOM container for web environment - */ - setupDOMContainer() { - // Create main container - this.containerElement = - document.getElementById('claude-flow-ui') || document.createElement('div'); - - if (!this.containerElement.id) { - this.containerElement.id = 'claude-flow-ui'; - this.containerElement.className = 'claude-flow-main-container'; - document.body.appendChild(this.containerElement); - } - - // Add CSS for transitions - this.addTransitionStyles(); - } - - /** - * Add CSS styles for view transitions - */ - addTransitionStyles() { - if (document.getElementById('claude-flow-styles')) return; - - const styles = document.createElement('style'); - styles.id = 'claude-flow-styles'; - styles.textContent = ` - .claude-flow-main-container { - width: 100%; - height: 100vh; - overflow: hidden; - position: relative; - font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; - background: #1a1a1a; - color: #ffffff; - } - - .claude-flow-view { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - opacity: 1; - transform: translateX(0); - transition: all ${this.transitionDuration}ms ease-in-out; - overflow-y: auto; - padding: 20px; - box-sizing: border-box; - } - - .claude-flow-view.entering { - opacity: 0; - transform: translateX(50px); - } - - .claude-flow-view.exiting { - opacity: 0; - transform: translateX(-50px); - } - - .claude-flow-view.hidden { - display: none; - } - - .claude-flow-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 20px; - padding-bottom: 10px; - border-bottom: 1px solid #333; - } - - .claude-flow-title { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .claude-flow-breadcrumb { - font-size: 14px; - color: #888; - } - - .claude-flow-content { - flex: 1; - overflow-y: auto; - } - - .claude-flow-loading { - display: flex; - justify-content: center; - align-items: center; - height: 200px; - font-size: 18px; - color: #888; - } - - .claude-flow-error { - background: #ff4444; - color: white; - padding: 15px; - border-radius: 5px; - margin: 10px 0; - } - - /* Responsive design */ - @media (max-width: 768px) { - .claude-flow-main-container { - padding: 10px; - } - - .claude-flow-view { - padding: 10px; - } - - .claude-flow-title { - font-size: 20px; - } - } - `; - - document.head.appendChild(styles); - } - - /** - * Register a view configuration - */ - async registerView(viewConfig) { - if (!viewConfig.id || !viewConfig.component) { - throw new Error('View config must have id and component'); - } - - const config = { - id: viewConfig.id, - name: viewConfig.name || viewConfig.id, - icon: viewConfig.icon || '๐Ÿ“„', - description: viewConfig.description || '', - component: viewConfig.component, - shortcut: viewConfig.shortcut, - toolCount: viewConfig.toolCount || 0, - lazy: viewConfig.lazy !== false, // Default to lazy loading - preload: viewConfig.preload || false, - permissions: viewConfig.permissions || [], - dependencies: viewConfig.dependencies || [], - metadata: viewConfig.metadata || {}, - }; - - this.registeredViews.set(viewConfig.id, config); - - // Preload if requested - if (config.preload) { - await this.preloadView(config.id); - } - - this.eventBus.emit('view:registered', { viewId: config.id, config }); - - console.log(`๐Ÿ–ผ๏ธ Registered view: ${config.name} (${config.id})`); - } - - /** - * Load and display a view - */ - async loadView(viewId, params = {}) { - if (!this.isInitialized) { - throw new Error('ViewManager not initialized'); - } - - const viewConfig = this.registeredViews.get(viewId); - if (!viewConfig) { - throw new Error(`View not registered: ${viewId}`); - } - - try { - this.eventBus.emit('view:loading', { viewId, params }); - - // Check dependencies - await this.checkDependencies(viewConfig); - - // Load view component if not already loaded - if (!this.loadedViews.has(viewId)) { - await this.loadViewComponent(viewId, viewConfig); - } - - // Hide current view with transition - if (this.currentView && this.currentView !== viewId) { - await this.hideCurrentView(); - } - - // Show new view - await this.showView(viewId, params); - - // Update state - this.currentView = viewId; - this.viewStates.set(viewId, { - params, - loadTime: Date.now(), - lastAccess: Date.now(), - }); - - this.eventBus.emit('view:loaded', { viewId, params }); - - console.log(`๐Ÿ–ผ๏ธ Loaded view: ${viewConfig.name}`); - } catch (error) { - this.eventBus.emit('view:error', { viewId, error: error.message, params }); - throw error; - } - } - - /** - * Load view component - */ - async loadViewComponent(viewId, viewConfig) { - try { - let ViewComponent; - - // Check if we're in a browser environment - if (typeof document !== 'undefined') { - // Browser environment - create DOM-based view - ViewComponent = await this.createDOMView(viewId, viewConfig); - } else { - // Node.js environment - create terminal-based view - ViewComponent = await this.createTerminalView(viewId, viewConfig); - } - - this.loadedViews.set(viewId, { - component: ViewComponent, - config: viewConfig, - element: ViewComponent.element || null, - instance: ViewComponent.instance || null, - loadTime: Date.now(), - }); - } catch (error) { - console.error(`โŒ Failed to load view component ${viewId}:`, error); - throw error; - } - } - - /** - * Create DOM-based view for browser - */ - async createDOMView(viewId, viewConfig) { - const element = document.createElement('div'); - element.className = 'claude-flow-view hidden'; - element.id = `view-${viewId}`; - - // Create view header - const header = document.createElement('div'); - header.className = 'claude-flow-header'; - - const titleSection = document.createElement('div'); - const title = document.createElement('h1'); - title.className = 'claude-flow-title'; - title.textContent = `${viewConfig.icon} ${viewConfig.name}`; - - const breadcrumb = document.createElement('div'); - breadcrumb.className = 'claude-flow-breadcrumb'; - breadcrumb.textContent = viewConfig.description; - - titleSection.appendChild(title); - titleSection.appendChild(breadcrumb); - header.appendChild(titleSection); - - // Create view content - const content = document.createElement('div'); - content.className = 'claude-flow-content'; - content.id = `content-${viewId}`; - - element.appendChild(header); - element.appendChild(content); - this.containerElement.appendChild(element); - - // Create view instance based on component type - let instance; - try { - // Try to dynamically import the view component - const module = await this.importViewComponent(viewConfig.component); - instance = new module.default(content, this.eventBus, viewConfig); - } catch (error) { - // Fallback to basic view - instance = this.createBasicView(content, viewConfig); - } - - return { - element, - instance, - render: (params) => instance.render(params), - destroy: () => instance.destroy?.(), - }; - } - - /** - * Create terminal-based view for Node.js - */ - async createTerminalView(viewId, viewConfig) { - // For terminal environment, create a text-based view - let instance; - try { - const module = await this.importViewComponent(viewConfig.component); - instance = new module.default(null, this.eventBus, viewConfig); - } catch (error) { - instance = this.createBasicTerminalView(viewConfig); - } - - return { - element: null, - instance, - render: (params) => instance.render(params), - destroy: () => instance.destroy?.(), - }; - } - - /** - * Import view component dynamically - */ - async importViewComponent(componentName) { - try { - // Try to import from views directory - return await import(`../views/${componentName}.js`); - } catch (error) { - console.warn(`Could not import ${componentName}, using fallback`); - throw error; - } - } - - /** - * Create basic fallback view for browser - */ - createBasicView(container, viewConfig) { - return { - render: (params) => { - container.innerHTML = ` -
-
-

${viewConfig.name}

-

${viewConfig.description}

-

This view is under development.

- ${viewConfig.toolCount ? `

Will support ${viewConfig.toolCount} tools.

` : ''} -
${JSON.stringify(params, null, 2)}
-
-
- `; - }, - destroy: () => { - container.innerHTML = ''; - }, - }; - } - - /** - * Create basic fallback view for terminal - */ - createBasicTerminalView(viewConfig) { - return { - render: (params) => { - console.log(`\n๐Ÿ“„ ${viewConfig.name}`); - console.log(` ${viewConfig.description}`); - if (viewConfig.toolCount) { - console.log(` Tools: ${viewConfig.toolCount}`); - } - console.log(` Params:`, params); - console.log(` [This view is under development]\n`); - }, - destroy: () => {}, - }; - } - - /** - * Show view with transition - */ - async showView(viewId, params) { - const loadedView = this.loadedViews.get(viewId); - if (!loadedView) { - throw new Error(`View not loaded: ${viewId}`); - } - - // Render view with parameters - await loadedView.component.render(params); - - if (loadedView.element) { - // Browser environment - handle DOM transitions - loadedView.element.classList.remove('hidden'); - loadedView.element.classList.add('entering'); - - // Remove transition class after animation - setTimeout(() => { - if (loadedView.element) { - loadedView.element.classList.remove('entering'); - } - }, this.transitionDuration); - } - - this.eventBus.emit('view:shown', { viewId, params }); - } - - /** - * Hide current view with transition - */ - async hideCurrentView() { - if (!this.currentView) return; - - const loadedView = this.loadedViews.get(this.currentView); - if (loadedView?.element) { - loadedView.element.classList.add('exiting'); - - // Hide after transition - setTimeout(() => { - if (loadedView.element) { - loadedView.element.classList.remove('exiting'); - loadedView.element.classList.add('hidden'); - } - }, this.transitionDuration); - } - - this.eventBus.emit('view:hidden', { viewId: this.currentView }); - } - - /** - * Refresh current view - */ - async refreshView(viewId) { - const viewState = this.viewStates.get(viewId); - if (viewState) { - await this.loadView(viewId, viewState.params); - } - } - - /** - * Preload a view - */ - async preloadView(viewId) { - const viewConfig = this.registeredViews.get(viewId); - if (!viewConfig || this.loadedViews.has(viewId)) { - return; - } - - await this.loadViewComponent(viewId, viewConfig); - console.log(`๐Ÿ”„ Preloaded view: ${viewConfig.name}`); - } - - /** - * Check view dependencies - */ - async checkDependencies(viewConfig) { - if (!viewConfig.dependencies || viewConfig.dependencies.length === 0) { - return; - } - - for (const dependency of viewConfig.dependencies) { - if (!this.loadedViews.has(dependency)) { - await this.preloadView(dependency); - } - } - } - - /** - * Unload a view - */ - async unloadView(viewId) { - const loadedView = this.loadedViews.get(viewId); - if (!loadedView) return; - - // Call destroy method if available - if (loadedView.component.destroy) { - await loadedView.component.destroy(); - } - - // Remove DOM element - if (loadedView.element) { - loadedView.element.remove(); - } - - // Remove from loaded views - this.loadedViews.delete(viewId); - - // Clear state - this.viewStates.delete(viewId); - - this.eventBus.emit('view:unloaded', { viewId }); - console.log(`๐Ÿ—‘๏ธ Unloaded view: ${viewId}`); - } - - /** - * Get view configuration - */ - getViewConfig(viewId) { - return this.registeredViews.get(viewId); - } - - /** - * Get all registered views - */ - getAllViews() { - return Array.from(this.registeredViews.values()); - } - - /** - * Get view count - */ - getViewCount() { - return this.registeredViews.size; - } - - /** - * Check if view exists - */ - hasView(viewId) { - return this.registeredViews.has(viewId); - } - - /** - * Get view state - */ - getViewState(viewId) { - return this.viewStates.get(viewId); - } - - /** - * Set view state - */ - setViewState(viewId, state) { - const existing = this.viewStates.get(viewId) || {}; - this.viewStates.set(viewId, { ...existing, ...state }); - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - this.eventBus.on('view:reload', async (data) => { - await this.refreshView(data.viewId); - }); - - this.eventBus.on('view:unload', async (data) => { - await this.unloadView(data.viewId); - }); - - this.eventBus.on('view:preload', async (data) => { - await this.preloadView(data.viewId); - }); - } - - /** - * Get memory usage statistics - */ - getMemoryStats() { - return { - registeredViews: this.registeredViews.size, - loadedViews: this.loadedViews.size, - viewStates: this.viewStates.size, - currentView: this.currentView, - }; - } - - /** - * Cleanup and shutdown - */ - async shutdown() { - // Unload all views - for (const viewId of this.loadedViews.keys()) { - await this.unloadView(viewId); - } - - // Clear all data - this.registeredViews.clear(); - this.viewStates.clear(); - this.currentView = null; - - this.eventBus.emit('view-manager:shutdown'); - } -} - -export default ViewManager; diff --git a/src/ui/web-ui/index.js b/src/ui/web-ui/index.js deleted file mode 100644 index c882d3552a..0000000000 --- a/src/ui/web-ui/index.js +++ /dev/null @@ -1,292 +0,0 @@ -/** - * Enhanced Web UI - Main Entry Point - * Modular UI architecture supporting 71+ MCP tools and CLI commands - */ - -// Core Architecture Components -export { UIManager, VIEW_CATEGORIES, MCP_TOOL_CATEGORIES } from './core/UIManager.js'; -export { MCPIntegrationLayer } from './core/MCPIntegrationLayer.js'; -export { EventBus } from './core/EventBus.js'; -export { ViewManager } from './core/ViewManager.js'; -export { StateManager } from './core/StateManager.js'; - -// Component Library -export { ComponentLibrary } from './components/ComponentLibrary.js'; - -// Views -export { default as NeuralNetworkView } from './views/NeuralNetworkView.js'; -export { default as GitHubIntegrationView } from './views/GitHubIntegrationView.js'; -export { default as WorkflowAutomationView } from './views/WorkflowAutomationView.js'; -export { default as DAAView } from './views/DAAView.js'; - -// Main UI Controllers -export { EnhancedWebUI } from './EnhancedWebUI.js'; -export { EnhancedProcessUI, launchEnhancedUI } from './EnhancedProcessUI.js'; - -/** - * Initialize Enhanced Web UI System - * @param {Object} options Configuration options - * @returns {Promise} Initialized UI system - */ -export async function initializeEnhancedUI(options = {}) { - const { - mode = 'auto', // 'full', 'enhanced', 'fallback', 'auto' - existingUI = null, - enableAllFeatures = true, - } = options; - - try { - if (mode === 'full' || (mode === 'auto' && typeof window !== 'undefined')) { - // Browser environment - full UI manager - const { UIManager } = await import('./core/UIManager.js'); - const uiManager = new UIManager(); - await uiManager.initialize(); - return uiManager; - } else if (mode === 'enhanced' || (mode === 'auto' && existingUI)) { - // Enhanced process UI - const { EnhancedWebUI } = await import('./EnhancedWebUI.js'); - const enhancedUI = new EnhancedWebUI(); - await enhancedUI.initialize(existingUI); - return enhancedUI; - } else { - // Terminal/fallback mode - const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js'); - const processUI = new EnhancedProcessUI(); - return processUI; - } - } catch (error) { - console.warn('Enhanced UI initialization failed, using fallback:', error); - - // Always provide fallback - const { EnhancedProcessUI } = await import('./EnhancedProcessUI.js'); - const processUI = new EnhancedProcessUI(); - return processUI; - } -} - -/** - * Launch Enhanced UI in terminal mode - */ -export async function launchTerminalUI() { - const { launchEnhancedUI } = await import('./EnhancedProcessUI.js'); - return launchEnhancedUI(); -} - -/** - * Tool Categories and Counts - */ -export const TOOL_CATEGORIES_INFO = { - neural: { - name: 'Neural Network Tools', - count: 15, - tools: [ - 'neural_train', - 'neural_predict', - 'neural_status', - 'neural_patterns', - 'model_load', - 'model_save', - 'pattern_recognize', - 'cognitive_analyze', - 'learning_adapt', - 'neural_compress', - 'ensemble_create', - 'transfer_learn', - 'neural_explain', - 'wasm_optimize', - 'inference_run', - ], - }, - memory: { - name: 'Memory & Persistence Tools', - count: 10, - tools: [ - 'memory_usage', - 'memory_backup', - 'memory_restore', - 'memory_compress', - 'memory_sync', - 'cache_manage', - 'state_snapshot', - 'context_restore', - 'memory_analytics', - 'memory_persist', - ], - }, - monitoring: { - name: 'Monitoring & Analysis Tools', - count: 13, - tools: [ - 'performance_report', - 'bottleneck_analyze', - 'token_usage', - 'benchmark_run', - 'metrics_collect', - 'trend_analysis', - 'cost_analysis', - 'quality_assess', - 'error_analysis', - 'usage_stats', - 'health_check', - 'swarm_monitor', - 'agent_metrics', - ], - }, - workflow: { - name: 'Workflow & Automation Tools', - count: 11, - tools: [ - 'workflow_create', - 'workflow_execute', - 'automation_setup', - 'pipeline_create', - 'scheduler_manage', - 'trigger_setup', - 'workflow_template', - 'batch_process', - 'parallel_execute', - 'sparc_mode', - 'task_orchestrate', - ], - }, - github: { - name: 'GitHub Integration Tools', - count: 8, - tools: [ - 'github_repo_analyze', - 'github_pr_manage', - 'github_issue_track', - 'github_release_coord', - 'github_workflow_auto', - 'github_code_review', - 'github_sync_coord', - 'github_metrics', - ], - }, - daa: { - name: 'Dynamic Agent Architecture Tools', - count: 8, - tools: [ - 'daa_agent_create', - 'daa_capability_match', - 'daa_resource_alloc', - 'daa_lifecycle_manage', - 'daa_communication', - 'daa_consensus', - 'daa_fault_tolerance', - 'daa_optimization', - ], - }, - system: { - name: 'System & Utilities Tools', - count: 6, - tools: [ - 'security_scan', - 'backup_create', - 'restore_system', - 'log_analysis', - 'diagnostic_run', - 'config_manage', - ], - }, - cli: { - name: 'CLI Command Bridge', - count: 9, - commands: [ - 'hive-mind', - 'github', - 'training', - 'analysis', - 'automation', - 'coordination', - 'hooks', - 'mcp', - 'config', - ], - }, -}; - -/** - * Get total tool count - */ -export function getTotalToolCount() { - return Object.values(TOOL_CATEGORIES_INFO).reduce((total, category) => { - return total + category.count; - }, 0); -} - -/** - * Get architecture information - */ -export function getArchitectureInfo() { - return { - version: '2.0.0', - totalTools: getTotalToolCount(), - categories: Object.keys(TOOL_CATEGORIES_INFO).length, - features: [ - 'Modular view system', - 'MCP tool integration', - 'Real-time updates', - 'State persistence', - 'Event-driven architecture', - 'Component library', - 'Responsive design', - 'Fallback modes', - 'Tool statistics', - 'Cross-platform support', - ], - compatibility: { - browser: true, - node: true, - terminal: true, - vscode: true, - }, - }; -} - -// Auto-initialization for browser environments -if (typeof window !== 'undefined') { - // Check if we should auto-initialize - window.claudeFlowEnhancedUI = { - initialize: initializeEnhancedUI, - launch: launchTerminalUI, - getInfo: getArchitectureInfo, - toolCategories: TOOL_CATEGORIES_INFO, - }; - - // Auto-enhance existing UI if present - window.addEventListener('DOMContentLoaded', async () => { - if (window.claudeFlowProcessUI && !window.claudeFlowEnhanced) { - try { - console.log('๐ŸŽจ Auto-enhancing existing process UI...'); - const enhancedUI = await initializeEnhancedUI({ - mode: 'enhanced', - existingUI: window.claudeFlowProcessUI, - }); - window.claudeFlowEnhanced = enhancedUI; - console.log('โœ… Enhanced UI auto-initialization complete'); - } catch (error) { - console.warn('Enhanced UI auto-initialization failed:', error); - } - } - }); -} - -// Export for Node.js environments -if (typeof module !== 'undefined' && module.exports) { - module.exports = { - initializeEnhancedUI, - launchTerminalUI, - getArchitectureInfo, - TOOL_CATEGORIES_INFO, - getTotalToolCount, - }; -} - -export default { - initializeEnhancedUI, - launchTerminalUI, - getArchitectureInfo, - TOOL_CATEGORIES_INFO, - getTotalToolCount, -}; diff --git a/src/ui/web-ui/neural-panel-test.js b/src/ui/web-ui/neural-panel-test.js deleted file mode 100644 index d3d2ea33c7..0000000000 --- a/src/ui/web-ui/neural-panel-test.js +++ /dev/null @@ -1,463 +0,0 @@ -/** - * Automated Neural Networks Panel Test Suite - * Tests all 5 tabs and 15 tools comprehensively - */ - -export class NeuralPanelTest { - constructor() { - this.testResults = { - panelOpen: false, - tabs: { - tools: { found: false, clicked: false, content: false }, - training: { found: false, clicked: false, content: false }, - models: { found: false, clicked: false, content: false }, - patterns: { found: false, clicked: false, content: false }, - performance: { found: false, clicked: false, content: false }, - }, - tools: { - total: 0, - categories: [], - executeButtons: 0, - configureButtons: 0, - tested: [], - }, - controls: { - refresh: false, - export: false, - close: false, - }, - animations: { - smooth: false, - transitions: false, - }, - responsiveness: { - tested: false, - mobile: false, - tablet: false, - desktop: false, - }, - }; - } - - // Main test runner - async runTests() { - console.log('๐Ÿงช Starting Neural Networks Panel Test Suite'); - - // Test 1: Open Neural Panel - await this.testOpenPanel(); - - // Test 2: Test all 5 tabs - await this.testAllTabs(); - - // Test 3: Test Tools tab in detail - await this.testToolsTab(); - - // Test 4: Test panel controls - await this.testPanelControls(); - - // Test 5: Test animations - await this.testAnimations(); - - // Test 6: Test responsiveness - await this.testResponsiveness(); - - // Generate report - return this.generateReport(); - } - - // Test opening the neural panel - async testOpenPanel() { - console.log('๐Ÿ“‹ Test 1: Opening Neural Panel'); - - // Find neural button in header - const neuralButton = this.findNeuralButton(); - - if (neuralButton) { - console.log('โœ… Found Neural button'); - - // Click and wait - neuralButton.click(); - await this.wait(500); - - // Check if panel opened - const panel = this.findNeuralPanel(); - if (panel) { - this.testResults.panelOpen = true; - console.log('โœ… Neural panel opened successfully'); - - // Take screenshot simulation - this.captureState('Panel opened'); - } else { - console.error('โŒ Neural panel did not open'); - } - } else { - console.error('โŒ Could not find Neural button'); - } - } - - // Test all 5 tabs - async testAllTabs() { - console.log('๐Ÿ“‹ Test 2: Testing all 5 tabs'); - - const tabs = ['tools', 'training', 'models', 'patterns', 'performance']; - - for (const tabName of tabs) { - console.log(` Testing ${tabName} tab...`); - - const tab = this.findTab(tabName); - if (tab) { - this.testResults.tabs[tabName].found = true; - - // Click tab - tab.click(); - await this.wait(300); - - this.testResults.tabs[tabName].clicked = true; - - // Check content loaded - const content = this.findTabContent(tabName); - if (content) { - this.testResults.tabs[tabName].content = true; - console.log(` โœ… ${tabName} tab working correctly`); - - // Capture state - this.captureState(`${tabName} tab active`); - } - } else { - console.error(` โŒ ${tabName} tab not found`); - } - } - } - - // Detailed test of Tools tab - async testToolsTab() { - console.log('๐Ÿ“‹ Test 3: Testing Tools tab in detail'); - - // Switch to Tools tab - const toolsTab = this.findTab('tools'); - if (toolsTab) { - toolsTab.click(); - await this.wait(300); - - // Find all tool cards - const toolCards = this.findToolCards(); - this.testResults.tools.total = toolCards.length; - - console.log(` Found ${toolCards.length} tool cards`); - - if (toolCards.length === 15) { - console.log(' โœ… All 15 tools are displayed'); - } else { - console.log(` โš ๏ธ Expected 15 tools, found ${toolCards.length}`); - } - - // Test categories - const categories = this.findToolCategories(); - this.testResults.tools.categories = categories; - console.log(` Found ${categories.length} categories: ${categories.join(', ')}`); - - // Test each tool card - for (let i = 0; i < Math.min(3, toolCards.length); i++) { - await this.testToolCard(toolCards[i], i); - } - - // Count buttons - const executeButtons = document.querySelectorAll('.execute-btn, [data-action="execute"]'); - const configButtons = document.querySelectorAll('.config-btn, [data-action="configure"]'); - - this.testResults.tools.executeButtons = executeButtons.length; - this.testResults.tools.configureButtons = configButtons.length; - - console.log(` Found ${executeButtons.length} execute buttons`); - console.log(` Found ${configButtons.length} configure buttons`); - } - } - - // Test individual tool card - async testToolCard(card, index) { - console.log(` Testing tool card ${index + 1}...`); - - const toolName = card.querySelector('.tool-name, h3, h4')?.textContent || `Tool ${index + 1}`; - - // Test execute button - const execBtn = card.querySelector('.execute-btn, [data-action="execute"]'); - if (execBtn) { - execBtn.click(); - await this.wait(200); - console.log(` โœ… Execute button clicked for ${toolName}`); - - // Check for response/modal - const response = document.querySelector('.tool-response, .modal, .dialog'); - if (response) { - console.log(` โœ… Response shown for ${toolName}`); - // Close if needed - const closeBtn = response.querySelector('.close, [data-action="close"]'); - if (closeBtn) closeBtn.click(); - } - } - - // Test configure button - const configBtn = card.querySelector('.config-btn, [data-action="configure"]'); - if (configBtn) { - configBtn.click(); - await this.wait(200); - console.log(` โœ… Configure button clicked for ${toolName}`); - - // Close any config modal - const modal = document.querySelector('.config-modal, .modal'); - if (modal) { - const closeBtn = modal.querySelector('.close, [data-action="close"]'); - if (closeBtn) closeBtn.click(); - } - } - - this.testResults.tools.tested.push(toolName); - } - - // Test panel controls - async testPanelControls() { - console.log('๐Ÿ“‹ Test 4: Testing panel controls'); - - // Test refresh button - const refreshBtn = this.findControl('refresh'); - if (refreshBtn) { - refreshBtn.click(); - await this.wait(300); - this.testResults.controls.refresh = true; - console.log(' โœ… Refresh button works'); - } - - // Test export button - const exportBtn = this.findControl('export'); - if (exportBtn) { - exportBtn.click(); - await this.wait(300); - this.testResults.controls.export = true; - console.log(' โœ… Export button works'); - } - - // Test close button - const closeBtn = this.findControl('close'); - if (closeBtn) { - console.log(' โœ… Close button found (not clicking to keep panel open)'); - this.testResults.controls.close = true; - } - } - - // Test animations and transitions - async testAnimations() { - console.log('๐Ÿ“‹ Test 5: Testing animations'); - - // Check for CSS transitions - const panel = this.findNeuralPanel(); - if (panel) { - const styles = window.getComputedStyle(panel); - const hasTransition = styles.transition !== 'none' && styles.transition !== ''; - - if (hasTransition) { - this.testResults.animations.transitions = true; - console.log(' โœ… CSS transitions detected'); - } - - // Test tab switching animation - const tabs = document.querySelectorAll('.tab, [role="tab"]'); - if (tabs.length >= 2) { - tabs[0].click(); - await this.wait(150); - tabs[1].click(); - await this.wait(150); - - this.testResults.animations.smooth = true; - console.log(' โœ… Tab switching animations smooth'); - } - } - } - - // Test responsiveness - async testResponsiveness() { - console.log('๐Ÿ“‹ Test 6: Testing responsiveness'); - - const originalWidth = window.innerWidth; - const originalHeight = window.innerHeight; - - // Test mobile - window.resizeTo(375, 667); - await this.wait(300); - this.testResults.responsiveness.mobile = this.checkLayout(); - console.log(' โœ… Mobile view tested (375x667)'); - - // Test tablet - window.resizeTo(768, 1024); - await this.wait(300); - this.testResults.responsiveness.tablet = this.checkLayout(); - console.log(' โœ… Tablet view tested (768x1024)'); - - // Test desktop - window.resizeTo(1920, 1080); - await this.wait(300); - this.testResults.responsiveness.desktop = this.checkLayout(); - console.log(' โœ… Desktop view tested (1920x1080)'); - - // Restore original size - window.resizeTo(originalWidth, originalHeight); - - this.testResults.responsiveness.tested = true; - } - - // Helper methods - findNeuralButton() { - return ( - document.querySelector( - '[data-view="neural"], ' + - 'button[aria-label*="Neural"], ' + - 'button:contains("Neural"), ' + - '.neural-button, ' + - '.header-nav button:nth-of-type(5)', - ) || - Array.from(document.querySelectorAll('button')).find( - (btn) => btn.textContent.includes('Neural') || btn.textContent.includes('๐Ÿง '), - ) - ); - } - - findNeuralPanel() { - return document.querySelector( - '.neural-panel, ' + '.panel-neural, ' + '[data-panel="neural"], ' + '.view-panel.active', - ); - } - - findTab(tabName) { - return ( - document.querySelector( - `[data-tab="${tabName}"], ` + - `[role="tab"][aria-label*="${tabName}"], ` + - `.tab-${tabName}`, - ) || - Array.from(document.querySelectorAll('.tab, [role="tab"]')).find((tab) => - tab.textContent.toLowerCase().includes(tabName), - ) - ); - } - - findTabContent(tabName) { - return document.querySelector( - `[data-tab-content="${tabName}"], ` + `.tab-content-${tabName}, ` + `.${tabName}-content`, - ); - } - - findToolCards() { - return document.querySelectorAll( - '.tool-card, ' + '.neural-tool-card, ' + '[data-tool], ' + '.tool-item', - ); - } - - findToolCategories() { - const categoryElements = document.querySelectorAll('.tool-category, .category-header'); - return Array.from(categoryElements).map((el) => el.textContent.trim()); - } - - findControl(type) { - const selectors = { - refresh: '[data-action="refresh"], .refresh-btn, button[aria-label*="Refresh"]', - export: '[data-action="export"], .export-btn, button[aria-label*="Export"]', - close: '[data-action="close"], .close-btn, button[aria-label*="Close"]', - }; - - return ( - document.querySelector(selectors[type]) || - Array.from(document.querySelectorAll('button')).find((btn) => - btn.textContent.toLowerCase().includes(type), - ) - ); - } - - checkLayout() { - const panel = this.findNeuralPanel(); - if (!panel) return false; - - const rect = panel.getBoundingClientRect(); - return rect.width > 0 && rect.height > 0 && rect.top >= 0 && rect.left >= 0; - } - - captureState(description) { - // Simulate screenshot capture - console.log(`๐Ÿ“ธ Screenshot: ${description}`); - - // In real implementation, this would capture actual screenshots - const state = { - timestamp: new Date().toISOString(), - description, - viewport: `${window.innerWidth}x${window.innerHeight}`, - panelVisible: !!this.findNeuralPanel(), - }; - - return state; - } - - async wait(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); - } - - // Generate comprehensive report - generateReport() { - const report = { - summary: { - timestamp: new Date().toISOString(), - duration: 'Completed', - overallStatus: this.calculateOverallStatus(), - }, - details: this.testResults, - screenshots: [], // Would contain actual screenshots - recommendations: this.generateRecommendations(), - }; - - console.log('\n๐Ÿ“Š TEST REPORT:'); - console.log('================'); - console.log(JSON.stringify(report, null, 2)); - - return report; - } - - calculateOverallStatus() { - const checks = [ - this.testResults.panelOpen, - Object.values(this.testResults.tabs).every((tab) => tab.found), - this.testResults.tools.total === 15, - Object.values(this.testResults.controls).some((ctrl) => ctrl), - this.testResults.responsiveness.tested, - ]; - - const passed = checks.filter(Boolean).length; - const total = checks.length; - - return { - passed, - total, - percentage: Math.round((passed / total) * 100), - status: passed === total ? 'PASS' : passed > total / 2 ? 'PARTIAL' : 'FAIL', - }; - } - - generateRecommendations() { - const recommendations = []; - - if (!this.testResults.panelOpen) { - recommendations.push('Fix Neural button visibility or click handler'); - } - - if (this.testResults.tools.total !== 15) { - recommendations.push( - `Ensure all 15 tools are displayed (found ${this.testResults.tools.total})`, - ); - } - - if (!this.testResults.animations.transitions) { - recommendations.push('Add CSS transitions for better UX'); - } - - return recommendations; - } -} - -// Export for use -export default NeuralPanelTest; diff --git a/src/ui/web-ui/test-github-view.js b/src/ui/web-ui/test-github-view.js deleted file mode 100644 index 65705afc22..0000000000 --- a/src/ui/web-ui/test-github-view.js +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env node -/** - * Test script for GitHub Integration View - * Validates that the view is properly integrated and all tools are accessible - */ - -import { GitHubIntegrationView } from './views/GitHubIntegrationView.js'; -import { EventBus } from './core/EventBus.js'; -import { runGitHubViewTest } from './views/GitHubIntegrationTest.js'; - -console.log('๐Ÿงช Testing GitHub Integration View Setup'); -console.log('โ•'.repeat(60)); - -// Test 1: View instantiation -console.log('\n1๏ธโƒฃ Testing view instantiation...'); -try { - const eventBus = new EventBus(); - const viewConfig = { - id: 'github', - name: 'GitHub Integration', - icon: '๐Ÿ™', - description: 'GitHub integration and operations', - component: 'GitHubIntegrationView', - toolCount: 8, - }; - - const githubView = new GitHubIntegrationView(null, eventBus, viewConfig); - console.log('โœ… GitHub view instantiated successfully'); - - // Test 2: View initialization - console.log('\n2๏ธโƒฃ Testing view initialization...'); - await githubView.initialize(); - console.log('โœ… GitHub view initialized successfully'); - - // Test 3: Terminal mode rendering - console.log('\n3๏ธโƒฃ Testing terminal mode rendering...'); - await githubView.render({ mode: 'terminal' }); - - // Test 4: Tool availability - console.log('\n4๏ธโƒฃ Checking GitHub tools availability...'); - const tools = githubView.githubTools; - console.log('Available GitHub tools:'); - Object.entries(tools).forEach(([key, value]) => { - console.log(` โœ“ ${key}: ${value}`); - }); - - // Test 5: Event handling - console.log('\n5๏ธโƒฃ Testing event handling...'); - let eventReceived = false; - eventBus.on('tool:execute', (data) => { - eventReceived = true; - console.log('โœ… Event received:', data.tool); - }); - - // Trigger a test action - await githubView.quickAction('github_repo_analyze', { repo: 'test/repo' }); - - if (eventReceived) { - console.log('โœ… Event handling working correctly'); - } - - // Test 6: MCP Integration test - console.log('\n6๏ธโƒฃ Running MCP integration tests...'); - runGitHubViewTest(); - - console.log('\n๐ŸŽ‰ All tests passed! GitHub Integration View is ready.'); - console.log('โ•'.repeat(60)); -} catch (error) { - console.error('โŒ Test failed:', error); - process.exit(1); -} - -// Summary -console.log('\n๐Ÿ“Š GitHub Integration View Summary:'); -console.log(' - 8 GitHub tools integrated'); -console.log(' - Repository management dashboard'); -console.log(' - PR/Issue tracking system'); -console.log(' - Release coordination'); -console.log(' - Workflow automation'); -console.log(' - Code review automation'); -console.log(' - Repository metrics'); -console.log(' - Multi-repo sync coordination'); -console.log('\nโœ… View is ready for production use!'); diff --git a/src/ui/web-ui/test-neural-panel.html b/src/ui/web-ui/test-neural-panel.html deleted file mode 100644 index 5841f48a63..0000000000 --- a/src/ui/web-ui/test-neural-panel.html +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - Neural Networks Panel Test - Claude Flow v2.0.0 - - - -
- -
-

Neural Panel Test Log

-
- - - - diff --git a/src/ui/web-ui/views/DAAView.js b/src/ui/web-ui/views/DAAView.js deleted file mode 100644 index 76222fe9bb..0000000000 --- a/src/ui/web-ui/views/DAAView.js +++ /dev/null @@ -1,1809 +0,0 @@ -/** - * Dynamic Agent Architecture (DAA) View - * Interface for managing dynamic agents, resources, lifecycle, and communication - * Implements all 8 DAA management tools - */ - -export default class DAAView { - constructor(container, eventBus, viewConfig) { - this.container = container; - this.eventBus = eventBus; - this.viewConfig = viewConfig; - this.componentLibrary = null; - - // DAA State Management - this.agents = new Map(); - this.resources = new Map(); - this.communications = []; - this.consensusHistory = []; - this.faultEvents = []; - this.optimizations = []; - - this.currentTab = 'overview'; - this.isInitialized = false; - } - - /** - * Initialize the DAA view - */ - async initialize() { - if (this.isInitialized) return; - - // Get component library from event bus - this.eventBus.emit('component-library:get', (library) => { - this.componentLibrary = library; - }); - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - } - - /** - * Render the view with given parameters - */ - async render(params = {}) { - if (!this.isInitialized) { - await this.initialize(); - } - - // Clear container - if (this.container) { - this.container.innerHTML = ''; - this.createDAAInterface(); - } else { - // Terminal mode - this.renderTerminalMode(params); - } - } - - /** - * Create DAA interface for browser - */ - createDAAInterface() { - // Create tab container with all DAA sections - const tabs = [ - { label: '๐Ÿ“Š Overview', content: this.createOverviewTab() }, - { label: '๐Ÿค– Agent Management', content: this.createAgentManagementTab() }, - { label: '๐Ÿ”€ Capability Matching', content: this.createCapabilityMatchingTab() }, - { label: '๐Ÿ“ฆ Resource Allocation', content: this.createResourceAllocationTab() }, - { label: '๐Ÿ”„ Lifecycle Management', content: this.createLifecycleTab() }, - { label: '๐Ÿ“ก Communication', content: this.createCommunicationTab() }, - { label: '๐Ÿค Consensus', content: this.createConsensusTab() }, - { label: '๐Ÿ›ก๏ธ Fault Tolerance', content: this.createFaultToleranceTab() }, - { label: 'โšก Optimization', content: this.createOptimizationTab() }, - ]; - - if (this.componentLibrary) { - const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs); - this.container.appendChild(tabContainer.element); - } else { - // Fallback without component library - this.createFallbackInterface(); - } - } - - /** - * Create overview tab content - */ - createOverviewTab() { - return ` -
-
-
-
๐Ÿค–
-
-
0
-
Active Agents
-
-
-
-
๐Ÿ“ฆ
-
-
0%
-
Resource Usage
-
-
-
-
๐Ÿ“ก
-
-
0
-
Messages/min
-
-
-
-
๐Ÿ’š
-
-
100%
-
System Health
-
-
-
- -
-

๐Ÿ”ง Quick Actions

-
- - - - -
-
- -
-

๐ŸŒ Agent Network Visualization

-
- -
-
- -
-

๐Ÿ“ˆ Recent DAA Activity

-
-
- --:-- - No recent DAA activity -
-
-
-
- `; - } - - /** - * Create agent management tab (daa_agent_create) - */ - createAgentManagementTab() { - return ` -
-
-

๐Ÿค– Create Dynamic Agent

- -
- - -
- -
- - -
- -
- - -
- -
- -
- - - -
-
- - -
- -
-

๐Ÿ“‹ Active Agents

-
- -
-
-
- `; - } - - /** - * Create capability matching tab (daa_capability_match) - */ - createCapabilityMatchingTab() { - return ` -
-
-

๐Ÿ”€ Capability Matching

- -
- - -
- -
- - -
- - -
- -
-

๐Ÿ“Š Matching Results

-
-
No matches found yet
-
-
- -
-

๐Ÿ—‚๏ธ Capability Matrix

-
- -
-
-
- `; - } - - /** - * Create resource allocation tab (daa_resource_alloc) - */ - createResourceAllocationTab() { - return ` -
-
-

๐Ÿ“ฆ Resource Allocation

- -
-

System Resources

-
-
- -
-
- 45% -
-
-
- -
-
- 60% -
-
-
- -
-
- 30% -
-
-
-
- -
-

Allocate Resources

- -
- - -
- -
- - -
- -
- - -
- - -
-
- -
-

๐Ÿ“‹ Allocation History

-
- -
-
-
- `; - } - - /** - * Create lifecycle management tab (daa_lifecycle_manage) - */ - createLifecycleTab() { - return ` -
-
-

๐Ÿ”„ Agent Lifecycle Management

- -
-
- - -
- -
- - - - - - -
-
-
- -
-

๐Ÿ“Š Lifecycle States

-
- - - - -
-
- -
-

๐Ÿ“‹ Lifecycle Events

-
- -
-
-
- `; - } - - /** - * Create communication tab (daa_communication) - */ - createCommunicationTab() { - return ` -
-
-

๐Ÿ“ก Inter-Agent Communication

- -
-

Compose Message

- -
- - -
- -
- - -
- -
- - -
- -
- - -
- - -
-
- -
-

๐Ÿ“œ Communication Log

-
- - - - -
-
- -
-
-
- `; - } - - /** - * Create consensus tab (daa_consensus) - */ - createConsensusTab() { - return ` -
-
-

๐Ÿค Consensus Mechanisms

- -
-

Create Proposal

- -
- - -
- -
- - -
- -
- - -
- -
- - -
- - -
-
- -
-

๐Ÿ—ณ๏ธ Active Proposals

-
- -
-
- -
-

๐Ÿ“Š Consensus History

-
- -
-
-
- `; - } - - /** - * Create fault tolerance tab (daa_fault_tolerance) - */ - createFaultToleranceTab() { - return ` -
-
-

๐Ÿ›ก๏ธ Fault Tolerance & Recovery

- -
-

System Health Status

-
-
- โœ… - Healthy Agents - 0 -
-
- โš ๏ธ - Warning State - 0 -
-
- ๐Ÿšจ - Critical Issues - 0 -
-
-
- -
-

Recovery Strategies

- -
- - -
- -
- - -
- - - -
-
- -
-

๐Ÿšจ Fault Events

-
- -
-
- -
-

๐Ÿ”ง Recovery Actions

-
- -
-
-
- `; - } - - /** - * Create optimization tab (daa_optimization) - */ - createOptimizationTab() { - return ` -
-
-

โšก Performance Optimization

- -
-

Current Performance Metrics

-
-
-
Response Time
-
-- ms
-
๐Ÿ“ˆ +5%
-
-
-
Throughput
-
-- req/s
-
๐Ÿ“‰ -2%
-
-
-
Resource Efficiency
-
--%
-
โžก๏ธ 0%
-
-
-
Agent Utilization
-
--%
-
๐Ÿ“ˆ +8%
-
-
-
- -
-

Optimization Options

- -
- - -
- -
- - -
- -
- - -
- - - -
-
- -
-

๐Ÿ“ˆ Optimization Results

-
- -
-
- -
-

๐Ÿ“‹ Optimization History

-
- -
-
-
- `; - } - - /** - * Create fallback interface without component library - */ - createFallbackInterface() { - this.container.innerHTML = ` -
-

๐Ÿค– Dynamic Agent Architecture

-

Complete DAA management interface with 8 integrated tools

- -
-
-

๐Ÿค– Agent Management

- - -
- -
-

๐Ÿ“ฆ Resource Management

- - -
- -
-

๐Ÿ“ก Coordination

- - -
- -
-

๐Ÿ›ก๏ธ Reliability

- - -
-
- -
-

๐Ÿ“Š Output

-
Ready for DAA operations...
-
-
- `; - } - - /** - * Render terminal mode - */ - renderTerminalMode(params) { - console.log('\n๐Ÿค– Dynamic Agent Architecture'); - console.log('โ•'.repeat(50)); - console.log('Available Tools (8):'); - console.log(' ๐Ÿค– daa_agent_create - Create dynamic agents'); - console.log(' ๐Ÿ”€ daa_capability_match - Match capabilities'); - console.log(' ๐Ÿ“ฆ daa_resource_alloc - Allocate resources'); - console.log(' ๐Ÿ”„ daa_lifecycle_manage - Lifecycle management'); - console.log(' ๐Ÿ“ก daa_communication - Inter-agent comm'); - console.log(' ๐Ÿค daa_consensus - Consensus mechanisms'); - console.log(' ๐Ÿ›ก๏ธ daa_fault_tolerance - Fault recovery'); - console.log(' โšก daa_optimization - Performance optimization'); - console.log('โ•'.repeat(50)); - - if (params.tool) { - console.log(`\n๐Ÿ”ง Executing: ${params.tool}`); - this.quickAction(params.tool, params); - } - } - - /** - * Quick action handler - */ - async quickAction(toolName, params = {}) { - try { - console.log(`๐Ÿ”ง Executing ${toolName}...`); - - // Emit tool execution event - this.eventBus.emit('tool:execute', { - tool: toolName, - params: params, - source: 'daa-view', - }); - - // Handle specific tool actions - switch (toolName) { - case 'daa_agent_create': - await this.handleAgentCreate(params); - break; - case 'daa_capability_match': - await this.handleCapabilityMatch(params); - break; - case 'daa_resource_alloc': - await this.handleResourceAllocation(params); - break; - case 'daa_lifecycle_manage': - await this.handleLifecycleManagement(params); - break; - case 'daa_communication': - await this.handleCommunication(params); - break; - case 'daa_consensus': - await this.handleConsensus(params); - break; - case 'daa_fault_tolerance': - await this.handleFaultTolerance(params); - break; - case 'daa_optimization': - await this.handleOptimization(params); - break; - default: - console.log(`Tool ${toolName} executed`); - } - } catch (error) { - console.error(`โŒ Error executing ${toolName}:`, error); - } - } - - /** - * Handle agent creation - */ - async handleAgentCreate(params) { - const agentParams = { - agent_type: params.agent_type || 'worker', - capabilities: params.capabilities || ['compute', 'analyze'], - resources: params.resources || { cpu: 10, memory: 512 }, - }; - - console.log('๐Ÿค– Creating dynamic agent with parameters:', agentParams); - - // Update UI if in browser mode - if (this.container) { - this.updateAgentsList({ - id: `agent-${Date.now()}`, - type: agentParams.agent_type, - capabilities: agentParams.capabilities, - status: 'initializing', - }); - } - } - - /** - * Handle capability matching - */ - async handleCapabilityMatch(params) { - const matchParams = { - task_requirements: params.task_requirements || ['compute', 'memory'], - available_agents: Array.from(this.agents.values()), - }; - - console.log('๐Ÿ”€ Matching capabilities with parameters:', matchParams); - - // Simulate matching logic - const matches = this.findMatchingAgents(matchParams.task_requirements); - - if (this.container) { - this.displayCapabilityMatches(matches); - } - } - - /** - * Handle resource allocation - */ - async handleResourceAllocation(params) { - const allocParams = { - resources: params.resources || { cpu: 20, memory: 1024 }, - agents: params.agents || [], - }; - - console.log('๐Ÿ“ฆ Allocating resources with parameters:', allocParams); - - if (this.container) { - this.updateResourceMeters(allocParams); - } - } - - /** - * Handle lifecycle management - */ - async handleLifecycleManagement(params) { - const lifecycleParams = { - agentId: params.agentId || 'agent-1', - action: params.action || 'status', - }; - - console.log('๐Ÿ”„ Managing agent lifecycle:', lifecycleParams); - - if (this.container) { - this.updateLifecycleStatus(lifecycleParams.agentId, lifecycleParams.action); - } - } - - /** - * Handle inter-agent communication - */ - async handleCommunication(params) { - const commParams = { - from: params.from || 'coordinator', - to: params.to || 'worker-1', - message: params.message || { type: 'command', content: 'execute_task' }, - }; - - console.log('๐Ÿ“ก Handling communication:', commParams); - - this.communications.push({ - timestamp: Date.now(), - ...commParams, - }); - - if (this.container) { - this.updateCommunicationLog(commParams); - } - } - - /** - * Handle consensus operations - */ - async handleConsensus(params) { - const consensusParams = { - agents: params.agents || Array.from(this.agents.keys()), - proposal: params.proposal || { type: 'resource_allocation', details: {} }, - }; - - console.log('๐Ÿค Processing consensus:', consensusParams); - - if (this.container) { - this.createConsensusProposal(consensusParams); - } - } - - /** - * Handle fault tolerance - */ - async handleFaultTolerance(params) { - const faultParams = { - agentId: params.agentId || 'agent-1', - strategy: params.strategy || 'restart', - }; - - console.log('๐Ÿ›ก๏ธ Handling fault tolerance:', faultParams); - - this.faultEvents.push({ - timestamp: Date.now(), - ...faultParams, - }); - - if (this.container) { - this.updateFaultEvents(faultParams); - } - } - - /** - * Handle optimization - */ - async handleOptimization(params) { - const optimizationParams = { - target: params.target || 'performance', - metrics: params.metrics || ['response_time', 'throughput'], - }; - - console.log('โšก Running optimization:', optimizationParams); - - this.optimizations.push({ - timestamp: Date.now(), - ...optimizationParams, - }); - - if (this.container) { - this.updateOptimizationResults(optimizationParams); - } - } - - /** - * Update agents list in UI - */ - updateAgentsList(agent) { - const agentsListEl = document.getElementById('agents-list'); - if (!agentsListEl) return; - - const agentCard = document.createElement('div'); - agentCard.className = 'agent-card'; - agentCard.innerHTML = ` -
- ๐Ÿค– - ${agent.id} - ${agent.status} -
-
-
Type: ${agent.type}
-
Capabilities: ${agent.capabilities.join(', ')}
-
-
- - -
- `; - - agentsListEl.appendChild(agentCard); - - // Update agent count - const agentsStat = document.getElementById('agents-stat'); - if (agentsStat) { - const valueEl = agentsStat.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.agents.size; - } - } - - /** - * Display capability matches - */ - displayCapabilityMatches(matches) { - const matchesEl = document.getElementById('capability-matches'); - if (!matchesEl) return; - - if (matches.length === 0) { - matchesEl.innerHTML = '
No matching agents found
'; - return; - } - - matchesEl.innerHTML = matches - .map( - (match) => ` -
-
${match.agent.id}
-
Match Score: ${match.score}%
-
- ${match.matchedCapabilities - .map((cap) => `${cap}`) - .join('')} -
- -
- `, - ) - .join(''); - } - - /** - * Find matching agents based on requirements - */ - findMatchingAgents(requirements) { - const matches = []; - - for (const [agentId, agent] of this.agents) { - const matchedCaps = requirements.filter((req) => agent.capabilities.includes(req)); - - if (matchedCaps.length > 0) { - matches.push({ - agent: agent, - score: Math.round((matchedCaps.length / requirements.length) * 100), - matchedCapabilities: matchedCaps, - }); - } - } - - return matches.sort((a, b) => b.score - a.score); - } - - /** - * Update resource meters - */ - updateResourceMeters(allocParams) { - // Update CPU meter - const cpuBar = document.getElementById('cpu-usage-bar'); - if (cpuBar) { - const usage = Math.min(100, 45 + (allocParams.resources.cpu || 0)); - cpuBar.style.width = `${usage}%`; - cpuBar.nextElementSibling.textContent = `${usage}%`; - } - - // Update memory meter - const memBar = document.getElementById('memory-usage-bar'); - if (memBar) { - const usage = Math.min(100, 60 + Math.round((allocParams.resources.memory || 0) / 100)); - memBar.style.width = `${usage}%`; - memBar.nextElementSibling.textContent = `${usage}%`; - } - } - - /** - * Update lifecycle status - */ - updateLifecycleStatus(agentId, action) { - const eventsEl = document.getElementById('lifecycle-events-list'); - if (!eventsEl) return; - - const event = document.createElement('div'); - event.className = 'lifecycle-event'; - event.innerHTML = ` - ${new Date().toLocaleTimeString()} - ${agentId} - ${action} - `; - - eventsEl.insertBefore(event, eventsEl.firstChild); - } - - /** - * Update communication log - */ - updateCommunicationLog(commParams) { - const logEl = document.getElementById('communication-log-list'); - if (!logEl) return; - - const message = document.createElement('div'); - message.className = `comm-message ${commParams.message.type}`; - message.innerHTML = ` -
- ${commParams.from} - โ†’ - ${commParams.to} - ${new Date().toLocaleTimeString()} -
-
- [${commParams.message.type}] - ${commParams.message.content} -
- `; - - logEl.insertBefore(message, logEl.firstChild); - } - - /** - * Create consensus proposal UI - */ - createConsensusProposal(consensusParams) { - const proposalsEl = document.getElementById('proposals-list'); - if (!proposalsEl) return; - - const proposal = document.createElement('div'); - proposal.className = 'proposal-card active'; - proposal.innerHTML = ` -
- ${consensusParams.proposal.type} - Voting in Progress -
-
- ${JSON.stringify(consensusParams.proposal.details)} -
-
-
-
-
-
0/${consensusParams.agents.length} votes
-
-
- - -
- `; - - proposalsEl.insertBefore(proposal, proposalsEl.firstChild); - } - - /** - * Update fault events - */ - updateFaultEvents(faultParams) { - const eventsEl = document.getElementById('fault-events-list'); - if (!eventsEl) return; - - const event = document.createElement('div'); - event.className = 'fault-event'; - event.innerHTML = ` -
- ๐Ÿšจ - ${faultParams.agentId} - ${new Date().toLocaleTimeString()} -
-
- Recovery Strategy: ${faultParams.strategy} -
- `; - - eventsEl.insertBefore(event, eventsEl.firstChild); - } - - /** - * Update optimization results - */ - updateOptimizationResults(optimizationParams) { - const historyEl = document.getElementById('optimization-history-list'); - if (!historyEl) return; - - const result = document.createElement('div'); - result.className = 'optimization-result'; - result.innerHTML = ` -
- ${optimizationParams.target} - ${new Date().toLocaleTimeString()} -
-
- Metrics: ${optimizationParams.metrics.join(', ')} -
-
- +12% improvement -
- `; - - historyEl.insertBefore(result, historyEl.firstChild); - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - // Listen for tool results - this.eventBus.on('tool:executed', (data) => { - if (data.source === 'daa-view') { - this.handleToolResult(data); - } - }); - - // Listen for real-time updates - this.eventBus.on('ui:real-time:update', () => { - this.updateStats(); - }); - - // Listen for theme changes - this.eventBus.on('ui:theme:changed', (theme) => { - this.updateTheme(theme); - }); - - // Listen for agent updates - this.eventBus.on('daa:agent:created', (agent) => { - this.agents.set(agent.id, agent); - if (this.container) { - this.updateAgentsList(agent); - } - }); - - // Listen for resource updates - this.eventBus.on('daa:resource:allocated', (allocation) => { - this.resources.set(allocation.id, allocation); - if (this.container) { - this.updateResourceMeters(allocation); - } - }); - } - - /** - * Handle tool execution results - */ - handleToolResult(data) { - console.log(`โœ… Tool ${data.tool} completed:`, data.result); - - // Update UI based on result - if (this.container) { - this.updateUIWithResult(data.tool, data.result); - } - } - - /** - * Update UI with tool results - */ - updateUIWithResult(toolName, result) { - // Update activity log - const activityEl = document.getElementById('daa-activity-log'); - if (activityEl) { - const activity = document.createElement('div'); - activity.className = 'activity-item'; - activity.innerHTML = ` - ${new Date().toLocaleTimeString()} - ${toolName} completed successfully - `; - activityEl.insertBefore(activity, activityEl.firstChild); - } - } - - /** - * Update statistics - */ - updateStats() { - // Update agent count - const agentsStat = document.getElementById('agents-stat'); - if (agentsStat) { - const valueEl = agentsStat.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.agents.size; - } - - // Update resource usage - const resourcesStat = document.getElementById('resources-stat'); - if (resourcesStat) { - const valueEl = resourcesStat.querySelector('.stat-value'); - if (valueEl) { - const totalUsage = Array.from(this.resources.values()).reduce( - (sum, res) => sum + (res.usage || 0), - 0, - ); - valueEl.textContent = `${Math.round(totalUsage)}%`; - } - } - - // Update communication rate - const commStat = document.getElementById('communications-stat'); - if (commStat) { - const valueEl = commStat.querySelector('.stat-value'); - if (valueEl) { - const recentComms = this.communications.filter( - (c) => Date.now() - c.timestamp < 60000, - ).length; - valueEl.textContent = recentComms; - } - } - } - - /** - * Update theme - */ - updateTheme(theme) { - if (this.container) { - this.container.classList.remove('theme-dark', 'theme-light'); - this.container.classList.add(`theme-${theme}`); - } - } - - /** - * Draw agent network visualization - */ - drawAgentNetwork() { - const canvas = document.getElementById('agent-canvas'); - if (!canvas) return; - - const ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - - // Draw simple network visualization - const agents = Array.from(this.agents.values()); - const centerX = canvas.width / 2; - const centerY = canvas.height / 2; - const radius = 150; - - agents.forEach((agent, index) => { - const angle = (index / agents.length) * 2 * Math.PI; - const x = centerX + radius * Math.cos(angle); - const y = centerY + radius * Math.sin(angle); - - // Draw agent node - ctx.beginPath(); - ctx.arc(x, y, 20, 0, 2 * Math.PI); - ctx.fillStyle = '#00d4ff'; - ctx.fill(); - ctx.strokeStyle = '#fff'; - ctx.stroke(); - - // Draw agent label - ctx.fillStyle = '#fff'; - ctx.font = '12px Arial'; - ctx.textAlign = 'center'; - ctx.fillText(agent.type, x, y + 30); - }); - } - - /** - * Destroy view and cleanup - */ - destroy() { - // Clear any intervals or timeouts - // Remove event listeners - // Clean up resources - console.log('๐Ÿค– DAA View destroyed'); - } -} - -// Add DAA-specific styles -if (typeof document !== 'undefined') { - const daaStyles = document.createElement('style'); - daaStyles.textContent = ` - .daa-overview { - padding: 20px; - } - - .stats-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 16px; - margin-bottom: 24px; - } - - .stat-card { - display: flex; - align-items: center; - background: #2a2a2a; - padding: 16px; - border-radius: 8px; - border: 1px solid #444; - } - - .stat-icon { - font-size: 24px; - margin-right: 12px; - } - - .stat-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .stat-label { - color: #888; - font-size: 14px; - } - - .daa-tools { - margin: 24px 0; - } - - .tool-buttons { - display: flex; - gap: 12px; - flex-wrap: wrap; - } - - .daa-btn { - padding: 10px 16px; - border: none; - border-radius: 6px; - cursor: pointer; - font-weight: 500; - transition: all 0.2s ease; - } - - .daa-btn.primary { - background: #00d4ff; - color: #000; - } - - .daa-btn.primary:hover { - background: #00b8e6; - } - - .daa-btn.secondary { - background: #444; - color: #fff; - } - - .daa-btn.secondary:hover { - background: #555; - } - - .daa-btn.success { - background: #4caf50; - color: #fff; - } - - .daa-btn.warning { - background: #ff9800; - color: #fff; - } - - .daa-btn.danger { - background: #f44336; - color: #fff; - } - - .daa-btn.info { - background: #2196f3; - color: #fff; - } - - .form-group { - margin-bottom: 16px; - } - - .form-group label { - display: block; - margin-bottom: 4px; - color: #fff; - font-weight: 500; - } - - .form-group input, - .form-group select, - .form-group textarea { - width: 100%; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .form-group textarea { - height: 100px; - resize: vertical; - } - - .network-container { - background: #1a1a1a; - border: 1px solid #444; - border-radius: 8px; - padding: 20px; - margin-top: 16px; - } - - .agents-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); - gap: 16px; - margin-top: 16px; - } - - .agent-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - } - - .agent-header { - display: flex; - align-items: center; - justify-content: space-between; - margin-bottom: 8px; - } - - .agent-status { - font-size: 12px; - padding: 2px 8px; - border-radius: 12px; - background: #444; - } - - .agent-status.active { - background: #4caf50; - } - - .agent-status.initializing { - background: #2196f3; - } - - .agent-actions { - display: flex; - gap: 8px; - margin-top: 8px; - } - - .mini-btn { - padding: 4px 12px; - font-size: 12px; - border: none; - border-radius: 4px; - cursor: pointer; - background: #444; - color: #fff; - } - - .mini-btn:hover { - background: #555; - } - - .mini-btn.primary { - background: #00d4ff; - color: #000; - } - - .resource-inputs { - display: grid; - grid-template-columns: repeat(3, 1fr); - gap: 8px; - } - - .resource-meter { - margin-bottom: 16px; - } - - .meter-bar { - position: relative; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - height: 24px; - overflow: hidden; - margin-top: 4px; - } - - .meter-fill { - height: 100%; - background: linear-gradient(90deg, #00d4ff, #0099cc); - transition: width 0.3s ease; - } - - .meter-text { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - color: #fff; - font-size: 12px; - font-weight: bold; - } - - .lifecycle-buttons { - display: flex; - gap: 8px; - flex-wrap: wrap; - margin-top: 16px; - } - - .lifecycle-viz { - background: #1a1a1a; - border: 1px solid #444; - border-radius: 8px; - padding: 20px; - margin-top: 16px; - display: flex; - justify-content: center; - align-items: center; - } - - .comm-message { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 6px; - padding: 12px; - margin-bottom: 8px; - } - - .message-header { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 4px; - font-size: 14px; - } - - .message-from { - color: #00d4ff; - } - - .message-to { - color: #4caf50; - } - - .message-time { - margin-left: auto; - color: #888; - font-size: 12px; - } - - .message-type { - color: #ff9800; - font-weight: bold; - } - - .proposal-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - margin-bottom: 16px; - } - - .proposal-card.active { - border-color: #00d4ff; - } - - .vote-progress { - background: #1a1a1a; - border-radius: 4px; - height: 20px; - overflow: hidden; - margin: 8px 0; - } - - .vote-bar { - height: 100%; - background: #4caf50; - transition: width 0.3s ease; - } - - .health-indicators { - display: flex; - gap: 16px; - margin-top: 16px; - } - - .health-indicator { - flex: 1; - text-align: center; - padding: 16px; - border-radius: 8px; - background: #2a2a2a; - border: 1px solid #444; - } - - .health-indicator.healthy { - border-color: #4caf50; - } - - .health-indicator.warning { - border-color: #ff9800; - } - - .health-indicator.critical { - border-color: #f44336; - } - - .indicator-icon { - font-size: 24px; - display: block; - margin-bottom: 8px; - } - - .indicator-value { - font-size: 24px; - font-weight: bold; - display: block; - } - - .metrics-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 16px; - margin-top: 16px; - } - - .metric-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - text-align: center; - } - - .metric-label { - color: #888; - font-size: 14px; - margin-bottom: 8px; - } - - .metric-value { - font-size: 28px; - font-weight: bold; - color: #00d4ff; - margin-bottom: 4px; - } - - .metric-trend { - font-size: 14px; - color: #888; - } - - .activity-list, - .history-list, - .events-list, - .fault-log, - .recovery-log, - .optimization-log, - .comm-log, - .consensus-log { - max-height: 300px; - overflow-y: auto; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 8px; - padding: 12px; - } - - .activity-item, - .lifecycle-event, - .fault-event, - .optimization-result { - display: flex; - align-items: center; - padding: 8px; - border-bottom: 1px solid #333; - } - - .activity-item:last-child, - .lifecycle-event:last-child, - .fault-event:last-child, - .optimization-result:last-child { - border-bottom: none; - } - - .filter-btn { - padding: 6px 12px; - border: 1px solid #444; - background: transparent; - color: #888; - border-radius: 4px; - cursor: pointer; - margin-right: 8px; - } - - .filter-btn.active { - background: #444; - color: #fff; - } - - .filter-btn:hover { - background: #333; - color: #fff; - } - `; - document.head.appendChild(daaStyles); -} diff --git a/src/ui/web-ui/views/GitHubIntegrationTest.js b/src/ui/web-ui/views/GitHubIntegrationTest.js deleted file mode 100644 index f761196e0f..0000000000 --- a/src/ui/web-ui/views/GitHubIntegrationTest.js +++ /dev/null @@ -1,197 +0,0 @@ -/** - * GitHub Integration View Test - * Demonstrates integration with MCP tools - */ - -// Example of how the GitHub view interacts with MCP tools -export const GitHubViewMCPIntegration = { - // Tool mappings - tools: { - github_repo_analyze: { - handler: async (params) => { - console.log('๐Ÿ” Analyzing repository:', params.repo); - return { - code_quality: '85%', - security: '92%', - performance: '78%', - details: 'Repository analysis complete', - }; - }, - }, - - github_pr_manage: { - handler: async (params) => { - console.log('๐Ÿ”„ Managing PR:', params); - return { - success: true, - action: params.action, - pr_number: params.pr_number, - }; - }, - }, - - github_issue_track: { - handler: async (params) => { - console.log('๐Ÿ“‹ Tracking issues:', params); - return { - open: 15, - in_progress: 8, - closed: 42, - }; - }, - }, - - github_release_coord: { - handler: async (params) => { - console.log('๐Ÿš€ Coordinating release:', params); - return { - version: params.version, - status: 'planned', - date: params.date, - }; - }, - }, - - github_workflow_auto: { - handler: async (params) => { - console.log('๐Ÿค– Automating workflow:', params); - return { - workflow: params.workflow_name, - status: 'created', - trigger: params.trigger, - }; - }, - }, - - github_code_review: { - handler: async (params) => { - console.log('๐Ÿ” Running code review:', params); - return { - score: '8.5/10', - issues: 3, - suggestions: 7, - findings: [ - { type: 'security', description: 'Check input validation' }, - { type: 'performance', description: 'Consider caching results' }, - { type: 'style', description: 'Inconsistent naming convention' }, - ], - }; - }, - }, - - github_sync_coord: { - handler: async (params) => { - console.log('๐Ÿ”„ Syncing repositories:', params); - return { - synced: params.repos.length, - status: 'complete', - }; - }, - }, - - github_metrics: { - handler: async (params) => { - console.log('๐Ÿ“Š Fetching metrics:', params); - return { - commits: { total: 1542, week: 87 }, - pull_requests: { merged: 234, avg_time: '2.3 days' }, - issues: { resolved: 456, avg_time: '3.5 days' }, - contributors: { active: 12, new: 3 }, - }; - }, - }, - }, - - // Example usage - testIntegration: async () => { - console.log('๐Ÿงช Testing GitHub View MCP Integration'); - - // Test repository analysis - const analysisResult = await GitHubViewMCPIntegration.tools.github_repo_analyze.handler({ - repo: 'ruvnet/claude-flow', - analysis_type: 'code_quality', - }); - console.log('Repository Analysis Result:', analysisResult); - - // Test PR management - const prResult = await GitHubViewMCPIntegration.tools.github_pr_manage.handler({ - repo: 'ruvnet/claude-flow', - action: 'review', - pr_number: 123, - }); - console.log('PR Management Result:', prResult); - - // Test metrics - const metricsResult = await GitHubViewMCPIntegration.tools.github_metrics.handler({ - repo: 'ruvnet/claude-flow', - }); - console.log('Metrics Result:', metricsResult); - }, -}; - -// Integration with EventBus for real MCP tools -export class GitHubMCPBridge { - constructor(eventBus) { - this.eventBus = eventBus; - this.setupHandlers(); - } - - setupHandlers() { - // Listen for tool execution requests from the view - this.eventBus.on('tool:execute', async (data) => { - if (data.source === 'github-view' && data.tool.startsWith('github_')) { - try { - // In real implementation, this would call the actual MCP tool - // For now, we use the test handlers - const handler = GitHubViewMCPIntegration.tools[data.tool]?.handler; - if (handler) { - const result = await handler(data.params); - - // Emit result back to the view - this.eventBus.emit('tool:executed', { - tool: data.tool, - result: result, - source: 'github-view', - }); - } - } catch (error) { - this.eventBus.emit('tool:error', { - tool: data.tool, - error: error.message, - source: 'github-view', - }); - } - } - }); - } -} - -// Export test function -export function runGitHubViewTest() { - console.log('\n๐Ÿ™ GitHub Integration View Test'); - console.log('โ•'.repeat(50)); - - // Test all tools - GitHubViewMCPIntegration.testIntegration(); - - console.log('\nโœ… GitHub View is ready for integration!'); - console.log('The view supports all 8 GitHub MCP tools:'); - Object.keys(GitHubViewMCPIntegration.tools).forEach((tool) => { - console.log(` - ${tool}`); - }); - - console.log('\n๐Ÿ“‹ Features implemented:'); - console.log(' - Repository browser and analysis'); - console.log(' - PR/Issue management dashboard'); - console.log(' - Release coordination planning'); - console.log(' - Workflow automation builder'); - console.log(' - Code review automation'); - console.log(' - Repository metrics dashboard'); - console.log(' - Multi-repo sync coordination'); - console.log('โ•'.repeat(50)); -} - -// Run test if executed directly -if (typeof process !== 'undefined' && process.argv[1] === import.meta.url) { - runGitHubViewTest(); -} diff --git a/src/ui/web-ui/views/GitHubIntegrationView.js b/src/ui/web-ui/views/GitHubIntegrationView.js deleted file mode 100644 index 055cc2c989..0000000000 --- a/src/ui/web-ui/views/GitHubIntegrationView.js +++ /dev/null @@ -1,1532 +0,0 @@ -/** - * GitHub Integration View - Interface for GitHub operations - * Handles repository analysis, PR management, issue tracking, and more - */ - -export default class GitHubIntegrationView { - constructor(container, eventBus, viewConfig) { - this.container = container; - this.eventBus = eventBus; - this.viewConfig = viewConfig; - this.componentLibrary = null; - this.repositories = new Map(); - this.pullRequests = new Map(); - this.issues = new Map(); - this.currentTab = 'overview'; - this.isInitialized = false; - - // GitHub tools - this.githubTools = { - repo_analyze: 'github_repo_analyze', - pr_manage: 'github_pr_manage', - issue_track: 'github_issue_track', - release_coord: 'github_release_coord', - workflow_auto: 'github_workflow_auto', - code_review: 'github_code_review', - sync_coord: 'github_sync_coord', - metrics: 'github_metrics', - }; - } - - /** - * Initialize the GitHub integration view - */ - async initialize() { - if (this.isInitialized) return; - - // Get component library from event bus - this.eventBus.emit('component-library:get', (library) => { - this.componentLibrary = library; - }); - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - } - - /** - * Render the view with given parameters - */ - async render(params = {}) { - if (!this.isInitialized) { - await this.initialize(); - } - - // Clear container - if (this.container) { - this.container.innerHTML = ''; - this.createGitHubInterface(); - } else { - // Terminal mode - this.renderTerminalMode(params); - } - } - - /** - * Create GitHub interface for browser - */ - createGitHubInterface() { - // Create tab container - const tabs = [ - { label: '๐Ÿ  Overview', content: this.createOverviewTab() }, - { label: '๐Ÿ“ Repositories', content: this.createRepositoriesTab() }, - { label: '๐Ÿ”„ Pull Requests', content: this.createPullRequestsTab() }, - { label: '๐Ÿ“‹ Issues', content: this.createIssuesTab() }, - { label: '๐Ÿš€ Releases', content: this.createReleasesTab() }, - { label: '๐Ÿค– Automation', content: this.createAutomationTab() }, - { label: '๐Ÿ“Š Analytics', content: this.createAnalyticsTab() }, - { label: '๐Ÿ” Code Review', content: this.createCodeReviewTab() }, - ]; - - if (this.componentLibrary) { - const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs); - this.container.appendChild(tabContainer.element); - } else { - // Fallback without component library - this.createFallbackInterface(); - } - } - - /** - * Create overview tab content - */ - createOverviewTab() { - return ` -
-
-
-
๐Ÿ“
-
-
0
-
Repositories
-
-
-
-
๐Ÿ”„
-
-
0
-
Open PRs
-
-
-
-
๐Ÿ“‹
-
-
0
-
Open Issues
-
-
-
-
โšก
-
-
0
-
Active Workflows
-
-
-
- -
-

๐Ÿ”ง Quick Actions

-
- - - - -
-
- -
-

๐Ÿ“ˆ Recent GitHub Activity

-
-
- --:-- - No recent activity -
-
-
-
- `; - } - - /** - * Create repositories tab content - */ - createRepositoriesTab() { - return ` -
-
-

๐Ÿ“ Repository Management

- -
- - - -
- - -
- -
-

๐Ÿ“Š Repository Analysis

-
-
- - -
-
- - -
- -
- -
- -
-
- -
-

๐Ÿ“‹ Repository List

-
- -
-
-
- `; - } - - /** - * Create pull requests tab content - */ - createPullRequestsTab() { - return ` -
-
-

๐Ÿ”„ Pull Request Management

- -
- - - -
-
- -
-

๐Ÿ“Š PR Dashboard

-
- - -
- -
- -
-
- -
-

โšก PR Actions

-
- - -
-
- - -
-
- - -
- -
-
- `; - } - - /** - * Create issues tab content - */ - createIssuesTab() { - return ` -
-
-

๐Ÿ“‹ Issue Tracking & Triage

- -
- - - -
-
- -
-

๐Ÿ“Š Issue Dashboard

-
-
- Open - 0 -
-
- In Progress - 0 -
-
- Closed - 0 -
-
- -
- - -
- -
- -
-
- -
-

๐Ÿท๏ธ Issue Triage

-
-
- - -
-
- - -
- -
-
-
- `; - } - - /** - * Create releases tab content - */ - createReleasesTab() { - return ` -
-
-

๐Ÿš€ Release Coordination

- -
- - - -
-
- -
-

๐Ÿ“… Release Planning

-
-
- - -
-
- - -
-
- - -
-
- - -
- -
-
- -
-

๐Ÿ“‹ Release History

-
- -
-
-
- `; - } - - /** - * Create automation tab content - */ - createAutomationTab() { - return ` -
-
-

๐Ÿค– Workflow Automation

- -
- - - -
-
- -
-

๐Ÿ”ง Workflow Builder

-
-
- - -
-
- - -
-
- - -
-
- - -
- -
-
- -
-

๐Ÿ“‹ Automation Templates

-
-
-

๐Ÿงช Test Automation

-

Automated testing on every PR

- -
-
-

๐Ÿ“ฆ Release Automation

-

Automated releases with changelog

- -
-
-

๐Ÿ” Code Review

-

Automated code review checks

- -
-
-
-
- `; - } - - /** - * Create analytics tab content - */ - createAnalyticsTab() { - return ` -
-
-

๐Ÿ“Š Repository Metrics

- -
- - - -
-
- -
-

๐Ÿ“ˆ Metrics Dashboard

-
-
-

๐Ÿ“ Commits

-
- -
-
- Total: 0 - This Week: 0 -
-
- -
-

๐Ÿ”„ Pull Requests

-
- -
-
- Merged: 0 - Avg Time: -- -
-
- -
-

๐Ÿ“‹ Issues

-
- -
-
- Resolved: 0 - Avg Time: -- -
-
- -
-

๐Ÿ‘ฅ Contributors

-
- -
-
- Active: 0 - New: 0 -
-
-
-
- -
-

๐ŸŽฏ Custom Metrics

-
-
- - -
-
- - -
-
- - -
- -
-
-
- `; - } - - /** - * Create code review tab content - */ - createCodeReviewTab() { - return ` -
-
-

๐Ÿ” Automated Code Review

- -
- - - -
-
- -
-

โš™๏ธ Review Configuration

-
-
- - -
-
- - -
-
- - -
-
- - -
- -
-
- -
-

๐Ÿ“Š Review Results

-
- -
- -
- -
-
- -
-

๐Ÿ“‹ Review Rules

-
-
- - Check for security vulnerabilities -
-
- - Verify test coverage -
-
- - Check code complexity -
-
- - Validate documentation -
-
-
-
- `; - } - - /** - * Create fallback interface without component library - */ - createFallbackInterface() { - this.container.innerHTML = ` -
-

๐Ÿ™ GitHub Integration

-

Complete GitHub operations interface with 8 integrated tools

- -
-
-

๐Ÿ“ Repository Management

- - - -
- -
-

๐Ÿ”„ PR & Issues

- - - -
- -
-

๐Ÿš€ Automation

- - -
-
- -
-

๐Ÿ“Š Output

-
Ready for GitHub operations...
-
-
- `; - } - - /** - * Render terminal mode - */ - renderTerminalMode(params) { - console.log('\n๐Ÿ™ GitHub Integration Operations'); - console.log('โ•'.repeat(50)); - console.log('Available Tools (8):'); - console.log(' ๐Ÿ“Š github_repo_analyze - Repository analysis'); - console.log(' ๐Ÿ”„ github_pr_manage - PR management'); - console.log(' ๐Ÿ“‹ github_issue_track - Issue tracking'); - console.log(' ๐Ÿš€ github_release_coord - Release coordination'); - console.log(' ๐Ÿค– github_workflow_auto - Workflow automation'); - console.log(' ๐Ÿ” github_code_review - Code reviews'); - console.log(' ๐Ÿ”„ github_sync_coord - Multi-repo sync'); - console.log(' ๐Ÿ“Š github_metrics - Repository metrics'); - console.log('โ•'.repeat(50)); - - if (params.tool) { - console.log(`\n๐Ÿ”ง Executing: ${params.tool}`); - this.quickAction(params.tool, params); - } - } - - /** - * Quick action handler - */ - async quickAction(toolName, params = {}) { - try { - console.log(`๐Ÿ”ง Executing ${toolName}...`); - - // Emit tool execution event - this.eventBus.emit('tool:execute', { - tool: toolName, - params: params, - source: 'github-view', - }); - - // Handle specific tool actions - switch (toolName) { - case 'github_repo_analyze': - await this.handleRepoAnalysis(params); - break; - case 'github_pr_manage': - await this.handlePRManagement(params); - break; - case 'github_issue_track': - await this.handleIssueTracking(params); - break; - case 'github_code_review': - await this.handleCodeReview(params); - break; - default: - console.log(`Tool ${toolName} executed`); - } - } catch (error) { - console.error(`โŒ Error executing ${toolName}:`, error); - } - } - - /** - * Handle repository analysis - */ - async handleRepoAnalysis(params) { - const analysisParams = { - repo: params.repo || 'owner/repo', - analysis_type: params.analysis_type || 'code_quality', - }; - - console.log('๐Ÿ“Š Analyzing repository with parameters:', analysisParams); - - // Update UI if in browser mode - if (this.container) { - const resultsEl = document.getElementById('analysis-results'); - if (resultsEl) { - resultsEl.innerHTML = '
Analysis in progress...
'; - } - } - } - - /** - * Handle PR management - */ - async handlePRManagement(params) { - const prParams = { - repo: params.repo || 'owner/repo', - action: params.action || 'review', - pr_number: params.pr_number, - }; - - console.log('๐Ÿ”„ Managing PR with parameters:', prParams); - - // Update UI if in browser mode - if (this.container) { - this.updatePRList(); - } - } - - /** - * Handle issue tracking - */ - async handleIssueTracking(params) { - const issueParams = { - repo: params.repo || 'owner/repo', - action: params.action || 'track', - }; - - console.log('๐Ÿ“‹ Tracking issues with parameters:', issueParams); - - // Update UI if in browser mode - if (this.container) { - this.updateIssueList(); - } - } - - /** - * Handle code review - */ - async handleCodeReview(params) { - const reviewParams = { - repo: params.repo || 'owner/repo', - pr: params.pr || 1, - type: params.type || 'full', - }; - - console.log('๐Ÿ” Running code review with parameters:', reviewParams); - - // Update UI if in browser mode - if (this.container) { - const summaryEl = document.getElementById('review-summary'); - if (summaryEl) { - summaryEl.innerHTML = '
Code review in progress...
'; - } - } - } - - /** - * Repository analysis functions - */ - async analyzeRepository() { - const repo = - document.getElementById('analyze-repo')?.value || prompt('Enter repository (owner/repo):'); - if (!repo) return; - - this.quickAction('github_repo_analyze', { repo }); - } - - async runRepoAnalysis() { - const repo = document.getElementById('analyze-repo')?.value; - const analysisType = document.getElementById('analysis-type')?.value; - - if (!repo) { - alert('Please enter a repository'); - return; - } - - this.quickAction('github_repo_analyze', { repo, analysis_type: analysisType }); - } - - /** - * PR management functions - */ - async createPullRequest() { - const repo = prompt('Enter repository (owner/repo):'); - if (!repo) return; - - console.log('๐Ÿ”„ Creating pull request for:', repo); - this.eventBus.emit('tool:execute', { - tool: 'github_pr_create', - params: { repo }, - source: 'github-view', - }); - } - - async executePRAction() { - const repo = document.getElementById('pr-repo')?.value; - const prNumber = document.getElementById('pr-number')?.value; - const action = document.getElementById('pr-action')?.value; - - if (!repo || !prNumber) { - alert('Please enter repository and PR number'); - return; - } - - this.quickAction('github_pr_manage', { repo, pr_number: prNumber, action }); - } - - /** - * Issue tracking functions - */ - async trackIssues() { - const repo = prompt('Enter repository (owner/repo):'); - if (!repo) return; - - this.quickAction('github_issue_track', { repo, action: 'track' }); - } - - async runTriage() { - const repo = document.getElementById('triage-repo')?.value; - const action = document.getElementById('triage-action')?.value; - - if (!repo) { - alert('Please enter a repository'); - return; - } - - this.quickAction('github_issue_track', { repo, action }); - } - - /** - * Metrics functions - */ - async checkMetrics() { - const repo = prompt('Enter repository (owner/repo):'); - if (!repo) return; - - this.quickAction('github_metrics', { repo }); - } - - async fetchMetrics() { - const repo = - document.getElementById('metrics-repo')?.value || prompt('Enter repository (owner/repo):'); - if (!repo) return; - - this.quickAction('github_metrics', { repo }); - } - - /** - * Code review functions - */ - async startCodeReview() { - const repo = - document.getElementById('review-repo')?.value || prompt('Enter repository (owner/repo):'); - const pr = document.getElementById('review-pr')?.value || prompt('Enter PR number:'); - - if (!repo || !pr) return; - - this.quickAction('github_code_review', { repo, pr }); - } - - async runCodeReview() { - const repo = document.getElementById('review-repo')?.value; - const pr = document.getElementById('review-pr')?.value; - const reviewType = document.getElementById('review-type')?.value; - - if (!repo || !pr) { - alert('Please enter repository and PR number'); - return; - } - - this.quickAction('github_code_review', { repo, pr, type: reviewType }); - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - // Listen for tool results - this.eventBus.on('tool:executed', (data) => { - if (data.source === 'github-view') { - this.handleToolResult(data); - } - }); - - // Listen for real-time updates - this.eventBus.on('ui:real-time:update', () => { - this.updateStats(); - }); - - // Listen for repository updates - this.eventBus.on('github:repo:updated', (data) => { - this.updateRepositoryList(data); - }); - - // Listen for PR updates - this.eventBus.on('github:pr:updated', (data) => { - this.updatePRList(data); - }); - - // Listen for issue updates - this.eventBus.on('github:issue:updated', (data) => { - this.updateIssueList(data); - }); - - // Make this view instance globally accessible for button handlers - if (typeof window !== 'undefined') { - window.githubView = this; - } - } - - /** - * Handle tool execution results - */ - handleToolResult(data) { - console.log(`โœ… Tool ${data.tool} completed:`, data.result); - - // Update UI based on result - if (this.container) { - this.updateUIWithResult(data.tool, data.result); - } - } - - /** - * Update UI with tool results - */ - updateUIWithResult(toolName, result) { - switch (toolName) { - case 'github_repo_analyze': - this.updateAnalysisResults(result); - break; - case 'github_pr_manage': - this.updatePRResults(result); - break; - case 'github_issue_track': - this.updateIssueResults(result); - break; - case 'github_code_review': - this.updateReviewResults(result); - break; - case 'github_metrics': - this.updateMetricsResults(result); - break; - } - } - - /** - * Update analysis results - */ - updateAnalysisResults(result) { - const resultsEl = document.getElementById('analysis-results'); - if (resultsEl) { - resultsEl.innerHTML = ` -
-

๐Ÿ“Š Analysis Complete

-
-
- Code Quality: - ${result.code_quality || 'N/A'} -
-
- Security: - ${result.security || 'N/A'} -
-
- Performance: - ${result.performance || 'N/A'} -
-
-
${result.details || ''}
-
- `; - } - } - - /** - * Update statistics - */ - updateStats() { - // Update repository count - const reposStatEl = document.getElementById('repos-stat'); - if (reposStatEl) { - const valueEl = reposStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.repositories.size; - } - - // Update PR count - const prsStatEl = document.getElementById('prs-stat'); - if (prsStatEl) { - const valueEl = prsStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.pullRequests.size; - } - - // Update issue count - const issuesStatEl = document.getElementById('issues-stat'); - if (issuesStatEl) { - const valueEl = issuesStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.issues.size; - } - } - - /** - * Update repository list - */ - updateRepositoryList(data) { - const listEl = document.getElementById('repositories-list'); - if (listEl) { - // Update repository cards - console.log('Updating repository list:', data); - } - } - - /** - * Update PR list - */ - updatePRList(data) { - const listEl = document.getElementById('pr-list'); - if (listEl) { - // Update PR cards - console.log('Updating PR list:', data); - } - } - - /** - * Update issue list - */ - updateIssueList(data) { - const listEl = document.getElementById('issue-list'); - if (listEl) { - // Update issue cards - console.log('Updating issue list:', data); - } - } - - /** - * Update review results - */ - updateReviewResults(result) { - const summaryEl = document.getElementById('review-summary'); - if (summaryEl) { - summaryEl.innerHTML = ` -
-

๐Ÿ” Review Complete

-
Overall Score: ${result.score || 'N/A'}
-
- Issues Found: ${result.issues || 0} - Suggestions: ${result.suggestions || 0} -
-
- `; - } - - const findingsEl = document.getElementById('review-findings'); - if (findingsEl && result.findings) { - findingsEl.innerHTML = result.findings - .map( - (finding) => ` -
- ${finding.type} - ${finding.description} -
- `, - ) - .join(''); - } - } - - /** - * Update metrics results - */ - updateMetricsResults(result) { - // Update metric values - if (result.commits) { - const commitsEl = document.getElementById('total-commits'); - if (commitsEl) commitsEl.textContent = result.commits.total || 0; - } - - if (result.pull_requests) { - const mergedEl = document.getElementById('merged-prs'); - if (mergedEl) mergedEl.textContent = result.pull_requests.merged || 0; - } - - if (result.issues) { - const resolvedEl = document.getElementById('resolved-issues'); - if (resolvedEl) resolvedEl.textContent = result.issues.resolved || 0; - } - } - - /** - * Destroy view and cleanup - */ - destroy() { - // Clear any intervals or timeouts - // Remove event listeners - // Clean up resources - console.log('๐Ÿ™ GitHub Integration View destroyed'); - } -} - -// Make view accessible globally for button handlers -if (typeof window !== 'undefined') { - window.githubView = null; -} - -// Add GitHub-specific styles -if (typeof document !== 'undefined') { - const githubStyles = document.createElement('style'); - githubStyles.textContent = ` - .github-overview { - padding: 20px; - } - - .stats-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 16px; - margin-bottom: 24px; - } - - .stat-card { - display: flex; - align-items: center; - background: #2a2a2a; - padding: 16px; - border-radius: 8px; - border: 1px solid #444; - } - - .stat-icon { - font-size: 24px; - margin-right: 12px; - } - - .stat-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .stat-label { - color: #888; - font-size: 14px; - } - - .github-tools { - margin: 24px 0; - } - - .tool-buttons { - display: flex; - gap: 12px; - flex-wrap: wrap; - } - - .github-btn { - padding: 10px 16px; - border: none; - border-radius: 6px; - cursor: pointer; - font-weight: 500; - transition: all 0.2s ease; - } - - .github-btn.primary { - background: #00d4ff; - color: #000; - } - - .github-btn.primary:hover { - background: #00b8e6; - } - - .github-btn.secondary { - background: #444; - color: #fff; - } - - .github-btn.secondary:hover { - background: #555; - } - - .form-group { - margin-bottom: 16px; - } - - .form-group label { - display: block; - margin-bottom: 4px; - color: #fff; - font-weight: 500; - } - - .form-group input, - .form-group select, - .form-group textarea { - width: 100%; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .form-group textarea { - height: 100px; - resize: vertical; - } - - .search-input { - width: 100%; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - margin: 16px 0; - } - - .repo-grid, - .pr-list, - .issue-list, - .release-list { - display: grid; - gap: 16px; - margin-top: 16px; - } - - .template-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); - gap: 16px; - } - - .template-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - } - - .template-card h4 { - margin: 0 0 8px 0; - color: #00d4ff; - } - - .template-card p { - margin: 0 0 12px 0; - color: #888; - font-size: 14px; - } - - .metric-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - } - - .metric-card h4 { - margin: 0 0 12px 0; - color: #fff; - } - - .chart-container { - height: 150px; - background: #1a1a1a; - border-radius: 4px; - margin-bottom: 12px; - display: flex; - align-items: center; - justify-content: center; - color: #666; - } - - .metric-stats { - display: flex; - justify-content: space-between; - font-size: 14px; - } - - .metric-stats span { - color: #888; - } - - .metric-stats span span { - color: #00d4ff; - font-weight: bold; - } - - .pr-filters, - .issue-filters { - display: flex; - gap: 12px; - margin-bottom: 16px; - } - - .pr-filters select, - .issue-filters select { - flex: 1; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .issue-stats { - display: flex; - gap: 24px; - margin: 16px 0; - } - - .issue-stat { - display: flex; - flex-direction: column; - align-items: center; - } - - .issue-stat .stat-label { - font-size: 14px; - color: #888; - } - - .issue-stat .stat-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .analysis-display, - .review-summary, - .review-findings { - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - padding: 16px; - margin-top: 16px; - } - - .analysis-scores, - .review-stats { - display: flex; - gap: 24px; - margin: 12px 0; - } - - .score-item { - display: flex; - gap: 8px; - } - - .score-label { - color: #888; - } - - .score-value { - color: #00d4ff; - font-weight: bold; - } - - .rules-list { - display: flex; - flex-direction: column; - gap: 8px; - } - - .rule-item { - display: flex; - align-items: center; - gap: 8px; - padding: 8px; - background: #2a2a2a; - border-radius: 4px; - } - - .rule-item input[type="checkbox"] { - width: auto; - } - - .finding-item { - display: flex; - gap: 12px; - padding: 8px; - background: #2a2a2a; - border-radius: 4px; - margin-bottom: 8px; - } - - .finding-type { - padding: 2px 8px; - background: #444; - border-radius: 4px; - font-size: 12px; - font-weight: bold; - } - - .finding-desc { - flex: 1; - color: #ccc; - } - - .activity-list { - max-height: 200px; - overflow-y: auto; - } - - .activity-item { - display: flex; - gap: 12px; - padding: 8px; - border-bottom: 1px solid #333; - } - - .activity-time { - color: #666; - font-size: 12px; - } - - .activity-desc { - color: #ccc; - flex: 1; - } - `; - document.head.appendChild(githubStyles); -} diff --git a/src/ui/web-ui/views/NeuralNetworkView.js b/src/ui/web-ui/views/NeuralNetworkView.js deleted file mode 100644 index 94f15fcb99..0000000000 --- a/src/ui/web-ui/views/NeuralNetworkView.js +++ /dev/null @@ -1,919 +0,0 @@ -/** - * Neural Network View - Interface for neural network operations - * Handles training, prediction, pattern analysis, and model management - */ - -export default class NeuralNetworkView { - constructor(container, eventBus, viewConfig) { - this.container = container; - this.eventBus = eventBus; - this.viewConfig = viewConfig; - this.componentLibrary = null; - this.models = new Map(); - this.trainingJobs = new Map(); - this.currentTab = 'overview'; - this.isInitialized = false; - } - - /** - * Initialize the neural network view - */ - async initialize() { - if (this.isInitialized) return; - - // Get component library from event bus - this.eventBus.emit('component-library:get', (library) => { - this.componentLibrary = library; - }); - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - } - - /** - * Render the view with given parameters - */ - async render(params = {}) { - if (!this.isInitialized) { - await this.initialize(); - } - - // Clear container - if (this.container) { - this.container.innerHTML = ''; - this.createNeuralNetworkInterface(); - } else { - // Terminal mode - this.renderTerminalMode(params); - } - } - - /** - * Create neural network interface for browser - */ - createNeuralNetworkInterface() { - // Create tab container - const tabs = [ - { label: '๐Ÿ“Š Overview', content: this.createOverviewTab() }, - { label: '๐Ÿง  Training', content: this.createTrainingTab() }, - { label: '๐Ÿ”ฎ Prediction', content: this.createPredictionTab() }, - { label: '๐ŸŽฏ Patterns', content: this.createPatternsTab() }, - { label: '๐Ÿ’พ Models', content: this.createModelsTab() }, - { label: 'โšก Optimization', content: this.createOptimizationTab() }, - ]; - - if (this.componentLibrary) { - const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs); - this.container.appendChild(tabContainer.element); - } else { - // Fallback without component library - this.createFallbackInterface(); - } - } - - /** - * Create overview tab content - */ - createOverviewTab() { - return ` -
-
-
-
๐Ÿง 
-
-
0
-
Models
-
-
-
-
โšก
-
-
0
-
Training Jobs
-
-
-
-
๐ŸŽฏ
-
-
--
-
Avg Accuracy
-
-
-
-
๐Ÿš€
-
-
--
-
WASM Status
-
-
-
- -
-

๐Ÿ”ง Quick Actions

-
- - - - -
-
- -
-

๐Ÿ“ˆ Recent Activity

-
-
- --:-- - No recent activity -
-
-
-
- `; - } - - /** - * Create training tab content - */ - createTrainingTab() { - return ` -
-
-

๐Ÿง  Neural Network Training

- -
- - -
- -
- - -
- -
- - -
- -
- - -
- - -
- -
-

๐Ÿ“Š Training Progress

-
-
No training in progress
-
- -
- -
-
- -
-

๐Ÿ“‹ Training History

-
- -
-
-
- `; - } - - /** - * Create prediction tab content - */ - createPredictionTab() { - return ` -
-
-

๐Ÿ”ฎ AI Prediction

- -
- - -
- -
- - -
- - -
- -
-

๐Ÿ“Š Prediction Results

-
-
No predictions yet
-
- -
-

๐ŸŽฏ Confidence Score

-
-
- 0% -
-
-
- -
-

๐Ÿ“‹ Recent Predictions

-
- -
-
-
- `; - } - - /** - * Create patterns tab content - */ - createPatternsTab() { - return ` -
-
-

๐ŸŽฏ Pattern Analysis

- -
- - -
- -
- - -
- -
- - -
- - -
- -
-

๐Ÿ“Š Pattern Insights

-
-
No pattern analysis yet
-
-
- -
-

๐Ÿง  Cognitive Analysis

- -
- - -
- - - -
- -
-
-
- `; - } - - /** - * Create models tab content - */ - createModelsTab() { - return ` -
-
-

๐Ÿ’พ Model Management

- -
- - - -
-
- -
-

๐Ÿ“‹ Available Models

-
- -
-
- -
-

๐Ÿ”ง Model Operations

- -
-
-

๐Ÿ—œ๏ธ Compress Model

-

Reduce model size for faster inference

- -
- -
-

๐Ÿ”„ Transfer Learning

-

Adapt model to new domain

- -
- -
-

๐Ÿ“Š Model Explain

-

Get AI explainability insights

- -
-
-
-
- `; - } - - /** - * Create optimization tab content - */ - createOptimizationTab() { - return ` -
-
-

๐Ÿš€ WASM SIMD Optimization

- -
-
-
๐Ÿš€
-
Checking WASM status...
-
-
- -
- - -
-
- -
-

๐Ÿ”ฎ Inference Optimization

- -
- - -
- -
- - -
- - - -
- -
-
- -
-

๐Ÿ“ˆ Performance Metrics

- -
-
-
Inference Speed
-
-- ms
-
- -
-
Memory Usage
-
-- MB
-
- -
-
WASM Speedup
-
--x
-
-
-
-
- `; - } - - /** - * Create fallback interface without component library - */ - createFallbackInterface() { - this.container.innerHTML = ` -
-

๐Ÿง  Neural Network Operations

-

Advanced neural network interface with 15 integrated tools

- -
-
-

๐Ÿง  Training & Models

- - - - -
- -
-

๐Ÿ”ฎ Prediction & Analysis

- - - - -
- -
-

โšก Optimization

- - - - -
-
- -
-

๐Ÿ“Š Output

-
Ready for neural operations...
-
-
- `; - } - - /** - * Render terminal mode - */ - renderTerminalMode(params) { - console.log('\n๐Ÿง  Neural Network Operations'); - console.log('โ•'.repeat(50)); - console.log('Available Tools (15):'); - console.log(' ๐Ÿง  neural_train - Train neural patterns'); - console.log(' ๐Ÿ”ฎ neural_predict - Make AI predictions'); - console.log(' ๐Ÿ“Š neural_status - Check model status'); - console.log(' ๐ŸŽฏ neural_patterns - Analyze patterns'); - console.log(' ๐Ÿ’พ model_save - Save trained models'); - console.log(' ๐Ÿ“ฅ model_load - Load models'); - console.log(' ๐ŸŽฏ pattern_recognize- Pattern recognition'); - console.log(' ๐Ÿง  cognitive_analyze- Behavior analysis'); - console.log(' ๐Ÿ”„ learning_adapt - Adaptive learning'); - console.log(' ๐Ÿ—œ๏ธ neural_compress - Model compression'); - console.log(' ๐Ÿ”— ensemble_create - Model ensembles'); - console.log(' ๐Ÿ”„ transfer_learn - Transfer learning'); - console.log(' ๐Ÿ“Š neural_explain - AI explainability'); - console.log(' ๐Ÿš€ wasm_optimize - WASM optimization'); - console.log(' ๐Ÿ”ฎ inference_run - Neural inference'); - console.log('โ•'.repeat(50)); - - if (params.tool) { - console.log(`\n๐Ÿ”ง Executing: ${params.tool}`); - this.quickAction(params.tool, params); - } - } - - /** - * Quick action handler - */ - async quickAction(toolName, params = {}) { - try { - console.log(`๐Ÿ”ง Executing ${toolName}...`); - - // Emit tool execution event - this.eventBus.emit('tool:execute', { - tool: toolName, - params: params, - source: 'neural-view', - }); - - // Handle specific tool actions - switch (toolName) { - case 'neural_train': - await this.handleTraining(params); - break; - case 'neural_predict': - await this.handlePrediction(params); - break; - case 'neural_patterns': - await this.handlePatternAnalysis(params); - break; - default: - console.log(`Tool ${toolName} executed`); - } - } catch (error) { - console.error(`โŒ Error executing ${toolName}:`, error); - } - } - - /** - * Handle training operations - */ - async handleTraining(params) { - const trainingParams = { - pattern_type: params.pattern_type || 'coordination', - training_data: params.training_data || 'sample_data', - epochs: params.epochs || 50, - }; - - console.log('๐Ÿง  Training neural network with parameters:', trainingParams); - - // Update UI if in browser mode - if (this.container) { - const statusEl = document.getElementById('training-status'); - if (statusEl) { - statusEl.innerHTML = '
Training in progress...
'; - } - } - } - - /** - * Handle prediction operations - */ - async handlePrediction(params) { - const predictionParams = { - modelId: params.modelId || 'default_model', - input: params.input || 'sample_input', - }; - - console.log('๐Ÿ”ฎ Running prediction with parameters:', predictionParams); - - // Update UI if in browser mode - if (this.container) { - const outputEl = document.getElementById('prediction-output'); - if (outputEl) { - outputEl.innerHTML = '
Prediction in progress...
'; - } - } - } - - /** - * Handle pattern analysis - */ - async handlePatternAnalysis(params) { - const analysisParams = { - action: params.action || 'analyze', - operation: params.operation || 'sample_operation', - outcome: params.outcome || 'sample_outcome', - }; - - console.log('๐ŸŽฏ Analyzing patterns with parameters:', analysisParams); - - // Update UI if in browser mode - if (this.container) { - const insightsEl = document.getElementById('pattern-insights'); - if (insightsEl) { - insightsEl.innerHTML = '
Pattern analysis in progress...
'; - } - } - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - // Listen for tool results - this.eventBus.on('tool:executed', (data) => { - if (data.source === 'neural-view') { - this.handleToolResult(data); - } - }); - - // Listen for real-time updates - this.eventBus.on('ui:real-time:update', () => { - this.updateStats(); - }); - - // Listen for theme changes - this.eventBus.on('ui:theme:changed', (theme) => { - this.updateTheme(theme); - }); - } - - /** - * Handle tool execution results - */ - handleToolResult(data) { - console.log(`โœ… Tool ${data.tool} completed:`, data.result); - - // Update UI based on result - if (this.container) { - this.updateUIWithResult(data.tool, data.result); - } - } - - /** - * Update UI with tool results - */ - updateUIWithResult(toolName, result) { - // Update based on specific tool - switch (toolName) { - case 'neural_train': - this.updateTrainingResults(result); - break; - case 'neural_predict': - this.updatePredictionResults(result); - break; - case 'neural_patterns': - this.updatePatternResults(result); - break; - } - } - - /** - * Update training results in UI - */ - updateTrainingResults(result) { - const statusEl = document.getElementById('training-status'); - if (statusEl) { - statusEl.innerHTML = ` -
- โœ… Training completed! -
-
Epochs: ${result.epochs}
-
Accuracy: ${result.accuracy}
-
Loss: ${result.loss}
-
-
- `; - } - } - - /** - * Update prediction results in UI - */ - updatePredictionResults(result) { - const outputEl = document.getElementById('prediction-output'); - if (outputEl) { - outputEl.innerHTML = ` -
-
${result.prediction}
-
Confidence: ${result.confidence}
-
- `; - } - - // Update confidence bar - const confidenceBar = document.querySelector('.confidence-fill'); - const confidenceText = document.querySelector('.confidence-text'); - if (confidenceBar && confidenceText) { - const confidence = Math.round(result.confidence * 100); - confidenceBar.style.width = `${confidence}%`; - confidenceText.textContent = `${confidence}%`; - } - } - - /** - * Update pattern analysis results - */ - updatePatternResults(result) { - const insightsEl = document.getElementById('pattern-insights'); - if (insightsEl) { - insightsEl.innerHTML = ` -
-
Pattern Analysis Complete
-
${result.insights}
-
- Patterns: ${result.patterns ? result.patterns.join(', ') : 'None'} -
-
- `; - } - } - - /** - * Update statistics - */ - updateStats() { - // Update model count - const modelsStatEl = document.getElementById('models-stat'); - if (modelsStatEl) { - const valueEl = modelsStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.models.size; - } - - // Update training jobs count - const trainingStatEl = document.getElementById('training-stat'); - if (trainingStatEl) { - const valueEl = trainingStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.trainingJobs.size; - } - } - - /** - * Update theme - */ - updateTheme(theme) { - if (this.container) { - this.container.classList.remove('theme-dark', 'theme-light'); - this.container.classList.add(`theme-${theme}`); - } - } - - /** - * Destroy view and cleanup - */ - destroy() { - // Clear any intervals or timeouts - // Remove event listeners - // Clean up resources - console.log('๐Ÿง  Neural Network View destroyed'); - } -} - -// Add neural network specific styles -if (typeof document !== 'undefined') { - const neuralStyles = document.createElement('style'); - neuralStyles.textContent = ` - .neural-overview { - padding: 20px; - } - - .stats-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 16px; - margin-bottom: 24px; - } - - .stat-card { - display: flex; - align-items: center; - background: #2a2a2a; - padding: 16px; - border-radius: 8px; - border: 1px solid #444; - } - - .stat-icon { - font-size: 24px; - margin-right: 12px; - } - - .stat-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .stat-label { - color: #888; - font-size: 14px; - } - - .neural-tools { - margin: 24px 0; - } - - .tool-buttons { - display: flex; - gap: 12px; - flex-wrap: wrap; - } - - .neural-btn { - padding: 10px 16px; - border: none; - border-radius: 6px; - cursor: pointer; - font-weight: 500; - transition: all 0.2s ease; - } - - .neural-btn.primary { - background: #00d4ff; - color: #000; - } - - .neural-btn.primary:hover { - background: #00b8e6; - } - - .neural-btn.secondary { - background: #444; - color: #fff; - } - - .neural-btn.secondary:hover { - background: #555; - } - - .form-group { - margin-bottom: 16px; - } - - .form-group label { - display: block; - margin-bottom: 4px; - color: #fff; - font-weight: 500; - } - - .form-group input, - .form-group select, - .form-group textarea { - width: 100%; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .form-group textarea { - height: 100px; - resize: vertical; - } - - .confidence-bar { - position: relative; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - height: 24px; - overflow: hidden; - } - - .confidence-fill { - height: 100%; - background: linear-gradient(90deg, #00d4ff, #0099cc); - transition: width 0.3s ease; - } - - .confidence-text { - position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - color: #fff; - font-size: 12px; - font-weight: bold; - } - - .operation-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); - gap: 16px; - } - - .operation-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - } - - .operation-card h4 { - margin: 0 0 8px 0; - color: #00d4ff; - } - - .operation-card p { - margin: 0 0 12px 0; - color: #888; - font-size: 14px; - } - `; - document.head.appendChild(neuralStyles); -} diff --git a/src/ui/web-ui/views/WorkflowAutomationView.js b/src/ui/web-ui/views/WorkflowAutomationView.js deleted file mode 100644 index 4ce1b08f4f..0000000000 --- a/src/ui/web-ui/views/WorkflowAutomationView.js +++ /dev/null @@ -1,1515 +0,0 @@ -/** - * Workflow & Automation View - Interface for workflow and automation tools - * Handles workflow creation, automation rules, pipelines, scheduling, and SPARC modes - */ - -class WorkflowAutomationView { - constructor(container, eventBus, viewConfig) { - this.container = container; - this.eventBus = eventBus; - this.viewConfig = viewConfig; - this.componentLibrary = null; - this.workflows = new Map(); - this.pipelines = new Map(); - this.automationRules = new Map(); - this.scheduledTasks = new Map(); - this.currentTab = 'overview'; - this.isInitialized = false; - this.draggedElement = null; - this.dropZones = new Set(); - } - - /** - * Initialize the workflow & automation view - */ - async initialize() { - if (this.isInitialized) return; - - // Get component library from event bus - this.eventBus.emit('component-library:get', (library) => { - this.componentLibrary = library; - }); - - // Setup event handlers - this.setupEventHandlers(); - - this.isInitialized = true; - } - - /** - * Render the view with given parameters - */ - async render(params = {}) { - if (!this.isInitialized) { - await this.initialize(); - } - - // Clear container - if (this.container) { - this.container.innerHTML = ''; - this.createWorkflowInterface(); - } else { - // Terminal mode - this.renderTerminalMode(params); - } - } - - /** - * Create workflow interface for browser - */ - createWorkflowInterface() { - // Create tab container - const tabs = [ - { label: '๐Ÿ“Š Overview', content: this.createOverviewTab() }, - { label: '๐Ÿ”„ Workflows', content: this.createWorkflowsTab() }, - { label: 'โšก Automation', content: this.createAutomationTab() }, - { label: '๐Ÿš€ Pipelines', content: this.createPipelinesTab() }, - { label: '๐Ÿ“… Scheduler', content: this.createSchedulerTab() }, - { label: '๐ŸŽฏ SPARC Modes', content: this.createSparcModesTab() }, - { label: '๐Ÿ“ฆ Batch & Parallel', content: this.createBatchTab() }, - ]; - - if (this.componentLibrary) { - const tabContainer = this.componentLibrary.getComponent('TabContainer')(tabs); - this.container.appendChild(tabContainer.element); - } else { - // Fallback without component library - this.createFallbackInterface(); - } - } - - /** - * Create overview tab content - */ - createOverviewTab() { - return ` -
-
-
-
๐Ÿ”„
-
-
0
-
Active Workflows
-
-
-
-
๐Ÿš€
-
-
0
-
Running Pipelines
-
-
-
-
โšก
-
-
0
-
Automation Rules
-
-
-
-
๐Ÿ“…
-
-
0
-
Scheduled Tasks
-
-
-
- -
-

๐Ÿ”ง Quick Actions

-
- - - - -
-
- -
-

๐Ÿ“ˆ Recent Activity

-
-
- --:-- - No recent activity -
-
-
-
- `; - } - - /** - * Create workflows tab content with visual builder - */ - createWorkflowsTab() { - return ` -
-
-

๐Ÿ”„ Visual Workflow Builder

- -
-
-

๐Ÿ“ฆ Workflow Components

-
-
- ๐ŸŽฏ - Trigger -
-
- โšก - Action -
-
- ๐Ÿ”€ - Condition -
-
- ๐Ÿ” - Loop -
-
- ๐Ÿ”€ - Parallel -
-
- ๐ŸŽฏ - SPARC Mode -
-
-
- -
-
-
- Drop to start workflow -
-
-
- -
-

โš™๏ธ Properties

-
-

Select a component to configure

-
-
-
- -
- - - - -
-
- -
-

๐Ÿ“‹ Saved Workflows

-
- -
-
-
- `; - } - - /** - * Create automation tab content - */ - createAutomationTab() { - return ` -
-
-

โšก Automation Rules

- -
-

Create New Rule

- -
- - -
- -
- - -
- -
- - -
- -
- -
-
- -
- -
-
- - -
-
- -
-

๐Ÿ“‹ Active Rules

-
- -
-
- -
-

๐ŸŽฏ Event Triggers

- -
-
- -
- - - - - - - -
-
- - -
-
-
- `; - } - - /** - * Create pipelines tab content - */ - createPipelinesTab() { - return ` -
-
-

๐Ÿš€ CI/CD Pipeline Builder

- -
-
- - -
- -
- - -
- -
-

Pipeline Stages

-
-
- - -
-
- - -
-
- -
- - -
-
- -
-

๐Ÿ“Š Pipeline Monitor

-
- -
-
- -
-

๐Ÿ“‹ Execution History

-
- -
-
-
- `; - } - - /** - * Create scheduler tab content - */ - createSchedulerTab() { - return ` -
-
-

๐Ÿ“… Task Scheduler

- -
-
- - -
- -
- - -
- -
- - -
- -
-
- - -
-
- -
- - -
- - -
-
- -
-

๐Ÿ“† Schedule Calendar

-
- -
-
- -
-

๐Ÿ“‹ Scheduled Tasks

-
- -
-
-
- `; - } - - /** - * Create SPARC modes tab content - */ - createSparcModesTab() { - return ` -
-
-

๐ŸŽฏ SPARC Development Modes

- -
-
- - -
- -
-

Select a SPARC mode to see its description and capabilities.

-
- -
- - -
- -
- -
- - - -
-
- - -
-
- -
-

๐ŸŽญ Multi-Mode Orchestration

- -
-

Boomerang Pattern

-

Create an iterative development flow where results from one phase inform the next.

- -
-
- 1 - -
-
โ†’
-
- 2 - -
-
โ†’
-
- 3 - -
-
โ†’
-
- 4 - -
-
โ†’
-
- 5 - -
-
โ†ฉ๏ธ
-
- - -
-
- -
-

๐Ÿ“‹ SPARC Execution History

-
- -
-
-
- `; - } - - /** - * Create batch & parallel tab content - */ - createBatchTab() { - return ` -
-
-

๐Ÿ“ฆ Batch Processing

- -
-
- - -
- -
- - -
- -
- - -
- - -
-
- -
-

โšก Parallel Execution

- -
-
- -
-
- - -
-
- -
- -
- - -
- - -
-
- -
-

๐Ÿ“Š Execution Monitor

-
- -
-
-
- `; - } - - /** - * Create fallback interface without component library - */ - createFallbackInterface() { - this.container.innerHTML = ` -
-

๐Ÿ”„ Workflow & Automation Tools

-

Comprehensive workflow automation with 11 integrated tools

- -
-
-

๐Ÿ”„ Workflow Management

- - - - -
- -
-

โšก Automation & Pipelines

- - - - -
- -
-

๐ŸŽฏ Execution Modes

- - - - -
-
- -
-

๐Ÿ“Š Output

-
Ready for workflow operations...
-
-
- `; - } - - /** - * Render terminal mode - */ - renderTerminalMode(params) { - console.log('\n๐Ÿ”„ Workflow & Automation Tools'); - console.log('โ•'.repeat(50)); - console.log('Available Tools (11):'); - console.log(' ๐Ÿ”„ workflow_create - Create custom workflows'); - console.log(' โ–ถ๏ธ workflow_execute - Execute workflows'); - console.log(' โšก automation_setup - Setup automation rules'); - console.log(' ๐Ÿš€ pipeline_create - Create CI/CD pipelines'); - console.log(' ๐Ÿ“… scheduler_manage - Manage task scheduling'); - console.log(' ๐ŸŽฏ trigger_setup - Configure event triggers'); - console.log(' ๐Ÿ“‹ workflow_template- Manage templates'); - console.log(' ๐Ÿ“ฆ batch_process - Batch processing'); - console.log(' โšก parallel_execute - Parallel execution'); - console.log(' ๐ŸŽฏ sparc_mode - SPARC development modes'); - console.log(' ๐ŸŽญ task_orchestrate - Task orchestration'); - console.log('โ•'.repeat(50)); - - if (params.tool) { - console.log(`\n๐Ÿ”ง Executing: ${params.tool}`); - this.quickAction(params.tool, params); - } - } - - /** - * Quick action handler - */ - async quickAction(toolName, params = {}) { - try { - console.log(`๐Ÿ”ง Executing ${toolName}...`); - - // Emit tool execution event - this.eventBus.emit('tool:execute', { - tool: toolName, - params: params, - source: 'workflow-view', - }); - - // Handle specific tool actions - switch (toolName) { - case 'workflow_create': - await this.handleWorkflowCreate(params); - break; - case 'automation_setup': - await this.handleAutomationSetup(params); - break; - case 'sparc_mode': - await this.handleSparcMode(params); - break; - default: - console.log(`Tool ${toolName} executed`); - } - } catch (error) { - console.error(`โŒ Error executing ${toolName}:`, error); - } - } - - /** - * Handle workflow creation - */ - async handleWorkflowCreate(params) { - const workflowParams = { - name: params.name || 'New Workflow', - steps: params.steps || [], - triggers: params.triggers || [], - }; - - console.log('๐Ÿ”„ Creating workflow with parameters:', workflowParams); - - // Update UI if in browser mode - if (this.container) { - const listEl = document.getElementById('workflows-list'); - if (listEl) { - const workflowCard = this.createWorkflowCard(workflowParams); - listEl.appendChild(workflowCard); - } - } - } - - /** - * Handle automation setup - */ - async handleAutomationSetup(params) { - const automationParams = { - rules: params.rules || [], - }; - - console.log('โšก Setting up automation with parameters:', automationParams); - - // Update UI if in browser mode - if (this.container) { - const listEl = document.getElementById('automation-rules-list'); - if (listEl) { - const ruleCard = this.createRuleCard(automationParams); - listEl.appendChild(ruleCard); - } - } - } - - /** - * Handle SPARC mode execution - */ - async handleSparcMode(params) { - const sparcParams = { - mode: params.mode || 'code', - task_description: params.task_description || 'Build feature', - options: params.options || {}, - }; - - console.log('๐ŸŽฏ Executing SPARC mode with parameters:', sparcParams); - - // Update UI if in browser mode - if (this.container) { - const historyEl = document.getElementById('sparc-history-list'); - if (historyEl) { - const historyItem = this.createSparcHistoryItem(sparcParams); - historyEl.appendChild(historyItem); - } - } - } - - /** - * Create workflow card element - */ - createWorkflowCard(workflow) { - const card = document.createElement('div'); - card.className = 'workflow-card'; - card.innerHTML = ` -
-

${workflow.name}

- Active -
-
- ${workflow.steps.length} steps - ${workflow.triggers.length} triggers -
-
- - -
- `; - return card; - } - - /** - * Create rule card element - */ - createRuleCard(rule) { - const card = document.createElement('div'); - card.className = 'rule-card'; - card.innerHTML = ` -
-

Automation Rule

- Active -
-
- ${rule.rules.length} conditions -
-
- - -
- `; - return card; - } - - /** - * Create SPARC history item - */ - createSparcHistoryItem(execution) { - const item = document.createElement('div'); - item.className = 'history-item'; - item.innerHTML = ` - ${new Date().toLocaleTimeString()} - ${execution.mode} - ${execution.task_description.substring(0, 50)}... - `; - return item; - } - - /** - * Initialize drag and drop for workflow builder - */ - initializeDragDrop() { - if (!this.container) return; - - // Setup draggable components - const draggables = this.container.querySelectorAll('.draggable-component'); - draggables.forEach((draggable) => { - draggable.addEventListener('dragstart', this.handleDragStart.bind(this)); - draggable.addEventListener('dragend', this.handleDragEnd.bind(this)); - }); - - // Setup drop zones - const canvas = document.getElementById('workflow-canvas'); - if (canvas) { - canvas.addEventListener('dragover', this.handleDragOver.bind(this)); - canvas.addEventListener('drop', this.handleDrop.bind(this)); - } - } - - /** - * Handle drag start - */ - handleDragStart(e) { - this.draggedElement = e.target; - e.target.classList.add('dragging'); - e.dataTransfer.effectAllowed = 'copy'; - e.dataTransfer.setData('componentType', e.target.dataset.type); - } - - /** - * Handle drag end - */ - handleDragEnd(e) { - e.target.classList.remove('dragging'); - this.draggedElement = null; - } - - /** - * Handle drag over - */ - handleDragOver(e) { - e.preventDefault(); - e.dataTransfer.dropEffect = 'copy'; - } - - /** - * Handle drop - */ - handleDrop(e) { - e.preventDefault(); - const componentType = e.dataTransfer.getData('componentType'); - this.addWorkflowComponent(componentType, e); - } - - /** - * Add workflow component to canvas - */ - addWorkflowComponent(type, event) { - const canvas = document.getElementById('workflow-canvas'); - if (!canvas) return; - - const component = document.createElement('div'); - component.className = 'workflow-component'; - component.dataset.type = type; - - const icons = { - trigger: '๐ŸŽฏ', - action: 'โšก', - condition: '๐Ÿ”€', - loop: '๐Ÿ”', - parallel: '๐Ÿ”€', - sparc: '๐ŸŽฏ', - }; - - component.innerHTML = ` -
- ${icons[type]} - ${type} -
-
- -
-
-
-
-
- `; - - canvas.appendChild(component); - } - - /** - * Update SPARC mode description - */ - updateSparcDescription() { - const modeSelect = document.getElementById('sparc-mode'); - const descriptionEl = document.getElementById('sparc-description'); - - if (!modeSelect || !descriptionEl) return; - - const descriptions = { - architect: '๐Ÿ—๏ธ Design system architecture and create technical specifications', - code: '๐Ÿ’ป Implement features with clean, maintainable code', - tdd: '๐Ÿงช Write tests first, then implement functionality', - debug: '๐Ÿ› Identify and fix bugs systematically', - 'security-review': '๐Ÿ”’ Analyze code for security vulnerabilities', - 'docs-writer': '๐Ÿ“ Create comprehensive documentation', - integration: '๐Ÿ”— Connect systems and APIs seamlessly', - monitoring: '๐Ÿ“Š Setup monitoring and observability', - optimization: 'โšก Improve performance and efficiency', - devops: '๐Ÿ”ง Automate deployment and infrastructure', - mcp: '๐ŸŽ›๏ธ Integrate MCP tools and protocols', - swarm: '๐Ÿ Orchestrate multi-agent workflows', - ask: 'โ“ Interactive problem-solving assistant', - tutorial: '๐ŸŽ“ Create step-by-step tutorials', - generic: '๐Ÿ”จ Handle any development task', - }; - - const selectedMode = modeSelect.value; - descriptionEl.innerHTML = `

${descriptions[selectedMode] || 'Select a SPARC mode to see its description.'}

`; - } - - /** - * Setup event handlers - */ - setupEventHandlers() { - // Listen for tool results - this.eventBus.on('tool:executed', (data) => { - if (data.source === 'workflow-view') { - this.handleToolResult(data); - } - }); - - // Listen for real-time updates - this.eventBus.on('ui:real-time:update', () => { - this.updateStats(); - }); - - // Listen for theme changes - this.eventBus.on('ui:theme:changed', (theme) => { - this.updateTheme(theme); - }); - - // Initialize drag and drop when view is rendered - this.eventBus.on('view:rendered', () => { - this.initializeDragDrop(); - }); - } - - /** - * Handle tool execution results - */ - handleToolResult(data) { - console.log(`โœ… Tool ${data.tool} completed:`, data.result); - - // Update UI based on result - if (this.container) { - this.updateUIWithResult(data.tool, data.result); - } - } - - /** - * Update UI with tool results - */ - updateUIWithResult(toolName, result) { - // Update activity log - const activityLog = document.getElementById('workflow-activity-log'); - if (activityLog) { - const activityItem = document.createElement('div'); - activityItem.className = 'activity-item'; - activityItem.innerHTML = ` - ${new Date().toLocaleTimeString()} - ${toolName} executed successfully - `; - activityLog.insertBefore(activityItem, activityLog.firstChild); - } - } - - /** - * Update statistics - */ - updateStats() { - // Update workflow count - const workflowsStatEl = document.getElementById('workflows-stat'); - if (workflowsStatEl) { - const valueEl = workflowsStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.workflows.size; - } - - // Update pipeline count - const pipelinesStatEl = document.getElementById('pipelines-stat'); - if (pipelinesStatEl) { - const valueEl = pipelinesStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.pipelines.size; - } - - // Update automation rules count - const rulesStatEl = document.getElementById('rules-stat'); - if (rulesStatEl) { - const valueEl = rulesStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.automationRules.size; - } - - // Update scheduled tasks count - const scheduledStatEl = document.getElementById('scheduled-stat'); - if (scheduledStatEl) { - const valueEl = scheduledStatEl.querySelector('.stat-value'); - if (valueEl) valueEl.textContent = this.scheduledTasks.size; - } - } - - /** - * Update theme - */ - updateTheme(theme) { - if (this.container) { - this.container.classList.remove('theme-dark', 'theme-light'); - this.container.classList.add(`theme-${theme}`); - } - } - - /** - * Destroy view and cleanup - */ - destroy() { - // Clear any intervals or timeouts - // Remove event listeners - // Clean up resources - console.log('๐Ÿ”„ Workflow & Automation View destroyed'); - } -} - -// Add workflow specific styles -if (typeof document !== 'undefined') { - const workflowStyles = document.createElement('style'); - workflowStyles.textContent = ` - .workflow-overview { - padding: 20px; - } - - .stats-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 16px; - margin-bottom: 24px; - } - - .stat-card { - display: flex; - align-items: center; - background: #2a2a2a; - padding: 16px; - border-radius: 8px; - border: 1px solid #444; - } - - .stat-icon { - font-size: 24px; - margin-right: 12px; - } - - .stat-value { - font-size: 24px; - font-weight: bold; - color: #00d4ff; - } - - .stat-label { - color: #888; - font-size: 14px; - } - - .workflow-tools { - margin: 24px 0; - } - - .tool-buttons { - display: flex; - gap: 12px; - flex-wrap: wrap; - } - - .workflow-btn { - padding: 10px 16px; - border: none; - border-radius: 6px; - cursor: pointer; - font-weight: 500; - transition: all 0.2s ease; - } - - .workflow-btn.primary { - background: #00d4ff; - color: #000; - } - - .workflow-btn.primary:hover { - background: #00b8e6; - } - - .workflow-btn.secondary { - background: #444; - color: #fff; - } - - .workflow-btn.secondary:hover { - background: #555; - } - - .workflow-btn.small { - padding: 6px 12px; - font-size: 14px; - } - - .workflow-btn.danger { - background: #ff4444; - color: #fff; - } - - .builder-container { - display: grid; - grid-template-columns: 200px 1fr 250px; - gap: 16px; - height: 500px; - margin: 20px 0; - } - - .builder-sidebar { - background: #1a1a1a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - overflow-y: auto; - } - - .component-palette { - display: flex; - flex-direction: column; - gap: 8px; - } - - .draggable-component { - display: flex; - align-items: center; - gap: 8px; - background: #2a2a2a; - border: 1px solid #444; - border-radius: 6px; - padding: 8px 12px; - cursor: move; - transition: all 0.2s ease; - } - - .draggable-component:hover { - background: #333; - border-color: #00d4ff; - } - - .draggable-component.dragging { - opacity: 0.5; - } - - .builder-canvas { - background: #1a1a1a; - border: 2px dashed #444; - border-radius: 8px; - padding: 16px; - overflow: auto; - position: relative; - } - - .canvas-grid { - min-height: 100%; - position: relative; - } - - .drop-zone { - border: 2px dashed #666; - border-radius: 8px; - padding: 40px; - text-align: center; - color: #888; - transition: all 0.2s ease; - } - - .drop-zone.drag-over { - border-color: #00d4ff; - background: rgba(0, 212, 255, 0.1); - } - - .workflow-component { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 12px; - margin: 8px 0; - position: relative; - } - - .component-header { - display: flex; - align-items: center; - gap: 8px; - margin-bottom: 8px; - } - - .component-config { - width: 100%; - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .builder-properties { - background: #1a1a1a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - overflow-y: auto; - } - - .form-group { - margin-bottom: 16px; - } - - .form-group label { - display: block; - margin-bottom: 4px; - color: #fff; - font-weight: 500; - } - - .form-group input, - .form-group select, - .form-group textarea { - width: 100%; - padding: 8px 12px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .form-group textarea { - height: 100px; - resize: vertical; - } - - .sparc-description { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - margin: 16px 0; - } - - .boomerang-phases { - display: flex; - align-items: center; - gap: 16px; - margin: 20px 0; - padding: 20px; - background: #2a2a2a; - border-radius: 8px; - overflow-x: auto; - } - - .phase-item { - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; - } - - .phase-number { - display: flex; - align-items: center; - justify-content: center; - width: 32px; - height: 32px; - background: #00d4ff; - color: #000; - border-radius: 50%; - font-weight: bold; - } - - .phase-arrow { - font-size: 24px; - color: #00d4ff; - } - - .phase-mode { - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .pipeline-stage { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 12px; - margin-bottom: 12px; - } - - .pipeline-stage input { - width: 100%; - margin-bottom: 8px; - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .pipeline-stage textarea { - width: 100%; - height: 60px; - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - resize: vertical; - } - - .monitor-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); - gap: 16px; - } - - .workflows-grid, - .rules-grid, - .tasks-grid { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); - gap: 16px; - } - - .workflow-card, - .rule-card { - background: #2a2a2a; - border: 1px solid #444; - border-radius: 8px; - padding: 16px; - } - - .workflow-header, - .rule-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 12px; - } - - .workflow-status, - .rule-status { - font-size: 12px; - padding: 4px 8px; - background: #00d4ff; - color: #000; - border-radius: 4px; - } - - .activity-list, - .history-list { - max-height: 300px; - overflow-y: auto; - } - - .activity-item, - .history-item { - display: flex; - gap: 12px; - padding: 8px; - border-bottom: 1px solid #333; - } - - .activity-time, - .history-time { - color: #888; - font-size: 14px; - } - - .event-checkboxes { - display: flex; - flex-direction: column; - gap: 8px; - } - - .event-checkboxes label { - display: flex; - align-items: center; - gap: 8px; - color: #fff; - } - - .parallel-tasks { - display: flex; - flex-direction: column; - gap: 8px; - } - - .parallel-task-item { - display: flex; - gap: 8px; - } - - .task-input { - flex: 1; - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - - .task-type { - padding: 6px; - background: #1a1a1a; - border: 1px solid #444; - border-radius: 4px; - color: #fff; - } - `; - document.head.appendChild(workflowStyles); -} - -export default WorkflowAutomationView; -export { WorkflowAutomationView };