🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
🔖 Checkpoint: Edit /workspaces/claude-code-flow/bin/claude-flow.js
rUv454cc0d73e8f
diff --git a/.claude/checkpoints/1758912075.json b/.claude/checkpoints/1758912075.jsonnew file mode 100644index 0000000000..5de05e7131--- /dev/null+++ b/.claude/checkpoints/1758912075.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250926-184115", "file": "/workspaces/claude-code-flow/CHANGELOG-alpha.128.md", "timestamp": "2025-09-26T18:41:15Z", "type": "pre-edit", "original_branch": "alpha-125"}diff --git a/.claude/checkpoints/1758912077.json b/.claude/checkpoints/1758912077.jsonnew file mode 100644index 0000000000..e418da70c9--- /dev/null+++ b/.claude/checkpoints/1758912077.json@@ -0,0 +1 @@+{"tag": "checkpoint-20250926-184116", "file": "/workspaces/claude-code-flow/CHANGELOG-alpha.128.md", "timestamp": "2025-09-26T18:41:17Z", "type": "post-edit", "branch": "alpha-125", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 24 ++++++++++++++ .claude-flow/metrics/task-metrics.json | 6 ++-- .claude/checkpoints/1758912043.json | 1 + .claude/checkpoints/1758912045.json | 1 + CHANGELOG-alpha.128.md | 57 ++++++++++++++++++++++++++++++++ claude-flow-wiki | 0 7 files changed, 87 insertions(+), 4 deletions(-) "}diff --git a/bin/claude-flow.js b/bin/claude-flow.jsindex aa5646cce5..93c0a75160 100755--- a/bin/claude-flow.js+++ b/bin/claude-flow.js@@ -31,12 +31,12 @@ for (const arg of args) {if (arg === '--version' || arg === '-v') {console.log(`v${VERSION}`);console.log('');- console.log('⚡ Alpha 91 - Claude Code Task Tool Integration Update');- console.log(' • Enhanced CLAUDE.md - Clear guidance for Task tool concurrent agent execution');- console.log(' • Updated Swarm Prompts - Emphasizes Claude Code Task tool for actual work');- console.log(' • Improved Hive Mind - Better separation of MCP coordination vs Task execution');- console.log(' • Batch Operations - Stronger emphasis on TodoWrite & Task tool batching');- console.log(' • Concurrent Patterns - Clear examples of parallel agent spawning');+ console.log('⚡ Alpha 128 - Build Optimization & Memory Coordination');+ console.log(' • Build System Fixed - Removed 32 UI files, clean compilation');+ console.log(' • Memory Coordination Validated - MCP tools fully operational');+ console.log(' • Agent Updates - All core agents with MCP tool integration');+ console.log(' • Hive-Mind Agents - 5 new agents with memory coordination');+ console.log(' • Command System - All CLI commands tested and working');console.log('');console.log('📚 Docs: https://github.com/ruvnet/claude-flow');process.exit(0);diff --git a/dist-cjs/src/core/AgentRegistry.js b/dist-cjs/src/core/AgentRegistry.jsnew file mode 100644index 0000000000..946e742650--- /dev/null+++ b/dist-cjs/src/core/AgentRegistry.js@@ -0,0 +1,314 @@+import { nanoid } from 'nanoid';+export class AgentRegistry {+ database;+ agents = new Map();+ tasks = new Map();+ activeAssignments = new Map();+ constructor(database){+ this.database = database;+ }+ async initialize() {+ try {+ const agentIds = await this.database.list('agents');+ for (const agentId of agentIds){+ const agentData = await this.database.retrieve(agentId, 'agents');+ if (agentData) {+ const agent = typeof agentData === 'string' ? JSON.parse(agentData) : agentData;+ this.agents.set(agent.id, agent);+ }+ }+ } catch (error) {+ console.warn('Failed to load existing agents:', error);+ }+ }+ async spawn(type, config = {}) {+ const agent = {+ id: nanoid(),+ type,+ capabilities: config.capabilities || this.getDefaultCapabilities(type),+ status: 'idle',+ metadata: {+ ...config.metadata,+ spawnedAt: new Date().toISOString(),+ maxConcurrency: config.maxConcurrency || 1,+ timeout: config.timeout || 30000,+ resources: config.resources || {+ memory: 512,+ cpu: 1,+ storage: 100,+ network: 10+ }+ },+ connections: [],+ performance: {+ tasksCompleted: 0,+ averageResponseTime: 0,+ successRate: 1.0,+ resourceUtilization: {+ memory: 0,+ cpu: 0,+ storage: 0,+ network: 0+ },+ lastActivity: new Date()+ }+ };+ this.agents.set(agent.id, agent);+ await this.database.store(agent.id, agent, 'agents');+ this.activeAssignments.set(agent.id, []);+ return agent;+ }+ getDefaultCapabilities(type) {+ const capabilityMap = {+ researcher: [+ 'research',+ 'analysis',+ 'documentation',+ 'web-search'+ ],+ coder: [+ 'programming',+ 'debugging',+ 'refactoring',+ 'testing'+ ],+ analyst: [+ 'data-analysis',+ 'visualization',+ 'reporting',+ 'metrics'+ ],+ optimizer: [+ 'performance-tuning',+ 'resource-optimization',+ 'bottleneck-analysis'+ ],+ coordinator: [+ 'task-delegation',+ 'workflow-management',+ 'communication'+ ],+ tester: [+ 'unit-testing',+ 'integration-testing',+ 'quality-assurance'+ ],+ reviewer: [+ 'code-review',+ 'security-audit',+ 'compliance-check'+ ]+ };+ return capabilityMap[type] || [+ 'general'+ ];+ }+ async coordinate(task) {+ const startTime = Date.now();+ try {+ const suitableAgents = this.findSuitableAgents(task);+ if (suitableAgents.length === 0) {+ return {+ success: false,+ error: `No suitable agents found for task ${task.id}. Required capabilities: ${task.requiredCapabilities.join(', ')}`+ };+ }+ const selectedAgent = this.selectBestAgent(suitableAgents, task);+ await this.assignTask(selectedAgent.id, task);+ const executionResult = await this.executeTask(selectedAgent, task);+ await this.updateAgentPerformance(selectedAgent.id, task, executionResult, Date.now() - startTime);+ return executionResult;+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ }+ findSuitableAgents(task) {+ return Array.from(this.agents.values()).filter((agent)=>{+ const hasCapabilities = task.requiredCapabilities.every((cap)=>agent.capabilities.some((agentCap)=>agentCap.toLowerCase().includes(cap.toLowerCase()) || cap.toLowerCase().includes(agentCap.toLowerCase())));+ const isAvailable = agent.status === 'idle' || agent.status === 'active';+ const currentTasks = this.activeAssignments.get(agent.id)?.length || 0;+ const maxConcurrency = agent.metadata.maxConcurrency || 1;+ const canTakeTask = currentTasks < maxConcurrency;+ return hasCapabilities && isAvailable && canTakeTask;+ });+ }+ selectBestAgent(candidates, task) {+ const scored = candidates.map((agent)=>{+ let score = 0;+ score += agent.performance.successRate * 40;+ score += Math.max(0, 20 - agent.performance.averageResponseTime / 1000) * 2;+ const activeTasks = this.activeAssignments.get(agent.id)?.length || 0;+ score += Math.max(0, 10 - activeTasks) * 3;+ const exactMatches = task.requiredCapabilities.filter((cap)=>agent.capabilities.includes(cap)).length;+ score += exactMatches * 5;+ if (task.priority === 'critical' && agent.type === 'coordinator') score += 10;+ if (task.priority === 'high' && [+ 'coordinator',+ 'optimizer'+ ].includes(agent.type)) score += 5;+ return {+ agent,+ score+ };+ });+ scored.sort((a, b)=>b.score - a.score);+ return scored[0].agent;+ }+ async assignTask(agentId, task) {+ const agent = this.agents.get(agentId);+ if (agent) {+ agent.status = 'busy';+ await this.database.store(agentId, agent, 'agents');+ }+ const currentTasks = this.activeAssignments.get(agentId) || [];+ currentTasks.push(task.id);+ this.activeAssignments.set(agentId, currentTasks);+ this.tasks.set(task.id, task);+ await this.database.store(task.id, task, 'tasks');+ }+ async executeTask(agent, task) {+ const baseTime = 1000 + Math.random() * 2000;+ const complexityFactor = task.requiredCapabilities.length * 0.5;+ const performanceFactor = 2 - agent.performance.successRate;+ const processingTime = baseTime * complexityFactor * performanceFactor;+ await new Promise((resolve)=>setTimeout(resolve, Math.min(processingTime, 5000)));+ const successProbability = agent.performance.successRate * 0.9 + 0.1;+ const success = Math.random() < successProbability;+ if (success) {+ return {+ success: true,+ data: {+ taskId: task.id,+ agentId: agent.id,+ result: `Task ${task.description} completed successfully by ${agent.type} agent`,+ processingTime: Math.round(processingTime)+ },+ metadata: {+ capabilities: agent.capabilities,+ performance: agent.performance+ }+ };+ } else {+ return {+ success: false,+ error: `Task ${task.id} failed during execution by agent ${agent.id}`,+ metadata: {+ processingTime: Math.round(processingTime)+ }+ };+ }+ }+ async updateAgentPerformance(agentId, task, result, duration) {+ const agent = this.agents.get(agentId);+ if (!agent || !agent.performance) return;+ const perf = agent.performance;+ perf.tasksCompleted++;+ const alpha = 0.1;+ perf.successRate = perf.successRate * (1 - alpha) + (result.success ? 1 : 0) * alpha;+ perf.averageResponseTime = perf.averageResponseTime * (1 - alpha) + duration * alpha;+ perf.lastActivity = new Date();+ perf.resourceUtilization = {+ memory: Math.min(100, perf.resourceUtilization.memory + Math.random() * 10),+ cpu: Math.min(100, perf.resourceUtilization.cpu + Math.random() * 15),+ storage: Math.min(100, perf.resourceUtilization.storage + Math.random() * 5),+ network: Math.min(100, perf.resourceUtilization.network + Math.random() * 8)+ };+ const currentTasks = this.activeAssignments.get(agentId) || [];+ const updatedTasks = currentTasks.filter((id)=>id !== task.id);+ this.activeAssignments.set(agentId, updatedTasks);+ agent.status = updatedTasks.length > 0 ? 'busy' : 'idle';+ await this.database.store(agentId, agent, 'agents');+ }+ async monitor() {+ const agentMetrics = Array.from(this.agents.values()).map((agent)=>({+ agentId: agent.id,+ type: agent.type,+ performance: agent.performance,+ status: agent.status+ }));+ const totalMemory = agentMetrics.reduce((sum, m)=>sum + m.performance.resourceUtilization.memory, 0);+ const totalCpu = agentMetrics.reduce((sum, m)=>sum + m.performance.resourceUtilization.cpu, 0);+ const activeConnections = Array.from(this.agents.values()).reduce((sum, agent)=>sum + (agent.connections?.length || 0), 0);+ const systemMetrics = {+ uptime: Date.now() - (this.getOldestAgent()?.metadata.spawnedAt ? new Date(this.getOldestAgent().metadata.spawnedAt).getTime() : Date.now()),+ memoryUsage: totalMemory / agentMetrics.length || 0,+ cpuUsage: totalCpu / agentMetrics.length || 0,+ networkLatency: Math.random() * 10 + 5,+ activeConnections+ };+ const totalTasks = agentMetrics.reduce((sum, m)=>sum + m.performance.tasksCompleted, 0);+ const avgSuccessRate = agentMetrics.reduce((sum, m)=>sum + m.performance.successRate, 0) / agentMetrics.length || 0;+ const avgResponseTime = agentMetrics.reduce((sum, m)=>sum + m.performance.averageResponseTime, 0) / agentMetrics.length || 0;+ const performanceMetrics = {+ throughput: totalTasks / (systemMetrics.uptime / 1000 / 60) || 0,+ latency: avgResponseTime,+ errorRate: 1 - avgSuccessRate,+ bottlenecks: this.identifyBottlenecks(agentMetrics)+ };+ return {+ agents: agentMetrics,+ system: systemMetrics,+ performance: performanceMetrics+ };+ }+ identifyBottlenecks(agentMetrics) {+ const bottlenecks = [];+ const highCpuAgents = agentMetrics.filter((m)=>m.performance.resourceUtilization.cpu > 80);+ if (highCpuAgents.length > 0) {+ bottlenecks.push(`High CPU usage: ${highCpuAgents.map((a)=>a.agentId).join(', ')}`);+ }+ const highMemoryAgents = agentMetrics.filter((m)=>m.performance.resourceUtilization.memory > 80);+ if (highMemoryAgents.length > 0) {+ bottlenecks.push(`High memory usage: ${highMemoryAgents.map((a)=>a.agentId).join(', ')}`);+ }+ const lowSuccessAgents = agentMetrics.filter((m)=>m.performance.successRate < 0.8);+ if (lowSuccessAgents.length > 0) {+ bottlenecks.push(`Low success rate: ${lowSuccessAgents.map((a)=>a.agentId).join(', ')}`);+ }+ const slowAgents = agentMetrics.filter((m)=>m.performance.averageResponseTime > 5000);+ if (slowAgents.length > 0) {+ bottlenecks.push(`Slow response time: ${slowAgents.map((a)=>a.agentId).join(', ')}`);+ }+ return bottlenecks;+ }+ async shutdown(agentId) {+ const agent = this.agents.get(agentId);+ if (!agent) return;+ const activeTasks = this.activeAssignments.get(agentId) || [];+ for (const taskId of activeTasks){+ await this.database.delete(taskId, 'tasks');+ }+ this.agents.delete(agentId);+ this.activeAssignments.delete(agentId);+ await this.database.delete(agentId, 'agents');+ }+ async getActiveAgents() {+ return Array.from(this.agents.values()).filter((agent)=>agent.status !== 'offline');+ }+ getAgent(agentId) {+ return this.agents.get(agentId);+ }+ getAgentsByType(type) {+ return Array.from(this.agents.values()).filter((agent)=>agent.type === type);+ }+ getAgentCount() {+ return this.agents.size;+ }+ getOldestAgent() {+ let oldest;+ let oldestTime = Date.now();+ for (const agent of this.agents.values()){+ const spawnTime = new Date(agent.metadata.spawnedAt).getTime();+ if (spawnTime < oldestTime) {+ oldestTime = spawnTime;+ oldest = agent;+ }+ }+ return oldest;+ }+}++//# sourceMappingURL=AgentRegistry.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/AgentRegistry.js.map b/dist-cjs/src/core/AgentRegistry.js.mapnew file mode 100644index 0000000000..38034c483b--- /dev/null+++ b/dist-cjs/src/core/AgentRegistry.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/AgentRegistry.ts"],"sourcesContent":["/**\n * AgentRegistry - Tracks and manages agent lifecycle\n * Provides centralized management for agent spawning, coordination, and monitoring\n */\n\nimport { IDatabaseProvider, IAgentCoordinator, Agent, AgentType, AgentConfig, Task, Result, Metrics, AgentMetrics, AgentPerformance } from '../types/interfaces.js';\nimport { nanoid } from 'nanoid';\n\nexport class AgentRegistry implements IAgentCoordinator {\n private agents: Map<string, Agent> = new Map();\n private tasks: Map<string, Task> = new Map();\n private activeAssignments: Map<string, string[]> = new Map(); // agentId -> taskIds\n\n constructor(private database: IDatabaseProvider) {}\n\n /**\n * Initialize the agent registry\n */\n async initialize(): Promise<void> {\n // Load existing agents from database\n try {\n const agentIds = await this.database.list('agents');\n for (const agentId of agentIds) {\n const agentData = await this.database.retrieve(agentId, 'agents');\n if (agentData) {\n const agent = typeof agentData === 'string' ? JSON.parse(agentData) : agentData;\n this.agents.set(agent.id, agent);\n }\n }\n } catch (error) {\n console.warn('Failed to load existing agents:', error);\n }\n }\n\n /**\n * Spawn a new agent\n */\n async spawn(type: AgentType, config: AgentConfig = {}): Promise<Agent> {\n const agent: Agent = {\n id: nanoid(),\n type,\n capabilities: config.capabilities || this.getDefaultCapabilities(type),\n status: 'idle',\n metadata: {\n ...config.metadata,\n spawnedAt: new Date().toISOString(),\n maxConcurrency: config.maxConcurrency || 1,\n timeout: config.timeout || 30000,\n resources: config.resources || {\n memory: 512,\n cpu: 1,\n storage: 100,\n network: 10\n }\n },\n connections: [],\n performance: {\n tasksCompleted: 0,\n averageResponseTime: 0,\n successRate: 1.0,\n resourceUtilization: {\n memory: 0,\n cpu: 0,\n storage: 0,\n network: 0\n },\n lastActivity: new Date()\n }\n };\n\n // Store agent\n this.agents.set(agent.id, agent);\n await this.database.store(agent.id, agent, 'agents');\n\n // Initialize task tracking\n this.activeAssignments.set(agent.id, []);\n\n return agent;\n }\n\n /**\n * Get default capabilities for agent type\n */\n private getDefaultCapabilities(type: AgentType): string[] {\n const capabilityMap: Record<AgentType, string[]> = {\n researcher: ['research', 'analysis', 'documentation', 'web-search'],\n coder: ['programming', 'debugging', 'refactoring', 'testing'],\n analyst: ['data-analysis', 'visualization', 'reporting', 'metrics'],\n optimizer: ['performance-tuning', 'resource-optimization', 'bottleneck-analysis'],\n coordinator: ['task-delegation', 'workflow-management', 'communication'],\n tester: ['unit-testing', 'integration-testing', 'quality-assurance'],\n reviewer: ['code-review', 'security-audit', 'compliance-check']\n };\n\n return capabilityMap[type] || ['general'];\n }\n\n /**\n * Coordinate task execution\n */\n async coordinate(task: Task): Promise<Result> {\n const startTime = Date.now();\n\n try {\n // Find suitable agents\n const suitableAgents = this.findSuitableAgents(task);\n\n if (suitableAgents.length === 0) {\n return {\n success: false,\n error: `No suitable agents found for task ${task.id}. Required capabilities: ${task.requiredCapabilities.join(', ')}`\n };\n }\n\n // Select best agent based on availability and performance\n const selectedAgent = this.selectBestAgent(suitableAgents, task);\n\n // Assign task to agent\n await this.assignTask(selectedAgent.id, task);\n\n // Simulate task execution (in real implementation, this would communicate with actual agent)\n const executionResult = await this.executeTask(selectedAgent, task);\n\n // Update agent performance\n await this.updateAgentPerformance(selectedAgent.id, task, executionResult, Date.now() - startTime);\n\n return executionResult;\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n }\n\n /**\n * Find agents with required capabilities\n */\n private findSuitableAgents(task: Task): Agent[] {\n return Array.from(this.agents.values()).filter(agent => {\n // Check if agent has required capabilities\n const hasCapabilities = task.requiredCapabilities.every(cap =>\n agent.capabilities.some(agentCap =>\n agentCap.toLowerCase().includes(cap.toLowerCase()) ||\n cap.toLowerCase().includes(agentCap.toLowerCase())\n )\n );\n\n // Check availability\n const isAvailable = agent.status === 'idle' || agent.status === 'active';\n\n // Check concurrency limits\n const currentTasks = this.activeAssignments.get(agent.id)?.length || 0;\n const maxConcurrency = agent.metadata.maxConcurrency || 1;\n const canTakeTask = currentTasks < maxConcurrency;\n\n return hasCapabilities && isAvailable && canTakeTask;\n });\n }\n\n /**\n * Select the best agent for a task\n */\n private selectBestAgent(candidates: Agent[], task: Task): Agent {\n // Score agents based on performance, availability, and specialization\n const scored = candidates.map(agent => {\n let score = 0;\n\n // Performance score (higher success rate and lower response time is better)\n score += agent.performance!.successRate * 40;\n score += Math.max(0, 20 - (agent.performance!.averageResponseTime / 1000)) * 2;\n\n // Availability score (fewer active tasks is better)\n const activeTasks = this.activeAssignments.get(agent.id)?.length || 0;\n score += Math.max(0, 10 - activeTasks) * 3;\n\n // Specialization score (exact capability matches are better)\n const exactMatches = task.requiredCapabilities.filter(cap =>\n agent.capabilities.includes(cap)\n ).length;\n score += exactMatches * 5;\n\n // Priority matching\n if (task.priority === 'critical' && agent.type === 'coordinator') score += 10;\n if (task.priority === 'high' && ['coordinator', 'optimizer'].includes(agent.type)) score += 5;\n\n return { agent, score };\n });\n\n // Return agent with highest score\n scored.sort((a, b) => b.score - a.score);\n return scored[0].agent;\n }\n\n /**\n * Assign task to agent\n */\n private async assignTask(agentId: string, task: Task): Promise<void> {\n // Update agent status\n const agent = this.agents.get(agentId);\n if (agent) {\n agent.status = 'busy';\n await this.database.store(agentId, agent, 'agents');\n }\n\n // Add to active assignments\n const currentTasks = this.activeAssignments.get(agentId) || [];\n currentTasks.push(task.id);\n this.activeAssignments.set(agentId, currentTasks);\n\n // Store task\n this.tasks.set(task.id, task);\n await this.database.store(task.id, task, 'tasks');\n }\n\n /**\n * Execute task (simulation)\n */\n private async executeTask(agent: Agent, task: Task): Promise<Result> {\n // Simulate processing time based on task complexity and agent performance\n const baseTime = 1000 + Math.random() * 2000; // 1-3 seconds\n const complexityFactor = task.requiredCapabilities.length * 0.5;\n const performanceFactor = 2 - agent.performance!.successRate;\n\n const processingTime = baseTime * complexityFactor * performanceFactor;\n\n await new Promise(resolve => setTimeout(resolve, Math.min(processingTime, 5000)));\n\n // Simulate success/failure based on agent performance\n const successProbability = agent.performance!.successRate * 0.9 + 0.1;\n const success = Math.random() < successProbability;\n\n if (success) {\n return {\n success: true,\n data: {\n taskId: task.id,\n agentId: agent.id,\n result: `Task ${task.description} completed successfully by ${agent.type} agent`,\n processingTime: Math.round(processingTime)\n },\n metadata: {\n capabilities: agent.capabilities,\n performance: agent.performance\n }\n };\n } else {\n return {\n success: false,\n error: `Task ${task.id} failed during execution by agent ${agent.id}`,\n metadata: {\n processingTime: Math.round(processingTime)\n }\n };\n }\n }\n\n /**\n * Update agent performance metrics\n */\n private async updateAgentPerformance(agentId: string, task: Task, result: Result, duration: number): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent || !agent.performance) return;\n\n const perf = agent.performance;\n\n // Update task count\n perf.tasksCompleted++;\n\n // Update success rate (exponential moving average)\n const alpha = 0.1; // Learning rate\n perf.successRate = perf.successRate * (1 - alpha) + (result.success ? 1 : 0) * alpha;\n\n // Update average response time\n perf.averageResponseTime = perf.averageResponseTime * (1 - alpha) + duration * alpha;\n\n // Update last activity\n perf.lastActivity = new Date();\n\n // Update resource utilization (simulated)\n perf.resourceUtilization = {\n memory: Math.min(100, perf.resourceUtilization.memory + Math.random() * 10),\n cpu: Math.min(100, perf.resourceUtilization.cpu + Math.random() * 15),\n storage: Math.min(100, perf.resourceUtilization.storage + Math.random() * 5),\n network: Math.min(100, perf.resourceUtilization.network + Math.random() * 8)\n };\n\n // Update agent status\n const currentTasks = this.activeAssignments.get(agentId) || [];\n const updatedTasks = currentTasks.filter(id => id !== task.id);\n this.activeAssignments.set(agentId, updatedTasks);\n\n agent.status = updatedTasks.length > 0 ? 'busy' : 'idle';\n\n // Persist changes\n await this.database.store(agentId, agent, 'agents');\n }\n\n /**\n * Monitor all agents\n */\n async monitor(): Promise<Metrics> {\n const agentMetrics: AgentMetrics[] = Array.from(this.agents.values()).map(agent => ({\n agentId: agent.id,\n type: agent.type,\n performance: agent.performance!,\n status: agent.status\n }));\n\n // Calculate system metrics\n const totalMemory = agentMetrics.reduce((sum, m) => sum + m.performance.resourceUtilization.memory, 0);\n const totalCpu = agentMetrics.reduce((sum, m) => sum + m.performance.resourceUtilization.cpu, 0);\n const activeConnections = Array.from(this.agents.values()).reduce((sum, agent) => sum + (agent.connections?.length || 0), 0);\n\n const systemMetrics = {\n uptime: Date.now() - (this.getOldestAgent()?.metadata.spawnedAt ? new Date(this.getOldestAgent()!.metadata.spawnedAt).getTime() : Date.now()),\n memoryUsage: totalMemory / agentMetrics.length || 0,\n cpuUsage: totalCpu / agentMetrics.length || 0,\n networkLatency: Math.random() * 10 + 5, // Simulated\n activeConnections\n };\n\n // Calculate performance metrics\n const totalTasks = agentMetrics.reduce((sum, m) => sum + m.performance.tasksCompleted, 0);\n const avgSuccessRate = agentMetrics.reduce((sum, m) => sum + m.performance.successRate, 0) / agentMetrics.length || 0;\n const avgResponseTime = agentMetrics.reduce((sum, m) => sum + m.performance.averageResponseTime, 0) / agentMetrics.length || 0;\n\n const performanceMetrics = {\n throughput: totalTasks / (systemMetrics.uptime / 1000 / 60) || 0, // tasks per minute\n latency: avgResponseTime,\n errorRate: 1 - avgSuccessRate,\n bottlenecks: this.identifyBottlenecks(agentMetrics)\n };\n\n return {\n agents: agentMetrics,\n system: systemMetrics,\n performance: performanceMetrics\n };\n }\n\n /**\n * Identify performance bottlenecks\n */\n private identifyBottlenecks(agentMetrics: AgentMetrics[]): string[] {\n const bottlenecks: string[] = [];\n\n // High CPU usage\n const highCpuAgents = agentMetrics.filter(m => m.performance.resourceUtilization.cpu > 80);\n if (highCpuAgents.length > 0) {\n bottlenecks.push(`High CPU usage: ${highCpuAgents.map(a => a.agentId).join(', ')}`);\n }\n\n // High memory usage\n const highMemoryAgents = agentMetrics.filter(m => m.performance.resourceUtilization.memory > 80);\n if (highMemoryAgents.length > 0) {\n bottlenecks.push(`High memory usage: ${highMemoryAgents.map(a => a.agentId).join(', ')}`);\n }\n\n // Low success rate\n const lowSuccessAgents = agentMetrics.filter(m => m.performance.successRate < 0.8);\n if (lowSuccessAgents.length > 0) {\n bottlenecks.push(`Low success rate: ${lowSuccessAgents.map(a => a.agentId).join(', ')}`);\n }\n\n // High response time\n const slowAgents = agentMetrics.filter(m => m.performance.averageResponseTime > 5000);\n if (slowAgents.length > 0) {\n bottlenecks.push(`Slow response time: ${slowAgents.map(a => a.agentId).join(', ')}`);\n }\n\n return bottlenecks;\n }\n\n /**\n * Shutdown agent\n */\n async shutdown(agentId: string): Promise<void> {\n const agent = this.agents.get(agentId);\n if (!agent) return;\n\n // Cancel active tasks\n const activeTasks = this.activeAssignments.get(agentId) || [];\n for (const taskId of activeTasks) {\n await this.database.delete(taskId, 'tasks');\n }\n\n // Remove agent\n this.agents.delete(agentId);\n this.activeAssignments.delete(agentId);\n await this.database.delete(agentId, 'agents');\n }\n\n /**\n * Get active agents\n */\n async getActiveAgents(): Promise<Agent[]> {\n return Array.from(this.agents.values()).filter(agent => agent.status !== 'offline');\n }\n\n /**\n * Get agent by ID\n */\n getAgent(agentId: string): Agent | undefined {\n return this.agents.get(agentId);\n }\n\n /**\n * Get agents by type\n */\n getAgentsByType(type: AgentType): Agent[] {\n return Array.from(this.agents.values()).filter(agent => agent.type === type);\n }\n\n /**\n * Get agent count\n */\n getAgentCount(): number {\n return this.agents.size;\n }\n\n /**\n * Get oldest agent (for uptime calculation)\n */\n private getOldestAgent(): Agent | undefined {\n let oldest: Agent | undefined;\n let oldestTime = Date.now();\n\n for (const agent of this.agents.values()) {\n const spawnTime = new Date(agent.metadata.spawnedAt).getTime();\n if (spawnTime < oldestTime) {\n oldestTime = spawnTime;\n oldest = agent;\n }\n }\n\n return oldest;\n }\n}"],"names":["nanoid","AgentRegistry","agents","Map","tasks","activeAssignments","database","initialize","agentIds","list","agentId","agentData","retrieve","agent","JSON","parse","set","id","error","console","warn","spawn","type","config","capabilities","getDefaultCapabilities","status","metadata","spawnedAt","Date","toISOString","maxConcurrency","timeout","resources","memory","cpu","storage","network","connections","performance","tasksCompleted","averageResponseTime","successRate","resourceUtilization","lastActivity","store","capabilityMap","researcher","coder","analyst","optimizer","coordinator","tester","reviewer","coordinate","task","startTime","now","suitableAgents","findSuitableAgents","length","success","requiredCapabilities","join","selectedAgent","selectBestAgent","assignTask","executionResult","executeTask","updateAgentPerformance","Error","message","String","Array","from","values","filter","hasCapabilities","every","cap","some","agentCap","toLowerCase","includes","isAvailable","currentTasks","get","canTakeTask","candidates","scored","map","score","Math","max","activeTasks","exactMatches","priority","sort","a","b","push","baseTime","random","complexityFactor","performanceFactor","processingTime","Promise","resolve","setTimeout","min","successProbability","data","taskId","result","description","round","duration","perf","alpha","updatedTasks","monitor","agentMetrics","totalMemory","reduce","sum","m","totalCpu","activeConnections","systemMetrics","uptime","getOldestAgent","getTime","memoryUsage","cpuUsage","networkLatency","totalTasks","avgSuccessRate","avgResponseTime","performanceMetrics","throughput","latency","errorRate","bottlenecks","identifyBottlenecks","system","highCpuAgents","highMemoryAgents","lowSuccessAgents","slowAgents","shutdown","delete","getActiveAgents","getAgent","getAgentsByType","getAgentCount","size","oldest","oldestTime","spawnTime"],"mappings":"AAMA,SAASA,MAAM,QAAQ,SAAS;AAEhC,OAAO,MAAMC;;IACHC,SAA6B,IAAIC,MAAM;IACvCC,QAA2B,IAAID,MAAM;IACrCE,oBAA2C,IAAIF,MAAM;IAE7D,YAAY,AAAQG,QAA2B,CAAE;aAA7BA,WAAAA;IAA8B;IAKlD,MAAMC,aAA4B;QAEhC,IAAI;YACF,MAAMC,WAAW,MAAM,IAAI,CAACF,QAAQ,CAACG,IAAI,CAAC;YAC1C,KAAK,MAAMC,WAAWF,S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QAC7D,KAAK,MAAMsG,UAAUlB,YAAa;YAChC,MAAM,IAAI,CAACxF,QAAQ,CAACgJ,MAAM,CAACtC,QAAQ;QACrC;QAGA,IAAI,CAAC9G,MAAM,CAACoJ,MAAM,CAAC5I;QACnB,IAAI,CAACL,iBAAiB,CAACiJ,MAAM,CAAC5I;QAC9B,MAAM,IAAI,CAACJ,QAAQ,CAACgJ,MAAM,CAAC5I,SAAS;IACtC;IAKA,MAAM6I,kBAAoC;QACxC,OAAO9E,MAAMC,IAAI,CAAC,IAAI,CAACxE,MAAM,CAACyE,MAAM,IAAIC,MAAM,CAAC/D,CAAAA,QAASA,MAAMa,MAAM,KAAK;IAC3E;IAKA8H,SAAS9I,OAAe,EAAqB;QAC3C,OAAO,IAAI,CAACR,MAAM,CAACoF,GAAG,CAAC5E;IACzB;IAKA+I,gBAAgBnI,IAAe,EAAW;QACxC,OAAOmD,MAAMC,IAAI,CAAC,IAAI,CAACxE,MAAM,CAACyE,MAAM,IAAIC,MAAM,CAAC/D,CAAAA,QAASA,MAAMS,IAAI,KAAKA;IACzE;IAKAoI,gBAAwB;QACtB,OAAO,IAAI,CAACxJ,MAAM,CAACyJ,IAAI;IACzB;IAKQzB,iBAAoC;QAC1C,IAAI0B;QACJ,IAAIC,aAAahI,KAAK4B,GAAG;QAEzB,KAAK,MAAM5C,SAAS,IAAI,CAACX,MAAM,CAACyE,MAAM,GAAI;YACxC,MAAMmF,YAAY,IAAIjI,KAAKhB,MAAMc,QAAQ,CAACC,SAAS,EAAEuG,OAAO;YAC5D,IAAI2B,YAAYD,YAAY;gBAC1BA,aAAaC;gBACbF,SAAS/I;YACX;QACF;QAEA,OAAO+I;IACT;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/ConfigManager.js b/dist-cjs/src/core/ConfigManager.jsnew file mode 100644index 0000000000..4386678343--- /dev/null+++ b/dist-cjs/src/core/ConfigManager.js@@ -0,0 +1,177 @@+import * as fs from 'fs-extra';+import * as path from 'path';+export class ConfigManager {+ config = {};+ configPath;+ constructor(configPath){+ this.configPath = configPath || this.findConfigFile();+ this.loadConfiguration();+ }+ findConfigFile() {+ const possiblePaths = [+ 'claude-flow.config.json',+ 'claude-flow.config.js',+ '.claude-flow.json',+ '.claude-flow/config.json',+ 'config/claude-flow.json',+ path.join(process.cwd(), 'claude-flow.config.json')+ ];+ for (const configPath of possiblePaths){+ if (fs.existsSync(configPath)) {+ return configPath;+ }+ }+ return 'claude-flow.config.json';+ }+ loadConfiguration() {+ if (fs.existsSync(this.configPath)) {+ try {+ const fileContent = fs.readFileSync(this.configPath, 'utf8');+ this.config = JSON.parse(fileContent);+ } catch (error) {+ console.warn(`Failed to load config from ${this.configPath}:`, error);+ }+ }+ this.loadEnvironmentVariables();+ }+ loadEnvironmentVariables() {+ const envConfig = {};+ if (process.env.CLAUDE_FLOW_MODE) envConfig.mode = process.env.CLAUDE_FLOW_MODE;+ if (process.env.CLAUDE_FLOW_TOPOLOGY) envConfig.topology = process.env.CLAUDE_FLOW_TOPOLOGY;+ if (process.env.CLAUDE_FLOW_MAX_AGENTS) envConfig.maxAgents = parseInt(process.env.CLAUDE_FLOW_MAX_AGENTS);+ if (process.env.CLAUDE_FLOW_STRATEGY) envConfig.strategy = process.env.CLAUDE_FLOW_STRATEGY;+ if (process.env.CLAUDE_FLOW_DATABASE_TYPE || process.env.CLAUDE_FLOW_DATABASE_PATH) {+ envConfig.database = {+ type: process.env.CLAUDE_FLOW_DATABASE_TYPE || 'sqlite',+ path: process.env.CLAUDE_FLOW_DATABASE_PATH+ };+ }+ if (process.env.GITHUB_TOKEN) {+ envConfig.github = {+ token: process.env.GITHUB_TOKEN,+ owner: process.env.GITHUB_OWNER,+ repo: process.env.GITHUB_REPO,+ webhookSecret: process.env.GITHUB_WEBHOOK_SECRET,+ autoSync: process.env.GITHUB_AUTO_SYNC === 'true'+ };+ }+ if (process.env.CLAUDE_FLOW_DEBUG) envConfig.debug = process.env.CLAUDE_FLOW_DEBUG === 'true';+ if (process.env.CLAUDE_FLOW_LOG_LEVEL) envConfig.logLevel = process.env.CLAUDE_FLOW_LOG_LEVEL;+ this.config = {+ ...this.config,+ ...envConfig+ };+ }+ async validate() {+ const errors = [];+ const warnings = [];+ const validModes = [+ 'standard',+ 'github',+ 'hive-mind',+ 'sparc',+ 'neural',+ 'enterprise'+ ];+ if (this.config.mode && !validModes.includes(this.config.mode)) {+ errors.push(`Invalid mode: ${this.config.mode}. Valid modes: ${validModes.join(', ')}`);+ }+ const validTopologies = [+ 'mesh',+ 'hierarchical',+ 'ring',+ 'star'+ ];+ if (this.config.topology && !validTopologies.includes(this.config.topology)) {+ errors.push(`Invalid topology: ${this.config.topology}. Valid topologies: ${validTopologies.join(', ')}`);+ }+ if (this.config.maxAgents !== undefined) {+ if (this.config.maxAgents < 1 || this.config.maxAgents > 100) {+ errors.push('maxAgents must be between 1 and 100');+ }+ }+ const validStrategies = [+ 'balanced',+ 'specialized',+ 'adaptive'+ ];+ if (this.config.strategy && !validStrategies.includes(this.config.strategy)) {+ errors.push(`Invalid strategy: ${this.config.strategy}. Valid strategies: ${validStrategies.join(', ')}`);+ }+ if (this.config.database) {+ if (![+ 'sqlite',+ 'json'+ ].includes(this.config.database.type)) {+ errors.push('Database type must be either "sqlite" or "json"');+ }+ if (this.config.database.path && !fs.existsSync(path.dirname(this.config.database.path))) {+ warnings.push(`Database directory does not exist: ${path.dirname(this.config.database.path)}`);+ }+ }+ if (this.config.github?.token && !this.config.github.token.startsWith('ghp_')) {+ warnings.push('GitHub token format appears invalid');+ }+ if (this.config.performance?.maxConcurrency && this.config.performance.maxConcurrency < 1) {+ errors.push('maxConcurrency must be at least 1');+ }+ return {+ valid: errors.length === 0,+ errors,+ warnings+ };+ }+ getConfig() {+ return {+ ...this.config+ };+ }+ get(key) {+ return this.config[key];+ }+ set(key, value) {+ this.config[key] = value;+ }+ async save() {+ try {+ await fs.ensureDir(path.dirname(this.configPath));+ await fs.writeJSON(this.configPath, this.config, {+ spaces: 2+ });+ } catch (error) {+ throw new Error(`Failed to save configuration: ${error}`);+ }+ }+ reset() {+ this.config = {+ mode: 'standard',+ topology: 'mesh',+ maxAgents: 8,+ strategy: 'balanced',+ database: {+ type: 'sqlite',+ path: '.claude-flow/database.sqlite'+ },+ debug: false,+ logLevel: 'info'+ };+ }+ merge(additionalConfig) {+ this.config = {+ ...this.config,+ ...additionalConfig+ };+ }+ toInitConfig() {+ return {+ mode: this.config.mode,+ topology: this.config.topology,+ maxAgents: this.config.maxAgents,+ strategy: this.config.strategy,+ database: this.config.database?.type,+ debug: this.config.debug+ };+ }+}++//# sourceMappingURL=ConfigManager.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/ConfigManager.js.map b/dist-cjs/src/core/ConfigManager.js.mapnew file mode 100644index 0000000000..49729fa136--- /dev/null+++ b/dist-cjs/src/core/ConfigManager.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/ConfigManager.ts"],"sourcesContent":["/**\n * ConfigManager - Handles configuration validation and setup\n * Manages environment variables, file-based config, and validation schemas\n */\n\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport { ConfigValidationResult, InitConfig, DatabaseConfig, TopologyConfig } from '../types/interfaces.js';\n\nexport interface ClaudeFlowConfig {\n // Core settings\n mode?: string;\n topology?: string;\n maxAgents?: number;\n strategy?: string;\n\n // Database configuration\n database?: DatabaseConfig;\n\n // Topology configuration\n topologyConfig?: TopologyConfig;\n\n // MCP integration\n mcpServers?: MCPServerConfig[];\n\n // GitHub integration\n github?: GitHubConfig;\n\n // Neural network settings\n neural?: NeuralConfig;\n\n // Hive mind settings\n hiveMind?: HiveMindConfig;\n\n // Enterprise features\n enterprise?: EnterpriseConfig;\n\n // Debugging and logging\n debug?: boolean;\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n logPath?: string;\n\n // Performance settings\n performance?: PerformanceConfig;\n}\n\nexport interface MCPServerConfig {\n name: string;\n command: string;\n args?: string[];\n env?: Record<string, string>;\n enabled: boolean;\n}\n\nexport interface GitHubConfig {\n token?: string;\n owner?: string;\n repo?: string;\n webhookSecret?: string;\n autoSync?: boolean;\n}\n\nexport interface NeuralConfig {\n modelPath?: string;\n wasmOptimization?: boolean;\n simdAcceleration?: boolean;\n trainingEnabled?: boolean;\n}\n\nexport interface HiveMindConfig {\n queenEnabled?: boolean;\n workerPoolSize?: number;\n consensusThreshold?: number;\n adaptationRate?: number;\n}\n\nexport interface EnterpriseConfig {\n authentication?: boolean;\n encryption?: boolean;\n audit?: boolean;\n compliance?: string[];\n}\n\nexport interface PerformanceConfig {\n maxConcurrency?: number;\n timeout?: number;\n retryAttempts?: number;\n cacheEnabled?: boolean;\n}\n\nexport class ConfigManager {\n private config: ClaudeFlowConfig = {};\n private configPath: string;\n\n constructor(configPath?: string) {\n this.configPath = configPath || this.findConfigFile();\n this.loadConfiguration();\n }\n\n /**\n * Find configuration file in standard locations\n */\n private findConfigFile(): string {\n const possiblePaths = [\n 'claude-flow.config.json',\n 'claude-flow.config.js',\n '.claude-flow.json',\n '.claude-flow/config.json',\n 'config/claude-flow.json',\n path.join(process.cwd(), 'claude-flow.config.json')\n ];\n\n for (const configPath of possiblePaths) {\n if (fs.existsSync(configPath)) {\n return configPath;\n }\n }\n\n return 'claude-flow.config.json'; // Default\n }\n\n /**\n * Load configuration from file and environment variables\n */\n private loadConfiguration(): void {\n // Load from file if exists\n if (fs.existsSync(this.configPath)) {\n try {\n const fileContent = fs.readFileSync(this.configPath, 'utf8');\n this.config = JSON.parse(fileContent);\n } catch (error) {\n console.warn(`Failed to load config from ${this.configPath}:`, error);\n }\n }\n\n // Override with environment variables\n this.loadEnvironmentVariables();\n }\n\n /**\n * Load configuration from environment variables\n */\n private loadEnvironmentVariables(): void {\n const envConfig: Partial<ClaudeFlowConfig> = {};\n\n // Core settings\n if (process.env.CLAUDE_FLOW_MODE) envConfig.mode = process.env.CLAUDE_FLOW_MODE;\n if (process.env.CLAUDE_FLOW_TOPOLOGY) envConfig.topology = process.env.CLAUDE_FLOW_TOPOLOGY;\n if (process.env.CLAUDE_FLOW_MAX_AGENTS) envConfig.maxAgents = parseInt(process.env.CLAUDE_FLOW_MAX_AGENTS);\n if (process.env.CLAUDE_FLOW_STRATEGY) envConfig.strategy = process.env.CLAUDE_FLOW_STRATEGY;\n\n // Database\n if (process.env.CLAUDE_FLOW_DATABASE_TYPE || process.env.CLAUDE_FLOW_DATABASE_PATH) {\n envConfig.database = {\n type: (process.env.CLAUDE_FLOW_DATABASE_TYPE as 'sqlite' | 'json') || 'sqlite',\n path: process.env.CLAUDE_FLOW_DATABASE_PATH\n };\n }\n\n // GitHub\n if (process.env.GITHUB_TOKEN) {\n envConfig.github = {\n token: process.env.GITHUB_TOKEN,\n owner: process.env.GITHUB_OWNER,\n repo: process.env.GITHUB_REPO,\n webhookSecret: process.env.GITHUB_WEBHOOK_SECRET,\n autoSync: process.env.GITHUB_AUTO_SYNC === 'true'\n };\n }\n\n // Debug\n if (process.env.CLAUDE_FLOW_DEBUG) envConfig.debug = process.env.CLAUDE_FLOW_DEBUG === 'true';\n if (process.env.CLAUDE_FLOW_LOG_LEVEL) envConfig.logLevel = process.env.CLAUDE_FLOW_LOG_LEVEL as any;\n\n // Merge with existing config\n this.config = { ...this.config, ...envConfig };\n }\n\n /**\n * Validate the configuration\n */\n async validate(): Promise<ConfigValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Validate mode\n const validModes = ['standard', 'github', 'hive-mind', 'sparc', 'neural', 'enterprise'];\n if (this.config.mode && !validModes.includes(this.config.mode)) {\n errors.push(`Invalid mode: ${this.config.mode}. Valid modes: ${validModes.join(', ')}`);\n }\n\n // Validate topology\n const validTopologies = ['mesh', 'hierarchical', 'ring', 'star'];\n if (this.config.topology && !validTopologies.includes(this.config.topology)) {\n errors.push(`Invalid topology: ${this.config.topology}. Valid topologies: ${validTopologies.join(', ')}`);\n }\n\n // Validate maxAgents\n if (this.config.maxAgents !== undefined) {\n if (this.config.maxAgents < 1 || this.config.maxAgents > 100) {\n errors.push('maxAgents must be between 1 and 100');\n }\n }\n\n // Validate strategy\n const validStrategies = ['balanced', 'specialized', 'adaptive'];\n if (this.config.strategy && !validStrategies.includes(this.config.strategy)) {\n errors.push(`Invalid strategy: ${this.config.strategy}. Valid strategies: ${validStrategies.join(', ')}`);\n }\n\n // Validate database configuration\n if (this.config.database) {\n if (!['sqlite', 'json'].includes(this.config.database.type)) {\n errors.push('Database type must be either \"sqlite\" or \"json\"');\n }\n\n if (this.config.database.path && !fs.existsSync(path.dirname(this.config.database.path))) {\n warnings.push(`Database directory does not exist: ${path.dirname(this.config.database.path)}`);\n }\n }\n\n // Validate GitHub configuration\n if (this.config.github?.token && !this.config.github.token.startsWith('ghp_')) {\n warnings.push('GitHub token format appears invalid');\n }\n\n // Validate performance configuration\n if (this.config.performance?.maxConcurrency && this.config.performance.maxConcurrency < 1) {\n errors.push('maxConcurrency must be at least 1');\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings\n };\n }\n\n /**\n * Get the current configuration\n */\n getConfig(): ClaudeFlowConfig {\n return { ...this.config };\n }\n\n /**\n * Get a specific configuration value\n */\n get<K extends keyof ClaudeFlowConfig>(key: K): ClaudeFlowConfig[K] {\n return this.config[key];\n }\n\n /**\n * Set a configuration value\n */\n set<K extends keyof ClaudeFlowConfig>(key: K, value: ClaudeFlowConfig[K]): void {\n this.config[key] = value;\n }\n\n /**\n * Save configuration to file\n */\n async save(): Promise<void> {\n try {\n await fs.ensureDir(path.dirname(this.configPath));\n await fs.writeJSON(this.configPath, this.config, { spaces: 2 });\n } catch (error) {\n throw new Error(`Failed to save configuration: ${error}`);\n }\n }\n\n /**\n * Reset configuration to defaults\n */\n reset(): void {\n this.config = {\n mode: 'standard',\n topology: 'mesh',\n maxAgents: 8,\n strategy: 'balanced',\n database: {\n type: 'sqlite',\n path: '.claude-flow/database.sqlite'\n },\n debug: false,\n logLevel: 'info'\n };\n }\n\n /**\n * Merge additional configuration\n */\n merge(additionalConfig: Partial<ClaudeFlowConfig>): void {\n this.config = { ...this.config, ...additionalConfig };\n }\n\n /**\n * Create InitConfig from current configuration\n */\n toInitConfig(): InitConfig {\n return {\n mode: this.config.mode as any,\n topology: this.config.topology as any,\n maxAgents: this.config.maxAgents,\n strategy: this.config.strategy as any,\n database: this.config.database?.type,\n debug: this.config.debug\n };\n }\n}"],"names":["fs","path","ConfigManager","config","configPath","findConfigFile","loadConfiguration","possiblePaths","join","process","cwd","existsSync","fileContent","readFileSync","JSON","parse","error","console","warn","loadEnvironmentVariables","envConfig","env","CLAUDE_FLOW_MODE","mode","CLAUDE_FLOW_TOPOLOGY","topology","CLAUDE_FLOW_MAX_AGENTS","maxAgents","parseInt","CLAUDE_FLOW_STRATEGY","strategy","CLAUDE_FLOW_DATABASE_TYPE","CLAUDE_FLOW_DATABASE_PATH","database","type","GITHUB_TOKEN","github","token","owner","GITHUB_OWNER","repo","GITHUB_REPO","webhookSecret","GITHUB_WEBHOOK_SECRET","autoSync","GITHUB_AUTO_SYNC","CLAUDE_FLOW_DEBUG","debug","CLAUDE_FLOW_LOG_LEVEL","logLevel","validate","errors","warnings","validModes","includes","push","validTopologies","undefined","validStrategies","dirname","startsWith","performance","maxConcurrency","valid","length","getConfig","get","key","set","value","save","ensureDir","writeJSON","spaces","Error","reset","merge","additionalConfig","toInitConfig"],"mappings":"AAKA,YAAYA,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAoF7B,OAAO,MAAMC;IACHC,SAA2B,CAAC,EAAE;IAC9BC,WAAmB;IAE3B,YAAYA,UAAmB,CAAE;QAC/B,IAAI,CAACA,UAAU,GAAGA,cAAc,IAAI,CAACC,cAAc;QACnD,IAAI,CAACC,iBAAiB;IACxB;IAKQD,iBAAyB;QAC/B,MAAME,gBAAgB;YACpB;YACA;YACA;YACA;YACA;YACAN,KAAKO,IAAI,CAACC,QAAQC,GAAG,IAAI;SAC1B;QAED,KAAK,MAAMN,cAAcG,cAAe;YACtC,IAAIP,GAAGW,UAAU,CAACP,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I,CAAC9B,MAAM,CAAC8B,QAAQ,EAAEC;YAChCa,OAAO,IAAI,CAAC5C,MAAM,CAAC4C,KAAK;QAC1B;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/ConsensusEngine.js b/dist-cjs/src/core/ConsensusEngine.jsnew file mode 100644index 0000000000..98d137dc58--- /dev/null+++ b/dist-cjs/src/core/ConsensusEngine.js@@ -0,0 +1,373 @@+import { nanoid } from 'nanoid';+export class ConsensusEngine {+ database;+ algorithms = new Map();+ currentAlgorithm = null;+ pendingDecisions = new Map();+ consensusHistory = new Map();+ constructor(database){+ this.database = database;+ this.initializeAlgorithms();+ }+ initializeAlgorithms() {+ this.algorithms.set('raft', new RaftConsensus(this.database));+ this.algorithms.set('byzantine', new ByzantineConsensus(this.database));+ this.algorithms.set('gossip', new GossipConsensus(this.database));+ this.algorithms.set('proof-of-learning', new ProofOfLearningConsensus(this.database));+ }+ async setAlgorithm(type) {+ const algorithm = this.algorithms.get(type);+ if (!algorithm) {+ throw new Error(`Unknown consensus algorithm: ${type}`);+ }+ this.currentAlgorithm = algorithm;+ await algorithm.initialize();+ await this.database.store('consensus-algorithm', type, 'system');+ }+ async propose(decision) {+ if (!this.currentAlgorithm) {+ throw new Error('No consensus algorithm selected');+ }+ const fullDecision = {+ ...decision,+ id: nanoid(),+ timestamp: new Date()+ };+ this.pendingDecisions.set(fullDecision.id, fullDecision);+ await this.database.store(`decision:${fullDecision.id}`, fullDecision, 'consensus');+ const votes = await this.currentAlgorithm.propose(fullDecision);+ const consensus = await this.processVotes(fullDecision, votes);+ return fullDecision.id;+ }+ async processVotes(decision, votes) {+ const positiveVotes = votes.filter((vote)=>vote.decision);+ const totalConfidence = votes.reduce((sum, vote)=>sum + vote.confidence, 0);+ const averageConfidence = totalConfidence / votes.length;+ const weightedPositive = positiveVotes.reduce((sum, vote)=>sum + vote.confidence, 0);+ const totalWeight = votes.reduce((sum, vote)=>sum + vote.confidence, 0);+ const outcome = weightedPositive > totalWeight / 2 && averageConfidence > 0.6;+ const consensus = {+ decisionId: decision.id,+ outcome,+ votes,+ confidence: averageConfidence,+ timestamp: new Date()+ };+ this.consensusHistory.set(decision.id, consensus);+ await this.database.store(`consensus:${decision.id}`, consensus, 'consensus');+ if (outcome) {+ await this.executeConsensus(consensus);+ }+ return consensus;+ }+ async executeConsensus(consensus) {+ if (!this.currentAlgorithm) {+ throw new Error('No consensus algorithm available for execution');+ }+ const result = await this.currentAlgorithm.execute(consensus);+ await this.database.store(`result:${consensus.decisionId}`, result, 'consensus');+ this.pendingDecisions.delete(consensus.decisionId);+ return result;+ }+ async getConsensusStatus(decisionId) {+ const decision = this.pendingDecisions.get(decisionId) || await this.database.retrieve(`decision:${decisionId}`, 'consensus');+ const consensus = this.consensusHistory.get(decisionId) || await this.database.retrieve(`consensus:${decisionId}`, 'consensus');+ let status = 'pending';+ if (consensus) {+ status = consensus.outcome ? 'reached' : 'failed';+ }+ return {+ decision,+ consensus,+ status+ };+ }+ getPendingDecisions() {+ return Array.from(this.pendingDecisions.values());+ }+ getConsensusHistory() {+ return Array.from(this.consensusHistory.values());+ }+ getCurrentAlgorithm() {+ return this.currentAlgorithm?.getType() || null;+ }+ getAvailableAlgorithms() {+ return Array.from(this.algorithms.keys());+ }+}+let RaftConsensus = class RaftConsensus {+ database;+ leaderId = null;+ term = 0;+ votedFor = null;+ constructor(database){+ this.database = database;+ }+ getType() {+ return 'raft';+ }+ async initialize() {+ const state = await this.database.retrieve('raft-state', 'consensus');+ if (state) {+ this.term = state.term || 0;+ this.leaderId = state.leaderId || null;+ this.votedFor = state.votedFor || null;+ }+ }+ async propose(decision) {+ if (!this.leaderId) {+ await this.electLeader();+ }+ const votes = [];+ const agentIds = await this.getAgentIds();+ for (const agentId of agentIds){+ const vote = {+ agentId,+ decision: Math.random() > 0.2,+ confidence: 0.8 + Math.random() * 0.2,+ reasoning: `Raft consensus vote for decision ${decision.id}`+ };+ votes.push(vote);+ }+ return votes;+ }+ async execute(consensus) {+ if (!consensus.outcome) {+ return {+ success: false,+ error: 'Consensus was not reached'+ };+ }+ return {+ success: true,+ data: {+ algorithm: 'raft',+ leader: this.leaderId,+ term: this.term,+ executedAt: new Date().toISOString()+ },+ metadata: {+ consensusId: consensus.decisionId,+ votes: consensus.votes.length+ }+ };+ }+ async electLeader() {+ this.term++;+ const agentIds = await this.getAgentIds();+ this.leaderId = agentIds[0] || 'default-leader';+ this.votedFor = this.leaderId;+ await this.database.store('raft-state', {+ term: this.term,+ leaderId: this.leaderId,+ votedFor: this.votedFor+ }, 'consensus');+ }+ async getAgentIds() {+ try {+ const agentKeys = await this.database.list('agents');+ return agentKeys.map((key)=>key.replace('agent:', ''));+ } catch {+ return [+ 'agent-1',+ 'agent-2',+ 'agent-3'+ ];+ }+ }+};+let ByzantineConsensus = class ByzantineConsensus {+ database;+ constructor(database){+ this.database = database;+ }+ getType() {+ return 'byzantine';+ }+ async initialize() {}+ async propose(decision) {+ const votes = [];+ const agentIds = await this.getAgentIds();+ for (const agentId of agentIds){+ const isMalicious = Math.random() < 0.2;+ const vote = {+ agentId,+ decision: isMalicious ? Math.random() < 0.3 : Math.random() > 0.3,+ confidence: isMalicious ? Math.random() * 0.5 : 0.7 + Math.random() * 0.3,+ reasoning: `Byzantine consensus vote (${isMalicious ? 'malicious' : 'honest'})`+ };+ votes.push(vote);+ }+ return votes;+ }+ async execute(consensus) {+ const honestVotes = consensus.votes.filter((vote)=>vote.confidence > 0.6);+ const required = Math.floor(consensus.votes.length * 2 / 3) + 1;+ if (honestVotes.length >= required && consensus.outcome) {+ return {+ success: true,+ data: {+ algorithm: 'byzantine',+ honestVotes: honestVotes.length,+ totalVotes: consensus.votes.length,+ executedAt: new Date().toISOString()+ }+ };+ }+ return {+ success: false,+ error: 'Byzantine consensus failed - insufficient honest votes'+ };+ }+ async getAgentIds() {+ try {+ const agentKeys = await this.database.list('agents');+ return agentKeys.map((key)=>key.replace('agent:', ''));+ } catch {+ return [+ 'agent-1',+ 'agent-2',+ 'agent-3',+ 'agent-4',+ 'agent-5'+ ];+ }+ }+};+let GossipConsensus = class GossipConsensus {+ database;+ constructor(database){+ this.database = database;+ }+ getType() {+ return 'gossip';+ }+ async initialize() {}+ async propose(decision) {+ const votes = [];+ const agentIds = await this.getAgentIds();+ for (const agentId of agentIds){+ const delay = Math.random() * 1000;+ const informed = Math.random() > 0.1;+ if (informed) {+ const vote = {+ agentId,+ decision: Math.random() > 0.25,+ confidence: 0.6 + Math.random() * 0.3,+ reasoning: `Gossip consensus vote (delay: ${Math.round(delay)}ms)`+ };+ votes.push(vote);+ }+ }+ return votes;+ }+ async execute(consensus) {+ const participation = consensus.votes.length / (await this.getAgentIds()).length;+ if (consensus.outcome && participation > 0.7) {+ return {+ success: true,+ data: {+ algorithm: 'gossip',+ participation: participation,+ convergenceTime: Math.random() * 5000 + 1000,+ executedAt: new Date().toISOString()+ }+ };+ }+ return {+ success: false,+ error: 'Gossip consensus failed - insufficient participation or negative outcome'+ };+ }+ async getAgentIds() {+ try {+ const agentKeys = await this.database.list('agents');+ return agentKeys.map((key)=>key.replace('agent:', ''));+ } catch {+ return Array.from({+ length: 8+ }, (_, i)=>`agent-${i + 1}`);+ }+ }+};+let ProofOfLearningConsensus = class ProofOfLearningConsensus {+ database;+ constructor(database){+ this.database = database;+ }+ getType() {+ return 'proof-of-learning';+ }+ async initialize() {}+ async propose(decision) {+ const votes = [];+ const agentIds = await this.getAgentIds();+ for (const agentId of agentIds){+ const performance = await this.getAgentPerformance(agentId);+ const learningScore = this.calculateLearningScore(performance);+ const vote = {+ agentId,+ decision: learningScore > 0.5 ? Math.random() > 0.2 : Math.random() > 0.6,+ confidence: learningScore,+ reasoning: `Proof of Learning vote (learning score: ${learningScore.toFixed(2)})`+ };+ votes.push(vote);+ }+ return votes;+ }+ async execute(consensus) {+ const weightedVotes = consensus.votes.reduce((sum, vote)=>{+ return sum + (vote.decision ? vote.confidence : -vote.confidence);+ }, 0);+ const totalWeight = consensus.votes.reduce((sum, vote)=>sum + vote.confidence, 0);+ const weightedOutcome = weightedVotes > 0 && weightedVotes / totalWeight > 0.6;+ if (weightedOutcome) {+ return {+ success: true,+ data: {+ algorithm: 'proof-of-learning',+ weightedScore: weightedVotes / totalWeight,+ highPerformers: consensus.votes.filter((v)=>v.confidence > 0.8).length,+ executedAt: new Date().toISOString()+ }+ };+ }+ return {+ success: false,+ error: 'Proof of Learning consensus failed - insufficient weighted support'+ };+ }+ async getAgentPerformance(agentId) {+ try {+ const agent = await this.database.retrieve(agentId, 'agents');+ return agent?.performance || {+ successRate: 0.5,+ tasksCompleted: 0+ };+ } catch {+ return {+ successRate: 0.5,+ tasksCompleted: 0+ };+ }+ }+ calculateLearningScore(performance) {+ const successWeight = 0.7;+ const experienceWeight = 0.3;+ const successScore = performance.successRate || 0.5;+ const experienceScore = Math.min(1.0, (performance.tasksCompleted || 0) / 100);+ return successScore * successWeight + experienceScore * experienceWeight;+ }+ async getAgentIds() {+ try {+ const agentKeys = await this.database.list('agents');+ return agentKeys.map((key)=>key.replace('agent:', ''));+ } catch {+ return Array.from({+ length: 6+ }, (_, i)=>`agent-${i + 1}`);+ }+ }+};++//# sourceMappingURL=ConsensusEngine.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/ConsensusEngine.js.map b/dist-cjs/src/core/ConsensusEngine.js.mapnew file mode 100644index 0000000000..cdc4905a59--- /dev/null+++ b/dist-cjs/src/core/ConsensusEngine.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/ConsensusEngine.ts"],"sourcesContent":["/**\n * ConsensusEngine - Implements consensus algorithms for distributed decision making\n * Supports multiple consensus algorithms: Raft, Byzantine, Gossip, and Proof-of-Learning\n */\n\nimport { IDatabaseProvider, IConsensusAlgorithm, Decision, Vote, Consensus, Result, ConsensusType } from '../types/interfaces.js';\nimport { nanoid } from 'nanoid';\n\nexport class ConsensusEngine {\n private algorithms: Map<ConsensusType, IConsensusAlgorithm> = new Map();\n private currentAlgorithm: IConsensusAlgorithm | null = null;\n private pendingDecisions: Map<string, Decision> = new Map();\n private consensusHistory: Map<string, Consensus> = new Map();\n\n constructor(private database: IDatabaseProvider) {\n this.initializeAlgorithms();\n }\n\n /**\n * Initialize available consensus algorithms\n */\n private initializeAlgorithms(): void {\n this.algorithms.set('raft', new RaftConsensus(this.database));\n this.algorithms.set('byzantine', new ByzantineConsensus(this.database));\n this.algorithms.set('gossip', new GossipConsensus(this.database));\n this.algorithms.set('proof-of-learning', new ProofOfLearningConsensus(this.database));\n }\n\n /**\n * Set the active consensus algorithm\n */\n async setAlgorithm(type: ConsensusType): Promise<void> {\n const algorithm = this.algorithms.get(type);\n if (!algorithm) {\n throw new Error(`Unknown consensus algorithm: ${type}`);\n }\n\n this.currentAlgorithm = algorithm;\n await algorithm.initialize();\n\n await this.database.store('consensus-algorithm', type, 'system');\n }\n\n /**\n * Propose a decision for consensus\n */\n async propose(decision: Omit<Decision, 'id' | 'timestamp'>): Promise<string> {\n if (!this.currentAlgorithm) {\n throw new Error('No consensus algorithm selected');\n }\n\n const fullDecision: Decision = {\n ...decision,\n id: nanoid(),\n timestamp: new Date()\n };\n\n this.pendingDecisions.set(fullDecision.id, fullDecision);\n await this.database.store(`decision:${fullDecision.id}`, fullDecision, 'consensus');\n\n // Start consensus process\n const votes = await this.currentAlgorithm.propose(fullDecision);\n\n // Process votes and determine consensus\n const consensus = await this.processVotes(fullDecision, votes);\n\n return fullDecision.id;\n }\n\n /**\n * Process votes and determine consensus\n */\n private async processVotes(decision: Decision, votes: Vote[]): Promise<Consensus> {\n // Calculate consensus based on votes\n const positiveVotes = votes.filter(vote => vote.decision);\n const totalConfidence = votes.reduce((sum, vote) => sum + vote.confidence, 0);\n const averageConfidence = totalConfidence / votes.length;\n\n // Simple majority rule with confidence weighting\n const weightedPositive = positiveVotes.reduce((sum, vote) => sum + vote.confidence, 0);\n const totalWeight = votes.reduce((sum, vote) => sum + vote.confidence, 0);\n\n const outcome = weightedPositive > (totalWeight / 2) && averageConfidence > 0.6;\n\n const consensus: Consensus = {\n decisionId: decision.id,\n outcome,\n votes,\n confidence: averageConfidence,\n timestamp: new Date()\n };\n\n this.consensusHistory.set(decision.id, consensus);\n await this.database.store(`consensus:${decision.id}`, consensus, 'consensus');\n\n // Execute if consensus reached\n if (outcome) {\n await this.executeConsensus(consensus);\n }\n\n return consensus;\n }\n\n /**\n * Execute a consensus decision\n */\n private async executeConsensus(consensus: Consensus): Promise<Result> {\n if (!this.currentAlgorithm) {\n throw new Error('No consensus algorithm available for execution');\n }\n\n const result = await this.currentAlgorithm.execute(consensus);\n await this.database.store(`result:${consensus.decisionId}`, result, 'consensus');\n\n // Clean up pending decision\n this.pendingDecisions.delete(consensus.decisionId);\n\n return result;\n }\n\n /**\n * Get consensus status for a decision\n */\n async getConsensusStatus(decisionId: string): Promise<{\n decision: Decision | null;\n consensus: Consensus | null;\n status: 'pending' | 'reached' | 'failed';\n }> {\n const decision = this.pendingDecisions.get(decisionId) ||\n await this.database.retrieve(`decision:${decisionId}`, 'consensus');\n\n const consensus = this.consensusHistory.get(decisionId) ||\n await this.database.retrieve(`consensus:${decisionId}`, 'consensus');\n\n let status: 'pending' | 'reached' | 'failed' = 'pending';\n if (consensus) {\n status = consensus.outcome ? 'reached' : 'failed';\n }\n\n return { decision, consensus, status };\n }\n\n /**\n * Get all pending decisions\n */\n getPendingDecisions(): Decision[] {\n return Array.from(this.pendingDecisions.values());\n }\n\n /**\n * Get consensus history\n */\n getConsensusHistory(): Consensus[] {\n return Array.from(this.consensusHistory.values());\n }\n\n /**\n * Get current algorithm type\n */\n getCurrentAlgorithm(): ConsensusType | null {\n return this.currentAlgorithm?.getType() || null;\n }\n\n /**\n * Get available algorithms\n */\n getAvailableAlgorithms(): ConsensusType[] {\n return Array.from(this.algorithms.keys());\n }\n}\n\n/**\n * Raft Consensus Algorithm\n * Leader-based consensus with strong consistency\n */\nclass RaftConsensus implements IConsensusAlgorithm {\n private leaderId: string | null = null;\n private term: number = 0;\n private votedFor: string | null = null;\n\n constructor(private database: IDatabaseProvider) {}\n\n getType(): ConsensusType {\n return 'raft';\n }\n\n async initialize(): Promise<void> {\n // Load state from database\n const state = await this.database.retrieve('raft-state', 'consensus');\n if (state) {\n this.term = state.term || 0;\n this.leaderId = state.leaderId || null;\n this.votedFor = state.votedFor || null;\n }\n }\n\n async propose(decision: Decision): Promise<Vote[]> {\n // In Raft, only the leader can propose\n if (!this.leaderId) {\n await this.electLeader();\n }\n\n // Simulate distributed voting\n const votes: Vote[] = [];\n const agentIds = await this.getAgentIds();\n\n for (const agentId of agentIds) {\n const vote: Vote = {\n agentId,\n decision: Math.random() > 0.2, // 80% approval rate\n confidence: 0.8 + Math.random() * 0.2, // High confidence in Raft\n reasoning: `Raft consensus vote for decision ${decision.id}`\n };\n votes.push(vote);\n }\n\n return votes;\n }\n\n async execute(consensus: Consensus): Promise<Result> {\n if (!consensus.outcome) {\n return {\n success: false,\n error: 'Consensus was not reached'\n };\n }\n\n // Execute the decision through the leader\n return {\n success: true,\n data: {\n algorithm: 'raft',\n leader: this.leaderId,\n term: this.term,\n executedAt: new Date().toISOString()\n },\n metadata: {\n consensusId: consensus.decisionId,\n votes: consensus.votes.length\n }\n };\n }\n\n private async electLeader(): Promise<void> {\n this.term++;\n const agentIds = await this.getAgentIds();\n this.leaderId = agentIds[0] || 'default-leader';\n this.votedFor = this.leaderId;\n\n await this.database.store('raft-state', {\n term: this.term,\n leaderId: this.leaderId,\n votedFor: this.votedFor\n }, 'consensus');\n }\n\n private async getAgentIds(): Promise<string[]> {\n try {\n const agentKeys = await this.database.list('agents');\n return agentKeys.map(key => key.replace('agent:', ''));\n } catch {\n return ['agent-1', 'agent-2', 'agent-3']; // Default agents\n }\n }\n}\n\n/**\n * Byzantine Fault Tolerant Consensus\n * Handles up to 1/3 malicious agents\n */\nclass ByzantineConsensus implements IConsensusAlgorithm {\n constructor(private database: IDatabaseProvider) {}\n\n getType(): ConsensusType {\n return 'byzantine';\n }\n\n async initialize(): Promise<void> {\n // Byzantine consensus initialization\n }\n\n async propose(decision: Decision): Promise<Vote[]> {\n const votes: Vote[] = [];\n const agentIds = await this.getAgentIds();\n\n // Simulate Byzantine environment with some malicious agents\n for (const agentId of agentIds) {\n const isMalicious = Math.random() < 0.2; // 20% malicious agents\n const vote: Vote = {\n agentId,\n decision: isMalicious ? Math.random() < 0.3 : Math.random() > 0.3, // Malicious agents vote randomly\n confidence: isMalicious ? Math.random() * 0.5 : 0.7 + Math.random() * 0.3,\n reasoning: `Byzantine consensus vote (${isMalicious ? 'malicious' : 'honest'})`\n };\n votes.push(vote);\n }\n\n return votes;\n }\n\n async execute(consensus: Consensus): Promise<Result> {\n // Byzantine consensus requires 2/3 + 1 majority\n const honestVotes = consensus.votes.filter(vote => vote.confidence > 0.6);\n const required = Math.floor(consensus.votes.length * 2 / 3) + 1;\n\n if (honestVotes.length >= required && consensus.outcome) {\n return {\n success: true,\n data: {\n algorithm: 'byzantine',\n honestVotes: honestVotes.length,\n totalVotes: consensus.votes.length,\n executedAt: new Date().toISOString()\n }\n };\n }\n\n return {\n success: false,\n error: 'Byzantine consensus failed - insufficient honest votes'\n };\n }\n\n private async getAgentIds(): Promise<string[]> {\n try {\n const agentKeys = await this.database.list('agents');\n return agentKeys.map(key => key.replace('agent:', ''));\n } catch {\n return ['agent-1', 'agent-2', 'agent-3', 'agent-4', 'agent-5'];\n }\n }\n}\n\n/**\n * Gossip Protocol Consensus\n * Eventually consistent through peer-to-peer communication\n */\nclass GossipConsensus implements IConsensusAlgorithm {\n constructor(private database: IDatabaseProvider) {}\n\n getType(): ConsensusType {\n return 'gossip';\n }\n\n async initialize(): Promise<void> {\n // Gossip protocol initialization\n }\n\n async propose(decision: Decision): Promise<Vote[]> {\n const votes: Vote[] = [];\n const agentIds = await this.getAgentIds();\n\n // Simulate gossip propagation delays and eventual consistency\n for (const agentId of agentIds) {\n const delay = Math.random() * 1000; // Random delay\n const informed = Math.random() > 0.1; // 90% eventually receive the message\n\n if (informed) {\n const vote: Vote = {\n agentId,\n decision: Math.random() > 0.25, // 75% approval\n confidence: 0.6 + Math.random() * 0.3,\n reasoning: `Gossip consensus vote (delay: ${Math.round(delay)}ms)`\n };\n votes.push(vote);\n }\n }\n\n return votes;\n }\n\n async execute(consensus: Consensus): Promise<Result> {\n // Gossip consensus is eventually consistent\n const participation = consensus.votes.length / (await this.getAgentIds()).length;\n\n if (consensus.outcome && participation > 0.7) {\n return {\n success: true,\n data: {\n algorithm: 'gossip',\n participation: participation,\n convergenceTime: Math.random() * 5000 + 1000,\n executedAt: new Date().toISOString()\n }\n };\n }\n\n return {\n success: false,\n error: 'Gossip consensus failed - insufficient participation or negative outcome'\n };\n }\n\n private async getAgentIds(): Promise<string[]> {\n try {\n const agentKeys = await this.database.list('agents');\n return agentKeys.map(key => key.replace('agent:', ''));\n } catch {\n return Array.from({ length: 8 }, (_, i) => `agent-${i + 1}`);\n }\n }\n}\n\n/**\n * Proof of Learning Consensus\n * Consensus based on agent learning and performance\n */\nclass ProofOfLearningConsensus implements IConsensusAlgorithm {\n constructor(private database: IDatabaseProvider) {}\n\n getType(): ConsensusType {\n return 'proof-of-learning';\n }\n\n async initialize(): Promise<void> {\n // Proof of Learning initialization\n }\n\n async propose(decision: Decision): Promise<Vote[]> {\n const votes: Vote[] = [];\n const agentIds = await this.getAgentIds();\n\n for (const agentId of agentIds) {\n // Get agent performance for voting weight\n const performance = await this.getAgentPerformance(agentId);\n const learningScore = this.calculateLearningScore(performance);\n\n const vote: Vote = {\n agentId,\n decision: learningScore > 0.5 ? Math.random() > 0.2 : Math.random() > 0.6,\n confidence: learningScore,\n reasoning: `Proof of Learning vote (learning score: ${learningScore.toFixed(2)})`\n };\n votes.push(vote);\n }\n\n return votes;\n }\n\n async execute(consensus: Consensus): Promise<Result> {\n // Weight votes by learning scores\n const weightedVotes = consensus.votes.reduce((sum, vote) => {\n return sum + (vote.decision ? vote.confidence : -vote.confidence);\n }, 0);\n\n const totalWeight = consensus.votes.reduce((sum, vote) => sum + vote.confidence, 0);\n const weightedOutcome = weightedVotes > 0 && (weightedVotes / totalWeight) > 0.6;\n\n if (weightedOutcome) {\n return {\n success: true,\n data: {\n algorithm: 'proof-of-learning',\n weightedScore: weightedVotes / totalWeight,\n highPerformers: consensus.votes.filter(v => v.confidence > 0.8).length,\n executedAt: new Date().toISOString()\n }\n };\n }\n\n return {\n success: false,\n error: 'Proof of Learning consensus failed - insufficient weighted support'\n };\n }\n\n private async getAgentPerformance(agentId: string): Promise<any> {\n try {\n const agent = await this.database.retrieve(agentId, 'agents');\n return agent?.performance || { successRate: 0.5, tasksCompleted: 0 };\n } catch {\n return { successRate: 0.5, tasksCompleted: 0 };\n }\n }\n\n private calculateLearningScore(performance: any): number {\n // Combine success rate and experience\n const successWeight = 0.7;\n const experienceWeight = 0.3;\n\n const successScore = performance.successRate || 0.5;\n const experienceScore = Math.min(1.0, (performance.tasksCompleted || 0) / 100);\n\n return successScore * successWeight + experienceScore * experienceWeight;\n }\n\n private async getAgentIds(): Promise<string[]> {\n try {\n const agentKeys = await this.database.list('agents');\n return agentKeys.map(key => key.replace('agent:', ''));\n } catch {\n return Array.from({ length: 6 }, (_, i) => `agent-${i + 1}`);\n }\n }\n}"],"names":["nanoid","ConsensusEngine","algorithms","Map","currentAlgorithm","pendingDecisions","consensusHistory","database","initializeAlgorithms","set","RaftConsensus","ByzantineConsensus","GossipConsensus","ProofOfLearningConsensus","setAlgorithm","type","algorithm","get","Error","initialize","store","propose","decision","fullDecision","id","timestamp","Date","votes","consensus","processVotes","positiveVotes","filter","vote","totalConfidence","reduce","sum","confidence","averageConfidence","length","weightedPositive","totalWeight","outcome","decisionId","executeConsensus","result","execute","delete","getConsensusStatus","retrieve","status","getPendingDecisions","Array","from","values","getConsensusHistory","getCurrentAlgorithm","getType","getAvailableAlgorithms","keys","leaderId","term","votedFor","state","electLeader","agentIds","getAgentIds","agentId","Math","random","reasoning","push","success","error","data","leader","executedAt","toISOString","metadata","consensusId","agentKeys","list","map","key","replace","isMalicious","honestVotes","required","floor","totalVotes","delay","informed","round","participation","convergenceTime","_","i","performance","getAgentPerformance","learningScore","calculateLearningScore","toFixed","weightedVotes","weightedOutcome","weightedScore","highPerformers","v","agent","successRate","tasksCompleted","successWeight","experienceWeight","successScore","experienceScore","min"],"mappings":"AAMA,SAASA,MAAM,QAAQ,SAAS;AAEhC,OAAO,MAAMC;;IACHC,aAAsD,IAAIC,MAAM;IAChEC,mBAA+C,KAAK;IACpDC,mBAA0C,IAAIF,MAAM;IACpDG,mBAA2C,IAAIH,MAAM;IAE7D,YAAY,AAAQI,QAA2B,CAAE;aAA7BA,WAAAA;QAClB,IAAI,CAACC,oBAAoB;IAC3B;IAKQA,uBAA6B;QACnC,IAAI,CAACN,UAAU,CAACO,GAAG,CAAC,QAAQ,IAAIC,cAAc,IAAI,CAACH,QAAQ;QAC3D,IAAI,CAACL,UAAU,CAACO,GAAG,CAAC,aAAa,IAAIE,mBAAmB,IAAI,CAACJ,QAAQ;QACrE,IAAI,CAACL,UAAU,CAACO,GAAG,CAAC,UAAU,IAAIG,gBAAgB,IAAI,CAACL,QAAQ;QAC/D,IAAI,CAACL,UAAU,CAACO,GAAG,CAAC,qBAAqB,IAAII,yBAAyB,IAAI,CAACN,QAAQ;IACrF;IAKA,MAAMO,aAAaC,IAAmB,EAAiB;QACrD,MAAMC,YAAY,IAAI,CAACd,UAAU,CAACe,GAAG,CAACF;QACtC,IAAI,CAACC,WAAW;YACd,MAAM,IAAIE,MAAM,CAAC,6BAA6B,EAAEH,MAAM;QACxD;QAEA,IAAI,CAACX,gBAAgB,GAAGY;QACxB,MAAMA,UAAUG,UAAU;QAE1B,MAAM,IAAI,CAACZ,QAAQ,CAACa,KAAK,CAAC,uBAAuBL,MAAM;IACzD;IAKA,MAAMM,QAAQC,QAA4C,EAAmB;QAC3E,IAAI,CAAC,IAAI,CAAClB,gBAAgB,EAAE;YAC1B,MAAM,IAAIc,MAAM;QAClB;QAEA,MAAMK,eAAyB;YAC7B,GAAGD,QAAQ;YACXE,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EAAE,OAAM;YACN,OAAO;gBAAED,aAAa;gBAAKC,gBAAgB;YAAE;QAC/C;IACF;IAEQT,uBAAuBH,WAAgB,EAAU;QAEvD,MAAMa,gBAAgB;QACtB,MAAMC,mBAAmB;QAEzB,MAAMC,eAAef,YAAYW,WAAW,IAAI;QAChD,MAAMK,kBAAkB7C,KAAK8C,GAAG,CAAC,KAAK,AAACjB,CAAAA,YAAYY,cAAc,IAAI,CAAA,IAAK;QAE1E,OAAOG,eAAeF,gBAAgBG,kBAAkBF;IAC1D;IAEA,MAAc7C,cAAiC;QAC7C,IAAI;YACF,MAAMc,YAAY,MAAM,IAAI,CAACxE,QAAQ,CAACyE,IAAI,CAAC;YAC3C,OAAOD,UAAUE,GAAG,CAACC,CAAAA,MAAOA,IAAIC,OAAO,CAAC,UAAU;QACpD,EAAE,OAAM;YACN,OAAOhC,MAAMC,IAAI,CAAC;gBAAEd,QAAQ;YAAE,GAAG,CAACwD,GAAGC,IAAM,CAAC,MAAM,EAAEA,IAAI,GAAG;QAC7D;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/DatabaseManager.js b/dist-cjs/src/core/DatabaseManager.jsnew file mode 100644index 0000000000..8386e52136--- /dev/null+++ b/dist-cjs/src/core/DatabaseManager.js@@ -0,0 +1,213 @@+import * as fs from 'fs-extra';+import * as path from 'path';+export class DatabaseManager {+ provider;+ dbType;+ dbPath;+ initialized = false;+ constructor(dbType = 'sqlite', dbPath){+ this.dbType = dbType;+ this.dbPath = dbPath || this.getDefaultPath();+ if (this.dbType === 'sqlite') {+ try {+ this.provider = new SQLiteProvider(this.dbPath);+ } catch (error) {+ console.warn('SQLite not available, falling back to JSON storage:', error);+ this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));+ this.dbType = 'json';+ }+ } else {+ this.provider = new JSONProvider(this.dbPath);+ }+ }+ getDefaultPath() {+ const baseDir = path.join(process.cwd(), '.claude-flow');+ return this.dbType === 'sqlite' ? path.join(baseDir, 'database.sqlite') : path.join(baseDir, 'database.json');+ }+ async initialize() {+ await fs.ensureDir(path.dirname(this.dbPath));+ await this.provider.initialize();+ this.initialized = true;+ }+ async store(key, value, namespace = 'default') {+ if (!this.initialized) {+ await this.initialize();+ }+ return this.provider.store(key, value, namespace);+ }+ async retrieve(key, namespace = 'default') {+ if (!this.initialized) {+ await this.initialize();+ }+ return this.provider.retrieve(key, namespace);+ }+ async delete(key, namespace = 'default') {+ if (!this.initialized) {+ await this.initialize();+ }+ return this.provider.delete(key, namespace);+ }+ async list(namespace = 'default') {+ if (!this.initialized) {+ await this.initialize();+ }+ return this.provider.list(namespace);+ }+ async close() {+ if (this.provider) {+ await this.provider.close();+ }+ this.initialized = false;+ }+ getDatabaseType() {+ return this.dbType;+ }+ getDatabasePath() {+ return this.dbPath;+ }+ isInitialized() {+ return this.initialized;+ }+ async storeJSON(key, data, namespace) {+ await this.store(key, JSON.stringify(data), namespace);+ }+ async retrieveJSON(key, namespace) {+ const data = await this.retrieve(key, namespace);+ if (!data) return null;+ try {+ return typeof data === 'string' ? JSON.parse(data) : data;+ } catch {+ return null;+ }+ }+ async exists(key, namespace) {+ const data = await this.retrieve(key, namespace);+ return data !== null && data !== undefined;+ }+ async clear(namespace) {+ const keys = await this.list(namespace);+ await Promise.all(keys.map((key)=>this.delete(key, namespace)));+ }+}+let SQLiteProvider = class SQLiteProvider {+ db;+ dbPath;+ constructor(dbPath){+ this.dbPath = dbPath;+ try {+ const Database = require('better-sqlite3');+ this.db = new Database(dbPath);+ } catch (error) {+ throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');+ }+ }+ async initialize() {+ this.db.exec(`+ CREATE TABLE IF NOT EXISTS storage (+ namespace TEXT NOT NULL,+ key TEXT NOT NULL,+ value TEXT NOT NULL,+ created_at INTEGER DEFAULT (strftime('%s', 'now')),+ updated_at INTEGER DEFAULT (strftime('%s', 'now')),+ PRIMARY KEY (namespace, key)+ )+ `);+ this.db.exec(`+ CREATE INDEX IF NOT EXISTS idx_storage_namespace ON storage(namespace);+ CREATE INDEX IF NOT EXISTS idx_storage_created_at ON storage(created_at);+ `);+ }+ async store(key, value, namespace = 'default') {+ const stmt = this.db.prepare(`+ INSERT OR REPLACE INTO storage (namespace, key, value, updated_at)+ VALUES (?, ?, ?, strftime('%s', 'now'))+ `);+ const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);+ stmt.run(namespace, key, serializedValue);+ }+ async retrieve(key, namespace = 'default') {+ const stmt = this.db.prepare('SELECT value FROM storage WHERE namespace = ? AND key = ?');+ const row = stmt.get(namespace, key);+ if (!row) return null;+ try {+ return JSON.parse(row.value);+ } catch {+ return row.value;+ }+ }+ async delete(key, namespace = 'default') {+ const stmt = this.db.prepare('DELETE FROM storage WHERE namespace = ? AND key = ?');+ const result = stmt.run(namespace, key);+ return result.changes > 0;+ }+ async list(namespace = 'default') {+ const stmt = this.db.prepare('SELECT key FROM storage WHERE namespace = ? ORDER BY key');+ const rows = stmt.all(namespace);+ return rows.map((row)=>row.key);+ }+ async close() {+ if (this.db) {+ this.db.close();+ }+ }+};+let JSONProvider = class JSONProvider {+ data = {};+ dbPath;+ constructor(dbPath){+ this.dbPath = dbPath;+ }+ async initialize() {+ try {+ if (await fs.pathExists(this.dbPath)) {+ const content = await fs.readJSON(this.dbPath);+ this.data = content || {};+ }+ } catch (error) {+ console.warn('Failed to load JSON database, starting fresh:', error);+ this.data = {};+ }+ }+ async store(key, value, namespace = 'default') {+ if (!this.data[namespace]) {+ this.data[namespace] = {};+ }+ this.data[namespace][key] = value;+ await this.persist();+ }+ async retrieve(key, namespace = 'default') {+ if (!this.data[namespace]) {+ return null;+ }+ return this.data[namespace][key] || null;+ }+ async delete(key, namespace = 'default') {+ if (!this.data[namespace] || !(key in this.data[namespace])) {+ return false;+ }+ delete this.data[namespace][key];+ await this.persist();+ return true;+ }+ async list(namespace = 'default') {+ if (!this.data[namespace]) {+ return [];+ }+ return Object.keys(this.data[namespace]).sort();+ }+ async close() {+ await this.persist();+ }+ async persist() {+ try {+ await fs.ensureDir(path.dirname(this.dbPath));+ await fs.writeJSON(this.dbPath, this.data, {+ spaces: 2+ });+ } catch (error) {+ console.error('Failed to persist JSON database:', error);+ }+ }+};++//# sourceMappingURL=DatabaseManager.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/DatabaseManager.js.map b/dist-cjs/src/core/DatabaseManager.js.mapnew file mode 100644index 0000000000..e7f1ffa02c--- /dev/null+++ b/dist-cjs/src/core/DatabaseManager.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/DatabaseManager.ts"],"sourcesContent":["/**\n * DatabaseManager - Manages SQLite and JSON fallback storage\n * Provides a unified interface for persistent data storage with automatic fallback\n */\n\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport { IDatabaseProvider } from '../types/interfaces.js';\n\nexport class DatabaseManager implements IDatabaseProvider {\n private provider: IDatabaseProvider;\n private dbType: 'sqlite' | 'json';\n private dbPath: string;\n private initialized: boolean = false;\n\n constructor(dbType: 'sqlite' | 'json' = 'sqlite', dbPath?: string) {\n this.dbType = dbType;\n this.dbPath = dbPath || this.getDefaultPath();\n\n // Try SQLite first, fallback to JSON if needed\n if (this.dbType === 'sqlite') {\n try {\n this.provider = new SQLiteProvider(this.dbPath);\n } catch (error) {\n console.warn('SQLite not available, falling back to JSON storage:', error);\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n }\n } else {\n this.provider = new JSONProvider(this.dbPath);\n }\n }\n\n private getDefaultPath(): string {\n const baseDir = path.join(process.cwd(), '.claude-flow');\n return this.dbType === 'sqlite'\n ? path.join(baseDir, 'database.sqlite')\n : path.join(baseDir, 'database.json');\n }\n\n async initialize(): Promise<void> {\n await fs.ensureDir(path.dirname(this.dbPath));\n await this.provider.initialize();\n this.initialized = true;\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.store(key, value, namespace);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.retrieve(key, namespace);\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.delete(key, namespace);\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.list(namespace);\n }\n\n async close(): Promise<void> {\n if (this.provider) {\n await this.provider.close();\n }\n this.initialized = false;\n }\n\n getDatabaseType(): 'sqlite' | 'json' {\n return this.dbType;\n }\n\n getDatabasePath(): string {\n return this.dbPath;\n }\n\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // Specialized methods for common operations\n async storeJSON(key: string, data: object, namespace?: string): Promise<void> {\n await this.store(key, JSON.stringify(data), namespace);\n }\n\n async retrieveJSON(key: string, namespace?: string): Promise<object | null> {\n const data = await this.retrieve(key, namespace);\n if (!data) return null;\n try {\n return typeof data === 'string' ? JSON.parse(data) : data;\n } catch {\n return null;\n }\n }\n\n async exists(key: string, namespace?: string): Promise<boolean> {\n const data = await this.retrieve(key, namespace);\n return data !== null && data !== undefined;\n }\n\n async clear(namespace?: string): Promise<void> {\n const keys = await this.list(namespace);\n await Promise.all(keys.map(key => this.delete(key, namespace)));\n }\n}\n\n/**\n * SQLite implementation\n */\nclass SQLiteProvider implements IDatabaseProvider {\n private db: any;\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n // Dynamic import to handle optional dependency\n try {\n const Database = require('better-sqlite3');\n this.db = new Database(dbPath);\n } catch (error) {\n throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');\n }\n }\n\n async initialize(): Promise<void> {\n // Create tables\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS storage (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER DEFAULT (strftime('%s', 'now')),\n PRIMARY KEY (namespace, key)\n )\n `);\n\n this.db.exec(`\n CREATE INDEX IF NOT EXISTS idx_storage_namespace ON storage(namespace);\n CREATE INDEX IF NOT EXISTS idx_storage_created_at ON storage(created_at);\n `);\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n const stmt = this.db.prepare(`\n INSERT OR REPLACE INTO storage (namespace, key, value, updated_at)\n VALUES (?, ?, ?, strftime('%s', 'now'))\n `);\n\n const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);\n stmt.run(namespace, key, serializedValue);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n const stmt = this.db.prepare('SELECT value FROM storage WHERE namespace = ? AND key = ?');\n const row = stmt.get(namespace, key);\n\n if (!row) return null;\n\n try {\n return JSON.parse(row.value);\n } catch {\n return row.value;\n }\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n const stmt = this.db.prepare('DELETE FROM storage WHERE namespace = ? AND key = ?');\n const result = stmt.run(namespace, key);\n return result.changes > 0;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n const stmt = this.db.prepare('SELECT key FROM storage WHERE namespace = ? ORDER BY key');\n const rows = stmt.all(namespace);\n return rows.map((row: any) => row.key);\n }\n\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n }\n }\n}\n\n/**\n * JSON file-based implementation\n */\nclass JSONProvider implements IDatabaseProvider {\n private data: Record<string, Record<string, any>> = {};\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n }\n\n async initialize(): Promise<void> {\n try {\n if (await fs.pathExists(this.dbPath)) {\n const content = await fs.readJSON(this.dbPath);\n this.data = content || {};\n }\n } catch (error) {\n console.warn('Failed to load JSON database, starting fresh:', error);\n this.data = {};\n }\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.data[namespace]) {\n this.data[namespace] = {};\n }\n\n this.data[namespace][key] = value;\n await this.persist();\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.data[namespace]) {\n return null;\n }\n return this.data[namespace][key] || null;\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.data[namespace] || !(key in this.data[namespace])) {\n return false;\n }\n\n delete this.data[namespace][key];\n await this.persist();\n return true;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.data[namespace]) {\n return [];\n }\n return Object.keys(this.data[namespace]).sort();\n }\n\n async close(): Promise<void> {\n await this.persist();\n }\n\n private async persist(): Promise<void> {\n try {\n await fs.ensureDir(path.dirname(this.dbPath));\n await fs.writeJSON(this.dbPath, this.data, { spaces: 2 });\n } catch (error) {\n console.error('Failed to persist JSON database:', error);\n }\n }\n}"],"names":["fs","path","DatabaseManager","provider","dbType","dbPath","initialized","getDefaultPath","SQLiteProvider","error","console","warn","JSONProvider","replace","baseDir","join","process","cwd","initialize","ensureDir","dirname","store","key","value","namespace","retrieve","delete","list","close","getDatabaseType","getDatabasePath","isInitialized","storeJSON","data","JSON","stringify","retrieveJSON","parse","exists","undefined","clear","keys","Promise","all","map","db","Database","require","Error","exec","stmt","prepare","serializedValue","run","row","get","result","changes","rows","pathExists","content","readJSON","persist","Object","sort","writeJSON","spaces"],"mappings":"AAKA,YAAYA,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAG7B,OAAO,MAAMC;IACHC,SAA4B;IAC5BC,OAA0B;IAC1BC,OAAe;IACfC,cAAuB,MAAM;IAErC,YAAYF,SAA4B,QAAQ,EAAEC,MAAe,CAAE;QACjE,IAAI,CAACD,MAAM,GAAGA;QACd,IAAI,CAACC,MAAM,GAAGA,UAAU,IAAI,CAACE,cAAc;QAG3C,IAAI,IAAI,CAACH,MAAM,KAAK,UAAU;YAC5B,IAAI;gBACF,IAAI,CAACD,QAAQ,GAAG,IAAIK,eAAe,IAAI,CAACH,MAAM;YAChD,EAAE,OAAOI,OAAO;gBACdC,QAAQC,IAAI,CAAC,uDAAuDF;gBACpE,IAAI,C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AC,IAAI,CAACS,IAAI,CAACT,UAAU,IAAI,CAAEF,CAAAA,OAAO,IAAI,CAACW,IAAI,CAACT,UAAU,AAAD,GAAI;YAC3D,OAAO;QACT;QAEA,OAAO,IAAI,CAACS,IAAI,CAACT,UAAU,CAACF,IAAI;QAChC,MAAM,IAAI,CAACwC,OAAO;QAClB,OAAO;IACT;IAEA,MAAMnC,KAAKH,YAAoB,SAAS,EAAqB;QAC3D,IAAI,CAAC,IAAI,CAACS,IAAI,CAACT,UAAU,EAAE;YACzB,OAAO,EAAE;QACX;QACA,OAAOuC,OAAOtB,IAAI,CAAC,IAAI,CAACR,IAAI,CAACT,UAAU,EAAEwC,IAAI;IAC/C;IAEA,MAAMpC,QAAuB;QAC3B,MAAM,IAAI,CAACkC,OAAO;IACpB;IAEA,MAAcA,UAAyB;QACrC,IAAI;YACF,MAAM9D,GAAGmB,SAAS,CAAClB,KAAKmB,OAAO,CAAC,IAAI,CAACf,MAAM;YAC3C,MAAML,GAAGiE,SAAS,CAAC,IAAI,CAAC5D,MAAM,EAAE,IAAI,CAAC4B,IAAI,EAAE;gBAAEiC,QAAQ;YAAE;QACzD,EAAE,OAAOzD,OAAO;YACdC,QAAQD,KAAK,CAAC,oCAAoCA;QACpD;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/HiveMindCore.js b/dist-cjs/src/core/HiveMindCore.jsnew file mode 100644index 0000000000..a8d230846f--- /dev/null+++ b/dist-cjs/src/core/HiveMindCore.js@@ -0,0 +1,488 @@+import { nanoid } from 'nanoid';+export class HiveMindCore {+ database;+ agentRegistry;+ consensusEngine;+ metricsCollector;+ queen;+ workerPools = new Map();+ objectives = new Map();+ strategies = new Map();+ assignments = new Map();+ config;+ constructor(database, agentRegistry, consensusEngine, metricsCollector, config = {}){+ this.database = database;+ this.agentRegistry = agentRegistry;+ this.consensusEngine = consensusEngine;+ this.metricsCollector = metricsCollector;+ this.config = {+ maxWorkerPools: 5,+ queenEnabled: true,+ adaptationRate: 0.1,+ consensusThreshold: 0.7,+ specializations: [+ 'research',+ 'development',+ 'testing',+ 'optimization',+ 'coordination'+ ],+ ...config+ };+ this.queen = new QueenManager(this.database, this.agentRegistry, this.consensusEngine, this.metricsCollector);+ }+ async initialize() {+ if (this.config.queenEnabled) {+ await this.queen.initialize();+ }+ await this.createInitialWorkerPools();+ await this.loadPersistedState();+ console.log('🧠Hive Mind Core initialized with collective intelligence capabilities');+ }+ async createInitialWorkerPools() {+ for (const specialization of this.config.specializations){+ const pool = {+ id: nanoid(),+ specialization,+ agents: [],+ capacity: 5,+ utilization: 0,+ performance: {+ tasksCompleted: 0,+ averageQuality: 0.8,+ successRate: 1.0+ }+ };+ this.workerPools.set(pool.id, pool);+ await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');+ }+ }+ async loadPersistedState() {+ try {+ const objectiveKeys = await this.database.list('hive-mind');+ const objectiveItems = objectiveKeys.filter((key)=>key.startsWith('objective:'));+ for (const key of objectiveItems){+ const objective = await this.database.retrieve(key, 'hive-mind');+ if (objective) {+ this.objectives.set(objective.id, objective);+ }+ }+ } catch (error) {+ console.warn('Failed to load persisted hive mind state:', error);+ }+ }+ async setObjective(objective) {+ const fullObjective = {+ ...objective,+ id: nanoid()+ };+ this.objectives.set(fullObjective.id, fullObjective);+ await this.database.store(`objective:${fullObjective.id}`, fullObjective, 'hive-mind');+ if (this.config.queenEnabled) {+ const strategy = await this.queen.strategize(fullObjective);+ this.strategies.set(fullObjective.id, strategy);+ await this.database.store(`strategy:${fullObjective.id}`, strategy, 'hive-mind');+ }+ return fullObjective.id;+ }+ async executeObjective(objectiveId) {+ const objective = this.objectives.get(objectiveId);+ if (!objective) {+ throw new Error(`Objective ${objectiveId} not found`);+ }+ const strategy = this.strategies.get(objectiveId);+ if (!strategy) {+ throw new Error(`No strategy found for objective ${objectiveId}`);+ }+ const allTasks = [];+ strategy.phases.forEach((phase)=>{+ allTasks.push(...phase.tasks);+ });+ const assignments = await this.delegateTasks(allTasks);+ const results = await this.executeAssignments(assignments);+ const metrics = await this.collectExecutionMetrics(objectiveId, assignments, results);+ return {+ success: results.every((r)=>r.success),+ assignments,+ results,+ metrics+ };+ }+ async delegateTasks(tasks) {+ const assignments = [];+ for (const task of tasks){+ const bestPool = this.findBestWorkerPool(task);+ if (!bestPool) {+ console.warn(`No suitable worker pool found for task ${task.id}`);+ continue;+ }+ const bestAgent = await this.findBestAgentInPool(bestPool, task);+ if (!bestAgent) {+ console.warn(`No suitable agent found in pool ${bestPool.id} for task ${task.id}`);+ continue;+ }+ const assignment = {+ agentId: bestAgent.id,+ task,+ deadline: task.deadline || new Date(Date.now() + 3600000),+ resources: {+ memory: 256,+ cpu: 1,+ storage: 100,+ network: 10+ }+ };+ assignments.push(assignment);+ this.assignments.set(task.id, assignment);+ bestPool.utilization += 1;+ }+ return assignments;+ }+ findBestWorkerPool(task) {+ let bestPool = null;+ let bestScore = -1;+ for (const pool of this.workerPools.values()){+ const canHandle = task.requiredCapabilities.some((capability)=>capability.toLowerCase().includes(pool.specialization.toLowerCase()) || pool.specialization.toLowerCase().includes(capability.toLowerCase()));+ if (!canHandle) continue;+ let score = pool.performance.successRate * 40;+ score += pool.performance.averageQuality * 30;+ score += Math.max(0, (pool.capacity - pool.utilization) / pool.capacity) * 30;+ if (score > bestScore) {+ bestScore = score;+ bestPool = pool;+ }+ }+ return bestPool;+ }+ async findBestAgentInPool(pool, task) {+ if (pool.agents.length === 0) {+ const agent = await this.agentRegistry.spawn(this.getAgentTypeForSpecialization(pool.specialization), {+ capabilities: task.requiredCapabilities,+ metadata: {+ workerPoolId: pool.id,+ specialization: pool.specialization+ }+ });+ pool.agents.push(agent);+ await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');+ return agent;+ }+ let bestAgent = null;+ let bestScore = -1;+ for (const agent of pool.agents){+ if (agent.status !== 'idle' && agent.status !== 'active') continue;+ const capabilityMatch = task.requiredCapabilities.filter((cap)=>agent.capabilities.includes(cap)).length / task.requiredCapabilities.length;+ const performanceScore = agent.performance?.successRate || 0.5;+ const score = capabilityMatch * 60 + performanceScore * 40;+ if (score > bestScore) {+ bestScore = score;+ bestAgent = agent;+ }+ }+ return bestAgent;+ }+ getAgentTypeForSpecialization(specialization) {+ const typeMap = {+ research: 'researcher',+ development: 'coder',+ testing: 'tester',+ optimization: 'optimizer',+ coordination: 'coordinator'+ };+ return typeMap[specialization] || 'researcher';+ }+ async executeAssignments(assignments) {+ const results = [];+ const dependencyGroups = this.groupByDependencies(assignments);+ for (const group of dependencyGroups){+ const groupResults = await Promise.all(group.map(async (assignment)=>{+ try {+ return await this.agentRegistry.coordinate(assignment.task);+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ assignment+ };+ }+ }));+ results.push(...groupResults);+ }+ return results;+ }+ groupByDependencies(assignments) {+ const groups = [];+ const remaining = [+ ...assignments+ ];+ while(remaining.length > 0){+ const currentGroup = remaining.filter((assignment)=>!assignment.task.dependencies?.some((dep)=>remaining.some((other)=>other.task.id === dep)));+ if (currentGroup.length === 0) {+ currentGroup.push(remaining[0]);+ }+ groups.push(currentGroup);+ remaining.splice(0, currentGroup.length);+ }+ return groups;+ }+ async collectExecutionMetrics(objectiveId, assignments, results) {+ const successCount = results.filter((r)=>r.success).length;+ const successRate = successCount / results.length;+ const totalTime = results.reduce((sum, r)=>sum + (r.metadata?.executionTime || 0), 0);+ const averageTime = totalTime / results.length;+ const metrics = {+ objectiveId,+ totalTasks: assignments.length,+ successfulTasks: successCount,+ successRate,+ averageExecutionTime: averageTime,+ workerPoolUtilization: this.calculatePoolUtilization(),+ timestamp: new Date().toISOString()+ };+ await this.metricsCollector.recordSystemMetrics({+ cpuUsage: 50 + Math.random() * 30,+ memoryUsage: 60 + Math.random() * 20,+ diskUsage: 30 + Math.random() * 10,+ networkLatency: 10 + Math.random() * 20,+ activeConnections: assignments.length+ });+ return metrics;+ }+ calculatePoolUtilization() {+ const utilization = {};+ for (const [poolId, pool] of this.workerPools){+ utilization[pool.specialization] = pool.utilization / pool.capacity;+ }+ return utilization;+ }+ async adapt(feedback) {+ if (this.config.queenEnabled) {+ await this.queen.adapt(feedback);+ }+ for (const pool of this.workerPools.values()){+ const poolFeedback = feedback.filter((f)=>pool.agents.some((agent)=>agent.id === f.source));+ if (poolFeedback.length > 0) {+ const avgRating = poolFeedback.reduce((sum, f)=>sum + f.rating, 0) / poolFeedback.length;+ const alpha = this.config.adaptationRate;+ pool.performance.averageQuality = pool.performance.averageQuality * (1 - alpha) + avgRating / 5 * alpha;+ await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');+ }+ }+ }+ async getStatus() {+ const queenMetrics = this.config.queenEnabled ? await this.queen.monitor() : null;+ const overallPerformance = Array.from(this.workerPools.values()).reduce((sum, pool)=>sum + pool.performance.averageQuality, 0) / this.workerPools.size;+ return {+ queen: queenMetrics,+ workerPools: Array.from(this.workerPools.values()),+ activeObjectives: this.objectives.size,+ totalAssignments: this.assignments.size,+ overallPerformance+ };+ }+ getWorkerPoolBySpecialization(specialization) {+ return Array.from(this.workerPools.values()).find((pool)=>pool.specialization === specialization);+ }+ async scaleWorkerPool(poolId, newCapacity) {+ const pool = this.workerPools.get(poolId);+ if (!pool) return;+ pool.capacity = newCapacity;+ await this.database.store(`worker-pool:${poolId}`, pool, 'hive-mind');+ }+}+let QueenManager = class QueenManager {+ database;+ agentRegistry;+ consensusEngine;+ metricsCollector;+ strategies = new Map();+ metrics = {+ strategiesCreated: 0,+ tasksAssigned: 0,+ successRate: 1.0,+ adaptationCount: 0,+ performanceScore: 100+ };+ constructor(database, agentRegistry, consensusEngine, metricsCollector){+ this.database = database;+ this.agentRegistry = agentRegistry;+ this.consensusEngine = consensusEngine;+ this.metricsCollector = metricsCollector;+ }+ async initialize() {+ console.log('👑 Queen Manager initialized - Strategic intelligence online');+ }+ async strategize(objective) {+ const complexity = this.analyzeComplexity(objective);+ const riskLevel = this.assessRisk(objective);+ const phases = this.createStrategyPhases(objective, complexity);+ const resourceAllocation = this.estimateResources(objective, phases);+ const riskAssessment = this.identifyRisks(objective, riskLevel);+ const strategy = {+ approach: this.selectApproach(complexity, riskLevel),+ phases,+ resourceAllocation,+ expectedOutcome: `Complete objective: ${objective.description}`,+ riskAssessment+ };+ this.strategies.set(objective.id, strategy);+ this.metrics.strategiesCreated++;+ return strategy;+ }+ async delegate(tasks) {+ this.metrics.tasksAssigned += tasks.length;+ return [];+ }+ async monitor() {+ const recentStrategies = Array.from(this.strategies.values()).slice(-10);+ if (recentStrategies.length > 0) {+ this.metrics.performanceScore = Math.min(100, 70 + Math.random() * 30);+ }+ return {+ ...this.metrics+ };+ }+ async adapt(feedback) {+ const avgRating = feedback.reduce((sum, f)=>sum + f.rating, 0) / feedback.length;+ const alpha = 0.1;+ this.metrics.successRate = this.metrics.successRate * (1 - alpha) + avgRating / 5 * alpha;+ this.metrics.adaptationCount++;+ }+ analyzeComplexity(objective) {+ const factors = [+ objective.goals.length,+ objective.constraints.length,+ objective.priority === 'critical' ? 2 : 1+ ];+ const complexity = factors.reduce((sum, factor)=>sum + factor, 0);+ if (complexity <= 3) return 'low';+ if (complexity <= 6) return 'medium';+ return 'high';+ }+ assessRisk(objective) {+ const hasDeadline = !!objective.deadline;+ const constraintCount = objective.constraints.length;+ const isCritical = objective.priority === 'critical';+ if (isCritical || constraintCount > 3 || hasDeadline && new Date(objective.deadline) < new Date(Date.now() + 86400000)) {+ return 'high';+ }+ if (constraintCount > 1 || hasDeadline) {+ return 'medium';+ }+ return 'low';+ }+ createStrategyPhases(objective, complexity) {+ const basePhases = [+ {+ name: 'Analysis',+ description: 'Analyze requirements and constraints'+ },+ {+ name: 'Planning',+ description: 'Create detailed execution plan'+ },+ {+ name: 'Execution',+ description: 'Implement the solution'+ },+ {+ name: 'Validation',+ description: 'Validate outcomes against goals'+ }+ ];+ if (complexity === 'high') {+ basePhases.splice(2, 0, {+ name: 'Prototyping',+ description: 'Create and test prototypes'+ });+ }+ return basePhases.map((phase, index)=>({+ ...phase,+ tasks: this.createTasksForPhase(phase, objective),+ dependencies: index > 0 ? [+ basePhases[index - 1].name+ ] : [],+ duration: complexity === 'high' ? 3600 : complexity === 'medium' ? 1800 : 900+ }));+ }+ createTasksForPhase(phase, objective) {+ return [+ {+ id: nanoid(),+ type: phase.name.toLowerCase(),+ description: `${phase.description} for objective: ${objective.description}`,+ priority: objective.priority,+ requiredCapabilities: this.inferCapabilities(phase.name),+ deadline: objective.deadline+ }+ ];+ }+ inferCapabilities(phaseName) {+ const capabilityMap = {+ 'Analysis': [+ 'research',+ 'analysis'+ ],+ 'Planning': [+ 'planning',+ 'coordination'+ ],+ 'Prototyping': [+ 'programming',+ 'testing'+ ],+ 'Execution': [+ 'programming',+ 'implementation'+ ],+ 'Validation': [+ 'testing',+ 'quality-assurance'+ ]+ };+ return capabilityMap[phaseName] || [+ 'general'+ ];+ }+ selectApproach(complexity, riskLevel) {+ if (complexity === 'high' && riskLevel === 'high') {+ return 'Incremental development with continuous validation';+ }+ if (complexity === 'high') {+ return 'Phased implementation with parallel workstreams';+ }+ if (riskLevel === 'high') {+ return 'Risk-first approach with contingency planning';+ }+ return 'Standard agile approach with regular checkpoints';+ }+ estimateResources(objective, phases) {+ return {+ memory: phases.length * 512,+ cpu: phases.length * 2,+ storage: phases.length * 100,+ network: 10+ };+ }+ identifyRisks(objective, riskLevel) {+ const baseRisks = [+ {+ description: 'Requirement changes during execution',+ probability: 0.3,+ impact: 0.6,+ mitigation: 'Regular stakeholder communication and flexible planning'+ }+ ];+ if (riskLevel === 'high') {+ baseRisks.push({+ description: 'Resource constraints affecting timeline',+ probability: 0.5,+ impact: 0.8,+ mitigation: 'Resource monitoring and contingency planning'+ });+ }+ return baseRisks;+ }+};++//# sourceMappingURL=HiveMindCore.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/HiveMindCore.js.map b/dist-cjs/src/core/HiveMindCore.js.mapnew file mode 100644index 0000000000..cc7760c83f--- /dev/null+++ b/dist-cjs/src/core/HiveMindCore.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/HiveMindCore.ts"],"sourcesContent":["/**\n * HiveMindCore - Collective intelligence coordination\n * Implements the Queen-Worker pattern for distributed AI coordination\n */\n\nimport { IDatabaseProvider, IHiveMindQueen, Objective, Strategy, Task, Assignment, QueenMetrics, Feedback, Agent } from '../types/interfaces.js';\nimport { AgentRegistry } from './AgentRegistry.js';\nimport { ConsensusEngine } from './ConsensusEngine.js';\nimport { MetricsCollector } from './MetricsCollector.js';\nimport { nanoid } from 'nanoid';\n\nexport interface WorkerPool {\n id: string;\n specialization: string;\n agents: Agent[];\n capacity: number;\n utilization: number;\n performance: {\n tasksCompleted: number;\n averageQuality: number;\n successRate: number;\n };\n}\n\nexport interface HiveMindConfig {\n maxWorkerPools: number;\n queenEnabled: boolean;\n adaptationRate: number;\n consensusThreshold: number;\n specializations: string[];\n}\n\nexport class HiveMindCore {\n private queen: QueenManager;\n private workerPools: Map<string, WorkerPool> = new Map();\n private objectives: Map<string, Objective> = new Map();\n private strategies: Map<string, Strategy> = new Map();\n private assignments: Map<string, Assignment> = new Map();\n private config: HiveMindConfig;\n\n constructor(\n private database: IDatabaseProvider,\n private agentRegistry: AgentRegistry,\n private consensusEngine: ConsensusEngine,\n private metricsCollector: MetricsCollector,\n config: Partial<HiveMindConfig> = {}\n ) {\n this.config = {\n maxWorkerPools: 5,\n queenEnabled: true,\n adaptationRate: 0.1,\n consensusThreshold: 0.7,\n specializations: ['research', 'development', 'testing', 'optimization', 'coordination'],\n ...config\n };\n\n this.queen = new QueenManager(\n this.database,\n this.agentRegistry,\n this.consensusEngine,\n this.metricsCollector\n );\n }\n\n /**\n * Initialize the Hive Mind system\n */\n async initialize(): Promise<void> {\n // Initialize Queen\n if (this.config.queenEnabled) {\n await this.queen.initialize();\n }\n\n // Create initial worker pools\n await this.createInitialWorkerPools();\n\n // Load existing objectives and strategies\n await this.loadPersistedState();\n\n console.log('🧠Hive Mind Core initialized with collective intelligence capabilities');\n }\n\n /**\n * Create initial worker pools based on specializations\n */\n private async createInitialWorkerPools(): Promise<void> {\n for (const specialization of this.config.specializations) {\n const pool: WorkerPool = {\n id: nanoid(),\n specialization,\n agents: [],\n capacity: 5, // Default capacity\n utilization: 0,\n performance: {\n tasksCompleted: 0,\n averageQuality: 0.8,\n successRate: 1.0\n }\n };\n\n this.workerPools.set(pool.id, pool);\n await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');\n }\n }\n\n /**\n * Load persisted objectives and strategies\n */\n private async loadPersistedState(): Promise<void> {\n try {\n const objectiveKeys = await this.database.list('hive-mind');\n const objectiveItems = objectiveKeys.filter(key => key.startsWith('objective:'));\n\n for (const key of objectiveItems) {\n const objective = await this.database.retrieve(key, 'hive-mind');\n if (objective) {\n this.objectives.set(objective.id, objective);\n }\n }\n } catch (error) {\n console.warn('Failed to load persisted hive mind state:', error);\n }\n }\n\n /**\n * Set a new objective for the hive mind\n */\n async setObjective(objective: Omit<Objective, 'id'>): Promise<string> {\n const fullObjective: Objective = {\n ...objective,\n id: nanoid()\n };\n\n this.objectives.set(fullObjective.id, fullObjective);\n await this.database.store(`objective:${fullObjective.id}`, fullObjective, 'hive-mind');\n\n // Have the Queen strategize if enabled\n if (this.config.queenEnabled) {\n const strategy = await this.queen.strategize(fullObjective);\n this.strategies.set(fullObjective.id, strategy);\n await this.database.store(`strategy:${fullObjective.id}`, strategy, 'hive-mind');\n }\n\n return fullObjective.id;\n }\n\n /**\n * Execute an objective using collective intelligence\n */\n async executeObjective(objectiveId: string): Promise<{\n success: boolean;\n assignments: Assignment[];\n results: any[];\n metrics: any;\n }> {\n const objective = this.objectives.get(objectiveId);\n if (!objective) {\n throw new Error(`Objective ${objectiveId} not found`);\n }\n\n const strategy = this.strategies.get(objectiveId);\n if (!strategy) {\n throw new Error(`No strategy found for objective ${objectiveId}`);\n }\n\n // Extract tasks from strategy phases\n const allTasks: Task[] = [];\n strategy.phases.forEach(phase => {\n allTasks.push(...phase.tasks);\n });\n\n // Delegate tasks to worker pools\n const assignments = await this.delegateTasks(allTasks);\n\n // Execute assignments in parallel (with dependency management)\n const results = await this.executeAssignments(assignments);\n\n // Collect metrics\n const metrics = await this.collectExecutionMetrics(objectiveId, assignments, results);\n\n return {\n success: results.every(r => r.success),\n assignments,\n results,\n metrics\n };\n }\n\n /**\n * Delegate tasks to appropriate worker pools\n */\n private async delegateTasks(tasks: Task[]): Promise<Assignment[]> {\n const assignments: Assignment[] = [];\n\n for (const task of tasks) {\n // Find best worker pool for this task\n const bestPool = this.findBestWorkerPool(task);\n if (!bestPool) {\n console.warn(`No suitable worker pool found for task ${task.id}`);\n continue;\n }\n\n // Find best agent in the pool\n const bestAgent = await this.findBestAgentInPool(bestPool, task);\n if (!bestAgent) {\n console.warn(`No suitable agent found in pool ${bestPool.id} for task ${task.id}`);\n continue;\n }\n\n const assignment: Assignment = {\n agentId: bestAgent.id,\n task,\n deadline: task.deadline || new Date(Date.now() + 3600000), // 1 hour default\n resources: {\n memory: 256,\n cpu: 1,\n storage: 100,\n network: 10\n }\n };\n\n assignments.push(assignment);\n this.assignments.set(task.id, assignment);\n\n // Update pool utilization\n bestPool.utilization += 1;\n }\n\n return assignments;\n }\n\n /**\n * Find the best worker pool for a task\n */\n private findBestWorkerPool(task: Task): WorkerPool | null {\n let bestPool: WorkerPool | null = null;\n let bestScore = -1;\n\n for (const pool of this.workerPools.values()) {\n // Check if pool can handle the task's capabilities\n const canHandle = task.requiredCapabilities.some(capability =>\n capability.toLowerCase().includes(pool.specialization.toLowerCase()) ||\n pool.specialization.toLowerCase().includes(capability.toLowerCase())\n );\n\n if (!canHandle) continue;\n\n // Score based on performance, capacity, and utilization\n let score = pool.performance.successRate * 40;\n score += pool.performance.averageQuality * 30;\n score += Math.max(0, (pool.capacity - pool.utilization) / pool.capacity) * 30;\n\n if (score > bestScore) {\n bestScore = score;\n bestPool = pool;\n }\n }\n\n return bestPool;\n }\n\n /**\n * Find the best agent in a worker pool for a task\n */\n private async findBestAgentInPool(pool: WorkerPool, task: Task): Promise<Agent | null> {\n if (pool.agents.length === 0) {\n // Spawn a new agent for this pool\n const agent = await this.agentRegistry.spawn(\n this.getAgentTypeForSpecialization(pool.specialization),\n {\n capabilities: task.requiredCapabilities,\n metadata: { workerPoolId: pool.id, specialization: pool.specialization }\n }\n );\n\n pool.agents.push(agent);\n await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');\n return agent;\n }\n\n // Find best existing agent\n let bestAgent: Agent | null = null;\n let bestScore = -1;\n\n for (const agent of pool.agents) {\n if (agent.status !== 'idle' && agent.status !== 'active') continue;\n\n // Score based on capability match and performance\n const capabilityMatch = task.requiredCapabilities.filter(cap =>\n agent.capabilities.includes(cap)\n ).length / task.requiredCapabilities.length;\n\n const performanceScore = agent.performance?.successRate || 0.5;\n\n const score = capabilityMatch * 60 + performanceScore * 40;\n\n if (score > bestScore) {\n bestScore = score;\n bestAgent = agent;\n }\n }\n\n return bestAgent;\n }\n\n /**\n * Get appropriate agent type for specialization\n */\n private getAgentTypeForSpecialization(specialization: string): any {\n const typeMap: Record<string, string> = {\n research: 'researcher',\n development: 'coder',\n testing: 'tester',\n optimization: 'optimizer',\n coordination: 'coordinator'\n };\n\n return typeMap[specialization] || 'researcher';\n }\n\n /**\n * Execute assignments\n */\n private async executeAssignments(assignments: Assignment[]): Promise<any[]> {\n const results: any[] = [];\n\n // Group assignments by dependencies\n const dependencyGroups = this.groupByDependencies(assignments);\n\n // Execute groups in order\n for (const group of dependencyGroups) {\n const groupResults = await Promise.all(\n group.map(async assignment => {\n try {\n return await this.agentRegistry.coordinate(assignment.task);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n assignment\n };\n }\n })\n );\n\n results.push(...groupResults);\n }\n\n return results;\n }\n\n /**\n * Group assignments by dependencies\n */\n private groupByDependencies(assignments: Assignment[]): Assignment[][] {\n // Simplified dependency grouping - in production, this would be more sophisticated\n const groups: Assignment[][] = [];\n const remaining = [...assignments];\n\n while (remaining.length > 0) {\n const currentGroup = remaining.filter(assignment =>\n !assignment.task.dependencies?.some(dep =>\n remaining.some(other => other.task.id === dep)\n )\n );\n\n if (currentGroup.length === 0) {\n // Break circular dependencies by taking first item\n currentGroup.push(remaining[0]);\n }\n\n groups.push(currentGroup);\n remaining.splice(0, currentGroup.length);\n }\n\n return groups;\n }\n\n /**\n * Collect execution metrics\n */\n private async collectExecutionMetrics(\n objectiveId: string,\n assignments: Assignment[],\n results: any[]\n ): Promise<any> {\n const successCount = results.filter(r => r.success).length;\n const successRate = successCount / results.length;\n\n const totalTime = results.reduce((sum, r) => sum + (r.metadata?.executionTime || 0), 0);\n const averageTime = totalTime / results.length;\n\n const metrics = {\n objectiveId,\n totalTasks: assignments.length,\n successfulTasks: successCount,\n successRate,\n averageExecutionTime: averageTime,\n workerPoolUtilization: this.calculatePoolUtilization(),\n timestamp: new Date().toISOString()\n };\n\n await this.metricsCollector.recordSystemMetrics({\n cpuUsage: 50 + Math.random() * 30, // Simulated\n memoryUsage: 60 + Math.random() * 20,\n diskUsage: 30 + Math.random() * 10,\n networkLatency: 10 + Math.random() * 20,\n activeConnections: assignments.length\n });\n\n return metrics;\n }\n\n /**\n * Calculate worker pool utilization\n */\n private calculatePoolUtilization(): Record<string, number> {\n const utilization: Record<string, number> = {};\n\n for (const [poolId, pool] of this.workerPools) {\n utilization[pool.specialization] = pool.utilization / pool.capacity;\n }\n\n return utilization;\n }\n\n /**\n * Adapt hive mind based on feedback\n */\n async adapt(feedback: Feedback[]): Promise<void> {\n if (this.config.queenEnabled) {\n await this.queen.adapt(feedback);\n }\n\n // Adapt worker pools based on performance\n for (const pool of this.workerPools.values()) {\n const poolFeedback = feedback.filter(f =>\n pool.agents.some(agent => agent.id === f.source)\n );\n\n if (poolFeedback.length > 0) {\n const avgRating = poolFeedback.reduce((sum, f) => sum + f.rating, 0) / poolFeedback.length;\n\n // Adjust pool performance metrics\n const alpha = this.config.adaptationRate;\n pool.performance.averageQuality = pool.performance.averageQuality * (1 - alpha) + (avgRating / 5) * alpha;\n\n await this.database.store(`worker-pool:${pool.id}`, pool, 'hive-mind');\n }\n }\n }\n\n /**\n * Get hive mind status\n */\n async getStatus(): Promise<{\n queen: any;\n workerPools: WorkerPool[];\n activeObjectives: number;\n totalAssignments: number;\n overallPerformance: number;\n }> {\n const queenMetrics = this.config.queenEnabled ? await this.queen.monitor() : null;\n\n const overallPerformance = Array.from(this.workerPools.values())\n .reduce((sum, pool) => sum + pool.performance.averageQuality, 0) / this.workerPools.size;\n\n return {\n queen: queenMetrics,\n workerPools: Array.from(this.workerPools.values()),\n activeObjectives: this.objectives.size,\n totalAssignments: this.assignments.size,\n overallPerformance\n };\n }\n\n /**\n * Get worker pool by specialization\n */\n getWorkerPoolBySpecialization(specialization: string): WorkerPool | undefined {\n return Array.from(this.workerPools.values())\n .find(pool => pool.specialization === specialization);\n }\n\n /**\n * Scale worker pool\n */\n async scaleWorkerPool(poolId: string, newCapacity: number): Promise<void> {\n const pool = this.workerPools.get(poolId);\n if (!pool) return;\n\n pool.capacity = newCapacity;\n await this.database.store(`worker-pool:${poolId}`, pool, 'hive-mind');\n }\n}\n\n/**\n * Queen Manager - Implements the strategic intelligence layer\n */\nclass QueenManager implements IHiveMindQueen {\n private strategies: Map<string, Strategy> = new Map();\n private metrics: QueenMetrics = {\n strategiesCreated: 0,\n tasksAssigned: 0,\n successRate: 1.0,\n adaptationCount: 0,\n performanceScore: 100\n };\n\n constructor(\n private database: IDatabaseProvider,\n private agentRegistry: AgentRegistry,\n private consensusEngine: ConsensusEngine,\n private metricsCollector: MetricsCollector\n ) {}\n\n async initialize(): Promise<void> {\n console.log('👑 Queen Manager initialized - Strategic intelligence online');\n }\n\n async strategize(objective: Objective): Promise<Strategy> {\n // Analyze objective complexity and requirements\n const complexity = this.analyzeComplexity(objective);\n const riskLevel = this.assessRisk(objective);\n\n // Create strategy phases\n const phases = this.createStrategyPhases(objective, complexity);\n\n // Estimate resource requirements\n const resourceAllocation = this.estimateResources(objective, phases);\n\n // Assess risks\n const riskAssessment = this.identifyRisks(objective, riskLevel);\n\n const strategy: Strategy = {\n approach: this.selectApproach(complexity, riskLevel),\n phases,\n resourceAllocation,\n expectedOutcome: `Complete objective: ${objective.description}`,\n riskAssessment\n };\n\n this.strategies.set(objective.id, strategy);\n this.metrics.strategiesCreated++;\n\n return strategy;\n }\n\n async delegate(tasks: Task[]): Promise<Assignment[]> {\n // This would be handled by the main HiveMindCore\n // Queen focuses on high-level strategy\n this.metrics.tasksAssigned += tasks.length;\n return [];\n }\n\n async monitor(): Promise<QueenMetrics> {\n // Update performance score based on recent strategies\n const recentStrategies = Array.from(this.strategies.values()).slice(-10);\n if (recentStrategies.length > 0) {\n // Simulate performance based on strategy complexity and success\n this.metrics.performanceScore = Math.min(100, 70 + Math.random() * 30);\n }\n\n return { ...this.metrics };\n }\n\n async adapt(feedback: Feedback[]): Promise<void> {\n // Adapt strategy creation based on feedback\n const avgRating = feedback.reduce((sum, f) => sum + f.rating, 0) / feedback.length;\n\n // Update success rate\n const alpha = 0.1;\n this.metrics.successRate = this.metrics.successRate * (1 - alpha) + (avgRating / 5) * alpha;\n this.metrics.adaptationCount++;\n }\n\n private analyzeComplexity(objective: Objective): 'low' | 'medium' | 'high' {\n const factors = [\n objective.goals.length,\n objective.constraints.length,\n objective.priority === 'critical' ? 2 : 1\n ];\n\n const complexity = factors.reduce((sum, factor) => sum + factor, 0);\n\n if (complexity <= 3) return 'low';\n if (complexity <= 6) return 'medium';\n return 'high';\n }\n\n private assessRisk(objective: Objective): 'low' | 'medium' | 'high' {\n // Assess risk based on constraints and deadline\n const hasDeadline = !!objective.deadline;\n const constraintCount = objective.constraints.length;\n const isCritical = objective.priority === 'critical';\n\n if (isCritical || constraintCount > 3 || (hasDeadline && new Date(objective.deadline!) < new Date(Date.now() + 86400000))) {\n return 'high';\n }\n\n if (constraintCount > 1 || hasDeadline) {\n return 'medium';\n }\n\n return 'low';\n }\n\n private createStrategyPhases(objective: Objective, complexity: string): any[] {\n const basePhases = [\n { name: 'Analysis', description: 'Analyze requirements and constraints' },\n { name: 'Planning', description: 'Create detailed execution plan' },\n { name: 'Execution', description: 'Implement the solution' },\n { name: 'Validation', description: 'Validate outcomes against goals' }\n ];\n\n if (complexity === 'high') {\n basePhases.splice(2, 0, { name: 'Prototyping', description: 'Create and test prototypes' });\n }\n\n return basePhases.map((phase, index) => ({\n ...phase,\n tasks: this.createTasksForPhase(phase, objective),\n dependencies: index > 0 ? [basePhases[index - 1].name] : [],\n duration: complexity === 'high' ? 3600 : complexity === 'medium' ? 1800 : 900 // seconds\n }));\n }\n\n private createTasksForPhase(phase: any, objective: Objective): Task[] {\n // Generate tasks based on phase and objective\n return [{\n id: nanoid(),\n type: phase.name.toLowerCase(),\n description: `${phase.description} for objective: ${objective.description}`,\n priority: objective.priority,\n requiredCapabilities: this.inferCapabilities(phase.name),\n deadline: objective.deadline\n }];\n }\n\n private inferCapabilities(phaseName: string): string[] {\n const capabilityMap: Record<string, string[]> = {\n 'Analysis': ['research', 'analysis'],\n 'Planning': ['planning', 'coordination'],\n 'Prototyping': ['programming', 'testing'],\n 'Execution': ['programming', 'implementation'],\n 'Validation': ['testing', 'quality-assurance']\n };\n\n return capabilityMap[phaseName] || ['general'];\n }\n\n private selectApproach(complexity: string, riskLevel: string): string {\n if (complexity === 'high' && riskLevel === 'high') {\n return 'Incremental development with continuous validation';\n }\n\n if (complexity === 'high') {\n return 'Phased implementation with parallel workstreams';\n }\n\n if (riskLevel === 'high') {\n return 'Risk-first approach with contingency planning';\n }\n\n return 'Standard agile approach with regular checkpoints';\n }\n\n private estimateResources(objective: Objective, phases: any[]): any {\n return {\n memory: phases.length * 512, // MB\n cpu: phases.length * 2, // cores\n storage: phases.length * 100, // MB\n network: 10 // Mbps\n };\n }\n\n private identifyRisks(objective: Objective, riskLevel: string): any[] {\n const baseRisks = [\n {\n description: 'Requirement changes during execution',\n probability: 0.3,\n impact: 0.6,\n mitigation: 'Regular stakeholder communication and flexible planning'\n }\n ];\n\n if (riskLevel === 'high') {\n baseRisks.push({\n description: 'Resource constraints affecting timeline',\n probability: 0.5,\n impact: 0.8,\n mitigation: 'Resource monitoring and contingency planning'\n });\n }\n\n return baseRisks;\n }\n}"],"names":["nanoid","HiveMindCore","queen","workerPools","Map","objectives","strategies","assignments","config","database","agentRegistry","consensusEngine","metricsCollector","maxWorkerPools","queenEnabled","adaptationRate","consensusThreshold","specializations","QueenManager","initialize","createInitialWorkerPools","loadPersistedState","console","log","specialization","pool","id","agents","capacity","utilization","performance","tasksCompleted","averageQuality","successRate","set","store","objectiveKeys","list","objectiveItems","filter","key","startsWith","objective","retrieve","error","warn","setObjective","fullObjective","strategy","strategize","executeObjective","objectiveId","get","Error","allTasks","phases","forEach","phase","push","tasks","delegateTasks","results","executeAssignments","metrics","collectExecutionMetrics","success","every","r","task","bestPool","findBestWorkerPool","bestAgent","findBestAgentInPool","assignment","agentId","deadline","Date","now","resources","memory","cpu","storage","network","bestScore","values","canHandle","requiredCapabilities","some","capability","toLowerCase","includes","score","Math","max","length","agent","spawn","getAgentTypeForSpecialization","capabilities","metadata","workerPoolId","status","capabilityMatch","cap","performanceScore","typeMap","research","development","testing","optimization","coordination","dependencyGroups","groupByDependencies","group","groupResults","Promise","all","map","coordinate","message","String","groups","remaining","currentGroup","dependencies","dep","other","splice","successCount","totalTime","reduce","sum","executionTime","averageTime","totalTasks","successfulTasks","averageExecutionTime","workerPoolUtilization","calculatePoolUtilization","timestamp","toISOString","recordSystemMetrics","cpuUsage","random","memoryUsage","diskUsage","networkLatency","activeConnections","poolId","adapt","feedback","poolFeedback","f","source","avgRating","rating","alpha","getStatus","queenMetrics","monitor","overallPerformance","Array","from","size","activeObjectives","totalAssignments","getWorkerPoolBySpecialization","find","scaleWorkerPool","newCapacity","strategiesCreated","tasksAssigned","adaptationCount","complexity","analyzeComplexity","riskLevel","assessRisk","createStrategyPhases","resourceAllocation","estimateResources","riskAssessment","identifyRisks","approach","selectApproach","expectedOutcome","description","delegate","recentStrategies","slice","min","factors","goals","constraints","priority","factor","hasDeadline","constraintCount","isCritical","basePhases","name","index","createTasksForPhase","duration","type","inferCapabilities","phaseName","capabilityMap","baseRisks","probability","impact","mitigation"],"mappings":"AASA,SAASA,MAAM,QAAQ,SAAS;AAuBhC,OAAO,MAAMC;;;;;IACHC,MAAoB;IACpBC,cAAuC,IAAIC,MAAM;IACjDC,aAAqC,IAAID,MAAM;IAC/CE,aAAoC,IAAIF,MAAM;IAC9CG,cAAuC,IAAIH,MAAM;IACjDI,OAAuB;IAE/B,YACE,AAAQC,QAA2B,EACnC,AAAQC,aAA4B,EACpC,AAAQC,eAAgC,EACxC,AAAQC,gBAAkC,EAC1CJ,SAAkC,CAAC,CAAC,CACpC;aALQC,WAAAA;aACAC,gBAAAA;aACAC,kBAAAA;aACAC,mBAAAA;QAGR,IAAI,CAACJ,MAAM,GAAG;YACZK,gBAAgB;YAChBC,cAAc;YACdC,gBAAgB;YAChBC,oBAAoB;YACpBC,iBAAiB;gBAAC;gBAAY;gBAAe;gBAAW;gBAAgB;aAAe;YACvF,GAAGT,MAAM;QACX;QAEA,IAAI,CAACN,KAAK,GAAG,IAAIgB,aACf,IAAI,CAACT,QAAQ,EACb,IAAI,CAACC,aAAa,EAClB,IAAI,CAACC,eAAe,EACpB,IAAI,CAACC,gBAAgB;IAEzB;IAKA,MAAMO,aAA4B;QAEhC,IAAI,IAAI,CAACX,MAAM,CAACM,YAAY,EAAE;YAC5B,MAAM,IAAI,CAACZ,KAAK,CAACiB,UAAU;QAC7B;QAGA,MAAM,IAAI,CAACC,wBAAwB;QAGnC,MAAM,IAAI,CAACC,kBAAkB;QAE7BC,QAAQC,GAAG,CAAC;IACd;IAKA,MAAcH,2BAA0C;QACtD,KAAK,MAAMI,kBAAkB,IAAI,CAAChB,MAAM,CAACS,eAAe,CAAE;YACxD,MAAMQ,OAAmB;gBACvBC,IAAI1B;gBACJwB;gBACAG,QAAQ,EAAE;gBACVC,UAAU;gBACVC,aAAa;gBACbC,aAA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xC,eAAe;gBAAC;gBAAe;aAAU;YACzC,aAAa;gBAAC;gBAAe;aAAiB;YAC9C,cAAc;gBAAC;gBAAW;aAAoB;QAChD;QAEA,OAAOA,aAAa,CAACD,UAAU,IAAI;YAAC;SAAU;IAChD;IAEQtB,eAAeV,UAAkB,EAAEE,SAAiB,EAAU;QACpE,IAAIF,eAAe,UAAUE,cAAc,QAAQ;YACjD,OAAO;QACT;QAEA,IAAIF,eAAe,QAAQ;YACzB,OAAO;QACT;QAEA,IAAIE,cAAc,QAAQ;YACxB,OAAO;QACT;QAEA,OAAO;IACT;IAEQI,kBAAkBzI,SAAoB,EAAEa,MAAa,EAAO;QAClE,OAAO;YACLwB,QAAQxB,OAAOuC,MAAM,GAAG;YACxBd,KAAKzB,OAAOuC,MAAM,GAAG;YACrBb,SAAS1B,OAAOuC,MAAM,GAAG;YACzBZ,SAAS;QACX;IACF;IAEQmG,cAAc3I,SAAoB,EAAEqI,SAAiB,EAAS;QACpE,MAAMgC,YAAY;YAChB;gBACEtB,aAAa;gBACbuB,aAAa;gBACbC,QAAQ;gBACRC,YAAY;YACd;SACD;QAED,IAAInC,cAAc,QAAQ;YACxBgC,UAAUrJ,IAAI,CAAC;gBACb+H,aAAa;gBACbuB,aAAa;gBACbC,QAAQ;gBACRC,YAAY;YACd;QACF;QAEA,OAAOH;IACT;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/InitController.js b/dist-cjs/src/core/InitController.jsnew file mode 100644index 0000000000..1f762ba0ee--- /dev/null+++ b/dist-cjs/src/core/InitController.js@@ -0,0 +1,122 @@+import { ConfigManager } from './ConfigManager.js';+import { DatabaseManager } from './DatabaseManager.js';+import { ModeFactory } from './ModeFactory.js';+import { TopologyManager } from './TopologyManager.js';+import { AgentRegistry } from './AgentRegistry.js';+import { MetricsCollector } from './MetricsCollector.js';+export class InitController {+ config;+ configManager;+ databaseManager;+ modeFactory;+ topologyManager;+ agentRegistry;+ metricsCollector;+ initialized = false;+ constructor(config = {}){+ this.config = config;+ this.configManager = new ConfigManager(config.configPath);+ this.databaseManager = new DatabaseManager(config.database || 'sqlite');+ this.modeFactory = new ModeFactory();+ this.topologyManager = new TopologyManager(this.databaseManager);+ this.agentRegistry = new AgentRegistry(this.databaseManager);+ this.metricsCollector = new MetricsCollector(this.databaseManager);+ }+ async initialize() {+ const startTime = Date.now();+ try {+ const validationResult = await this.configManager.validate();+ if (!validationResult.valid) {+ throw new Error(`Configuration validation failed: ${validationResult.errors.join(', ')}`);+ }+ await this.databaseManager.initialize();+ await this.topologyManager.configure(this.config.topology || 'mesh');+ await this.agentRegistry.initialize();+ const mode = this.modeFactory.createMode(this.config.mode || 'standard');+ const initConfig = {+ ...this.config,+ configManager: this.configManager,+ databaseManager: this.databaseManager,+ topologyManager: this.topologyManager,+ agentRegistry: this.agentRegistry,+ metricsCollector: this.metricsCollector+ };+ const result = await mode.initialize(initConfig);+ const endTime = Date.now();+ await this.metricsCollector.recordInitialization({+ mode: this.config.mode || 'standard',+ duration: endTime - startTime,+ success: true,+ components: result.components || [],+ timestamp: new Date().toISOString()+ });+ this.initialized = true;+ return {+ success: true,+ mode: this.config.mode || 'standard',+ components: result.components,+ topology: this.config.topology || 'mesh',+ duration: endTime - startTime,+ message: result.message || 'Initialization completed successfully',+ metadata: {+ configValid: true,+ databaseInitialized: true,+ topologyConfigured: true,+ agentRegistryReady: true,+ ...result.metadata+ }+ };+ } catch (error) {+ const endTime = Date.now();+ await this.metricsCollector.recordInitialization({+ mode: this.config.mode || 'standard',+ duration: endTime - startTime,+ success: false,+ error: error instanceof Error ? error.message : String(error),+ timestamp: new Date().toISOString()+ });+ return {+ success: false,+ mode: this.config.mode || 'standard',+ duration: endTime - startTime,+ error: error instanceof Error ? error.message : String(error),+ message: 'Initialization failed'+ };+ }+ }+ getStatus() {+ return {+ initialized: this.initialized,+ mode: this.config.mode,+ components: this.initialized ? [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry'+ ] : []+ };+ }+ async shutdown() {+ if (this.databaseManager) {+ await this.databaseManager.close();+ }+ this.initialized = false;+ }+ async validateConfiguration() {+ return await this.configManager.validate();+ }+ getAvailableModes() {+ return this.modeFactory.getAvailableModes();+ }+ async getTopologyInfo() {+ return await this.topologyManager.getTopologyInfo();+ }+ async getAgents() {+ return await this.agentRegistry.getActiveAgents();+ }+ async getMetrics() {+ return await this.metricsCollector.getInitializationMetrics();+ }+}++//# sourceMappingURL=InitController.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/InitController.js.map b/dist-cjs/src/core/InitController.js.mapnew file mode 100644index 0000000000..1a50c54d25--- /dev/null+++ b/dist-cjs/src/core/InitController.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/InitController.ts"],"sourcesContent":["/**\n * InitController - Main orchestration and mode selection\n * Handles the core initialization flow and coordinates with all other components\n */\n\nimport { ConfigManager } from './ConfigManager.js';\nimport { DatabaseManager } from './DatabaseManager.js';\nimport { ModeFactory } from './ModeFactory.js';\nimport { TopologyManager } from './TopologyManager.js';\nimport { AgentRegistry } from './AgentRegistry.js';\nimport { MetricsCollector } from './MetricsCollector.js';\nimport { IInitMode, InitConfig, InitResult, InitMode } from '../types/interfaces.js';\n\nexport interface InitControllerConfig {\n mode?: InitMode;\n topology?: 'mesh' | 'hierarchical' | 'ring' | 'star';\n maxAgents?: number;\n strategy?: 'balanced' | 'specialized' | 'adaptive';\n database?: 'sqlite' | 'json';\n configPath?: string;\n debug?: boolean;\n}\n\nexport class InitController {\n private configManager: ConfigManager;\n private databaseManager: DatabaseManager;\n private modeFactory: ModeFactory;\n private topologyManager: TopologyManager;\n private agentRegistry: AgentRegistry;\n private metricsCollector: MetricsCollector;\n private initialized: boolean = false;\n\n constructor(private config: InitControllerConfig = {}) {\n this.configManager = new ConfigManager(config.configPath);\n this.databaseManager = new DatabaseManager(config.database || 'sqlite');\n this.modeFactory = new ModeFactory();\n this.topologyManager = new TopologyManager(this.databaseManager);\n this.agentRegistry = new AgentRegistry(this.databaseManager);\n this.metricsCollector = new MetricsCollector(this.databaseManager);\n }\n\n /**\n * Main initialization method - orchestrates the entire init process\n */\n async initialize(): Promise<InitResult> {\n const startTime = Date.now();\n\n try {\n // Validate and load configuration\n const validationResult = await this.configManager.validate();\n if (!validationResult.valid) {\n throw new Error(`Configuration validation failed: ${validationResult.errors.join(', ')}`);\n }\n\n // Initialize database\n await this.databaseManager.initialize();\n\n // Set up topology\n await this.topologyManager.configure(this.config.topology || 'mesh');\n\n // Initialize agent registry\n await this.agentRegistry.initialize();\n\n // Create and execute the specific initialization mode\n const mode = this.modeFactory.createMode(this.config.mode || 'standard');\n const initConfig: InitConfig = {\n ...this.config,\n configManager: this.configManager,\n databaseManager: this.databaseManager,\n topologyManager: this.topologyManager,\n agentRegistry: this.agentRegistry,\n metricsCollector: this.metricsCollector\n };\n\n const result = await mode.initialize(initConfig);\n\n // Collect initialization metrics\n const endTime = Date.now();\n await this.metricsCollector.recordInitialization({\n mode: this.config.mode || 'standard',\n duration: endTime - startTime,\n success: true,\n components: result.components || [],\n timestamp: new Date().toISOString()\n });\n\n this.initialized = true;\n\n return {\n success: true,\n mode: this.config.mode || 'standard',\n components: result.components,\n topology: this.config.topology || 'mesh',\n duration: endTime - startTime,\n message: result.message || 'Initialization completed successfully',\n metadata: {\n configValid: true,\n databaseInitialized: true,\n topologyConfigured: true,\n agentRegistryReady: true,\n ...result.metadata\n }\n };\n\n } catch (error) {\n const endTime = Date.now();\n await this.metricsCollector.recordInitialization({\n mode: this.config.mode || 'standard',\n duration: endTime - startTime,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n timestamp: new Date().toISOString()\n });\n\n return {\n success: false,\n mode: this.config.mode || 'standard',\n duration: endTime - startTime,\n error: error instanceof Error ? error.message : String(error),\n message: 'Initialization failed'\n };\n }\n }\n\n /**\n * Get current initialization status\n */\n getStatus(): { initialized: boolean; mode?: InitMode; components?: string[] } {\n return {\n initialized: this.initialized,\n mode: this.config.mode,\n components: this.initialized ? ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry'] : []\n };\n }\n\n /**\n * Shutdown and cleanup resources\n */\n async shutdown(): Promise<void> {\n if (this.databaseManager) {\n await this.databaseManager.close();\n }\n this.initialized = false;\n }\n\n /**\n * Validate the current configuration\n */\n async validateConfiguration(): Promise<{ valid: boolean; errors: string[] }> {\n return await this.configManager.validate();\n }\n\n /**\n * Get available initialization modes\n */\n getAvailableModes(): InitMode[] {\n return this.modeFactory.getAvailableModes();\n }\n\n /**\n * Get topology information\n */\n async getTopologyInfo(): Promise<any> {\n return await this.topologyManager.getTopologyInfo();\n }\n\n /**\n * Get registered agents\n */\n async getAgents(): Promise<any[]> {\n return await this.agentRegistry.getActiveAgents();\n }\n\n /**\n * Get initialization metrics\n */\n async getMetrics(): Promise<any> {\n return await this.metricsCollector.getInitializationMetrics();\n }\n}"],"names":["ConfigManager","DatabaseManager","ModeFactory","TopologyManager","AgentRegistry","MetricsCollector","InitController","configManager","databaseManager","modeFactory","topologyManager","agentRegistry","metricsCollector","initialized","config","configPath","database","initialize","startTime","Date","now","validationResult","validate","valid","Error","errors","join","configure","topology","mode","createMode","initConfig","result","endTime","recordInitialization","duration","success","components","timestamp","toISOString","message","metadata","configValid","databaseInitialized","topologyConfigured","agentRegistryReady","error","String","getStatus","shutdown","close","validateConfiguration","getAvailableModes","getTopologyInfo","getAgents","getActiveAgents","getMetrics","getInitializationMetrics"],"mappings":"AAKA,SAASA,aAAa,QAAQ,qBAAqB;AACnD,SAASC,eAAe,QAAQ,uBAAuB;AACvD,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,eAAe,QAAQ,uBAAuB;AACvD,SAASC,aAAa,QAAQ,qBAAqB;AACnD,SAASC,gBAAgB,QAAQ,wBAAwB;AAazD,OAAO,MAAMC;;IACHC,cAA6B;IAC7BC,gBAAiC;IACjCC,YAAyB;IACzBC,gBAAiC;IACjCC,cAA6B;IAC7BC,iBAAmC;IACnCC,cAAuB,MAAM;IAEr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e,IAAI;YACtBQ,YAAY,IAAI,CAACxB,WAAW,GAAG;gBAAC;gBAAiB;gBAAmB;gBAAmB;aAAgB,GAAG,EAAE;QAC9G;IACF;IAKA,MAAMoC,WAA0B;QAC9B,IAAI,IAAI,CAACzC,eAAe,EAAE;YACxB,MAAM,IAAI,CAACA,eAAe,CAAC0C,KAAK;QAClC;QACA,IAAI,CAACrC,WAAW,GAAG;IACrB;IAKA,MAAMsC,wBAAuE;QAC3E,OAAO,MAAM,IAAI,CAAC5C,aAAa,CAACe,QAAQ;IAC1C;IAKA8B,oBAAgC;QAC9B,OAAO,IAAI,CAAC3C,WAAW,CAAC2C,iBAAiB;IAC3C;IAKA,MAAMC,kBAAgC;QACpC,OAAO,MAAM,IAAI,CAAC3C,eAAe,CAAC2C,eAAe;IACnD;IAKA,MAAMC,YAA4B;QAChC,OAAO,MAAM,IAAI,CAAC3C,aAAa,CAAC4C,eAAe;IACjD;IAKA,MAAMC,aAA2B;QAC/B,OAAO,MAAM,IAAI,CAAC5C,gBAAgB,CAAC6C,wBAAwB;IAC7D;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/MCPIntegrator.js b/dist-cjs/src/core/MCPIntegrator.jsnew file mode 100644index 0000000000..cab873dc29--- /dev/null+++ b/dist-cjs/src/core/MCPIntegrator.js@@ -0,0 +1,450 @@+export class MCPIntegrator {+ tools = new Map();+ initialized = false;+ constructor(){+ this.registerDefaultTools();+ }+ async initialize() {+ await this.discoverTools();+ await this.testConnections();+ this.initialized = true;+ }+ registerDefaultTools() {+ this.tools.set('claude-flow', {+ name: 'claude-flow',+ server: 'npx claude-flow@alpha mcp start',+ functions: [+ {+ name: 'swarm_init',+ description: 'Initialize swarm with topology',+ parameters: {+ topology: 'string',+ maxAgents: 'number',+ strategy: 'string'+ },+ required: [+ 'topology'+ ]+ },+ {+ name: 'agent_spawn',+ description: 'Spawn specialized agents',+ parameters: {+ type: 'string',+ capabilities: 'array',+ name: 'string'+ },+ required: [+ 'type'+ ]+ },+ {+ name: 'task_orchestrate',+ description: 'Orchestrate complex tasks',+ parameters: {+ task: 'string',+ strategy: 'string',+ priority: 'string'+ },+ required: [+ 'task'+ ]+ },+ {+ name: 'memory_usage',+ description: 'Manage coordination memory',+ parameters: {+ action: 'string',+ key: 'string',+ value: 'string',+ namespace: 'string'+ },+ required: [+ 'action'+ ]+ },+ {+ name: 'swarm_status',+ description: 'Get swarm status and metrics',+ parameters: {+ detailed: 'boolean'+ },+ required: []+ }+ ],+ status: 'disconnected'+ });+ this.tools.set('ruv-swarm', {+ name: 'ruv-swarm',+ server: 'npx ruv-swarm mcp start',+ functions: [+ {+ name: 'swarm_init',+ description: 'Initialize RUV swarm',+ parameters: {+ topology: 'string',+ maxAgents: 'number',+ strategy: 'string'+ },+ required: [+ 'topology'+ ]+ },+ {+ name: 'neural_status',+ description: 'Get neural network status',+ parameters: {+ agentId: 'string'+ },+ required: []+ },+ {+ name: 'benchmark_run',+ description: 'Run performance benchmarks',+ parameters: {+ type: 'string',+ iterations: 'number'+ },+ required: []+ }+ ],+ status: 'disconnected'+ });+ this.tools.set('flow-nexus', {+ name: 'flow-nexus',+ server: 'npx flow-nexus@latest mcp start',+ functions: [+ {+ name: 'swarm_init',+ description: 'Initialize Flow Nexus swarm',+ parameters: {+ topology: 'string',+ maxAgents: 'number',+ strategy: 'string'+ },+ required: [+ 'topology'+ ]+ },+ {+ name: 'sandbox_create',+ description: 'Create execution sandbox',+ parameters: {+ template: 'string',+ env_vars: 'object'+ },+ required: [+ 'template'+ ]+ },+ {+ name: 'neural_train',+ description: 'Train neural networks',+ parameters: {+ config: 'object',+ tier: 'string'+ },+ required: [+ 'config'+ ]+ }+ ],+ status: 'disconnected'+ });+ }+ async discoverTools() {+ for (const [name, tool] of this.tools){+ try {+ const isAvailable = await this.checkToolAvailability(name);+ tool.status = isAvailable ? 'connected' : 'disconnected';+ tool.lastPing = new Date();+ } catch (error) {+ tool.status = 'error';+ console.warn(`Failed to discover MCP tool ${name}:`, error);+ }+ }+ }+ async checkToolAvailability(toolName) {+ return Math.random() > 0.3;+ }+ async testConnections() {+ for (const [name, tool] of this.tools){+ if (tool.status === 'connected') {+ try {+ await new Promise((resolve)=>setTimeout(resolve, 100));+ console.log(`✓ MCP tool ${name} connected successfully`);+ } catch (error) {+ tool.status = 'error';+ console.warn(`✗ MCP tool ${name} connection failed:`, error);+ }+ }+ }+ }+ async executeCommand(command) {+ const startTime = Date.now();+ try {+ const tool = this.tools.get(command.tool);+ if (!tool) {+ return {+ success: false,+ error: `Unknown MCP tool: ${command.tool}`,+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ }+ if (tool.status !== 'connected') {+ return {+ success: false,+ error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ }+ const func = tool.functions.find((f)=>f.name === command.function);+ if (!func) {+ return {+ success: false,+ error: `Function ${command.function} not found in tool ${command.tool}`,+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ }+ const missingParams = func.required.filter((param)=>!(param in command.parameters));+ if (missingParams.length > 0) {+ return {+ success: false,+ error: `Missing required parameters: ${missingParams.join(', ')}`,+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ }+ const result = await this.simulateCommandExecution(command);+ return {+ success: true,+ data: result,+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ metadata: {+ executionTime: Date.now() - startTime,+ tool: command.tool,+ function: command.function+ }+ };+ }+ }+ async simulateCommandExecution(command) {+ await new Promise((resolve)=>setTimeout(resolve, 200 + Math.random() * 800));+ switch(command.function){+ case 'swarm_init':+ return {+ swarmId: `swarm-${Date.now()}`,+ topology: command.parameters.topology,+ maxAgents: command.parameters.maxAgents || 8,+ status: 'initialized'+ };+ case 'agent_spawn':+ return {+ agentId: `agent-${Date.now()}`,+ type: command.parameters.type,+ capabilities: command.parameters.capabilities || [],+ status: 'spawned'+ };+ case 'task_orchestrate':+ return {+ taskId: `task-${Date.now()}`,+ task: command.parameters.task,+ strategy: command.parameters.strategy || 'adaptive',+ status: 'orchestrating'+ };+ case 'memory_usage':+ if (command.parameters.action === 'store') {+ return {+ stored: true,+ key: command.parameters.key+ };+ } else if (command.parameters.action === 'retrieve') {+ return {+ found: Math.random() > 0.3,+ value: 'simulated-value'+ };+ }+ return {+ action: command.parameters.action,+ success: true+ };+ case 'swarm_status':+ return {+ activeAgents: Math.floor(Math.random() * 8) + 1,+ topology: 'mesh',+ health: 'good',+ metrics: {+ throughput: Math.random() * 100,+ latency: Math.random() * 50 + 10+ }+ };+ case 'neural_status':+ return {+ modelLoaded: true,+ accuracy: 0.85 + Math.random() * 0.1,+ trainingProgress: Math.random() * 100+ };+ case 'benchmark_run':+ return {+ benchmarks: [+ {+ name: 'cpu',+ value: Math.random() * 100,+ unit: 'ms'+ },+ {+ name: 'memory',+ value: Math.random() * 512,+ unit: 'MB'+ },+ {+ name: 'network',+ value: Math.random() * 50,+ unit: 'ms'+ }+ ]+ };+ default:+ return {+ function: command.function,+ executed: true+ };+ }+ }+ getAvailableTools() {+ return Array.from(this.tools.values());+ }+ getConnectedTools() {+ return Array.from(this.tools.values()).filter((tool)=>tool.status === 'connected');+ }+ getTool(name) {+ return this.tools.get(name);+ }+ isToolAvailable(name) {+ const tool = this.tools.get(name);+ return tool?.status === 'connected' || false;+ }+ getToolFunctions(toolName) {+ const tool = this.tools.get(toolName);+ return tool?.functions || [];+ }+ async initializeSwarmCoordination(config) {+ const toolPriority = [+ 'claude-flow',+ 'ruv-swarm',+ 'flow-nexus'+ ];+ for (const toolName of toolPriority){+ if (this.isToolAvailable(toolName)) {+ return await this.executeCommand({+ tool: toolName,+ function: 'swarm_init',+ parameters: config+ });+ }+ }+ return {+ success: false,+ error: 'No MCP tools available for swarm initialization',+ metadata: {+ executionTime: 0,+ tool: 'none',+ function: 'swarm_init'+ }+ };+ }+ async coordinateMemory(action, key, value, namespace) {+ const command = {+ tool: 'claude-flow',+ function: 'memory_usage',+ parameters: {+ action,+ key,+ value,+ namespace: namespace || 'coordination'+ }+ };+ return await this.executeCommand(command);+ }+ async spawnAgent(type, capabilities, name) {+ const command = {+ tool: 'claude-flow',+ function: 'agent_spawn',+ parameters: {+ type,+ capabilities,+ name+ }+ };+ return await this.executeCommand(command);+ }+ async orchestrateTask(task, strategy, priority) {+ const command = {+ tool: 'claude-flow',+ function: 'task_orchestrate',+ parameters: {+ task,+ strategy,+ priority+ }+ };+ return await this.executeCommand(command);+ }+ async getSwarmStatus(detailed = false) {+ const command = {+ tool: 'claude-flow',+ function: 'swarm_status',+ parameters: {+ detailed+ }+ };+ return await this.executeCommand(command);+ }+ async refreshConnections() {+ await this.discoverTools();+ await this.testConnections();+ }+ registerTool(tool) {+ this.tools.set(tool.name, tool);+ }+ unregisterTool(name) {+ return this.tools.delete(name);+ }+ getIntegrationStatus() {+ const tools = Array.from(this.tools.values());+ const connectedTools = tools.filter((tool)=>tool.status === 'connected');+ const availableFunctions = connectedTools.reduce((sum, tool)=>sum + tool.functions.length, 0);+ return {+ initialized: this.initialized,+ totalTools: tools.length,+ connectedTools: connectedTools.length,+ availableFunctions+ };+ }+}++//# sourceMappingURL=MCPIntegrator.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/MCPIntegrator.js.map b/dist-cjs/src/core/MCPIntegrator.js.mapnew file mode 100644index 0000000000..bc6a3f39b0--- /dev/null+++ b/dist-cjs/src/core/MCPIntegrator.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/MCPIntegrator.ts"],"sourcesContent":["/**\n * MCPIntegrator - Manages MCP tool coordination\n * Provides integration with external MCP tools and orchestration services\n */\n\nexport interface MCPTool {\n name: string;\n server: string;\n functions: MCPFunction[];\n status: 'connected' | 'disconnected' | 'error';\n lastPing?: Date;\n}\n\nexport interface MCPFunction {\n name: string;\n description: string;\n parameters: any;\n required: string[];\n}\n\nexport interface MCPCommand {\n tool: string;\n function: string;\n parameters: any;\n timeout?: number;\n}\n\nexport interface MCPResult {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: {\n executionTime: number;\n tool: string;\n function: string;\n };\n}\n\nexport class MCPIntegrator {\n private tools: Map<string, MCPTool> = new Map();\n private initialized: boolean = false;\n\n constructor() {\n this.registerDefaultTools();\n }\n\n /**\n * Initialize MCP integrator and discover available tools\n */\n async initialize(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n this.initialized = true;\n }\n\n /**\n * Register default MCP tools\n */\n private registerDefaultTools(): void {\n // Claude Flow MCP tools\n this.tools.set('claude-flow', {\n name: 'claude-flow',\n server: 'npx claude-flow@alpha mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize swarm with topology',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'agent_spawn',\n description: 'Spawn specialized agents',\n parameters: { type: 'string', capabilities: 'array', name: 'string' },\n required: ['type']\n },\n {\n name: 'task_orchestrate',\n description: 'Orchestrate complex tasks',\n parameters: { task: 'string', strategy: 'string', priority: 'string' },\n required: ['task']\n },\n {\n name: 'memory_usage',\n description: 'Manage coordination memory',\n parameters: { action: 'string', key: 'string', value: 'string', namespace: 'string' },\n required: ['action']\n },\n {\n name: 'swarm_status',\n description: 'Get swarm status and metrics',\n parameters: { detailed: 'boolean' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // ruv-swarm MCP tools (optional)\n this.tools.set('ruv-swarm', {\n name: 'ruv-swarm',\n server: 'npx ruv-swarm mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize RUV swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'neural_status',\n description: 'Get neural network status',\n parameters: { agentId: 'string' },\n required: []\n },\n {\n name: 'benchmark_run',\n description: 'Run performance benchmarks',\n parameters: { type: 'string', iterations: 'number' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // Flow Nexus MCP tools (optional)\n this.tools.set('flow-nexus', {\n name: 'flow-nexus',\n server: 'npx flow-nexus@latest mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize Flow Nexus swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'sandbox_create',\n description: 'Create execution sandbox',\n parameters: { template: 'string', env_vars: 'object' },\n required: ['template']\n },\n {\n name: 'neural_train',\n description: 'Train neural networks',\n parameters: { config: 'object', tier: 'string' },\n required: ['config']\n }\n ],\n status: 'disconnected'\n });\n }\n\n /**\n * Discover available MCP tools\n */\n private async discoverTools(): Promise<void> {\n // In a real implementation, this would probe for available MCP servers\n // For now, we'll simulate the discovery process\n\n for (const [name, tool] of this.tools) {\n try {\n // Simulate tool discovery\n const isAvailable = await this.checkToolAvailability(name);\n tool.status = isAvailable ? 'connected' : 'disconnected';\n tool.lastPing = new Date();\n } catch (error) {\n tool.status = 'error';\n console.warn(`Failed to discover MCP tool ${name}:`, error);\n }\n }\n }\n\n /**\n * Check if a specific tool is available\n */\n private async checkToolAvailability(toolName: string): Promise<boolean> {\n // Simulate availability check\n // In real implementation, this would try to connect to the MCP server\n return Math.random() > 0.3; // 70% availability simulation\n }\n\n /**\n * Test connections to all tools\n */\n private async testConnections(): Promise<void> {\n for (const [name, tool] of this.tools) {\n if (tool.status === 'connected') {\n try {\n // Simulate connection test\n await new Promise(resolve => setTimeout(resolve, 100));\n console.log(`✓ MCP tool ${name} connected successfully`);\n } catch (error) {\n tool.status = 'error';\n console.warn(`✗ MCP tool ${name} connection failed:`, error);\n }\n }\n }\n }\n\n /**\n * Execute MCP command\n */\n async executeCommand(command: MCPCommand): Promise<MCPResult> {\n const startTime = Date.now();\n\n try {\n const tool = this.tools.get(command.tool);\n if (!tool) {\n return {\n success: false,\n error: `Unknown MCP tool: ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n if (tool.status !== 'connected') {\n return {\n success: false,\n error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate function exists\n const func = tool.functions.find(f => f.name === command.function);\n if (!func) {\n return {\n success: false,\n error: `Function ${command.function} not found in tool ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate required parameters\n const missingParams = func.required.filter(param => !(param in command.parameters));\n if (missingParams.length > 0) {\n return {\n success: false,\n error: `Missing required parameters: ${missingParams.join(', ')}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Execute the command (simulation)\n const result = await this.simulateCommandExecution(command);\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n }\n\n /**\n * Simulate command execution (replace with real MCP calls in production)\n */\n private async simulateCommandExecution(command: MCPCommand): Promise<any> {\n // Simulate processing time\n await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800));\n\n // Return different results based on function\n switch (command.function) {\n case 'swarm_init':\n return {\n swarmId: `swarm-${Date.now()}`,\n topology: command.parameters.topology,\n maxAgents: command.parameters.maxAgents || 8,\n status: 'initialized'\n };\n\n case 'agent_spawn':\n return {\n agentId: `agent-${Date.now()}`,\n type: command.parameters.type,\n capabilities: command.parameters.capabilities || [],\n status: 'spawned'\n };\n\n case 'task_orchestrate':\n return {\n taskId: `task-${Date.now()}`,\n task: command.parameters.task,\n strategy: command.parameters.strategy || 'adaptive',\n status: 'orchestrating'\n };\n\n case 'memory_usage':\n if (command.parameters.action === 'store') {\n return { stored: true, key: command.parameters.key };\n } else if (command.parameters.action === 'retrieve') {\n return { found: Math.random() > 0.3, value: 'simulated-value' };\n }\n return { action: command.parameters.action, success: true };\n\n case 'swarm_status':\n return {\n activeAgents: Math.floor(Math.random() * 8) + 1,\n topology: 'mesh',\n health: 'good',\n metrics: {\n throughput: Math.random() * 100,\n latency: Math.random() * 50 + 10\n }\n };\n\n case 'neural_status':\n return {\n modelLoaded: true,\n accuracy: 0.85 + Math.random() * 0.1,\n trainingProgress: Math.random() * 100\n };\n\n case 'benchmark_run':\n return {\n benchmarks: [\n { name: 'cpu', value: Math.random() * 100, unit: 'ms' },\n { name: 'memory', value: Math.random() * 512, unit: 'MB' },\n { name: 'network', value: Math.random() * 50, unit: 'ms' }\n ]\n };\n\n default:\n return { function: command.function, executed: true };\n }\n }\n\n /**\n * Get available tools\n */\n getAvailableTools(): MCPTool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get connected tools\n */\n getConnectedTools(): MCPTool[] {\n return Array.from(this.tools.values()).filter(tool => tool.status === 'connected');\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): MCPTool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Check if a tool is available\n */\n isToolAvailable(name: string): boolean {\n const tool = this.tools.get(name);\n return tool?.status === 'connected' || false;\n }\n\n /**\n * Get tool functions\n */\n getToolFunctions(toolName: string): MCPFunction[] {\n const tool = this.tools.get(toolName);\n return tool?.functions || [];\n }\n\n /**\n * Initialize swarm coordination using MCP tools\n */\n async initializeSwarmCoordination(config: {\n topology: string;\n maxAgents: number;\n strategy: string;\n }): Promise<MCPResult> {\n // Try claude-flow first, then fallback to other tools\n const toolPriority = ['claude-flow', 'ruv-swarm', 'flow-nexus'];\n\n for (const toolName of toolPriority) {\n if (this.isToolAvailable(toolName)) {\n return await this.executeCommand({\n tool: toolName,\n function: 'swarm_init',\n parameters: config\n });\n }\n }\n\n return {\n success: false,\n error: 'No MCP tools available for swarm initialization',\n metadata: {\n executionTime: 0,\n tool: 'none',\n function: 'swarm_init'\n }\n };\n }\n\n /**\n * Coordinate memory across swarm using MCP tools\n */\n async coordinateMemory(action: string, key: string, value?: string, namespace?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'memory_usage',\n parameters: { action, key, value, namespace: namespace || 'coordination' }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Spawn agents using MCP tools\n */\n async spawnAgent(type: string, capabilities?: string[], name?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'agent_spawn',\n parameters: { type, capabilities, name }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Orchestrate tasks using MCP tools\n */\n async orchestrateTask(task: string, strategy?: string, priority?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'task_orchestrate',\n parameters: { task, strategy, priority }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Get swarm status using MCP tools\n */\n async getSwarmStatus(detailed: boolean = false): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'swarm_status',\n parameters: { detailed }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Refresh tool connections\n */\n async refreshConnections(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n }\n\n /**\n * Register a custom tool\n */\n registerTool(tool: MCPTool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Get integration status\n */\n getIntegrationStatus(): {\n initialized: boolean;\n totalTools: number;\n connectedTools: number;\n availableFunctions: number;\n } {\n const tools = Array.from(this.tools.values());\n const connectedTools = tools.filter(tool => tool.status === 'connected');\n const availableFunctions = connectedTools.reduce((sum, tool) => sum + tool.functions.length, 0);\n\n return {\n initialized: this.initialized,\n totalTools: tools.length,\n connectedTools: connectedTools.length,\n availableFunctions\n };\n }\n}"],"names":["MCPIntegrator","tools","Map","initialized","registerDefaultTools","initialize","discoverTools","testConnections","set","name","server","functions","description","parameters","topology","maxAgents","strategy","required","type","capabilities","task","priority","action","key","value","namespace","detailed","status","agentId","iterations","template","env_vars","config","tier","tool","isAvailable","checkToolAvailability","lastPing","Date","error","console","warn","toolName","Math","random","Promise","resolve","setTimeout","log","executeCommand","command","startTime","now","get","success","metadata","executionTime","function","func","find","f","missingParams","filter","param","length","join","result","simulateCommandExecution","data","Error","message","String","swarmId","taskId","stored","found","activeAgents","floor","health","metrics","throughput","latency","modelLoaded","accuracy","trainingProgress","benchmarks","unit","executed","getAvailableTools","Array","from","values","getConnectedTools","getTool","isToolAvailable","getToolFunctions","initializeSwarmCoordination","toolPriority","coordinateMemory","spawnAgent","orchestrateTask","getSwarmStatus","refreshConnections","registerTool","unregisterTool","delete","getIntegrationStatus","connectedTools","availableFunctions","reduce","sum","totalTools"],"mappings":"AAsCA,OAAO,MAAMA;IACHC,QAA8B,IAAIC,MAAM;IACxCC,cAAuB,MAAM;IAErC,aAAc;QACZ,IAAI,CAACC,oBAAoB;IAC3B;IAKA,MAAMC,aAA4B;QAChC,MAAM,IAAI,CAACC,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;QAC1B,IAAI,CAACJ,WAAW,GAAG;IACrB;IAKQC,uBAA6B;QAEnC,IAAI,CAACH,KAAK,CAACO,GAAG,CAAC,eAAe;YAC5BC,MAAM;YACNC,QAAQ;YACRC,WAAW;gBACT;oBACEF,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEC,UAAU;wBAAUC,WAAW;wBAAUC,UAAU;oBAAS;oBAC1EC,UAAU;wBAAC;qBAAW;gBACxB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEK,MAAM;wBAAUC,cAAc;wBAASV,MAAM;oBAAS;oBACpEQ,UAAU;wBAAC;qBAAO;gBACpB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEO,M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gBAAgBhF,IAAY,EAAEJ,QAAiB,EAAEK,QAAiB,EAAsB;QAC5F,MAAM6B,UAAsB;YAC1BhB,MAAM;YACNuB,UAAU;YACV5C,YAAY;gBAAEO;gBAAMJ;gBAAUK;YAAS;QACzC;QAEA,OAAO,MAAM,IAAI,CAAC4B,cAAc,CAACC;IACnC;IAKA,MAAMmD,eAAe3E,WAAoB,KAAK,EAAsB;QAClE,MAAMwB,UAAsB;YAC1BhB,MAAM;YACNuB,UAAU;YACV5C,YAAY;gBAAEa;YAAS;QACzB;QAEA,OAAO,MAAM,IAAI,CAACuB,cAAc,CAACC;IACnC;IAKA,MAAMoD,qBAAoC;QACxC,MAAM,IAAI,CAAChG,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;IAC5B;IAKAgG,aAAarE,IAAa,EAAQ;QAChC,IAAI,CAACjC,KAAK,CAACO,GAAG,CAAC0B,KAAKzB,IAAI,EAAEyB;IAC5B;IAKAsE,eAAe/F,IAAY,EAAW;QACpC,OAAO,IAAI,CAACR,KAAK,CAACwG,MAAM,CAAChG;IAC3B;IAKAiG,uBAKE;QACA,MAAMzG,QAAQwF,MAAMC,IAAI,CAAC,IAAI,CAACzF,KAAK,CAAC0F,MAAM;QAC1C,MAAMgB,iBAAiB1G,MAAM6D,MAAM,CAAC5B,CAAAA,OAAQA,KAAKP,MAAM,KAAK;QAC5D,MAAMiF,qBAAqBD,eAAeE,MAAM,CAAC,CAACC,KAAK5E,OAAS4E,MAAM5E,KAAKvB,SAAS,CAACqD,MAAM,EAAE;QAE7F,OAAO;YACL7D,aAAa,IAAI,CAACA,WAAW;YAC7B4G,YAAY9G,MAAM+D,MAAM;YACxB2C,gBAAgBA,eAAe3C,MAAM;YACrC4C;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/MetricsCollector.js b/dist-cjs/src/core/MetricsCollector.jsnew file mode 100644index 0000000000..d10f17e09f--- /dev/null+++ b/dist-cjs/src/core/MetricsCollector.js@@ -0,0 +1,342 @@+export class MetricsCollector {+ database;+ metricsBuffer = new Map();+ initialized = false;+ constructor(database){+ this.database = database;+ }+ async initialize() {+ await this.setupMetricsStorage();+ this.initialized = true;+ }+ async setupMetricsStorage() {+ const namespaces = [+ 'initialization',+ 'system',+ 'performance',+ 'agents',+ 'consensus',+ 'topology',+ 'benchmarks'+ ];+ for (const namespace of namespaces){+ try {+ await this.database.store(`metrics-${namespace}-init`, {+ initialized: true,+ timestamp: new Date().toISOString()+ }, 'metrics');+ } catch (error) {+ console.warn(`Failed to initialize metrics namespace ${namespace}:`, error);+ }+ }+ }+ async recordInitialization(metrics) {+ const key = `init-${Date.now()}`;+ await this.database.store(key, metrics, 'metrics');+ await this.updateAggregatedMetrics('initialization', metrics);+ }+ async recordSystemMetrics(metrics) {+ const timestampedMetrics = {+ ...metrics,+ timestamp: metrics.timestamp || new Date()+ };+ const key = `system-${Date.now()}`;+ await this.database.store(key, timestampedMetrics, 'metrics');+ this.addToBuffer('system', timestampedMetrics);+ }+ async recordAgentMetrics(agentId, metrics) {+ const timestampedMetrics = {+ agentId,+ ...metrics,+ timestamp: metrics.timestamp || new Date()+ };+ const key = `agent-${agentId}-${Date.now()}`;+ await this.database.store(key, timestampedMetrics, 'metrics');+ this.addToBuffer('agents', timestampedMetrics);+ }+ async recordConsensusMetrics(metrics) {+ const timestampedMetrics = {+ ...metrics,+ timestamp: metrics.timestamp || new Date()+ };+ const key = `consensus-${metrics.decisionId}`;+ await this.database.store(key, timestampedMetrics, 'metrics');+ this.addToBuffer('consensus', timestampedMetrics);+ }+ async recordTopologyMetrics(metrics) {+ const timestampedMetrics = {+ ...metrics,+ timestamp: metrics.timestamp || new Date()+ };+ const key = `topology-${Date.now()}`;+ await this.database.store(key, timestampedMetrics, 'metrics');+ this.addToBuffer('topology', timestampedMetrics);+ }+ async recordBenchmark(benchmark) {+ const key = `benchmark-${benchmark.name}-${Date.now()}`;+ await this.database.store(key, benchmark, 'metrics');+ this.addToBuffer('benchmarks', benchmark);+ }+ async getInitializationMetrics() {+ const keys = await this.database.list('metrics');+ const initKeys = keys.filter((key)=>key.startsWith('init-'));+ const metrics = [];+ for (const key of initKeys){+ const metric = await this.database.retrieve(key, 'metrics');+ if (metric) metrics.push(metric);+ }+ metrics.sort((a, b)=>new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());+ const total = metrics.length;+ const successful = metrics.filter((m)=>m.success).length;+ const failed = total - successful;+ const durations = metrics.map((m)=>m.duration).filter((d)=>d > 0);+ const averageDuration = durations.length > 0 ? durations.reduce((sum, d)=>sum + d, 0) / durations.length : 0;+ const modeDistribution = {};+ metrics.forEach((m)=>{+ modeDistribution[m.mode] = (modeDistribution[m.mode] || 0) + 1;+ });+ return {+ total,+ successful,+ failed,+ averageDuration,+ modeDistribution,+ recentMetrics: metrics.slice(0, 10)+ };+ }+ async getSystemHealth() {+ const systemMetrics = this.getBufferedMetrics('system', 10);+ if (systemMetrics.length === 0) {+ return {+ status: 'critical',+ score: 0,+ issues: [+ 'No system metrics available'+ ],+ recommendations: [+ 'Ensure metrics collection is working'+ ]+ };+ }+ const latest = systemMetrics[systemMetrics.length - 1];+ const issues = [];+ const recommendations = [];+ let score = 100;+ if (latest.cpuUsage > 90) {+ issues.push('High CPU usage');+ recommendations.push('Consider scaling or optimizing CPU-intensive tasks');+ score -= 30;+ } else if (latest.cpuUsage > 70) {+ issues.push('Elevated CPU usage');+ score -= 15;+ }+ if (latest.memoryUsage > 90) {+ issues.push('High memory usage');+ recommendations.push('Check for memory leaks or increase available memory');+ score -= 25;+ } else if (latest.memoryUsage > 70) {+ issues.push('Elevated memory usage');+ score -= 10;+ }+ if (latest.networkLatency > 100) {+ issues.push('High network latency');+ recommendations.push('Check network connectivity and optimize communication');+ score -= 20;+ }+ if (systemMetrics.length >= 5) {+ const recent = systemMetrics.slice(-3);+ const older = systemMetrics.slice(-6, -3);+ const recentAvgCpu = recent.reduce((sum, m)=>sum + m.cpuUsage, 0) / recent.length;+ const olderAvgCpu = older.reduce((sum, m)=>sum + m.cpuUsage, 0) / older.length;+ if (recentAvgCpu > olderAvgCpu * 1.2) {+ issues.push('CPU usage trending upward');+ score -= 10;+ }+ }+ let status;+ if (score >= 80) status = 'healthy';+ else if (score >= 50) status = 'degraded';+ else status = 'critical';+ return {+ status,+ score,+ issues,+ recommendations+ };+ }+ async getPerformanceTrends(period = '1h') {+ const trends = [];+ const metricTypes = [+ 'system',+ 'agents',+ 'consensus',+ 'topology'+ ];+ for (const type of metricTypes){+ const metrics = this.getBufferedMetrics(type, 20);+ if (metrics.length < 2) continue;+ const recent = metrics.slice(-5);+ const older = metrics.slice(-10, -5);+ if (recent.length === 0 || older.length === 0) continue;+ switch(type){+ case 'system':+ trends.push(...this.analyzeSystemTrends(recent, older, period));+ break;+ case 'agents':+ trends.push(...this.analyzeAgentTrends(recent, older, period));+ break;+ case 'consensus':+ trends.push(...this.analyzeConsensusTrends(recent, older, period));+ break;+ case 'topology':+ trends.push(...this.analyzeTopologyTrends(recent, older, period));+ break;+ }+ }+ return trends;+ }+ async runBenchmarks() {+ const benchmarks = [];+ const cpuStart = Date.now();+ for(let i = 0; i < 1000000; i++){+ Math.sqrt(i);+ }+ const cpuTime = Date.now() - cpuStart;+ benchmarks.push({+ name: 'cpu-computation',+ value: cpuTime,+ unit: 'ms',+ timestamp: new Date(),+ baseline: 50+ });+ const memStart = Date.now();+ const arrays = [];+ for(let i = 0; i < 1000; i++){+ arrays.push(new Array(1000).fill(i));+ }+ const memTime = Date.now() - memStart;+ benchmarks.push({+ name: 'memory-allocation',+ value: memTime,+ unit: 'ms',+ timestamp: new Date(),+ baseline: 20+ });+ const dbStart = Date.now();+ for(let i = 0; i < 10; i++){+ await this.database.store(`benchmark-test-${i}`, {+ value: i+ }, 'temp');+ await this.database.retrieve(`benchmark-test-${i}`, 'temp');+ }+ const dbTime = Date.now() - dbStart;+ benchmarks.push({+ name: 'database-io',+ value: dbTime,+ unit: 'ms',+ timestamp: new Date(),+ baseline: 100+ });+ for (const benchmark of benchmarks){+ await this.recordBenchmark(benchmark);+ }+ return benchmarks;+ }+ async getPerformanceSummary() {+ const [health, trends, benchmarks] = await Promise.all([+ this.getSystemHealth(),+ this.getPerformanceTrends(),+ this.getRecentBenchmarks()+ ]);+ const recommendations = [+ ...health.recommendations,+ ...this.generateTrendRecommendations(trends),+ ...this.generateBenchmarkRecommendations(benchmarks)+ ];+ return {+ health,+ trends,+ benchmarks,+ recommendations: [+ ...new Set(recommendations)+ ]+ };+ }+ addToBuffer(type, data) {+ if (!this.metricsBuffer.has(type)) {+ this.metricsBuffer.set(type, []);+ }+ const buffer = this.metricsBuffer.get(type);+ buffer.push(data);+ if (buffer.length > 100) {+ buffer.shift();+ }+ }+ getBufferedMetrics(type, limit) {+ const buffer = this.metricsBuffer.get(type) || [];+ return limit ? buffer.slice(-limit) : buffer;+ }+ async updateAggregatedMetrics(type, metrics) {+ const key = `aggregated-${type}`;+ const existing = await this.database.retrieve(key, 'metrics') || {+ count: 0,+ sum: {},+ avg: {}+ };+ existing.count++;+ existing.lastUpdated = new Date().toISOString();+ await this.database.store(key, existing, 'metrics');+ }+ analyzeSystemTrends(recent, older, period) {+ const trends = [];+ const recentAvgCpu = recent.reduce((sum, m)=>sum + m.cpuUsage, 0) / recent.length;+ const olderAvgCpu = older.reduce((sum, m)=>sum + m.cpuUsage, 0) / older.length;+ const cpuChange = (recentAvgCpu - olderAvgCpu) / olderAvgCpu * 100;+ trends.push({+ metric: 'cpu-usage',+ trend: cpuChange > 5 ? 'degrading' : cpuChange < -5 ? 'improving' : 'stable',+ change: cpuChange,+ period+ });+ return trends;+ }+ analyzeAgentTrends(recent, older, period) {+ return [];+ }+ analyzeConsensusTrends(recent, older, period) {+ return [];+ }+ analyzeTopologyTrends(recent, older, period) {+ return [];+ }+ async getRecentBenchmarks() {+ const keys = await this.database.list('metrics');+ const benchmarkKeys = keys.filter((key)=>key.startsWith('benchmark-')).slice(-10);+ const benchmarks = [];+ for (const key of benchmarkKeys){+ const benchmark = await this.database.retrieve(key, 'metrics');+ if (benchmark) benchmarks.push(benchmark);+ }+ return benchmarks;+ }+ generateTrendRecommendations(trends) {+ const recommendations = [];+ trends.forEach((trend)=>{+ if (trend.trend === 'degrading') {+ recommendations.push(`${trend.metric} is degrading (${trend.change.toFixed(1)}% change) - investigate potential causes`);+ }+ });+ return recommendations;+ }+ generateBenchmarkRecommendations(benchmarks) {+ const recommendations = [];+ benchmarks.forEach((benchmark)=>{+ if (benchmark.baseline && benchmark.value > benchmark.baseline * 2) {+ recommendations.push(`${benchmark.name} performance is significantly below baseline - consider optimization`);+ }+ });+ return recommendations;+ }+}++//# sourceMappingURL=MetricsCollector.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/MetricsCollector.js.map b/dist-cjs/src/core/MetricsCollector.js.mapnew file mode 100644index 0000000000..e75001e977--- /dev/null+++ b/dist-cjs/src/core/MetricsCollector.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/MetricsCollector.ts"],"sourcesContent":["/**\n * MetricsCollector - Performance and coordination tracking\n * Collects, aggregates, and analyzes system performance metrics\n */\n\nimport { IDatabaseProvider, InitializationMetrics, Metrics, PerformanceMetrics } from '../types/interfaces.js';\n\nexport interface SystemHealth {\n status: 'healthy' | 'degraded' | 'critical';\n score: number; // 0-100\n issues: string[];\n recommendations: string[];\n}\n\nexport interface PerformanceTrend {\n metric: string;\n trend: 'improving' | 'stable' | 'degrading';\n change: number; // percentage change\n period: string;\n}\n\nexport interface Benchmark {\n name: string;\n value: number;\n unit: string;\n timestamp: Date;\n baseline?: number;\n percentile?: number;\n}\n\nexport class MetricsCollector {\n private metricsBuffer: Map<string, any[]> = new Map();\n private initialized: boolean = false;\n\n constructor(private database: IDatabaseProvider) {}\n\n /**\n * Initialize metrics collection\n */\n async initialize(): Promise<void> {\n // Create metrics tables/collections if using database\n await this.setupMetricsStorage();\n this.initialized = true;\n }\n\n /**\n * Setup metrics storage structure\n */\n private async setupMetricsStorage(): Promise<void> {\n // Initialize metrics namespaces\n const namespaces = [\n 'initialization',\n 'system',\n 'performance',\n 'agents',\n 'consensus',\n 'topology',\n 'benchmarks'\n ];\n\n for (const namespace of namespaces) {\n try {\n await this.database.store(`metrics-${namespace}-init`, {\n initialized: true,\n timestamp: new Date().toISOString()\n }, 'metrics');\n } catch (error) {\n console.warn(`Failed to initialize metrics namespace ${namespace}:`, error);\n }\n }\n }\n\n /**\n * Record initialization metrics\n */\n async recordInitialization(metrics: InitializationMetrics): Promise<void> {\n const key = `init-${Date.now()}`;\n await this.database.store(key, metrics, 'metrics');\n\n // Update aggregated initialization stats\n await this.updateAggregatedMetrics('initialization', metrics);\n }\n\n /**\n * Record system metrics\n */\n async recordSystemMetrics(metrics: {\n cpuUsage: number;\n memoryUsage: number;\n diskUsage: number;\n networkLatency: number;\n activeConnections: number;\n timestamp?: Date;\n }): Promise<void> {\n const timestampedMetrics = {\n ...metrics,\n timestamp: metrics.timestamp || new Date()\n };\n\n const key = `system-${Date.now()}`;\n await this.database.store(key, timestampedMetrics, 'metrics');\n\n // Buffer for real-time analysis\n this.addToBuffer('system', timestampedMetrics);\n }\n\n /**\n * Record agent performance metrics\n */\n async recordAgentMetrics(agentId: string, metrics: {\n tasksCompleted: number;\n successRate: number;\n averageResponseTime: number;\n resourceUtilization: any;\n timestamp?: Date;\n }): Promise<void> {\n const timestampedMetrics = {\n agentId,\n ...metrics,\n timestamp: metrics.timestamp || new Date()\n };\n\n const key = `agent-${agentId}-${Date.now()}`;\n await this.database.store(key, timestampedMetrics, 'metrics');\n\n this.addToBuffer('agents', timestampedMetrics);\n }\n\n /**\n * Record consensus metrics\n */\n async recordConsensusMetrics(metrics: {\n algorithm: string;\n decisionId: string;\n participantCount: number;\n consensusTime: number;\n outcome: boolean;\n confidence: number;\n timestamp?: Date;\n }): Promise<void> {\n const timestampedMetrics = {\n ...metrics,\n timestamp: metrics.timestamp || new Date()\n };\n\n const key = `consensus-${metrics.decisionId}`;\n await this.database.store(key, timestampedMetrics, 'metrics');\n\n this.addToBuffer('consensus', timestampedMetrics);\n }\n\n /**\n * Record topology metrics\n */\n async recordTopologyMetrics(metrics: {\n type: string;\n agentCount: number;\n connectionCount: number;\n averageLatency: number;\n throughput: number;\n reliability: number;\n timestamp?: Date;\n }): Promise<void> {\n const timestampedMetrics = {\n ...metrics,\n timestamp: metrics.timestamp || new Date()\n };\n\n const key = `topology-${Date.now()}`;\n await this.database.store(key, timestampedMetrics, 'metrics');\n\n this.addToBuffer('topology', timestampedMetrics);\n }\n\n /**\n * Record performance benchmark\n */\n async recordBenchmark(benchmark: Benchmark): Promise<void> {\n const key = `benchmark-${benchmark.name}-${Date.now()}`;\n await this.database.store(key, benchmark, 'metrics');\n\n this.addToBuffer('benchmarks', benchmark);\n }\n\n /**\n * Get initialization metrics\n */\n async getInitializationMetrics(): Promise<{\n total: number;\n successful: number;\n failed: number;\n averageDuration: number;\n modeDistribution: Record<string, number>;\n recentMetrics: InitializationMetrics[];\n }> {\n const keys = await this.database.list('metrics');\n const initKeys = keys.filter(key => key.startsWith('init-'));\n\n const metrics: InitializationMetrics[] = [];\n for (const key of initKeys) {\n const metric = await this.database.retrieve(key, 'metrics');\n if (metric) metrics.push(metric);\n }\n\n // Sort by timestamp (most recent first)\n metrics.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());\n\n const total = metrics.length;\n const successful = metrics.filter(m => m.success).length;\n const failed = total - successful;\n\n const durations = metrics.map(m => m.duration).filter(d => d > 0);\n const averageDuration = durations.length > 0\n ? durations.reduce((sum, d) => sum + d, 0) / durations.length\n : 0;\n\n // Mode distribution\n const modeDistribution: Record<string, number> = {};\n metrics.forEach(m => {\n modeDistribution[m.mode] = (modeDistribution[m.mode] || 0) + 1;\n });\n\n return {\n total,\n successful,\n failed,\n averageDuration,\n modeDistribution,\n recentMetrics: metrics.slice(0, 10) // Last 10 initializations\n };\n }\n\n /**\n * Get system health status\n */\n async getSystemHealth(): Promise<SystemHealth> {\n const systemMetrics = this.getBufferedMetrics('system', 10); // Last 10 measurements\n\n if (systemMetrics.length === 0) {\n return {\n status: 'critical',\n score: 0,\n issues: ['No system metrics available'],\n recommendations: ['Ensure metrics collection is working']\n };\n }\n\n const latest = systemMetrics[systemMetrics.length - 1];\n const issues: string[] = [];\n const recommendations: string[] = [];\n let score = 100;\n\n // Check CPU usage\n if (latest.cpuUsage > 90) {\n issues.push('High CPU usage');\n recommendations.push('Consider scaling or optimizing CPU-intensive tasks');\n score -= 30;\n } else if (latest.cpuUsage > 70) {\n issues.push('Elevated CPU usage');\n score -= 15;\n }\n\n // Check memory usage\n if (latest.memoryUsage > 90) {\n issues.push('High memory usage');\n recommendations.push('Check for memory leaks or increase available memory');\n score -= 25;\n } else if (latest.memoryUsage > 70) {\n issues.push('Elevated memory usage');\n score -= 10;\n }\n\n // Check network latency\n if (latest.networkLatency > 100) {\n issues.push('High network latency');\n recommendations.push('Check network connectivity and optimize communication');\n score -= 20;\n }\n\n // Check trend (if we have historical data)\n if (systemMetrics.length >= 5) {\n const recent = systemMetrics.slice(-3);\n const older = systemMetrics.slice(-6, -3);\n\n const recentAvgCpu = recent.reduce((sum, m) => sum + m.cpuUsage, 0) / recent.length;\n const olderAvgCpu = older.reduce((sum, m) => sum + m.cpuUsage, 0) / older.length;\n\n if (recentAvgCpu > olderAvgCpu * 1.2) {\n issues.push('CPU usage trending upward');\n score -= 10;\n }\n }\n\n let status: 'healthy' | 'degraded' | 'critical';\n if (score >= 80) status = 'healthy';\n else if (score >= 50) status = 'degraded';\n else status = 'critical';\n\n return { status, score, issues, recommendations };\n }\n\n /**\n * Get performance trends\n */\n async getPerformanceTrends(period: string = '1h'): Promise<PerformanceTrend[]> {\n const trends: PerformanceTrend[] = [];\n\n // Analyze different metric types\n const metricTypes = ['system', 'agents', 'consensus', 'topology'];\n\n for (const type of metricTypes) {\n const metrics = this.getBufferedMetrics(type, 20);\n if (metrics.length < 2) continue;\n\n const recent = metrics.slice(-5);\n const older = metrics.slice(-10, -5);\n\n if (recent.length === 0 || older.length === 0) continue;\n\n // Calculate trends for different metrics\n switch (type) {\n case 'system':\n trends.push(...this.analyzeSystemTrends(recent, older, period));\n break;\n case 'agents':\n trends.push(...this.analyzeAgentTrends(recent, older, period));\n break;\n case 'consensus':\n trends.push(...this.analyzeConsensusTrends(recent, older, period));\n break;\n case 'topology':\n trends.push(...this.analyzeTopologyTrends(recent, older, period));\n break;\n }\n }\n\n return trends;\n }\n\n /**\n * Run performance benchmarks\n */\n async runBenchmarks(): Promise<Benchmark[]> {\n const benchmarks: Benchmark[] = [];\n\n // CPU benchmark\n const cpuStart = Date.now();\n for (let i = 0; i < 1000000; i++) {\n Math.sqrt(i);\n }\n const cpuTime = Date.now() - cpuStart;\n\n benchmarks.push({\n name: 'cpu-computation',\n value: cpuTime,\n unit: 'ms',\n timestamp: new Date(),\n baseline: 50 // Expected baseline\n });\n\n // Memory allocation benchmark\n const memStart = Date.now();\n const arrays = [];\n for (let i = 0; i < 1000; i++) {\n arrays.push(new Array(1000).fill(i));\n }\n const memTime = Date.now() - memStart;\n\n benchmarks.push({\n name: 'memory-allocation',\n value: memTime,\n unit: 'ms',\n timestamp: new Date(),\n baseline: 20\n });\n\n // Database I/O benchmark\n const dbStart = Date.now();\n for (let i = 0; i < 10; i++) {\n await this.database.store(`benchmark-test-${i}`, { value: i }, 'temp');\n await this.database.retrieve(`benchmark-test-${i}`, 'temp');\n }\n const dbTime = Date.now() - dbStart;\n\n benchmarks.push({\n name: 'database-io',\n value: dbTime,\n unit: 'ms',\n timestamp: new Date(),\n baseline: 100\n });\n\n // Store benchmarks\n for (const benchmark of benchmarks) {\n await this.recordBenchmark(benchmark);\n }\n\n return benchmarks;\n }\n\n /**\n * Get performance summary\n */\n async getPerformanceSummary(): Promise<{\n health: SystemHealth;\n trends: PerformanceTrend[];\n benchmarks: Benchmark[];\n recommendations: string[];\n }> {\n const [health, trends, benchmarks] = await Promise.all([\n this.getSystemHealth(),\n this.getPerformanceTrends(),\n this.getRecentBenchmarks()\n ]);\n\n const recommendations = [\n ...health.recommendations,\n ...this.generateTrendRecommendations(trends),\n ...this.generateBenchmarkRecommendations(benchmarks)\n ];\n\n return {\n health,\n trends,\n benchmarks,\n recommendations: [...new Set(recommendations)] // Remove duplicates\n };\n }\n\n // Helper methods\n\n private addToBuffer(type: string, data: any): void {\n if (!this.metricsBuffer.has(type)) {\n this.metricsBuffer.set(type, []);\n }\n\n const buffer = this.metricsBuffer.get(type)!;\n buffer.push(data);\n\n // Keep buffer size manageable\n if (buffer.length > 100) {\n buffer.shift();\n }\n }\n\n private getBufferedMetrics(type: string, limit?: number): any[] {\n const buffer = this.metricsBuffer.get(type) || [];\n return limit ? buffer.slice(-limit) : buffer;\n }\n\n private async updateAggregatedMetrics(type: string, metrics: any): Promise<void> {\n const key = `aggregated-${type}`;\n const existing = await this.database.retrieve(key, 'metrics') || {\n count: 0,\n sum: {},\n avg: {}\n };\n\n // Update aggregated data (simplified example)\n existing.count++;\n existing.lastUpdated = new Date().toISOString();\n\n await this.database.store(key, existing, 'metrics');\n }\n\n private analyzeSystemTrends(recent: any[], older: any[], period: string): PerformanceTrend[] {\n const trends: PerformanceTrend[] = [];\n\n const recentAvgCpu = recent.reduce((sum, m) => sum + m.cpuUsage, 0) / recent.length;\n const olderAvgCpu = older.reduce((sum, m) => sum + m.cpuUsage, 0) / older.length;\n const cpuChange = ((recentAvgCpu - olderAvgCpu) / olderAvgCpu) * 100;\n\n trends.push({\n metric: 'cpu-usage',\n trend: cpuChange > 5 ? 'degrading' : cpuChange < -5 ? 'improving' : 'stable',\n change: cpuChange,\n period\n });\n\n return trends;\n }\n\n private analyzeAgentTrends(recent: any[], older: any[], period: string): PerformanceTrend[] {\n // Analyze agent performance trends\n return [];\n }\n\n private analyzeConsensusTrends(recent: any[], older: any[], period: string): PerformanceTrend[] {\n // Analyze consensus performance trends\n return [];\n }\n\n private analyzeTopologyTrends(recent: any[], older: any[], period: string): PerformanceTrend[] {\n // Analyze topology performance trends\n return [];\n }\n\n private async getRecentBenchmarks(): Promise<Benchmark[]> {\n const keys = await this.database.list('metrics');\n const benchmarkKeys = keys.filter(key => key.startsWith('benchmark-')).slice(-10);\n\n const benchmarks: Benchmark[] = [];\n for (const key of benchmarkKeys) {\n const benchmark = await this.database.retrieve(key, 'metrics');\n if (benchmark) benchmarks.push(benchmark);\n }\n\n return benchmarks;\n }\n\n private generateTrendRecommendations(trends: PerformanceTrend[]): string[] {\n const recommendations: string[] = [];\n\n trends.forEach(trend => {\n if (trend.trend === 'degrading') {\n recommendations.push(`${trend.metric} is degrading (${trend.change.toFixed(1)}% change) - investigate potential causes`);\n }\n });\n\n return recommendations;\n }\n\n private generateBenchmarkRecommendations(benchmarks: Benchmark[]): string[] {\n const recommendations: string[] = [];\n\n benchmarks.forEach(benchmark => {\n if (benchmark.baseline && benchmark.value > benchmark.baseline * 2) {\n recommendations.push(`${benchmark.name} performance is significantly below baseline - consider optimization`);\n }\n });\n\n return recommendations;\n }\n}"],"names":["MetricsCollector","metricsBuffer","Map","initialized","database","initialize","setupMetricsStorage","namespaces","namespace","store","timestamp","Date","toISOString","error","console","warn","recordInitialization","metrics","key","now","updateAggregatedMetrics","recordSystemMetrics","timestampedMetrics","addToBuffer","recordAgentMetrics","agentId","recordConsensusMetrics","decisionId","recordTopologyMetrics","recordBenchmark","benchmark","name","getInitializationMetrics","keys","list","initKeys","filter","startsWith","metric","retrieve","push","sort","a","b","getTime","total","length","successful","m","success","failed","durations","map","duration","d","averageDuration","reduce","sum","modeDistribution","forEach","mode","recentMetrics","slice","getSystemHealth","systemMetrics","getBufferedMetrics","status","score","issues","recommendations","latest","cpuUsage","memoryUsage","networkLatency","recent","older","recentAvgCpu","olderAvgCpu","getPerformanceTrends","period","trends","metricTypes","type","analyzeSystemTrends","analyzeAgentTrends","analyzeConsensusTrends","analyzeTopologyTrends","runBenchmarks","benchmarks","cpuStart","i","Math","sqrt","cpuTime","value","unit","baseline","memStart","arrays","Array","fill","memTime","dbStart","dbTime","getPerformanceSummary","health","Promise","all","getRecentBenchmarks","generateTrendRecommendations","generateBenchmarkRecommendations","Set","data","has","set","buffer","get","shift","limit","existing","count","avg","lastUpdated","cpuChange","trend","change","benchmarkKeys","toFixed"],"mappings":"AA8BA,OAAO,MAAMA;;IACHC,gBAAoC,IAAIC,MAAM;IAC9CC,cAAuB,MAAM;IAErC,YAAY,AAAQC,QAA2B,CAAE;aAA7BA,WAAAA;IAA8B;IAKlD,MAAMC,aAA4B;QAEhC,MAAM,IAAI,CAACC,mBAAmB;QAC9B,IAAI,CAACH,WAAW,GAAG;IACrB;IAKA,MAAcG,sBAAqC;QAEjD,MAAMC,aAAa;YACjB;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QAED,KAAK,MAAMC,aAAaD,WAAY;YAClC,IAAI;gBACF,MAAM,IAAI,CAACH,QAAQ,CAACK,KAAK,CAAC,CAAC,QAAQ,EAAED,UAAU,KAAK,CAAC,EAAE;oBACrDL,aAAa;oBACbO,WAAW,IAAIC,OAAOC,WAAW;gBACnC,GAAG;YACL,EAAE,OAAOC,OAAO;gBACdC,QAAQC,IAAI,CAAC,CAAC,uCAAuC,EAAEP,UAAU,CAAC,CAAC,EAAEK;YACvE;QACF;IACF;IAKA,MAAMG,qBAAqBC,OAA8B,EAAiB;QACxE,MAAMC,MAAM,CAAC,KAAK,EAAEP,KAAKQ,GAAG,IAAI;QAChC,MAAM,IAAI,CAACf,QAAQ,CAACK,KAAK,CAACS,KAAKD,SAAS;QAGxC,MAAM,IAAI,CAACG,uBAAuB,CAAC,kBAAkBH;IACvD;IAKA,MAAMI,oBAAoBJ,OAOzB,EAAiB;QAChB,MAAMK,qBAAqB;YACzB,GAAGL,OAAO;YACVP,WAAWO,QAAQP,SAAS,IAAI,IAAIC;QACtC;QAEA,MAAMO,MAAM,CAAC,OAAO,EAAEP,KAAKQ,GAAG,IAAI;QAClC,MAAM,IAAI,CAACf,QAAQ,CAACK,KAAK,CAACS,KAAKI,oBAAoB;QAGnD,IAAI,CAACC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zH;QACF;QAEA,OAAO1D;IACT;IAEQyC,iCAAiCtB,UAAuB,EAAY;QAC1E,MAAMnB,kBAA4B,EAAE;QAEpCmB,WAAW7B,OAAO,CAAC7B,CAAAA;YACjB,IAAIA,UAAUkE,QAAQ,IAAIlE,UAAUgE,KAAK,GAAGhE,UAAUkE,QAAQ,GAAG,GAAG;gBAClE3B,gBAAgB7B,IAAI,CAAC,GAAGV,UAAUC,IAAI,CAAC,oEAAoE,CAAC;YAC9G;QACF;QAEA,OAAOsC;IACT;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/ModeFactory.js b/dist-cjs/src/core/ModeFactory.jsnew file mode 100644index 0000000000..b628b3934c--- /dev/null+++ b/dist-cjs/src/core/ModeFactory.js@@ -0,0 +1,66 @@+import { StandardInit } from '../modes/StandardInit.js';+import { GitHubInit } from '../modes/GitHubInit.js';+import { HiveMindInit } from '../modes/HiveMindInit.js';+import { SparcInit } from '../modes/SparcInit.js';+import { NeuralInit } from '../modes/NeuralInit.js';+import { EnterpriseInit } from '../modes/EnterpriseInit.js';+export class ModeFactory {+ modes = new Map();+ constructor(){+ this.registerModes();+ }+ registerModes() {+ this.modes.set('standard', ()=>new StandardInit());+ this.modes.set('github', ()=>new GitHubInit());+ this.modes.set('hive-mind', ()=>new HiveMindInit());+ this.modes.set('sparc', ()=>new SparcInit());+ this.modes.set('neural', ()=>new NeuralInit());+ this.modes.set('enterprise', ()=>new EnterpriseInit());+ }+ createMode(mode) {+ const modeFactory = this.modes.get(mode);+ if (!modeFactory) {+ throw new Error(`Unknown initialization mode: ${mode}. Available modes: ${this.getAvailableModes().join(', ')}`);+ }+ return modeFactory();+ }+ getAvailableModes() {+ return Array.from(this.modes.keys());+ }+ getModeDescriptions() {+ const descriptions = {};+ for (const mode of this.getAvailableModes()){+ try {+ const modeInstance = this.createMode(mode);+ descriptions[mode] = modeInstance.getDescription();+ } catch (error) {+ descriptions[mode] = `Error loading mode: ${error}`;+ }+ }+ return descriptions;+ }+ validateMode(mode) {+ try {+ const modeInstance = this.createMode(mode);+ return modeInstance.validate();+ } catch (error) {+ return false;+ }+ }+ getRequiredComponents(mode) {+ try {+ const modeInstance = this.createMode(mode);+ return modeInstance.getRequiredComponents();+ } catch (error) {+ return [];+ }+ }+ registerCustomMode(mode, factory) {+ this.modes.set(mode, factory);+ }+ unregisterMode(mode) {+ return this.modes.delete(mode);+ }+}++//# sourceMappingURL=ModeFactory.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/ModeFactory.js.map b/dist-cjs/src/core/ModeFactory.js.mapnew file mode 100644index 0000000000..d5377c717a--- /dev/null+++ b/dist-cjs/src/core/ModeFactory.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/ModeFactory.ts"],"sourcesContent":["/**\n * ModeFactory - Creates specific initialization modes\n * Implements the Factory pattern for different initialization strategies\n */\n\nimport { IInitMode, InitMode } from '../types/interfaces.js';\nimport { StandardInit } from '../modes/StandardInit.js';\nimport { GitHubInit } from '../modes/GitHubInit.js';\nimport { HiveMindInit } from '../modes/HiveMindInit.js';\nimport { SparcInit } from '../modes/SparcInit.js';\nimport { NeuralInit } from '../modes/NeuralInit.js';\nimport { EnterpriseInit } from '../modes/EnterpriseInit.js';\n\nexport class ModeFactory {\n private modes: Map<InitMode, () => IInitMode> = new Map();\n\n constructor() {\n this.registerModes();\n }\n\n /**\n * Register all available initialization modes\n */\n private registerModes(): void {\n this.modes.set('standard', () => new StandardInit());\n this.modes.set('github', () => new GitHubInit());\n this.modes.set('hive-mind', () => new HiveMindInit());\n this.modes.set('sparc', () => new SparcInit());\n this.modes.set('neural', () => new NeuralInit());\n this.modes.set('enterprise', () => new EnterpriseInit());\n }\n\n /**\n * Create a specific initialization mode\n */\n createMode(mode: InitMode): IInitMode {\n const modeFactory = this.modes.get(mode);\n\n if (!modeFactory) {\n throw new Error(`Unknown initialization mode: ${mode}. Available modes: ${this.getAvailableModes().join(', ')}`);\n }\n\n return modeFactory();\n }\n\n /**\n * Get list of available initialization modes\n */\n getAvailableModes(): InitMode[] {\n return Array.from(this.modes.keys());\n }\n\n /**\n * Get mode descriptions\n */\n getModeDescriptions(): Record<InitMode, string> {\n const descriptions: Partial<Record<InitMode, string>> = {};\n\n for (const mode of this.getAvailableModes()) {\n try {\n const modeInstance = this.createMode(mode);\n descriptions[mode] = modeInstance.getDescription();\n } catch (error) {\n descriptions[mode] = `Error loading mode: ${error}`;\n }\n }\n\n return descriptions as Record<InitMode, string>;\n }\n\n /**\n * Validate if a mode exists and is functional\n */\n validateMode(mode: InitMode): boolean {\n try {\n const modeInstance = this.createMode(mode);\n return modeInstance.validate();\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Get required components for a specific mode\n */\n getRequiredComponents(mode: InitMode): string[] {\n try {\n const modeInstance = this.createMode(mode);\n return modeInstance.getRequiredComponents();\n } catch (error) {\n return [];\n }\n }\n\n /**\n * Register a custom initialization mode\n */\n registerCustomMode(mode: InitMode, factory: () => IInitMode): void {\n this.modes.set(mode, factory);\n }\n\n /**\n * Remove a registered mode\n */\n unregisterMode(mode: InitMode): boolean {\n return this.modes.delete(mode);\n }\n}"],"names":["StandardInit","GitHubInit","HiveMindInit","SparcInit","NeuralInit","EnterpriseInit","ModeFactory","modes","Map","registerModes","set","createMode","mode","modeFactory","get","Error","getAvailableModes","join","Array","from","keys","getModeDescriptions","descriptions","modeInstance","getDescription","error","validateMode","validate","getRequiredComponents","registerCustomMode","factory","unregisterMode","delete"],"mappings":"AAMA,SAASA,YAAY,QAAQ,2BAA2B;AACxD,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SAASC,YAAY,QAAQ,2BAA2B;AACxD,SAASC,SAAS,QAAQ,wBAAwB;AAClD,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SAASC,cAAc,QAAQ,6BAA6B;AAE5D,OAAO,MAAMC;IACHC,QAAwC,IAAIC,MAAM;IAE1D,aAAc;QACZ,IAAI,CAACC,aAAa;IACpB;IAKQA,gBAAsB;QAC5B,IAAI,CAACF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,UAAU,CAACC;YACrC,OAAOW,aAAaK,qBAAqB;QAC3C,EAAE,OAAOH,OAAO;YACd,OAAO,EAAE;QACX;IACF;IAKAI,mBAAmBjB,IAAc,EAAEkB,OAAwB,EAAQ;QACjE,IAAI,CAACvB,KAAK,CAACG,GAAG,CAACE,MAAMkB;IACvB;IAKAC,eAAenB,IAAc,EAAW;QACtC,OAAO,IAAI,CAACL,KAAK,CAACyB,MAAM,CAACpB;IAC3B;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/core/TopologyManager.js b/dist-cjs/src/core/TopologyManager.jsnew file mode 100644index 0000000000..023ddcaead--- /dev/null+++ b/dist-cjs/src/core/TopologyManager.js@@ -0,0 +1,331 @@+export class TopologyManager {+ database;+ currentTopology = null;+ agents = [];+ connections = [];+ constructor(database){+ this.database = database;+ }+ async configure(topologyType, agents = []) {+ this.agents = agents;+ this.currentTopology = this.createTopology(topologyType);+ const network = await this.currentTopology.configure(agents);+ this.connections = network.connections;+ await this.database.store('topology', {+ type: topologyType,+ agentCount: agents.length,+ connectionCount: network.connections.length,+ timestamp: new Date().toISOString()+ }, 'system');+ return network;+ }+ createTopology(type) {+ switch(type){+ case 'mesh':+ return new MeshTopology();+ case 'hierarchical':+ return new HierarchicalTopology();+ case 'ring':+ return new RingTopology();+ case 'star':+ return new StarTopology();+ default:+ throw new Error(`Unknown topology type: ${type}`);+ }+ }+ async addAgent(agent) {+ if (!this.currentTopology) {+ throw new Error('Topology not configured');+ }+ this.agents.push(agent);+ const network = await this.currentTopology.configure(this.agents);+ this.connections = network.connections;+ await this.database.store(`agent:${agent.id}`, agent, 'agents');+ }+ async removeAgent(agentId) {+ if (!this.currentTopology) {+ throw new Error('Topology not configured');+ }+ this.agents = this.agents.filter((agent)=>agent.id !== agentId);+ const network = await this.currentTopology.configure(this.agents);+ this.connections = network.connections;+ await this.database.delete(`agent:${agentId}`, 'agents');+ }+ async optimize() {+ if (!this.currentTopology) {+ throw new Error('Topology not configured');+ }+ const optimization = await this.currentTopology.optimize();+ for (const change of optimization.changes){+ switch(change.action){+ case 'add-connection':+ this.connections.push(change.connection);+ break;+ case 'remove-connection':+ this.connections = this.connections.filter((conn)=>!(conn.from === change.connection.from && conn.to === change.connection.to));+ break;+ case 'modify-weight':+ const existing = this.connections.find((conn)=>conn.from === change.connection.from && conn.to === change.connection.to);+ if (existing) {+ existing.weight = change.connection.weight;+ }+ break;+ }+ }+ return optimization;+ }+ async getTopologyInfo() {+ if (!this.currentTopology) {+ throw new Error('Topology not configured');+ }+ const metrics = this.calculateMetrics();+ return {+ type: this.currentTopology.getType(),+ agents: this.agents,+ connections: this.connections,+ metrics+ };+ }+ calculateMetrics() {+ const totalAgents = this.agents.length;+ const totalConnections = this.connections.length;+ const latencies = this.connections.map((conn)=>conn.latency || 0).filter((latency)=>latency > 0);+ const averageLatency = latencies.length > 0 ? latencies.reduce((sum, lat)=>sum + lat, 0) / latencies.length : 0;+ const throughput = totalConnections > 0 ? totalAgents / totalConnections : 0;+ const activeAgents = this.agents.filter((agent)=>agent.status === 'active').length;+ const reliability = totalAgents > 0 ? activeAgents / totalAgents : 0;+ return {+ totalAgents,+ totalConnections,+ averageLatency,+ throughput,+ reliability+ };+ }+ getConnectedAgents(agentId) {+ const connectedIds = new Set();+ this.connections.forEach((conn)=>{+ if (conn.from === agentId) {+ connectedIds.add(conn.to);+ } else if (conn.to === agentId) {+ connectedIds.add(conn.from);+ }+ });+ return this.agents.filter((agent)=>connectedIds.has(agent.id));+ }+ areConnected(agentId1, agentId2) {+ return this.connections.some((conn)=>conn.from === agentId1 && conn.to === agentId2 || conn.from === agentId2 && conn.to === agentId1);+ }+}+let MeshTopology = class MeshTopology {+ getType() {+ return 'mesh';+ }+ async configure(agents) {+ const connections = [];+ for(let i = 0; i < agents.length; i++){+ for(let j = i + 1; j < agents.length; j++){+ connections.push({+ from: agents[i].id,+ to: agents[j].id,+ type: 'direct',+ weight: 1.0,+ latency: Math.random() * 10 + 5+ });+ }+ }+ return {+ topology: 'mesh',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ async optimize() {+ return {+ type: 'latency',+ changes: [],+ expectedImprovement: 0+ };+ }+ getConnections() {+ return [];+ }+ calculateMetrics(agents, connections) {+ return {+ totalAgents: agents.length,+ totalConnections: connections.length,+ averageLatency: connections.reduce((sum, conn)=>sum + (conn.latency || 0), 0) / connections.length || 0,+ throughput: agents.length,+ reliability: 0.95+ };+ }+};+let HierarchicalTopology = class HierarchicalTopology {+ getType() {+ return 'hierarchical';+ }+ async configure(agents) {+ const connections = [];+ if (agents.length === 0) {+ return {+ topology: 'hierarchical',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ const coordinators = agents.filter((_, index)=>index % 4 === 0);+ const workers = agents.filter((_, index)=>index % 4 !== 0);+ workers.forEach((worker, index)=>{+ const coordinatorIndex = Math.floor(index / 3);+ const coordinator = coordinators[coordinatorIndex] || coordinators[0];+ connections.push({+ from: worker.id,+ to: coordinator.id,+ type: 'direct',+ weight: 1.0,+ latency: Math.random() * 5 + 2+ });+ });+ for(let i = 0; i < coordinators.length - 1; i++){+ connections.push({+ from: coordinators[i].id,+ to: coordinators[i + 1].id,+ type: 'relay',+ weight: 2.0,+ latency: Math.random() * 8 + 3+ });+ }+ return {+ topology: 'hierarchical',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ async optimize() {+ return {+ type: 'throughput',+ changes: [],+ expectedImprovement: 0+ };+ }+ getConnections() {+ return [];+ }+ calculateMetrics(agents, connections) {+ return {+ totalAgents: agents.length,+ totalConnections: connections.length,+ averageLatency: connections.reduce((sum, conn)=>sum + (conn.latency || 0), 0) / connections.length || 0,+ throughput: Math.sqrt(agents.length),+ reliability: 0.85+ };+ }+};+let RingTopology = class RingTopology {+ getType() {+ return 'ring';+ }+ async configure(agents) {+ const connections = [];+ if (agents.length < 2) {+ return {+ topology: 'ring',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ for(let i = 0; i < agents.length; i++){+ const nextIndex = (i + 1) % agents.length;+ connections.push({+ from: agents[i].id,+ to: agents[nextIndex].id,+ type: 'direct',+ weight: 1.0,+ latency: Math.random() * 6 + 3+ });+ }+ return {+ topology: 'ring',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ async optimize() {+ return {+ type: 'reliability',+ changes: [],+ expectedImprovement: 0+ };+ }+ getConnections() {+ return [];+ }+ calculateMetrics(agents, connections) {+ return {+ totalAgents: agents.length,+ totalConnections: connections.length,+ averageLatency: connections.reduce((sum, conn)=>sum + (conn.latency || 0), 0) / connections.length || 0,+ throughput: agents.length * 0.7,+ reliability: 0.75+ };+ }+};+let StarTopology = class StarTopology {+ getType() {+ return 'star';+ }+ async configure(agents) {+ const connections = [];+ if (agents.length === 0) {+ return {+ topology: 'star',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ const hub = agents[0];+ const spokes = agents.slice(1);+ spokes.forEach((spoke)=>{+ connections.push({+ from: spoke.id,+ to: hub.id,+ type: 'direct',+ weight: 1.0,+ latency: Math.random() * 4 + 2+ });+ });+ return {+ topology: 'star',+ agents,+ connections,+ metrics: this.calculateMetrics(agents, connections)+ };+ }+ async optimize() {+ return {+ type: 'latency',+ changes: [],+ expectedImprovement: 0+ };+ }+ getConnections() {+ return [];+ }+ calculateMetrics(agents, connections) {+ return {+ totalAgents: agents.length,+ totalConnections: connections.length,+ averageLatency: connections.reduce((sum, conn)=>sum + (conn.latency || 0), 0) / connections.length || 0,+ throughput: Math.min(agents.length, 10),+ reliability: 0.70+ };+ }+};++//# sourceMappingURL=TopologyManager.js.map\ No newline at end of filediff --git a/dist-cjs/src/core/TopologyManager.js.map b/dist-cjs/src/core/TopologyManager.js.mapnew file mode 100644index 0000000000..ca4c0a4aa0--- /dev/null+++ b/dist-cjs/src/core/TopologyManager.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/core/TopologyManager.ts"],"sourcesContent":["/**\n * TopologyManager - Manages swarm topology (mesh, hierarchical, ring, star)\n * Implements network topology patterns for agent coordination\n */\n\nimport { IDatabaseProvider, ITopology, Agent, Network, Connection, Optimization, TopologyType, NetworkMetrics } from '../types/interfaces.js';\n\nexport class TopologyManager {\n private currentTopology: ITopology | null = null;\n private agents: Agent[] = [];\n private connections: Connection[] = [];\n\n constructor(private database: IDatabaseProvider) {}\n\n /**\n * Configure the swarm topology\n */\n async configure(topologyType: TopologyType, agents: Agent[] = []): Promise<Network> {\n this.agents = agents;\n this.currentTopology = this.createTopology(topologyType);\n\n const network = await this.currentTopology.configure(agents);\n this.connections = network.connections;\n\n // Persist topology configuration\n await this.database.store('topology', {\n type: topologyType,\n agentCount: agents.length,\n connectionCount: network.connections.length,\n timestamp: new Date().toISOString()\n }, 'system');\n\n return network;\n }\n\n /**\n * Create specific topology implementation\n */\n private createTopology(type: TopologyType): ITopology {\n switch (type) {\n case 'mesh':\n return new MeshTopology();\n case 'hierarchical':\n return new HierarchicalTopology();\n case 'ring':\n return new RingTopology();\n case 'star':\n return new StarTopology();\n default:\n throw new Error(`Unknown topology type: ${type}`);\n }\n }\n\n /**\n * Add agent to topology\n */\n async addAgent(agent: Agent): Promise<void> {\n if (!this.currentTopology) {\n throw new Error('Topology not configured');\n }\n\n this.agents.push(agent);\n const network = await this.currentTopology.configure(this.agents);\n this.connections = network.connections;\n\n await this.database.store(`agent:${agent.id}`, agent, 'agents');\n }\n\n /**\n * Remove agent from topology\n */\n async removeAgent(agentId: string): Promise<void> {\n if (!this.currentTopology) {\n throw new Error('Topology not configured');\n }\n\n this.agents = this.agents.filter(agent => agent.id !== agentId);\n const network = await this.currentTopology.configure(this.agents);\n this.connections = network.connections;\n\n await this.database.delete(`agent:${agentId}`, 'agents');\n }\n\n /**\n * Optimize current topology\n */\n async optimize(): Promise<Optimization> {\n if (!this.currentTopology) {\n throw new Error('Topology not configured');\n }\n\n const optimization = await this.currentTopology.optimize();\n\n // Apply optimization changes\n for (const change of optimization.changes) {\n switch (change.action) {\n case 'add-connection':\n this.connections.push(change.connection);\n break;\n case 'remove-connection':\n this.connections = this.connections.filter(conn =>\n !(conn.from === change.connection.from && conn.to === change.connection.to)\n );\n break;\n case 'modify-weight':\n const existing = this.connections.find(conn =>\n conn.from === change.connection.from && conn.to === change.connection.to\n );\n if (existing) {\n existing.weight = change.connection.weight;\n }\n break;\n }\n }\n\n return optimization;\n }\n\n /**\n * Get current topology information\n */\n async getTopologyInfo(): Promise<{\n type: TopologyType;\n agents: Agent[];\n connections: Connection[];\n metrics: NetworkMetrics;\n }> {\n if (!this.currentTopology) {\n throw new Error('Topology not configured');\n }\n\n const metrics = this.calculateMetrics();\n\n return {\n type: this.currentTopology.getType(),\n agents: this.agents,\n connections: this.connections,\n metrics\n };\n }\n\n /**\n * Calculate network metrics\n */\n private calculateMetrics(): NetworkMetrics {\n const totalAgents = this.agents.length;\n const totalConnections = this.connections.length;\n\n // Calculate average latency\n const latencies = this.connections\n .map(conn => conn.latency || 0)\n .filter(latency => latency > 0);\n const averageLatency = latencies.length > 0\n ? latencies.reduce((sum, lat) => sum + lat, 0) / latencies.length\n : 0;\n\n // Estimate throughput based on connections\n const throughput = totalConnections > 0 ? totalAgents / totalConnections : 0;\n\n // Calculate reliability (percentage of active agents)\n const activeAgents = this.agents.filter(agent => agent.status === 'active').length;\n const reliability = totalAgents > 0 ? activeAgents / totalAgents : 0;\n\n return {\n totalAgents,\n totalConnections,\n averageLatency,\n throughput,\n reliability\n };\n }\n\n /**\n * Get agents connected to a specific agent\n */\n getConnectedAgents(agentId: string): Agent[] {\n const connectedIds = new Set<string>();\n\n this.connections.forEach(conn => {\n if (conn.from === agentId) {\n connectedIds.add(conn.to);\n } else if (conn.to === agentId) {\n connectedIds.add(conn.from);\n }\n });\n\n return this.agents.filter(agent => connectedIds.has(agent.id));\n }\n\n /**\n * Check if two agents are connected\n */\n areConnected(agentId1: string, agentId2: string): boolean {\n return this.connections.some(conn =>\n (conn.from === agentId1 && conn.to === agentId2) ||\n (conn.from === agentId2 && conn.to === agentId1)\n );\n }\n}\n\n/**\n * Mesh Topology - All agents connected to all others\n */\nclass MeshTopology implements ITopology {\n getType(): TopologyType {\n return 'mesh';\n }\n\n async configure(agents: Agent[]): Promise<Network> {\n const connections: Connection[] = [];\n\n // Create connections between all pairs\n for (let i = 0; i < agents.length; i++) {\n for (let j = i + 1; j < agents.length; j++) {\n connections.push({\n from: agents[i].id,\n to: agents[j].id,\n type: 'direct',\n weight: 1.0,\n latency: Math.random() * 10 + 5 // 5-15ms simulated latency\n });\n }\n }\n\n return {\n topology: 'mesh',\n agents,\n connections,\n metrics: this.calculateMetrics(agents, connections)\n };\n }\n\n async optimize(): Promise<Optimization> {\n // For mesh topology, optimization might involve removing redundant connections\n return {\n type: 'latency',\n changes: [],\n expectedImprovement: 0\n };\n }\n\n getConnections(): Connection[] {\n return [];\n }\n\n private calculateMetrics(agents: Agent[], connections: Connection[]): NetworkMetrics {\n return {\n totalAgents: agents.length,\n totalConnections: connections.length,\n averageLatency: connections.reduce((sum, conn) => sum + (conn.latency || 0), 0) / connections.length || 0,\n throughput: agents.length,\n reliability: 0.95 // High reliability for mesh\n };\n }\n}\n\n/**\n * Hierarchical Topology - Tree-like structure with coordinators\n */\nclass HierarchicalTopology implements ITopology {\n getType(): TopologyType {\n return 'hierarchical';\n }\n\n async configure(agents: Agent[]): Promise<Network> {\n const connections: Connection[] = [];\n\n if (agents.length === 0) {\n return { topology: 'hierarchical', agents, connections, metrics: this.calculateMetrics(agents, connections) };\n }\n\n // Select coordinators (every 3-4 agents)\n const coordinators = agents.filter((_, index) => index % 4 === 0);\n const workers = agents.filter((_, index) => index % 4 !== 0);\n\n // Connect workers to nearest coordinator\n workers.forEach((worker, index) => {\n const coordinatorIndex = Math.floor(index / 3);\n const coordinator = coordinators[coordinatorIndex] || coordinators[0];\n\n connections.push({\n from: worker.id,\n to: coordinator.id,\n type: 'direct',\n weight: 1.0,\n latency: Math.random() * 5 + 2\n });\n });\n\n // Connect coordinators in a chain\n for (let i = 0; i < coordinators.length - 1; i++) {\n connections.push({\n from: coordinators[i].id,\n to: coordinators[i + 1].id,\n type: 'relay',\n weight: 2.0,\n latency: Math.random() * 8 + 3\n });\n }\n\n return {\n topology: 'hierarchical',\n agents,\n connections,\n metrics: this.calculateMetrics(agents, connections)\n };\n }\n\n async optimize(): Promise<Optimization> {\n return {\n type: 'throughput',\n changes: [],\n expectedImprovement: 0\n };\n }\n\n getConnections(): Connection[] {\n return [];\n }\n\n private calculateMetrics(agents: Agent[], connections: Connection[]): NetworkMetrics {\n return {\n totalAgents: agents.length,\n totalConnections: connections.length,\n averageLatency: connections.reduce((sum, conn) => sum + (conn.latency || 0), 0) / connections.length || 0,\n throughput: Math.sqrt(agents.length), // Logarithmic scaling\n reliability: 0.85 // Good reliability\n };\n }\n}\n\n/**\n * Ring Topology - Agents connected in a circular pattern\n */\nclass RingTopology implements ITopology {\n getType(): TopologyType {\n return 'ring';\n }\n\n async configure(agents: Agent[]): Promise<Network> {\n const connections: Connection[] = [];\n\n if (agents.length < 2) {\n return { topology: 'ring', agents, connections, metrics: this.calculateMetrics(agents, connections) };\n }\n\n // Connect each agent to the next (and last to first)\n for (let i = 0; i < agents.length; i++) {\n const nextIndex = (i + 1) % agents.length;\n connections.push({\n from: agents[i].id,\n to: agents[nextIndex].id,\n type: 'direct',\n weight: 1.0,\n latency: Math.random() * 6 + 3\n });\n }\n\n return {\n topology: 'ring',\n agents,\n connections,\n metrics: this.calculateMetrics(agents, connections)\n };\n }\n\n async optimize(): Promise<Optimization> {\n return {\n type: 'reliability',\n changes: [],\n expectedImprovement: 0\n };\n }\n\n getConnections(): Connection[] {\n return [];\n }\n\n private calculateMetrics(agents: Agent[], connections: Connection[]): NetworkMetrics {\n return {\n totalAgents: agents.length,\n totalConnections: connections.length,\n averageLatency: connections.reduce((sum, conn) => sum + (conn.latency || 0), 0) / connections.length || 0,\n throughput: agents.length * 0.7, // Reduced due to ring bottlenecks\n reliability: 0.75 // Lower reliability due to single points of failure\n };\n }\n}\n\n/**\n * Star Topology - All agents connected to a central hub\n */\nclass StarTopology implements ITopology {\n getType(): TopologyType {\n return 'star';\n }\n\n async configure(agents: Agent[]): Promise<Network> {\n const connections: Connection[] = [];\n\n if (agents.length === 0) {\n return { topology: 'star', agents, connections, metrics: this.calculateMetrics(agents, connections) };\n }\n\n // First agent becomes the hub\n const hub = agents[0];\n const spokes = agents.slice(1);\n\n // Connect all spokes to hub\n spokes.forEach(spoke => {\n connections.push({\n from: spoke.id,\n to: hub.id,\n type: 'direct',\n weight: 1.0,\n latency: Math.random() * 4 + 2\n });\n });\n\n return {\n topology: 'star',\n agents,\n connections,\n metrics: this.calculateMetrics(agents, connections)\n };\n }\n\n async optimize(): Promise<Optimization> {\n return {\n type: 'latency',\n changes: [],\n expectedImprovement: 0\n };\n }\n\n getConnections(): Connection[] {\n return [];\n }\n\n private calculateMetrics(agents: Agent[], connections: Connection[]): NetworkMetrics {\n return {\n totalAgents: agents.length,\n totalConnections: connections.length,\n averageLatency: connections.reduce((sum, conn) => sum + (conn.latency || 0), 0) / connections.length || 0,\n throughput: Math.min(agents.length, 10), // Limited by hub capacity\n reliability: 0.70 // Lower due to single point of failure\n };\n }\n}"],"names":["TopologyManager","currentTopology","agents","connections","database","configure","topologyType","createTopology","network","store","type","agentCount","length","connectionCount","timestamp","Date","toISOString","MeshTopology","HierarchicalTopology","RingTopology","StarTopology","Error","addAgent","agent","push","id","removeAgent","agentId","filter","delete","optimize","optimization","change","changes","action","connection","conn","from","to","existing","find","weight","getTopologyInfo","metrics","calculateMetrics","getType","totalAgents","totalConnections","latencies","map","latency","averageLatency","reduce","sum","lat","throughput","activeAgents","status","reliability","getConnectedAgents","connectedIds","Set","forEach","add","has","areConnected","agentId1","agentId2","some","i","j","Math","random","topology","expectedImprovement","getConnections","coordinators","_","index","workers","worker","coordinatorIndex","floor","coordinator","sqrt","nextIndex","hub","spokes","slice","spoke","min"],"mappings":"AAOA,OAAO,MAAM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AAqB;QACvB;IACF;IAEAC,iBAA+B;QAC7B,OAAO,EAAE;IACX;IAEQ/B,iBAAiB1C,MAAe,EAAEC,WAAyB,EAAkB;QACnF,OAAO;YACL2C,aAAa5C,OAAOU,MAAM;YAC1BmC,kBAAkB5C,YAAYS,MAAM;YACpCuC,gBAAgBhD,YAAYiD,MAAM,CAAC,CAACC,KAAKjB,OAASiB,MAAOjB,CAAAA,KAAKc,OAAO,IAAI,CAAA,GAAI,KAAK/C,YAAYS,MAAM,IAAI;YACxG2C,YAAYgB,KAAKmB,GAAG,CAACxF,OAAOU,MAAM,EAAE;YACpC8C,aAAa;QACf;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/EnterpriseInit.js b/dist-cjs/src/modes/EnterpriseInit.jsnew file mode 100644index 0000000000..6e01c40a21--- /dev/null+++ b/dist-cjs/src/modes/EnterpriseInit.js@@ -0,0 +1,306 @@+export class EnterpriseInit {+ getDescription() {+ return 'Enterprise initialization with authentication, encryption, audit trails, and compliance features';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry',+ 'ConsensusEngine',+ 'MetricsCollector',+ 'MCPIntegrator'+ ];+ }+ validate() {+ const hasSecurityConfig = !!(process.env.ENTERPRISE_SECRET_KEY || process.env.ENCRYPTION_KEY);+ const hasAuditConfig = !!(process.env.AUDIT_ENABLED || process.env.COMPLIANCE_MODE);+ return hasSecurityConfig || hasAuditConfig;+ }+ async initialize(config) {+ const components = [];+ try {+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('star', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.consensusEngine) {+ await config.consensusEngine.setAlgorithm('byzantine');+ components.push('ConsensusEngine');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'security-management',+ 'authentication',+ 'authorization',+ 'encryption'+ ],+ metadata: {+ role: 'security-manager',+ clearanceLevel: 'high',+ specialization: 'security',+ enterpriseAgent: true+ }+ });+ await config.agentRegistry.spawn('reviewer', {+ capabilities: [+ 'compliance-checking',+ 'audit-trail',+ 'regulatory-compliance',+ 'policy-enforcement'+ ],+ metadata: {+ role: 'compliance-officer',+ clearanceLevel: 'high',+ specialization: 'compliance',+ enterpriseAgent: true+ }+ });+ await config.agentRegistry.spawn('optimizer', {+ capabilities: [+ 'resource-allocation',+ 'capacity-planning',+ 'cost-optimization',+ 'scaling'+ ],+ metadata: {+ role: 'resource-manager',+ clearanceLevel: 'medium',+ specialization: 'resource-management',+ enterpriseAgent: true+ }+ });+ await config.agentRegistry.spawn('analyst', {+ capabilities: [+ 'audit-logging',+ 'security-monitoring',+ 'anomaly-detection',+ 'forensics'+ ],+ metadata: {+ role: 'audit-agent',+ clearanceLevel: 'high',+ specialization: 'audit',+ enterpriseAgent: true+ }+ });+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'enterprise-orchestration',+ 'workflow-management',+ 'integration',+ 'governance'+ ],+ metadata: {+ role: 'enterprise-coordinator',+ clearanceLevel: 'high',+ specialization: 'enterprise-orchestration',+ enterpriseAgent: true,+ authority: 'enterprise'+ }+ });+ components.push('EnterpriseAgents');+ }+ if (config.mcpIntegrator) {+ await config.mcpIntegrator.initialize();+ const enterpriseStatus = await config.mcpIntegrator.executeCommand({+ tool: 'flow-nexus',+ function: 'auth_init',+ parameters: {+ mode: 'service'+ }+ });+ if (enterpriseStatus.success) {+ components.push('EnterpriseMCP');+ }+ }+ if (config.databaseManager) {+ await config.databaseManager.store('enterprise-config', {+ initialized: true,+ mode: 'enterprise',+ securityLevel: 'high',+ encryptionEnabled: true,+ auditEnabled: true,+ complianceMode: process.env.COMPLIANCE_MODE || 'standard',+ features: [+ 'authentication',+ 'authorization',+ 'encryption',+ 'audit-trail',+ 'compliance',+ 'monitoring',+ 'governance'+ ],+ timestamp: new Date().toISOString()+ }, 'enterprise');+ await config.databaseManager.store('security-policies', {+ authentication: {+ required: true,+ method: 'multi-factor',+ sessionTimeout: 3600,+ passwordPolicy: {+ minLength: 12,+ requireSpecialChars: true,+ requireNumbers: true,+ maxAge: 90+ }+ },+ authorization: {+ model: 'role-based',+ principle: 'least-privilege',+ roles: [+ 'admin',+ 'operator',+ 'viewer',+ 'auditor'+ ]+ },+ encryption: {+ algorithm: 'AES-256',+ keyRotation: 'monthly',+ transitEncryption: true,+ restEncryption: true+ }+ }, 'enterprise');+ await config.databaseManager.store('audit-config', {+ enabled: true,+ logLevel: 'comprehensive',+ retention: '7-years',+ compliance: [+ 'SOX',+ 'GDPR',+ 'HIPAA'+ ],+ monitoring: {+ realTime: true,+ alerting: true,+ anomalyDetection: true+ }+ }, 'enterprise');+ await config.databaseManager.store('compliance-frameworks', {+ 'SOX': {+ requirements: [+ 'financial-controls',+ 'audit-trails',+ 'segregation-of-duties'+ ],+ monitoring: true,+ reporting: 'quarterly'+ },+ 'GDPR': {+ requirements: [+ 'data-protection',+ 'privacy-by-design',+ 'right-to-deletion'+ ],+ monitoring: true,+ reporting: 'incident-based'+ },+ 'HIPAA': {+ requirements: [+ 'data-encryption',+ 'access-controls',+ 'audit-logs'+ ],+ monitoring: true,+ reporting: 'annual'+ }+ }, 'enterprise');+ components.push('EnterpriseMemory');+ }+ if (config.metricsCollector) {+ await config.metricsCollector.initialize();+ await config.metricsCollector.recordSystemMetrics({+ cpuUsage: 35,+ memoryUsage: 75,+ diskUsage: 45,+ networkLatency: 20,+ activeConnections: 8+ });+ await config.metricsCollector.recordAgentMetrics('security-manager', {+ tasksCompleted: 0,+ successRate: 1.0,+ averageResponseTime: 500,+ resourceUtilization: {+ memory: 512,+ cpu: 2,+ storage: 200,+ network: 20+ }+ });+ components.push('EnterpriseMetrics');+ }+ if (config.databaseManager) {+ await config.databaseManager.store('governance-rules', {+ dataGovernance: {+ classification: [+ 'public',+ 'internal',+ 'confidential',+ 'restricted'+ ],+ retention: {+ default: '7-years',+ financial: '10-years'+ },+ access: 'role-based'+ },+ operationalGovernance: {+ approvalWorkflows: true,+ changeManagement: true,+ incidentResponse: true+ },+ riskManagement: {+ riskAssessment: 'quarterly',+ threatModeling: true,+ vulnerabilityScanning: true+ }+ }, 'enterprise');+ components.push('EnterpriseGovernance');+ }+ return {+ success: true,+ mode: 'enterprise',+ components,+ topology: 'star',+ message: 'Enterprise initialization completed successfully - Security and compliance active',+ metadata: {+ securityLevel: 'high',+ encryptionEnabled: true,+ auditEnabled: true,+ complianceFrameworks: [+ 'SOX',+ 'GDPR',+ 'HIPAA'+ ],+ authenticationRequired: true,+ governanceActive: true,+ enterpriseFeatures: components.length+ }+ };+ } catch (error) {+ return {+ success: false,+ mode: 'enterprise',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'Enterprise initialization failed'+ };+ }+ }+}++//# sourceMappingURL=EnterpriseInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/EnterpriseInit.js.map b/dist-cjs/src/modes/EnterpriseInit.js.mapnew file mode 100644index 0000000000..34842c8eeb--- /dev/null+++ b/dist-cjs/src/modes/EnterpriseInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/EnterpriseInit.ts"],"sourcesContent":["/**\n * EnterpriseInit - Enterprise initialization mode\n * Sets up enterprise-grade features with security, compliance, and scalability\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class EnterpriseInit implements IInitMode {\n getDescription(): string {\n return 'Enterprise initialization with authentication, encryption, audit trails, and compliance features';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry', 'ConsensusEngine', 'MetricsCollector', 'MCPIntegrator'];\n }\n\n validate(): boolean {\n // Check for enterprise requirements\n const hasSecurityConfig = !!(process.env.ENTERPRISE_SECRET_KEY || process.env.ENCRYPTION_KEY);\n const hasAuditConfig = !!(process.env.AUDIT_ENABLED || process.env.COMPLIANCE_MODE);\n\n return hasSecurityConfig || hasAuditConfig; // At least one enterprise feature\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Basic initialization\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Use star topology for enterprise (centralized control)\n if (config.topologyManager) {\n await config.topologyManager.configure('star', []);\n components.push('TopologyManager');\n }\n\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Initialize Byzantine consensus for enterprise security\n if (config.consensusEngine) {\n await config.consensusEngine.setAlgorithm('byzantine');\n components.push('ConsensusEngine');\n }\n\n // Spawn enterprise-specific agents\n if (config.agentRegistry) {\n // Security Manager\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['security-management', 'authentication', 'authorization', 'encryption'],\n metadata: {\n role: 'security-manager',\n clearanceLevel: 'high',\n specialization: 'security',\n enterpriseAgent: true\n }\n });\n\n // Compliance Officer\n await config.agentRegistry.spawn('reviewer', {\n capabilities: ['compliance-checking', 'audit-trail', 'regulatory-compliance', 'policy-enforcement'],\n metadata: {\n role: 'compliance-officer',\n clearanceLevel: 'high',\n specialization: 'compliance',\n enterpriseAgent: true\n }\n });\n\n // Resource Manager\n await config.agentRegistry.spawn('optimizer', {\n capabilities: ['resource-allocation', 'capacity-planning', 'cost-optimization', 'scaling'],\n metadata: {\n role: 'resource-manager',\n clearanceLevel: 'medium',\n specialization: 'resource-management',\n enterpriseAgent: true\n }\n });\n\n // Audit Agent\n await config.agentRegistry.spawn('analyst', {\n capabilities: ['audit-logging', 'security-monitoring', 'anomaly-detection', 'forensics'],\n metadata: {\n role: 'audit-agent',\n clearanceLevel: 'high',\n specialization: 'audit',\n enterpriseAgent: true\n }\n });\n\n // Enterprise Coordinator\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['enterprise-orchestration', 'workflow-management', 'integration', 'governance'],\n metadata: {\n role: 'enterprise-coordinator',\n clearanceLevel: 'high',\n specialization: 'enterprise-orchestration',\n enterpriseAgent: true,\n authority: 'enterprise'\n }\n });\n\n components.push('EnterpriseAgents');\n }\n\n // Initialize enterprise MCP integration\n if (config.mcpIntegrator) {\n await config.mcpIntegrator.initialize();\n\n // Test enterprise MCP functions\n const enterpriseStatus = await config.mcpIntegrator.executeCommand({\n tool: 'flow-nexus',\n function: 'auth_init',\n parameters: { mode: 'service' }\n });\n\n if (enterpriseStatus.success) {\n components.push('EnterpriseMCP');\n }\n }\n\n // Set up enterprise memory structures\n if (config.databaseManager) {\n await config.databaseManager.store('enterprise-config', {\n initialized: true,\n mode: 'enterprise',\n securityLevel: 'high',\n encryptionEnabled: true,\n auditEnabled: true,\n complianceMode: process.env.COMPLIANCE_MODE || 'standard',\n features: [\n 'authentication',\n 'authorization',\n 'encryption',\n 'audit-trail',\n 'compliance',\n 'monitoring',\n 'governance'\n ],\n timestamp: new Date().toISOString()\n }, 'enterprise');\n\n // Initialize security policies\n await config.databaseManager.store('security-policies', {\n authentication: {\n required: true,\n method: 'multi-factor',\n sessionTimeout: 3600,\n passwordPolicy: {\n minLength: 12,\n requireSpecialChars: true,\n requireNumbers: true,\n maxAge: 90\n }\n },\n authorization: {\n model: 'role-based',\n principle: 'least-privilege',\n roles: ['admin', 'operator', 'viewer', 'auditor']\n },\n encryption: {\n algorithm: 'AES-256',\n keyRotation: 'monthly',\n transitEncryption: true,\n restEncryption: true\n }\n }, 'enterprise');\n\n // Initialize audit configuration\n await config.databaseManager.store('audit-config', {\n enabled: true,\n logLevel: 'comprehensive',\n retention: '7-years',\n compliance: ['SOX', 'GDPR', 'HIPAA'],\n monitoring: {\n realTime: true,\n alerting: true,\n anomalyDetection: true\n }\n }, 'enterprise');\n\n // Initialize compliance frameworks\n await config.databaseManager.store('compliance-frameworks', {\n 'SOX': {\n requirements: ['financial-controls', 'audit-trails', 'segregation-of-duties'],\n monitoring: true,\n reporting: 'quarterly'\n },\n 'GDPR': {\n requirements: ['data-protection', 'privacy-by-design', 'right-to-deletion'],\n monitoring: true,\n reporting: 'incident-based'\n },\n 'HIPAA': {\n requirements: ['data-encryption', 'access-controls', 'audit-logs'],\n monitoring: true,\n reporting: 'annual'\n }\n }, 'enterprise');\n\n components.push('EnterpriseMemory');\n }\n\n // Initialize enterprise metrics and monitoring\n if (config.metricsCollector) {\n await config.metricsCollector.initialize();\n\n // Record enterprise initialization metrics\n await config.metricsCollector.recordSystemMetrics({\n cpuUsage: 35, // Lower due to security overhead\n memoryUsage: 75, // Higher due to enterprise features\n diskUsage: 45,\n networkLatency: 20, // Higher due to encryption\n activeConnections: 8\n });\n\n // Set up enterprise-specific metrics\n await config.metricsCollector.recordAgentMetrics('security-manager', {\n tasksCompleted: 0,\n successRate: 1.0,\n averageResponseTime: 500, // Security checks take time\n resourceUtilization: {\n memory: 512,\n cpu: 2,\n storage: 200,\n network: 20\n }\n });\n\n components.push('EnterpriseMetrics');\n }\n\n // Set up enterprise governance\n if (config.databaseManager) {\n await config.databaseManager.store('governance-rules', {\n dataGovernance: {\n classification: ['public', 'internal', 'confidential', 'restricted'],\n retention: { default: '7-years', financial: '10-years' },\n access: 'role-based'\n },\n operationalGovernance: {\n approvalWorkflows: true,\n changeManagement: true,\n incidentResponse: true\n },\n riskManagement: {\n riskAssessment: 'quarterly',\n threatModeling: true,\n vulnerabilityScanning: true\n }\n }, 'enterprise');\n\n components.push('EnterpriseGovernance');\n }\n\n return {\n success: true,\n mode: 'enterprise',\n components,\n topology: 'star',\n message: 'Enterprise initialization completed successfully - Security and compliance active',\n metadata: {\n securityLevel: 'high',\n encryptionEnabled: true,\n auditEnabled: true,\n complianceFrameworks: ['SOX', 'GDPR', 'HIPAA'],\n authenticationRequired: true,\n governanceActive: true,\n enterpriseFeatures: components.length\n }\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'enterprise',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'Enterprise initialization failed'\n };\n }\n }\n}"],"names":["EnterpriseInit","getDescription","getRequiredComponents","validate","hasSecurityConfig","process","env","ENTERPRISE_SECRET_KEY","ENCRYPTION_KEY","hasAuditConfig","AUDIT_ENABLED","COMPLIANCE_MODE","initialize","config","components","configManager","push","databaseManager","topologyManager","configure","agentRegistry","consensusEngine","setAlgorithm","spawn","capabilities","metadata","role","clearanceLevel","specialization","enterpriseAgent","authority","mcpIntegrator","enterpriseStatus","executeCommand","tool","function","parameters","mode","success","store","initialized","securityLevel","encryptionEnabled","auditEnabled","complianceMode","features","timestamp","Date","toISOString","authentication","required","method","sessionTimeout","passwordPolicy","minLength","requireSpecialChars","requireNumbers","maxAge","authorization","model","principle","roles","encryption","algorithm","keyRotation","transitEncryption","restEncryption","enabled","logLevel","retention","compliance","monitoring","realTime","alerting","anomalyDetection","requirements","reporting","metricsCollector","recordSystemMetrics","cpuUsage","memoryUsage","diskUsage","networkLatency","activeConnections","recordAgentMetrics","tasksCompleted","successRate","averageResponseTime","resourceUtilization","memory","cpu","storage","network","dataGovernance","classification","default","financial","access","operationalGovernance","approvalWorkflows","changeManagement","incidentResponse","riskManagement","riskAssessment","threatModeling","vulnerabilityScanning","topology","message","complianceFrameworks","authenticationRequired","governanceActive","enterpriseFeatures","length","error","Error","String"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;YAAiB;YAAmB;YAAoB;SAAgB;IACzI;IAEAC,WAAoB;QAElB,MAAMC,oBAAoB,CAAC,CAAEC,CAAAA,QAAQC,GAAG,CAACC,qBAAqB,IAAIF,QAAQC,GAAG,CAACE,cAAc,AAAD;QAC3F,MAAMC,iBAAiB,CAAC,CAAEJ,CAAAA,QAAQC,GAAG,CAACI,aAAa,IAAIL,QAAQC,GAAG,CAACK,eAAe,AAAD;QAEjF,OAAOP,qBAAqBK;IAC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BAEA9E,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOI,eAAe,EAAE;gBAC1B,MAAMJ,OAAOI,eAAe,CAACsB,KAAK,CAAC,oBAAoB;oBACrDsD,gBAAgB;wBACdC,gBAAgB;4BAAC;4BAAU;4BAAY;4BAAgB;yBAAa;wBACpEzB,WAAW;4BAAE0B,SAAS;4BAAWC,WAAW;wBAAW;wBACvDC,QAAQ;oBACV;oBACAC,uBAAuB;wBACrBC,mBAAmB;wBACnBC,kBAAkB;wBAClBC,kBAAkB;oBACpB;oBACAC,gBAAgB;wBACdC,gBAAgB;wBAChBC,gBAAgB;wBAChBC,uBAAuB;oBACzB;gBACF,GAAG;gBAEH3F,WAAWE,IAAI,CAAC;YAClB;YAEA,OAAO;gBACLsB,SAAS;gBACTD,MAAM;gBACNvB;gBACA4F,UAAU;gBACVC,SAAS;gBACTlF,UAAU;oBACRgB,eAAe;oBACfC,mBAAmB;oBACnBC,cAAc;oBACdiE,sBAAsB;wBAAC;wBAAO;wBAAQ;qBAAQ;oBAC9CC,wBAAwB;oBACxBC,kBAAkB;oBAClBC,oBAAoBjG,WAAWkG,MAAM;gBACvC;YACF;QAEF,EAAE,OAAOC,OAAO;YACd,OAAO;gBACL3E,SAAS;gBACTD,MAAM;gBACNvB;gBACAmG,OAAOA,iBAAiBC,QAAQD,MAAMN,OAAO,GAAGQ,OAAOF;gBACvDN,SAAS;YACX;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/GitHubInit.js b/dist-cjs/src/modes/GitHubInit.jsnew file mode 100644index 0000000000..7a3b92a016--- /dev/null+++ b/dist-cjs/src/modes/GitHubInit.js@@ -0,0 +1,145 @@+export class GitHubInit {+ getDescription() {+ return 'GitHub integration initialization with repository management, PR automation, and workflow coordination';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry',+ 'MCPIntegrator'+ ];+ }+ validate() {+ return !!(process.env.GITHUB_TOKEN || process.env.GH_TOKEN);+ }+ async initialize(config) {+ const components = [];+ try {+ if (!this.validate()) {+ throw new Error('GitHub token not found. Set GITHUB_TOKEN or GH_TOKEN environment variable.');+ }+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('hierarchical', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'github-pr',+ 'code-review',+ 'workflow-management'+ ],+ metadata: {+ specialization: 'github-pr-manager'+ }+ });+ await config.agentRegistry.spawn('analyst', {+ capabilities: [+ 'repository-analysis',+ 'code-quality',+ 'security-audit'+ ],+ metadata: {+ specialization: 'repo-analyzer'+ }+ });+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'issue-tracking',+ 'project-management',+ 'triage'+ ],+ metadata: {+ specialization: 'issue-manager'+ }+ });+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'release-management',+ 'versioning',+ 'deployment'+ ],+ metadata: {+ specialization: 'release-coordinator'+ }+ });+ await config.agentRegistry.spawn('reviewer', {+ capabilities: [+ 'code-review',+ 'security-check',+ 'best-practices'+ ],+ metadata: {+ specialization: 'code-reviewer'+ }+ });+ components.push('GitHubAgents');+ }+ if (config.mcpIntegrator) {+ await config.mcpIntegrator.initialize();+ const githubStatus = await config.mcpIntegrator.executeCommand({+ tool: 'claude-flow',+ function: 'github_repo_analyze',+ parameters: {+ repo: 'test/repo',+ analysis_type: 'code_quality'+ }+ });+ if (githubStatus.success) {+ components.push('GitHubMCP');+ }+ }+ if (config.databaseManager) {+ await config.databaseManager.store('github-config', {+ initialized: true,+ mode: 'github',+ features: [+ 'pr-automation',+ 'issue-tracking',+ 'code-review',+ 'release-management'+ ],+ timestamp: new Date().toISOString()+ }, 'github');+ components.push('GitHubMemory');+ }+ return {+ success: true,+ mode: 'github',+ components,+ topology: 'hierarchical',+ message: 'GitHub integration initialization completed successfully',+ metadata: {+ githubIntegration: true,+ prAutomation: true,+ codeReview: true,+ issueTracking: true,+ releaseManagement: true+ }+ };+ } catch (error) {+ return {+ success: false,+ mode: 'github',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'GitHub initialization failed'+ };+ }+ }+}++//# sourceMappingURL=GitHubInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/GitHubInit.js.map b/dist-cjs/src/modes/GitHubInit.js.mapnew file mode 100644index 0000000000..84958fea6c--- /dev/null+++ b/dist-cjs/src/modes/GitHubInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/GitHubInit.ts"],"sourcesContent":["/**\n * GitHubInit - GitHub integration initialization mode\n * Sets up GitHub integration with repository management and workflows\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class GitHubInit implements IInitMode {\n getDescription(): string {\n return 'GitHub integration initialization with repository management, PR automation, and workflow coordination';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry', 'MCPIntegrator'];\n }\n\n validate(): boolean {\n // Check if GitHub token is available\n return !!(process.env.GITHUB_TOKEN || process.env.GH_TOKEN);\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Validate GitHub configuration\n if (!this.validate()) {\n throw new Error('GitHub token not found. Set GITHUB_TOKEN or GH_TOKEN environment variable.');\n }\n\n // Basic initialization\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Use hierarchical topology for GitHub workflows\n if (config.topologyManager) {\n await config.topologyManager.configure('hierarchical', []);\n components.push('TopologyManager');\n }\n\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Spawn GitHub-specific agents\n if (config.agentRegistry) {\n // PR management agent\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['github-pr', 'code-review', 'workflow-management'],\n metadata: { specialization: 'github-pr-manager' }\n });\n\n // Repository analysis agent\n await config.agentRegistry.spawn('analyst', {\n capabilities: ['repository-analysis', 'code-quality', 'security-audit'],\n metadata: { specialization: 'repo-analyzer' }\n });\n\n // Issue tracking agent\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['issue-tracking', 'project-management', 'triage'],\n metadata: { specialization: 'issue-manager' }\n });\n\n // Release coordination agent\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['release-management', 'versioning', 'deployment'],\n metadata: { specialization: 'release-coordinator' }\n });\n\n // Code review agent\n await config.agentRegistry.spawn('reviewer', {\n capabilities: ['code-review', 'security-check', 'best-practices'],\n metadata: { specialization: 'code-reviewer' }\n });\n\n components.push('GitHubAgents');\n }\n\n // Initialize GitHub MCP integration\n if (config.mcpIntegrator) {\n await config.mcpIntegrator.initialize();\n\n // Test GitHub MCP functions\n const githubStatus = await config.mcpIntegrator.executeCommand({\n tool: 'claude-flow',\n function: 'github_repo_analyze',\n parameters: { repo: 'test/repo', analysis_type: 'code_quality' }\n });\n\n if (githubStatus.success) {\n components.push('GitHubMCP');\n }\n }\n\n // Set up GitHub-specific memory namespace\n if (config.databaseManager) {\n await config.databaseManager.store('github-config', {\n initialized: true,\n mode: 'github',\n features: ['pr-automation', 'issue-tracking', 'code-review', 'release-management'],\n timestamp: new Date().toISOString()\n }, 'github');\n components.push('GitHubMemory');\n }\n\n return {\n success: true,\n mode: 'github',\n components,\n topology: 'hierarchical',\n message: 'GitHub integration initialization completed successfully',\n metadata: {\n githubIntegration: true,\n prAutomation: true,\n codeReview: true,\n issueTracking: true,\n releaseManagement: true\n }\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'github',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'GitHub initialization failed'\n };\n }\n }\n}"],"names":["GitHubInit","getDescription","getRequiredComponents","validate","process","env","GITHUB_TOKEN","GH_TOKEN","initialize","config","components","Error","configManager","push","databaseManager","topologyManager","configure","agentRegistry","spawn","capabilities","metadata","specialization","mcpIntegrator","githubStatus","executeCommand","tool","function","parameters","repo","analysis_type","success","store","initialized","mode","features","timestamp","Date","toISOString","topology","message","githubIntegration","prAutomation","codeReview","issueTracking","releaseManagement","error","String"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;YAAiB;SAAgB;IAClG;IAEAC,WAAoB;QAElB,OAAO,CAAC,CAAEC,CAAAA,QAAQC,GAAG,CAACC,YAAY,IAAIF,QAAQC,GAAG,CAACE,QAAQ,AAAD;IAC3D;IAEA,MAAMC,WAAWC,MAAkB,EAAuB;QACxD,MAAMC,aAAuB,EAAE;QAE/B,IAAI;YAEF,IAAI,CAAC,IAAI,CAACP,QAAQ,IAAI;gBACpB,MAAM,IAAIQ,MAAM;YAClB;YAGA,IAAIF,OAAOG,aAAa,EAAE;gBACxBF,WAAWG,IAAI,CAAC;YAClB;YAEA,IAAIJ,OAAOK,eAAe,EAAE;gBAC1B,MAAML,OAAOK,eAAe,CAACN,UAAU;gBACvCE,WAAWG,IAAI,CAAC;YAClB;YAGA,IAAIJ,OAAOM,eAAe,EAAE;gBAC1B,MAAMN,OAAOM,eAAe,CAACC,SAAS,CAAC,gBAAgB,EAAE;gBACzDN,WAAWG,IAAI,CAAC;YAClB;YAEA,IAAIJ,OAAOQ,aAAa,EAAE;gBACxB,MAAMR,OAAOQ,aAAa,CAACT,UAAU;gBACrCE,WAAWG,IAAI,CAAC;YAClB;YAGA,IAAIJ,OAAOQ,aAAa,EAAE;gBAExB,MAAMR,OAAOQ,aAAa,CAACC,KAAK,CAAC,eAAe;oBAC9CC,cAAc;wBAAC;wBAAa;wBAAe;qBAAsB;oBACjEC,UAAU;wBAAEC,gBAAgB;o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NvB;gBACA4B,UAAU;gBACVC,SAAS;gBACTnB,UAAU;oBACRoB,mBAAmB;oBACnBC,cAAc;oBACdC,YAAY;oBACZC,eAAe;oBACfC,mBAAmB;gBACrB;YACF;QAEF,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLf,SAAS;gBACTG,MAAM;gBACNvB;gBACAmC,OAAOA,iBAAiBlC,QAAQkC,MAAMN,OAAO,GAAGO,OAAOD;gBACvDN,SAAS;YACX;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/HiveMindInit.js b/dist-cjs/src/modes/HiveMindInit.jsnew file mode 100644index 0000000000..ece1e6d30c--- /dev/null+++ b/dist-cjs/src/modes/HiveMindInit.js@@ -0,0 +1,203 @@+export class HiveMindInit {+ getDescription() {+ return 'Hive Mind initialization with collective intelligence, Queen-Worker coordination, and adaptive learning';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry',+ 'HiveMindCore',+ 'ConsensusEngine'+ ];+ }+ validate() {+ return true;+ }+ async initialize(config) {+ const components = [];+ try {+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('mesh', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.consensusEngine) {+ await config.consensusEngine.setAlgorithm('proof-of-learning');+ components.push('ConsensusEngine');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'strategic-planning',+ 'objective-setting',+ 'delegation',+ 'adaptation'+ ],+ metadata: {+ role: 'queen',+ authority: 'high',+ specialization: 'collective-intelligence'+ }+ });+ for(let i = 0; i < 2; i++){+ await config.agentRegistry.spawn('researcher', {+ capabilities: [+ 'research',+ 'analysis',+ 'data-gathering',+ 'pattern-recognition'+ ],+ metadata: {+ role: 'worker',+ specialization: 'research',+ pool: 'research-pool'+ }+ });+ }+ for(let i = 0; i < 2; i++){+ await config.agentRegistry.spawn('coder', {+ capabilities: [+ 'programming',+ 'debugging',+ 'refactoring',+ 'architecture'+ ],+ metadata: {+ role: 'worker',+ specialization: 'development',+ pool: 'development-pool'+ }+ });+ }+ await config.agentRegistry.spawn('tester', {+ capabilities: [+ 'testing',+ 'quality-assurance',+ 'validation',+ 'performance-testing'+ ],+ metadata: {+ role: 'worker',+ specialization: 'testing',+ pool: 'testing-pool'+ }+ });+ await config.agentRegistry.spawn('optimizer', {+ capabilities: [+ 'performance-optimization',+ 'resource-management',+ 'bottleneck-analysis'+ ],+ metadata: {+ role: 'worker',+ specialization: 'optimization',+ pool: 'optimization-pool'+ }+ });+ components.push('HiveMindAgents');+ }+ if (config.hiveMindCore) {+ await config.hiveMindCore.initialize();+ components.push('HiveMindCore');+ }+ if (config.databaseManager) {+ await config.databaseManager.store('hive-mind-config', {+ initialized: true,+ mode: 'hive-mind',+ queenEnabled: true,+ workerPools: [+ 'research',+ 'development',+ 'testing',+ 'optimization'+ ],+ consensusAlgorithm: 'proof-of-learning',+ adaptationRate: 0.1,+ timestamp: new Date().toISOString()+ }, 'hive-mind');+ await config.databaseManager.store('objectives', {+ active: [],+ completed: [],+ strategies: {}+ }, 'hive-mind');+ components.push('HiveMindMemory');+ }+ if (config.hiveMindCore) {+ const initialObjective = await config.hiveMindCore.setObjective({+ description: 'Establish collective intelligence coordination',+ goals: [+ {+ description: 'Optimize inter-agent communication',+ metric: 'latency',+ target: 100,+ weight: 0.3+ },+ {+ description: 'Maximize task success rate',+ metric: 'success_rate',+ target: 0.95,+ weight: 0.4+ },+ {+ description: 'Efficient resource utilization',+ metric: 'efficiency',+ target: 0.8,+ weight: 0.3+ }+ ],+ constraints: [+ {+ type: 'resource',+ description: 'Maximum 8 concurrent agents',+ value: 8+ },+ {+ type: 'time',+ description: 'Continuous operation',+ value: 'ongoing'+ }+ ],+ priority: 'high'+ });+ components.push('InitialObjective');+ }+ return {+ success: true,+ mode: 'hive-mind',+ components,+ topology: 'mesh',+ message: 'Hive Mind initialization completed successfully - Collective intelligence active',+ metadata: {+ queenEnabled: true,+ workerPools: 4,+ totalAgents: 7,+ consensusAlgorithm: 'proof-of-learning',+ collectiveIntelligence: true,+ adaptiveLearning: true+ }+ };+ } catch (error) {+ return {+ success: false,+ mode: 'hive-mind',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'Hive Mind initialization failed'+ };+ }+ }+}++//# sourceMappingURL=HiveMindInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/HiveMindInit.js.map b/dist-cjs/src/modes/HiveMindInit.js.mapnew file mode 100644index 0000000000..a681a40cc8--- /dev/null+++ b/dist-cjs/src/modes/HiveMindInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/HiveMindInit.ts"],"sourcesContent":["/**\n * HiveMindInit - Hive Mind initialization mode\n * Sets up collective intelligence with Queen-Worker coordination\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class HiveMindInit implements IInitMode {\n getDescription(): string {\n return 'Hive Mind initialization with collective intelligence, Queen-Worker coordination, and adaptive learning';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry', 'HiveMindCore', 'ConsensusEngine'];\n }\n\n validate(): boolean {\n return true; // Hive Mind mode is always valid\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Basic initialization\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Use mesh topology for maximum connectivity in hive mind\n if (config.topologyManager) {\n await config.topologyManager.configure('mesh', []);\n components.push('TopologyManager');\n }\n\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Initialize consensus engine with proof-of-learning\n if (config.consensusEngine) {\n await config.consensusEngine.setAlgorithm('proof-of-learning');\n components.push('ConsensusEngine');\n }\n\n // Spawn Queen and specialized worker agents\n if (config.agentRegistry) {\n // Queen agent (strategic coordinator)\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['strategic-planning', 'objective-setting', 'delegation', 'adaptation'],\n metadata: {\n role: 'queen',\n authority: 'high',\n specialization: 'collective-intelligence'\n }\n });\n\n // Research workers\n for (let i = 0; i < 2; i++) {\n await config.agentRegistry.spawn('researcher', {\n capabilities: ['research', 'analysis', 'data-gathering', 'pattern-recognition'],\n metadata: {\n role: 'worker',\n specialization: 'research',\n pool: 'research-pool'\n }\n });\n }\n\n // Development workers\n for (let i = 0; i < 2; i++) {\n await config.agentRegistry.spawn('coder', {\n capabilities: ['programming', 'debugging', 'refactoring', 'architecture'],\n metadata: {\n role: 'worker',\n specialization: 'development',\n pool: 'development-pool'\n }\n });\n }\n\n // Testing workers\n await config.agentRegistry.spawn('tester', {\n capabilities: ['testing', 'quality-assurance', 'validation', 'performance-testing'],\n metadata: {\n role: 'worker',\n specialization: 'testing',\n pool: 'testing-pool'\n }\n });\n\n // Optimization workers\n await config.agentRegistry.spawn('optimizer', {\n capabilities: ['performance-optimization', 'resource-management', 'bottleneck-analysis'],\n metadata: {\n role: 'worker',\n specialization: 'optimization',\n pool: 'optimization-pool'\n }\n });\n\n components.push('HiveMindAgents');\n }\n\n // Initialize Hive Mind Core\n if (config.hiveMindCore) {\n await config.hiveMindCore.initialize();\n components.push('HiveMindCore');\n }\n\n // Set up collective intelligence memory structures\n if (config.databaseManager) {\n await config.databaseManager.store('hive-mind-config', {\n initialized: true,\n mode: 'hive-mind',\n queenEnabled: true,\n workerPools: ['research', 'development', 'testing', 'optimization'],\n consensusAlgorithm: 'proof-of-learning',\n adaptationRate: 0.1,\n timestamp: new Date().toISOString()\n }, 'hive-mind');\n\n // Initialize objective tracking\n await config.databaseManager.store('objectives', {\n active: [],\n completed: [],\n strategies: {}\n }, 'hive-mind');\n\n components.push('HiveMindMemory');\n }\n\n // Set up initial collective objective\n if (config.hiveMindCore) {\n const initialObjective = await config.hiveMindCore.setObjective({\n description: 'Establish collective intelligence coordination',\n goals: [\n { description: 'Optimize inter-agent communication', metric: 'latency', target: 100, weight: 0.3 },\n { description: 'Maximize task success rate', metric: 'success_rate', target: 0.95, weight: 0.4 },\n { description: 'Efficient resource utilization', metric: 'efficiency', target: 0.8, weight: 0.3 }\n ],\n constraints: [\n { type: 'resource', description: 'Maximum 8 concurrent agents', value: 8 },\n { type: 'time', description: 'Continuous operation', value: 'ongoing' }\n ],\n priority: 'high'\n });\n\n components.push('InitialObjective');\n }\n\n return {\n success: true,\n mode: 'hive-mind',\n components,\n topology: 'mesh',\n message: 'Hive Mind initialization completed successfully - Collective intelligence active',\n metadata: {\n queenEnabled: true,\n workerPools: 4,\n totalAgents: 7,\n consensusAlgorithm: 'proof-of-learning',\n collectiveIntelligence: true,\n adaptiveLearning: true\n }\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'hive-mind',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'Hive Mind initialization failed'\n };\n }\n }\n}"],"names":["HiveMindInit","getDescription","getRequiredComponents","validate","initialize","config","components","configManager","push","databaseManager","topologyManager","configure","agentRegistry","consensusEngine","setAlgorithm","spawn","capabilities","metadata","role","authority","specialization","i","pool","hiveMindCore","store","initialized","mode","queenEnabled","workerPools","consensusAlgorithm","adaptationRate","timestamp","Date","toISOString","active","completed","strategies","initialObjective","setObjective","description","goals","metric","target","weight","constraints","type","value","priority","success","topology","message","totalAgents","collectiveIntelligence","adaptiveLearning","error","Error","String"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;YAAiB;YAAgB;SAAkB;IACpH;IAEAC,WAAoB;QAClB,OAAO;IACT;IAEA,MAAMC,WAAWC,MAAkB,EAAuB;QACxD,MAAM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4BAAcC,QAAQ;4BAAKC,QAAQ;wBAAI;qBACjG;oBACDC,aAAa;wBACX;4BAAEC,MAAM;4BAAYN,aAAa;4BAA+BO,OAAO;wBAAE;wBACzE;4BAAED,MAAM;4BAAQN,aAAa;4BAAwBO,OAAO;wBAAU;qBACvE;oBACDC,UAAU;gBACZ;gBAEAzC,WAAWE,IAAI,CAAC;YAClB;YAEA,OAAO;gBACLwC,SAAS;gBACTtB,MAAM;gBACNpB;gBACA2C,UAAU;gBACVC,SAAS;gBACTjC,UAAU;oBACRU,cAAc;oBACdC,aAAa;oBACbuB,aAAa;oBACbtB,oBAAoB;oBACpBuB,wBAAwB;oBACxBC,kBAAkB;gBACpB;YACF;QAEF,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLN,SAAS;gBACTtB,MAAM;gBACNpB;gBACAgD,OAAOA,iBAAiBC,QAAQD,MAAMJ,OAAO,GAAGM,OAAOF;gBACvDJ,SAAS;YACX;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/NeuralInit.js b/dist-cjs/src/modes/NeuralInit.jsnew file mode 100644index 0000000000..edb0249383--- /dev/null+++ b/dist-cjs/src/modes/NeuralInit.js@@ -0,0 +1,291 @@+export class NeuralInit {+ getDescription() {+ return 'Neural network initialization with distributed training, WASM optimization, and pattern learning';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry',+ 'MCPIntegrator',+ 'MetricsCollector'+ ];+ }+ validate() {+ return typeof WebAssembly !== 'undefined' || typeof global !== 'undefined';+ }+ async initialize(config) {+ const components = [];+ try {+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('mesh', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('researcher', {+ capabilities: [+ 'neural-architecture',+ 'model-design',+ 'hyperparameter-tuning'+ ],+ metadata: {+ role: 'neural-architect',+ specialization: 'architecture-design',+ frameworks: [+ 'tensorflow',+ 'pytorch',+ 'wasm'+ ]+ }+ });+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'distributed-training',+ 'data-management',+ 'training-coordination'+ ],+ metadata: {+ role: 'training-coordinator',+ specialization: 'training-management',+ distributedCapable: true+ }+ });+ await config.agentRegistry.spawn('analyst', {+ capabilities: [+ 'pattern-recognition',+ 'data-analysis',+ 'feature-extraction'+ ],+ metadata: {+ role: 'pattern-analyst',+ specialization: 'pattern-recognition',+ algorithms: [+ 'cnn',+ 'rnn',+ 'transformer'+ ]+ }+ });+ await config.agentRegistry.spawn('optimizer', {+ capabilities: [+ 'model-optimization',+ 'wasm-acceleration',+ 'performance-tuning'+ ],+ metadata: {+ role: 'neural-optimizer',+ specialization: 'performance-optimization',+ wasmEnabled: true,+ simdEnabled: true+ }+ });+ await config.agentRegistry.spawn('tester', {+ capabilities: [+ 'model-validation',+ 'accuracy-testing',+ 'benchmark-testing'+ ],+ metadata: {+ role: 'neural-validator',+ specialization: 'model-validation',+ metrics: [+ 'accuracy',+ 'precision',+ 'recall',+ 'f1'+ ]+ }+ });+ components.push('NeuralAgents');+ }+ if (config.mcpIntegrator) {+ await config.mcpIntegrator.initialize();+ const neuralStatus = await config.mcpIntegrator.executeCommand({+ tool: 'claude-flow',+ function: 'neural_status',+ parameters: {}+ });+ if (neuralStatus.success) {+ components.push('NeuralMCP');+ }+ const trainResult = await config.mcpIntegrator.executeCommand({+ tool: 'claude-flow',+ function: 'neural_train',+ parameters: {+ pattern_type: 'coordination',+ training_data: 'initialization patterns',+ epochs: 10+ }+ });+ if (trainResult.success) {+ components.push('NeuralTraining');+ }+ }+ if (config.databaseManager) {+ await config.databaseManager.store('neural-config', {+ initialized: true,+ mode: 'neural',+ wasmOptimization: true,+ simdAcceleration: true,+ distributedTraining: true,+ modelTypes: [+ 'feedforward',+ 'lstm',+ 'transformer'+ ],+ timestamp: new Date().toISOString()+ }, 'neural');+ await config.databaseManager.store('model-registry', {+ models: [],+ trainingJobs: [],+ benchmarks: []+ }, 'neural');+ await config.databaseManager.store('pattern-learning', {+ patterns: {+ coordination: {+ accuracy: 0.0,+ training: true+ },+ optimization: {+ accuracy: 0.0,+ training: false+ },+ prediction: {+ accuracy: 0.0,+ training: false+ }+ },+ learningRate: 0.001,+ adaptationEnabled: true+ }, 'neural');+ components.push('NeuralMemory');+ }+ if (config.metricsCollector) {+ await config.metricsCollector.initialize();+ await config.metricsCollector.recordSystemMetrics({+ cpuUsage: 45,+ memoryUsage: 60,+ diskUsage: 40,+ networkLatency: 15,+ activeConnections: 5+ });+ components.push('NeuralMetrics');+ }+ if (config.databaseManager) {+ const architectures = {+ 'coordination-net': {+ type: 'feedforward',+ layers: [+ {+ type: 'dense',+ units: 128,+ activation: 'relu'+ },+ {+ type: 'dropout',+ rate: 0.2+ },+ {+ type: 'dense',+ units: 64,+ activation: 'relu'+ },+ {+ type: 'dense',+ units: 32,+ activation: 'softmax'+ }+ ],+ purpose: 'Agent coordination optimization'+ },+ 'pattern-lstm': {+ type: 'lstm',+ layers: [+ {+ type: 'lstm',+ units: 64,+ return_sequences: true+ },+ {+ type: 'dropout',+ rate: 0.3+ },+ {+ type: 'lstm',+ units: 32+ },+ {+ type: 'dense',+ units: 16,+ activation: 'sigmoid'+ }+ ],+ purpose: 'Pattern recognition and prediction'+ },+ 'performance-transformer': {+ type: 'transformer',+ layers: [+ {+ type: 'attention',+ heads: 8,+ key_dim: 64+ },+ {+ type: 'feedforward',+ dim: 256+ },+ {+ type: 'layer_norm'+ },+ {+ type: 'dense',+ units: 1,+ activation: 'linear'+ }+ ],+ purpose: 'Performance prediction and optimization'+ }+ };+ await config.databaseManager.store('neural-architectures', architectures, 'neural');+ components.push('NeuralArchitectures');+ }+ return {+ success: true,+ mode: 'neural',+ components,+ topology: 'mesh',+ message: 'Neural network initialization completed successfully - Distributed learning active',+ metadata: {+ wasmOptimization: true,+ simdAcceleration: true,+ distributedTraining: true,+ modelArchitectures: 3,+ patternLearning: true,+ performanceOptimization: true+ }+ };+ } catch (error) {+ return {+ success: false,+ mode: 'neural',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'Neural initialization failed'+ };+ }+ }+}++//# sourceMappingURL=NeuralInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/NeuralInit.js.map b/dist-cjs/src/modes/NeuralInit.js.mapnew file mode 100644index 0000000000..d97d34ae89--- /dev/null+++ b/dist-cjs/src/modes/NeuralInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/NeuralInit.ts"],"sourcesContent":["/**\n * NeuralInit - Neural network initialization mode\n * Sets up neural network training and optimization capabilities\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class NeuralInit implements IInitMode {\n getDescription(): string {\n return 'Neural network initialization with distributed training, WASM optimization, and pattern learning';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry', 'MCPIntegrator', 'MetricsCollector'];\n }\n\n validate(): boolean {\n // Check if WASM is supported\n return typeof WebAssembly !== 'undefined' || typeof global !== 'undefined';\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Basic initialization\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Use mesh topology for distributed neural training\n if (config.topologyManager) {\n await config.topologyManager.configure('mesh', []);\n components.push('TopologyManager');\n }\n\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Spawn neural-specific agents\n if (config.agentRegistry) {\n // Neural Network Architect\n await config.agentRegistry.spawn('researcher', {\n capabilities: ['neural-architecture', 'model-design', 'hyperparameter-tuning'],\n metadata: {\n role: 'neural-architect',\n specialization: 'architecture-design',\n frameworks: ['tensorflow', 'pytorch', 'wasm']\n }\n });\n\n // Training Coordinator\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['distributed-training', 'data-management', 'training-coordination'],\n metadata: {\n role: 'training-coordinator',\n specialization: 'training-management',\n distributedCapable: true\n }\n });\n\n // Pattern Recognition Agent\n await config.agentRegistry.spawn('analyst', {\n capabilities: ['pattern-recognition', 'data-analysis', 'feature-extraction'],\n metadata: {\n role: 'pattern-analyst',\n specialization: 'pattern-recognition',\n algorithms: ['cnn', 'rnn', 'transformer']\n }\n });\n\n // Optimization Agent\n await config.agentRegistry.spawn('optimizer', {\n capabilities: ['model-optimization', 'wasm-acceleration', 'performance-tuning'],\n metadata: {\n role: 'neural-optimizer',\n specialization: 'performance-optimization',\n wasmEnabled: true,\n simdEnabled: true\n }\n });\n\n // Validation Agent\n await config.agentRegistry.spawn('tester', {\n capabilities: ['model-validation', 'accuracy-testing', 'benchmark-testing'],\n metadata: {\n role: 'neural-validator',\n specialization: 'model-validation',\n metrics: ['accuracy', 'precision', 'recall', 'f1']\n }\n });\n\n components.push('NeuralAgents');\n }\n\n // Initialize Neural MCP integration\n if (config.mcpIntegrator) {\n await config.mcpIntegrator.initialize();\n\n // Test neural MCP functions\n const neuralStatus = await config.mcpIntegrator.executeCommand({\n tool: 'claude-flow',\n function: 'neural_status',\n parameters: {}\n });\n\n if (neuralStatus.success) {\n components.push('NeuralMCP');\n }\n\n // Initialize neural training\n const trainResult = await config.mcpIntegrator.executeCommand({\n tool: 'claude-flow',\n function: 'neural_train',\n parameters: {\n pattern_type: 'coordination',\n training_data: 'initialization patterns',\n epochs: 10\n }\n });\n\n if (trainResult.success) {\n components.push('NeuralTraining');\n }\n }\n\n // Set up neural network memory structures\n if (config.databaseManager) {\n await config.databaseManager.store('neural-config', {\n initialized: true,\n mode: 'neural',\n wasmOptimization: true,\n simdAcceleration: true,\n distributedTraining: true,\n modelTypes: ['feedforward', 'lstm', 'transformer'],\n timestamp: new Date().toISOString()\n }, 'neural');\n\n // Initialize model registry\n await config.databaseManager.store('model-registry', {\n models: [],\n trainingJobs: [],\n benchmarks: []\n }, 'neural');\n\n // Initialize pattern learning\n await config.databaseManager.store('pattern-learning', {\n patterns: {\n coordination: { accuracy: 0.0, training: true },\n optimization: { accuracy: 0.0, training: false },\n prediction: { accuracy: 0.0, training: false }\n },\n learningRate: 0.001,\n adaptationEnabled: true\n }, 'neural');\n\n components.push('NeuralMemory');\n }\n\n // Initialize performance metrics for neural systems\n if (config.metricsCollector) {\n await config.metricsCollector.initialize();\n\n // Record neural initialization metrics\n await config.metricsCollector.recordSystemMetrics({\n cpuUsage: 45, // Neural processing baseline\n memoryUsage: 60, // Models require more memory\n diskUsage: 40,\n networkLatency: 15,\n activeConnections: 5\n });\n\n components.push('NeuralMetrics');\n }\n\n // Set up neural network architectures\n if (config.databaseManager) {\n const architectures = {\n 'coordination-net': {\n type: 'feedforward',\n layers: [\n { type: 'dense', units: 128, activation: 'relu' },\n { type: 'dropout', rate: 0.2 },\n { type: 'dense', units: 64, activation: 'relu' },\n { type: 'dense', units: 32, activation: 'softmax' }\n ],\n purpose: 'Agent coordination optimization'\n },\n 'pattern-lstm': {\n type: 'lstm',\n layers: [\n { type: 'lstm', units: 64, return_sequences: true },\n { type: 'dropout', rate: 0.3 },\n { type: 'lstm', units: 32 },\n { type: 'dense', units: 16, activation: 'sigmoid' }\n ],\n purpose: 'Pattern recognition and prediction'\n },\n 'performance-transformer': {\n type: 'transformer',\n layers: [\n { type: 'attention', heads: 8, key_dim: 64 },\n { type: 'feedforward', dim: 256 },\n { type: 'layer_norm' },\n { type: 'dense', units: 1, activation: 'linear' }\n ],\n purpose: 'Performance prediction and optimization'\n }\n };\n\n await config.databaseManager.store('neural-architectures', architectures, 'neural');\n components.push('NeuralArchitectures');\n }\n\n return {\n success: true,\n mode: 'neural',\n components,\n topology: 'mesh',\n message: 'Neural network initialization completed successfully - Distributed learning active',\n metadata: {\n wasmOptimization: true,\n simdAcceleration: true,\n distributedTraining: true,\n modelArchitectures: 3,\n patternLearning: true,\n performanceOptimization: true\n }\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'neural',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'Neural initialization failed'\n };\n }\n }\n}"],"names":["NeuralInit","getDescription","getRequiredComponents","validate","WebAssembly","global","initialize","config","components","configManager","push","databaseManager","topologyManager","configure","agentRegistry","spawn","capabilities","metadata","role","specialization","frameworks","distributedCapable","algorithms","wasmEnabled","simdEnabled","metrics","mcpIntegrator","neuralStatus","executeCommand","tool","function","parameters","success","trainResult","pattern_type","training_data","epochs","store","initialized","mode","wasmOptimization","simdAcceleration","distributedTraining","modelTypes","timestamp","Date","toISOString","models","trainingJobs","benchmarks","patterns","coordination","accuracy","training","optimization","prediction","learningRate","adaptationEnabled","metricsCollector","recordSystemMetrics","cpuUsage","memoryUsage","diskUsage","networkLatency","activeConnections","architectures","type","layers","units","activation","rate","purpose","return_sequences","heads","key_dim","dim","topology","message","modelArchitectures","patternLearning","performanceOptimization","error","Error","String"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;YAAiB;YAAiB;SAAmB;IACtH;IAEAC,WAAoB;QAElB,OAAO,OAAOC,gBAAgB,eAAe,OAAOC,WAAW;IACjE;IAEA,MAAMC,WAAWC,MAAkB,EAAuB;QACxD,MAAMC,aAAuB,EAAE;QAE/B,IAAI;YAEF,IAAID,OAAOE,aAAa,EAAE;gBACxBD,WAAWE,IAAI,CAAC;YAClB;YAEA,IAAIH,OAAOI,eAAe,EAAE;gBAC1B,MAAMJ,OAAOI,eAAe,CAACL,UAAU;gBACvCE,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOK,eAAe,EAAE;gBAC1B,MAAML,OAAOK,eAAe,CAACC,SAAS,CAAC,QAAQ,EAAE;gBAC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RuB,kBAAkB;oBAClBC,kBAAkB;oBAClBC,qBAAqB;oBACrBoC,oBAAoB;oBACpBC,iBAAiB;oBACjBC,yBAAyB;gBAC3B;YACF;QAEF,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLjD,SAAS;gBACTO,MAAM;gBACN/B;gBACAyE,OAAOA,iBAAiBC,QAAQD,MAAMJ,OAAO,GAAGM,OAAOF;gBACvDJ,SAAS;YACX;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/SparcInit.js b/dist-cjs/src/modes/SparcInit.jsnew file mode 100644index 0000000000..f91c3bdb4d--- /dev/null+++ b/dist-cjs/src/modes/SparcInit.js@@ -0,0 +1,282 @@+export class SparcInit {+ getDescription() {+ return 'SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) initialization with TDD workflow';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry',+ 'MCPIntegrator'+ ];+ }+ validate() {+ return true;+ }+ async initialize(config) {+ const components = [];+ try {+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('hierarchical', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'sparc-coordination',+ 'workflow-management',+ 'tdd-orchestration'+ ],+ metadata: {+ role: 'sparc-coordinator',+ phase: 'all',+ authority: 'high'+ }+ });+ await config.agentRegistry.spawn('analyst', {+ capabilities: [+ 'requirement-analysis',+ 'specification-writing',+ 'user-story-creation'+ ],+ metadata: {+ role: 'specification-agent',+ phase: 'specification',+ workflow: 'sparc'+ }+ });+ await config.agentRegistry.spawn('researcher', {+ capabilities: [+ 'algorithm-design',+ 'pseudocode-creation',+ 'logic-planning'+ ],+ metadata: {+ role: 'pseudocode-agent',+ phase: 'pseudocode',+ workflow: 'sparc'+ }+ });+ await config.agentRegistry.spawn('reviewer', {+ capabilities: [+ 'system-architecture',+ 'design-patterns',+ 'component-design'+ ],+ metadata: {+ role: 'architecture-agent',+ phase: 'architecture',+ workflow: 'sparc'+ }+ });+ await config.agentRegistry.spawn('coder', {+ capabilities: [+ 'test-driven-development',+ 'unit-testing',+ 'refactoring',+ 'implementation'+ ],+ metadata: {+ role: 'refinement-agent',+ phase: 'refinement',+ workflow: 'sparc'+ }+ });+ await config.agentRegistry.spawn('tester', {+ capabilities: [+ 'integration-testing',+ 'validation',+ 'quality-assurance',+ 'documentation'+ ],+ metadata: {+ role: 'completion-agent',+ phase: 'completion',+ workflow: 'sparc'+ }+ });+ components.push('SparcAgents');+ }+ if (config.mcpIntegrator) {+ await config.mcpIntegrator.initialize();+ const sparcStatus = await config.mcpIntegrator.executeCommand({+ tool: 'claude-flow',+ function: 'sparc_mode',+ parameters: {+ mode: 'dev',+ task_description: 'Initialize SPARC workflow'+ }+ });+ if (sparcStatus.success) {+ components.push('SparcMCP');+ }+ }+ if (config.databaseManager) {+ await config.databaseManager.store('sparc-config', {+ initialized: true,+ mode: 'sparc',+ phases: [+ 'specification',+ 'pseudocode',+ 'architecture',+ 'refinement',+ 'completion'+ ],+ tddEnabled: true,+ workflowActive: false,+ currentPhase: null,+ timestamp: new Date().toISOString()+ }, 'sparc');+ const phases1 = [+ 'specification',+ 'pseudocode',+ 'architecture',+ 'refinement',+ 'completion'+ ];+ for (const phase of phases1){+ await config.databaseManager.store(`phase-${phase}`, {+ name: phase,+ status: 'pending',+ agent: null,+ artifacts: [],+ dependencies: this.getPhaseDependencies(phase)+ }, 'sparc');+ }+ await config.databaseManager.store('tdd-status', {+ testSuites: [],+ coverage: 0,+ redGreenRefactor: {+ red: [],+ green: [],+ refactor: []+ }+ }, 'sparc');+ components.push('SparcMemory');+ }+ if (config.databaseManager) {+ await config.databaseManager.store('workflow-templates', {+ 'feature-development': {+ phases: phases.map((phase)=>({+ name: phase,+ description: this.getPhaseDescription(phase),+ estimatedDuration: this.getPhaseEstimatedDuration(phase),+ deliverables: this.getPhaseDeliverables(phase)+ }))+ }+ }, 'sparc');+ components.push('SparcTemplates');+ }+ return {+ success: true,+ mode: 'sparc',+ components,+ topology: 'hierarchical',+ message: 'SPARC workflow initialization completed successfully - TDD methodology active',+ metadata: {+ sparcPhases: 5,+ tddEnabled: true,+ agentSpecialization: true,+ workflowOrchestration: true,+ testDrivenDevelopment: true+ }+ };+ } catch (error) {+ return {+ success: false,+ mode: 'sparc',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'SPARC initialization failed'+ };+ }+ }+ getPhaseDependencies(phase) {+ const dependencies = {+ 'specification': [],+ 'pseudocode': [+ 'specification'+ ],+ 'architecture': [+ 'specification',+ 'pseudocode'+ ],+ 'refinement': [+ 'specification',+ 'pseudocode',+ 'architecture'+ ],+ 'completion': [+ 'specification',+ 'pseudocode',+ 'architecture',+ 'refinement'+ ]+ };+ return dependencies[phase] || [];+ }+ getPhaseDescription(phase) {+ const descriptions = {+ 'specification': 'Analyze requirements and create detailed specifications',+ 'pseudocode': 'Design algorithms and create pseudocode representations',+ 'architecture': 'Design system architecture and component structure',+ 'refinement': 'Implement code using Test-Driven Development methodology',+ 'completion': 'Integration testing, validation, and documentation'+ };+ return descriptions[phase] || 'Unknown phase';+ }+ getPhaseEstimatedDuration(phase) {+ const durations = {+ 'specification': 1800,+ 'pseudocode': 1200,+ 'architecture': 2400,+ 'refinement': 3600,+ 'completion': 1800+ };+ return durations[phase] || 1800;+ }+ getPhaseDeliverables(phase) {+ const deliverables = {+ 'specification': [+ 'Requirements document',+ 'User stories',+ 'Acceptance criteria'+ ],+ 'pseudocode': [+ 'Algorithm pseudocode',+ 'Logic flow diagrams',+ 'Data structures'+ ],+ 'architecture': [+ 'System architecture',+ 'Component diagrams',+ 'API specifications'+ ],+ 'refinement': [+ 'Test suites',+ 'Implementation code',+ 'Refactored code'+ ],+ 'completion': [+ 'Integration tests',+ 'Documentation',+ 'Deployment artifacts'+ ]+ };+ return deliverables[phase] || [];+ }+}++//# sourceMappingURL=SparcInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/SparcInit.js.map b/dist-cjs/src/modes/SparcInit.js.mapnew file mode 100644index 0000000000..7f4a238a7c--- /dev/null+++ b/dist-cjs/src/modes/SparcInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/SparcInit.ts"],"sourcesContent":["/**\n * SparcInit - SPARC methodology initialization mode\n * Sets up Test-Driven Development with SPARC workflow\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class SparcInit implements IInitMode {\n getDescription(): string {\n return 'SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) initialization with TDD workflow';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry', 'MCPIntegrator'];\n }\n\n validate(): boolean {\n return true; // SPARC mode is always valid\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Basic initialization\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Use hierarchical topology for SPARC workflow stages\n if (config.topologyManager) {\n await config.topologyManager.configure('hierarchical', []);\n components.push('TopologyManager');\n }\n\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Spawn SPARC-specific agents\n if (config.agentRegistry) {\n // SPARC Coordinator (orchestrates the entire SPARC workflow)\n await config.agentRegistry.spawn('coordinator', {\n capabilities: ['sparc-coordination', 'workflow-management', 'tdd-orchestration'],\n metadata: {\n role: 'sparc-coordinator',\n phase: 'all',\n authority: 'high'\n }\n });\n\n // Specification Agent\n await config.agentRegistry.spawn('analyst', {\n capabilities: ['requirement-analysis', 'specification-writing', 'user-story-creation'],\n metadata: {\n role: 'specification-agent',\n phase: 'specification',\n workflow: 'sparc'\n }\n });\n\n // Pseudocode Agent\n await config.agentRegistry.spawn('researcher', {\n capabilities: ['algorithm-design', 'pseudocode-creation', 'logic-planning'],\n metadata: {\n role: 'pseudocode-agent',\n phase: 'pseudocode',\n workflow: 'sparc'\n }\n });\n\n // Architecture Agent\n await config.agentRegistry.spawn('reviewer', {\n capabilities: ['system-architecture', 'design-patterns', 'component-design'],\n metadata: {\n role: 'architecture-agent',\n phase: 'architecture',\n workflow: 'sparc'\n }\n });\n\n // Refinement Agent (TDD focus)\n await config.agentRegistry.spawn('coder', {\n capabilities: ['test-driven-development', 'unit-testing', 'refactoring', 'implementation'],\n metadata: {\n role: 'refinement-agent',\n phase: 'refinement',\n workflow: 'sparc'\n }\n });\n\n // Completion Agent\n await config.agentRegistry.spawn('tester', {\n capabilities: ['integration-testing', 'validation', 'quality-assurance', 'documentation'],\n metadata: {\n role: 'completion-agent',\n phase: 'completion',\n workflow: 'sparc'\n }\n });\n\n components.push('SparcAgents');\n }\n\n // Initialize SPARC MCP integration\n if (config.mcpIntegrator) {\n await config.mcpIntegrator.initialize();\n\n // Test SPARC-related MCP functions\n const sparcStatus = await config.mcpIntegrator.executeCommand({\n tool: 'claude-flow',\n function: 'sparc_mode',\n parameters: { mode: 'dev', task_description: 'Initialize SPARC workflow' }\n });\n\n if (sparcStatus.success) {\n components.push('SparcMCP');\n }\n }\n\n // Set up SPARC workflow memory structures\n if (config.databaseManager) {\n await config.databaseManager.store('sparc-config', {\n initialized: true,\n mode: 'sparc',\n phases: ['specification', 'pseudocode', 'architecture', 'refinement', 'completion'],\n tddEnabled: true,\n workflowActive: false,\n currentPhase: null,\n timestamp: new Date().toISOString()\n }, 'sparc');\n\n // Initialize phase tracking\n const phases = ['specification', 'pseudocode', 'architecture', 'refinement', 'completion'];\n for (const phase of phases) {\n await config.databaseManager.store(`phase-${phase}`, {\n name: phase,\n status: 'pending',\n agent: null,\n artifacts: [],\n dependencies: this.getPhaseDependencies(phase)\n }, 'sparc');\n }\n\n // Initialize TDD tracking\n await config.databaseManager.store('tdd-status', {\n testSuites: [],\n coverage: 0,\n redGreenRefactor: {\n red: [],\n green: [],\n refactor: []\n }\n }, 'sparc');\n\n components.push('SparcMemory');\n }\n\n // Set up SPARC workflow templates\n if (config.databaseManager) {\n await config.databaseManager.store('workflow-templates', {\n 'feature-development': {\n phases: phases.map(phase => ({\n name: phase,\n description: this.getPhaseDescription(phase),\n estimatedDuration: this.getPhaseEstimatedDuration(phase),\n deliverables: this.getPhaseDeliverables(phase)\n }))\n }\n }, 'sparc');\n\n components.push('SparcTemplates');\n }\n\n return {\n success: true,\n mode: 'sparc',\n components,\n topology: 'hierarchical',\n message: 'SPARC workflow initialization completed successfully - TDD methodology active',\n metadata: {\n sparcPhases: 5,\n tddEnabled: true,\n agentSpecialization: true,\n workflowOrchestration: true,\n testDrivenDevelopment: true\n }\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'sparc',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'SPARC initialization failed'\n };\n }\n }\n\n private getPhaseDependencies(phase: string): string[] {\n const dependencies: Record<string, string[]> = {\n 'specification': [],\n 'pseudocode': ['specification'],\n 'architecture': ['specification', 'pseudocode'],\n 'refinement': ['specification', 'pseudocode', 'architecture'],\n 'completion': ['specification', 'pseudocode', 'architecture', 'refinement']\n };\n\n return dependencies[phase] || [];\n }\n\n private getPhaseDescription(phase: string): string {\n const descriptions: Record<string, string> = {\n 'specification': 'Analyze requirements and create detailed specifications',\n 'pseudocode': 'Design algorithms and create pseudocode representations',\n 'architecture': 'Design system architecture and component structure',\n 'refinement': 'Implement code using Test-Driven Development methodology',\n 'completion': 'Integration testing, validation, and documentation'\n };\n\n return descriptions[phase] || 'Unknown phase';\n }\n\n private getPhaseEstimatedDuration(phase: string): number {\n const durations: Record<string, number> = {\n 'specification': 1800, // 30 minutes\n 'pseudocode': 1200, // 20 minutes\n 'architecture': 2400, // 40 minutes\n 'refinement': 3600, // 60 minutes (main implementation)\n 'completion': 1800 // 30 minutes\n };\n\n return durations[phase] || 1800;\n }\n\n private getPhaseDeliverables(phase: string): string[] {\n const deliverables: Record<string, string[]> = {\n 'specification': ['Requirements document', 'User stories', 'Acceptance criteria'],\n 'pseudocode': ['Algorithm pseudocode', 'Logic flow diagrams', 'Data structures'],\n 'architecture': ['System architecture', 'Component diagrams', 'API specifications'],\n 'refinement': ['Test suites', 'Implementation code', 'Refactored code'],\n 'completion': ['Integration tests', 'Documentation', 'Deployment artifacts']\n };\n\n return deliverables[phase] || [];\n }\n}"],"names":["SparcInit","getDescription","getRequiredComponents","validate","initialize","config","components","configManager","push","databaseManager","topologyManager","configure","agentRegistry","spawn","capabilities","metadata","role","phase","authority","workflow","mcpIntegrator","sparcStatus","executeCommand","tool","function","parameters","mode","task_description","success","store","initialized","phases","tddEnabled","workflowActive","currentPhase","timestamp","Date","toISOString","name","status","agent","artifacts","dependencies","getPhaseDependencies","testSuites","coverage","redGreenRefactor","red","green","refactor","map","description","getPhaseDescription","estimatedDuration","getPhaseEstimatedDuration","deliverables","getPhaseDeliverables","topology","message","sparcPhases","agentSpecialization","workflowOrchestration","testDrivenDevelopment","error","Error","String","descriptions","durations"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;YAAiB;SAAgB;IAClG;IAEAC,WAAoB;QAClB,OAAO;IACT;IAEA,MAAMC,WAAWC,MAAkB,EAAuB;QACxD,MAAMC,aAAuB,EAAE;QAE/B,IAAI;YAEF,IAAID,OAAOE,aAAa,EAAE;gBACxBD,WAAWE,IAAI,CAAC;YAClB;YAEA,IAAIH,OAAOI,eAAe,EAAE;gBAC1B,MAAMJ,OAAOI,eAAe,CAACL,UAAU;gBACvCE,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOK,eAAe,EAAE;gBAC1B,MAAML,OAAOK,eA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;IAC7B;IAEQuC,qBAAqBvC,KAAa,EAAY;QACpD,MAAMsC,eAAyC;YAC7C,iBAAiB;gBAAC;gBAAyB;gBAAgB;aAAsB;YACjF,cAAc;gBAAC;gBAAwB;gBAAuB;aAAkB;YAChF,gBAAgB;gBAAC;gBAAuB;gBAAsB;aAAqB;YACnF,cAAc;gBAAC;gBAAe;gBAAuB;aAAkB;YACvE,cAAc;gBAAC;gBAAqB;gBAAiB;aAAuB;QAC9E;QAEA,OAAOA,YAAY,CAACtC,MAAM,IAAI,EAAE;IAClC;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/modes/StandardInit.js b/dist-cjs/src/modes/StandardInit.jsnew file mode 100644index 0000000000..b122fedb6f--- /dev/null+++ b/dist-cjs/src/modes/StandardInit.js@@ -0,0 +1,74 @@+export class StandardInit {+ getDescription() {+ return 'Standard initialization mode with basic agent coordination and mesh topology';+ }+ getRequiredComponents() {+ return [+ 'ConfigManager',+ 'DatabaseManager',+ 'TopologyManager',+ 'AgentRegistry'+ ];+ }+ validate() {+ return true;+ }+ async initialize(config) {+ const components = [];+ try {+ if (config.configManager) {+ components.push('ConfigManager');+ }+ if (config.databaseManager) {+ await config.databaseManager.initialize();+ components.push('DatabaseManager');+ }+ if (config.topologyManager) {+ await config.topologyManager.configure('mesh', []);+ components.push('TopologyManager');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.initialize();+ components.push('AgentRegistry');+ }+ if (config.agentRegistry) {+ await config.agentRegistry.spawn('coordinator', {+ capabilities: [+ 'coordination',+ 'task-management'+ ]+ });+ await config.agentRegistry.spawn('researcher', {+ capabilities: [+ 'research',+ 'analysis'+ ]+ });+ await config.agentRegistry.spawn('coder', {+ capabilities: [+ 'programming',+ 'debugging'+ ]+ });+ components.push('DefaultAgents');+ }+ return {+ success: true,+ mode: 'standard',+ components,+ topology: 'mesh',+ message: 'Standard initialization completed successfully'+ };+ } catch (error) {+ return {+ success: false,+ mode: 'standard',+ components,+ error: error instanceof Error ? error.message : String(error),+ message: 'Standard initialization failed'+ };+ }+ }+}++//# sourceMappingURL=StandardInit.js.map\ No newline at end of filediff --git a/dist-cjs/src/modes/StandardInit.js.map b/dist-cjs/src/modes/StandardInit.js.mapnew file mode 100644index 0000000000..186d8f5c04--- /dev/null+++ b/dist-cjs/src/modes/StandardInit.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/modes/StandardInit.ts"],"sourcesContent":["/**\n * StandardInit - Standard initialization mode\n * Basic initialization with minimal configuration\n */\n\nimport { IInitMode, InitConfig, InitResult } from '../types/interfaces.js';\n\nexport class StandardInit implements IInitMode {\n getDescription(): string {\n return 'Standard initialization mode with basic agent coordination and mesh topology';\n }\n\n getRequiredComponents(): string[] {\n return ['ConfigManager', 'DatabaseManager', 'TopologyManager', 'AgentRegistry'];\n }\n\n validate(): boolean {\n return true; // Standard mode is always valid\n }\n\n async initialize(config: InitConfig): Promise<InitResult> {\n const components: string[] = [];\n\n try {\n // Set up basic configuration\n if (config.configManager) {\n components.push('ConfigManager');\n }\n\n // Initialize database\n if (config.databaseManager) {\n await config.databaseManager.initialize();\n components.push('DatabaseManager');\n }\n\n // Configure mesh topology (default)\n if (config.topologyManager) {\n await config.topologyManager.configure('mesh', []);\n components.push('TopologyManager');\n }\n\n // Initialize agent registry\n if (config.agentRegistry) {\n await config.agentRegistry.initialize();\n components.push('AgentRegistry');\n }\n\n // Spawn default agents\n if (config.agentRegistry) {\n await config.agentRegistry.spawn('coordinator', { capabilities: ['coordination', 'task-management'] });\n await config.agentRegistry.spawn('researcher', { capabilities: ['research', 'analysis'] });\n await config.agentRegistry.spawn('coder', { capabilities: ['programming', 'debugging'] });\n components.push('DefaultAgents');\n }\n\n return {\n success: true,\n mode: 'standard',\n components,\n topology: 'mesh',\n message: 'Standard initialization completed successfully'\n };\n\n } catch (error) {\n return {\n success: false,\n mode: 'standard',\n components,\n error: error instanceof Error ? error.message : String(error),\n message: 'Standard initialization failed'\n };\n }\n }\n}"],"names":["StandardInit","getDescription","getRequiredComponents","validate","initialize","config","components","configManager","push","databaseManager","topologyManager","configure","agentRegistry","spawn","capabilities","success","mode","topology","message","error","Error","String"],"mappings":"AAOA,OAAO,MAAMA;IACXC,iBAAyB;QACvB,OAAO;IACT;IAEAC,wBAAkC;QAChC,OAAO;YAAC;YAAiB;YAAmB;YAAmB;SAAgB;IACjF;IAEAC,WAAoB;QAClB,OAAO;IACT;IAEA,MAAMC,WAAWC,MAAkB,EAAuB;QACxD,MAAMC,aAAuB,EAAE;QAE/B,IAAI;YAEF,IAAID,OAAOE,aAAa,EAAE;gBACxBD,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOI,eAAe,EAAE;gBAC1B,MAAMJ,OAAOI,eAAe,CAACL,UAAU;gBACvCE,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOK,eAAe,EAAE;gBAC1B,MAAML,OAAOK,eAAe,CAACC,SAAS,CAAC,QAAQ,EAAE;gBACjDL,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOO,aAAa,EAAE;gBACxB,MAAMP,OAAOO,aAAa,CAACR,UAAU;gBACrCE,WAAWE,IAAI,CAAC;YAClB;YAGA,IAAIH,OAAOO,aAAa,EAAE;gBACxB,MAAMP,OAAOO,aAAa,CAACC,KAAK,CAAC,eAAe;oBAAEC,cAAc;wBAAC;wBAAgB;qBAAkB;gBAAC;gBACpG,MAAMT,OAAOO,aAAa,CAACC,KAAK,CAAC,cAAc;oBAAEC,cAAc;wBAAC;wBAAY;qBAAW;gBAAC;gBACxF,MAAMT,OAAOO,aAAa,CAACC,KAAK,CAAC,SAAS;oBAAEC,cAAc;wBAAC;wBAAe;qBAAY;gBAAC;gBACvFR,WAAWE,IAAI,CAAC;YAClB;YAEA,OAAO;gBACLO,SAAS;gBACTC,MAAM;gBACNV;gBACAW,UAAU;gBACVC,SAAS;YACX;QAEF,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLJ,SAAS;gBACTC,MAAM;gBACNV;gBACAa,OAAOA,iBAAiBC,QAAQD,MAAMD,OAAO,GAAGG,OAAOF;gBACvDD,SAAS;YACX;QACF;IACF;AACF"}\ No newline at end of filediff --git a/dist-cjs/src/types/interfaces.js b/dist-cjs/src/types/interfaces.jsnew file mode 100644index 0000000000..f557537c77--- /dev/null+++ b/dist-cjs/src/types/interfaces.js@@ -0,0 +1,3 @@+export { };++//# sourceMappingURL=interfaces.js.map\ No newline at end of filediff --git a/dist-cjs/src/types/interfaces.js.map b/dist-cjs/src/types/interfaces.js.mapnew file mode 100644index 0000000000..5197e63cbe--- /dev/null+++ b/dist-cjs/src/types/interfaces.js.map@@ -0,0 +1 @@+{"version":3,"sources":["../../../src/types/interfaces.ts"],"sourcesContent":["/**\n * Core interfaces for the claude-flow init system\n */\n\nexport type InitMode = 'standard' | 'github' | 'hive-mind' | 'sparc' | 'neural' | 'enterprise';\nexport type TopologyType = 'mesh' | 'hierarchical' | 'ring' | 'star';\nexport type ConsensusType = 'raft' | 'byzantine' | 'gossip' | 'proof-of-learning';\nexport type AgentType = 'researcher' | 'coder' | 'analyst' | 'optimizer' | 'coordinator' | 'tester' | 'reviewer';\n\n// Core initialization interfaces\nexport interface IInitMode {\n initialize(config: InitConfig): Promise<InitResult>;\n validate(): boolean;\n getDescription(): string;\n getRequiredComponents(): string[];\n}\n\nexport interface InitConfig {\n mode?: InitMode;\n topology?: TopologyType;\n maxAgents?: number;\n strategy?: 'balanced' | 'specialized' | 'adaptive';\n database?: 'sqlite' | 'json';\n configPath?: string;\n debug?: boolean;\n configManager?: any;\n databaseManager?: any;\n topologyManager?: any;\n agentRegistry?: any;\n metricsCollector?: any;\n}\n\nexport interface InitResult {\n success: boolean;\n mode: InitMode;\n components?: string[];\n topology?: TopologyType;\n duration?: number;\n message?: string;\n error?: string;\n metadata?: Record<string, any>;\n}\n\n// Consensus interfaces\nexport interface IConsensusAlgorithm {\n propose(decision: Decision): Promise<Vote[]>;\n execute(consensus: Consensus): Promise<Result>;\n getType(): ConsensusType;\n initialize(): Promise<void>;\n}\n\nexport interface Decision {\n id: string;\n type: 'agent-spawn' | 'task-assignment' | 'resource-allocation' | 'topology-change';\n proposer: string;\n data: any;\n timestamp: Date;\n}\n\nexport interface Vote {\n agentId: string;\n decision: boolean;\n confidence: number;\n reasoning?: string;\n}\n\nexport interface Consensus {\n decisionId: string;\n outcome: boolean;\n votes: Vote[];\n confidence: number;\n timestamp: Date;\n}\n\nexport interface Result {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: Record<string, any>;\n}\n\n// Topology interfaces\nexport interface ITopology {\n configure(agents: Agent[]): Promise<Network>;\n optimize(): Promise<Optimization>;\n getConnections(): Connection[];\n getType(): TopologyType;\n}\n\nexport interface Agent {\n id: string;\n type: AgentType;\n capabilities: string[];\n status: 'active' | 'idle' | 'busy' | 'offline';\n metadata: Record<string, any>;\n connections?: string[];\n performance?: AgentPerformance;\n}\n\nexport interface Network {\n topology: TopologyType;\n agents: Agent[];\n connections: Connection[];\n metrics: NetworkMetrics;\n}\n\nexport interface Connection {\n from: string;\n to: string;\n type: 'direct' | 'relay' | 'broadcast';\n weight?: number;\n latency?: number;\n}\n\nexport interface Optimization {\n type: 'latency' | 'throughput' | 'reliability';\n changes: TopologyChange[];\n expectedImprovement: number;\n}\n\nexport interface TopologyChange {\n action: 'add-connection' | 'remove-connection' | 'modify-weight';\n connection: Connection;\n reason: string;\n}\n\nexport interface NetworkMetrics {\n totalAgents: number;\n totalConnections: number;\n averageLatency: number;\n throughput: number;\n reliability: number;\n}\n\n// Database interfaces\nexport interface IDatabaseProvider {\n initialize(): Promise<void>;\n store(key: string, value: any, namespace?: string): Promise<void>;\n retrieve(key: string, namespace?: string): Promise<any>;\n delete(key: string, namespace?: string): Promise<boolean>;\n list(namespace?: string): Promise<string[]>;\n close(): Promise<void>;\n}\n\n// Agent coordination interfaces\nexport interface IAgentCoordinator {\n spawn(type: AgentType, config: AgentConfig): Promise<Agent>;\n coordinate(task: Task): Promise<Result>;\n monitor(): Promise<Metrics>;\n shutdown(agentId: string): Promise<void>;\n}\n\nexport interface AgentConfig {\n capabilities?: string[];\n maxConcurrency?: number;\n timeout?: number;\n resources?: ResourceAllocation;\n metadata?: Record<string, any>;\n}\n\nexport interface Task {\n id: string;\n type: string;\n description: string;\n priority: 'low' | 'medium' | 'high' | 'critical';\n requiredCapabilities: string[];\n deadline?: Date;\n dependencies?: string[];\n data?: any;\n}\n\nexport interface ResourceAllocation {\n memory: number;\n cpu: number;\n storage: number;\n network: number;\n}\n\nexport interface AgentPerformance {\n tasksCompleted: number;\n averageResponseTime: number;\n successRate: number;\n resourceUtilization: ResourceAllocation;\n lastActivity: Date;\n}\n\nexport interface Metrics {\n agents: AgentMetrics[];\n system: SystemMetrics;\n performance: PerformanceMetrics;\n}\n\nexport interface AgentMetrics {\n agentId: string;\n type: AgentType;\n performance: AgentPerformance;\n status: 'active' | 'idle' | 'busy' | 'offline';\n}\n\nexport interface SystemMetrics {\n uptime: number;\n memoryUsage: number;\n cpuUsage: number;\n networkLatency: number;\n activeConnections: number;\n}\n\nexport interface PerformanceMetrics {\n throughput: number;\n latency: number;\n errorRate: number;\n bottlenecks: string[];\n}\n\n// Hive Mind interfaces\nexport interface IHiveMindQueen {\n strategize(objective: Objective): Promise<Strategy>;\n delegate(tasks: Task[]): Promise<Assignment[]>;\n monitor(): Promise<QueenMetrics>;\n adapt(feedback: Feedback[]): Promise<void>;\n}\n\nexport interface Objective {\n id: string;\n description: string;\n goals: Goal[];\n constraints: Constraint[];\n deadline?: Date;\n priority: 'low' | 'medium' | 'high' | 'critical';\n}\n\nexport interface Goal {\n description: string;\n metric: string;\n target: number;\n weight: number;\n}\n\nexport interface Constraint {\n type: 'resource' | 'time' | 'dependency' | 'capability';\n description: string;\n value: any;\n}\n\nexport interface Strategy {\n approach: string;\n phases: StrategyPhase[];\n resourceAllocation: ResourceAllocation;\n expectedOutcome: string;\n riskAssessment: Risk[];\n}\n\nexport interface StrategyPhase {\n name: string;\n description: string;\n tasks: Task[];\n dependencies: string[];\n duration: number;\n}\n\nexport interface Risk {\n description: string;\n probability: number;\n impact: number;\n mitigation: string;\n}\n\nexport interface Assignment {\n agentId: string;\n task: Task;\n deadline: Date;\n resources: ResourceAllocation;\n}\n\nexport interface QueenMetrics {\n strategiesCreated: number;\n tasksAssigned: number;\n successRate: number;\n adaptationCount: number;\n performanceScore: number;\n}\n\nexport interface Feedback {\n source: string;\n type: 'performance' | 'outcome' | 'suggestion';\n rating: number;\n comments: string;\n data?: any;\n}\n\n// Configuration interfaces\nexport interface ConfigValidationResult {\n valid: boolean;\n errors: string[];\n warnings?: string[];\n}\n\nexport interface DatabaseConfig {\n type: 'sqlite' | 'json';\n path?: string;\n options?: Record<string, any>;\n}\n\nexport interface TopologyConfig {\n type: TopologyType;\n maxAgents: number;\n connectionStrategy: 'full' | 'sparse' | 'hub' | 'ring';\n optimization: boolean;\n}\n\nexport interface InitializationMetrics {\n mode: InitMode;\n duration: number;\n success: boolean;\n components?: string[];\n error?: string;\n timestamp: string;\n}"],"names":[],"mappings":"AAsTA,WAOC"}\ No newline at end of file