claude-flow 2.7.34 → 2.7.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/claude-flow +1 -1
  3. package/dist/src/__tests__/benchmarks/performance.bench.js +0 -19
  4. package/dist/src/__tests__/benchmarks/performance.bench.js.map +1 -1
  5. package/dist/src/__tests__/hook-matchers.test.js.map +1 -1
  6. package/dist/src/agents/agent-registry.js.map +1 -1
  7. package/dist/src/api/auth-service.js.map +1 -1
  8. package/dist/src/api/claude-client-enhanced.js +4 -2
  9. package/dist/src/api/claude-client-enhanced.js.map +1 -1
  10. package/dist/src/api/claude-client.js +4 -2
  11. package/dist/src/api/claude-client.js.map +1 -1
  12. package/dist/src/api/database-service.js.map +1 -1
  13. package/dist/src/api/swarm-api.js +1 -1
  14. package/dist/src/api/swarm-api.js.map +1 -1
  15. package/dist/src/cli/commands/hive-mind/wizard.js +1 -1
  16. package/dist/src/cli/commands/hive-mind/wizard.js.map +1 -1
  17. package/dist/src/cli/help-formatter.js +0 -5
  18. package/dist/src/cli/init/index.js +55 -33
  19. package/dist/src/cli/init/index.js.map +1 -1
  20. package/dist/src/cli/simple-commands/init/skills-copier.js +1 -1
  21. package/dist/src/cli/simple-commands/init/skills-copier.js.map +1 -1
  22. package/dist/src/cli/simple-orchestrator.js +1 -1
  23. package/dist/src/cli/simple-orchestrator.js.map +1 -1
  24. package/dist/src/coordination/conflict-resolution.js +1 -1
  25. package/dist/src/coordination/conflict-resolution.js.map +1 -1
  26. package/dist/src/coordination/load-balancer.js +1 -1
  27. package/dist/src/coordination/load-balancer.js.map +1 -1
  28. package/dist/src/core/DatabaseManager.js +39 -9
  29. package/dist/src/core/DatabaseManager.js.map +1 -1
  30. package/dist/src/core/config.js +1 -1
  31. package/dist/src/core/config.js.map +1 -1
  32. package/dist/src/enterprise/audit-manager.js +1 -1
  33. package/dist/src/enterprise/audit-manager.js.map +1 -1
  34. package/dist/src/providers/openai-provider.js +2 -2
  35. package/dist/src/providers/openai-provider.js.map +1 -1
  36. package/dist/src/sdk/checkpoint-manager.js +1 -1
  37. package/dist/src/sdk/checkpoint-manager.js.map +1 -1
  38. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js +1 -1
  39. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js.map +1 -1
  40. package/dist/src/swarm/coordinator.js +1 -1
  41. package/dist/src/swarm/coordinator.js.map +1 -1
  42. package/dist/src/utils/error-recovery.js +215 -0
  43. package/dist/src/utils/error-recovery.js.map +1 -0
  44. package/dist/src/utils/key-redactor.js.map +1 -1
  45. package/dist/src/utils/metrics-reader.js +10 -0
  46. package/dist/src/verification/rollback.js +2 -2
  47. package/dist/src/verification/rollback.js.map +1 -1
  48. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js +4 -2
  49. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js.map +1 -1
  50. package/docs/.claude-flow/metrics/performance.json +3 -3
  51. package/docs/.claude-flow/metrics/task-metrics.json +3 -3
  52. package/docs/architecture/README.md +555 -0
  53. package/docs/architecture/github-workflows-optimization-strategy.md +1079 -0
  54. package/docs/architecture/workflow-architecture-diagram.md +615 -0
  55. package/docs/architecture/workflow-optimization-implementation-guide.md +593 -0
  56. package/docs/features/AUTOMATIC_ERROR_RECOVERY_v2.7.35.md +321 -0
  57. package/docs/features/automatic-error-recovery.md +333 -0
  58. package/docs/fixes/WORKFLOW_FIXES.md +292 -0
  59. package/docs/fixes/WORKFLOW_FIXES_FINAL_STATUS.md +291 -0
  60. package/docs/fixes/github-workflow-fixes-pr888.md +279 -0
  61. package/docs/fixes/workflow-fixes-action-plan.md +388 -0
  62. package/docs/github-issues/README.md +88 -0
  63. package/docs/github-issues/wsl-enotempty-automatic-recovery.md +470 -0
  64. package/docs/github-workflow-fixes.md +219 -0
  65. package/docs/reviews/github-workflows-analysis-report.md +820 -0
  66. package/docs/reviews/pr-888-review-report.md +560 -0
  67. package/docs/testing/CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md +384 -0
  68. package/docs/testing/DOCKER_TEST_RESULTS_v2.7.35.md +305 -0
  69. package/docs/troubleshooting/wsl-better-sqlite3-error.md +239 -0
  70. package/docs/validation/workflow-fix-verification.md +206 -0
  71. package/package.json +7 -7
  72. package/scripts/create-github-issue.sh +64 -0
  73. package/scripts/test-docker-wsl.sh +198 -0
  74. package/src/__tests__/benchmarks/performance.bench.ts +2 -25
  75. package/src/__tests__/hook-matchers.test.ts +2 -0
  76. package/src/agents/agent-registry.ts +1 -1
  77. package/src/api/auth-service.ts +1 -1
  78. package/src/api/claude-client-enhanced.ts +2 -1
  79. package/src/api/claude-client.ts +2 -2
  80. package/src/api/database-service.ts +1 -2
  81. package/src/api/swarm-api.ts +2 -2
  82. package/src/cli/commands/hive-mind/wizard.ts +1 -1
  83. package/src/cli/init/index.ts +72 -42
  84. package/src/cli/simple-commands/init/skills-copier.js +1 -1
  85. package/src/cli/simple-orchestrator.ts +1 -1
  86. package/src/coordination/conflict-resolution.ts +1 -1
  87. package/src/coordination/load-balancer.ts +1 -1
  88. package/src/core/DatabaseManager.ts +55 -9
  89. package/src/core/config.ts +1 -1
  90. package/src/enterprise/audit-manager.ts +1 -1
  91. package/src/providers/openai-provider.ts +2 -2
  92. package/src/sdk/checkpoint-manager.ts +1 -1
  93. package/src/services/agentic-flow-hooks/workflow-hooks.ts +1 -1
  94. package/src/swarm/coordinator.ts +1 -1
  95. package/src/utils/error-recovery.ts +325 -0
  96. package/src/verification/rollback.ts +2 -2
  97. package/src/verification/tests/mocks/false-reporting-scenarios.test.ts +6 -3
  98. /package/docs/{BUG_REPORT_MEMORY_STATS.md → bug-reports/BUG_REPORT_MEMORY_STATS.md} +0 -0
  99. /package/docs/{MCP_2025_FEATURE_CONFIRMATION.md → features/MCP_2025_FEATURE_CONFIRMATION.md} +0 -0
  100. /package/docs/{OPTIONAL_LOCAL_EMBEDDINGS.md → features/OPTIONAL_LOCAL_EMBEDDINGS.md} +0 -0
  101. /package/docs/{mcp-2025-implementation-summary.md → features/mcp-2025-implementation-summary.md} +0 -0
  102. /package/docs/{mcp-spec-2025-implementation-plan.md → features/mcp-spec-2025-implementation-plan.md} +0 -0
  103. /package/docs/{AGENTIC_FLOW_ENABLED_LOG_FIX.md → fixes/AGENTIC_FLOW_ENABLED_LOG_FIX.md} +0 -0
  104. /package/docs/{MEMORY_COMMAND_FIX.md → fixes/MEMORY_COMMAND_FIX.md} +0 -0
  105. /package/docs/{NPX_MEMORY_FIX_v2.7.19.md → fixes/NPX_MEMORY_FIX_v2.7.19.md} +0 -0
  106. /package/docs/{REMOTE_INSTALL_FIX.md → fixes/REMOTE_INSTALL_FIX.md} +0 -0
  107. /package/docs/{SQLITE_FIX_COMPLETE_v2.7.21.md → fixes/SQLITE_FIX_COMPLETE_v2.7.21.md} +0 -0
  108. /package/docs/{NPM_PUBLISH_GUIDE_v2.7.33.md → guides/NPM_PUBLISH_GUIDE_v2.7.33.md} +0 -0
  109. /package/docs/{SWARM_INITIALIZATION_GUIDE.md → guides/SWARM_INITIALIZATION_GUIDE.md} +0 -0
  110. /package/docs/{AGENTDB_BRANCH_MERGE_VERIFICATION.md → integration/AGENTDB_BRANCH_MERGE_VERIFICATION.md} +0 -0
  111. /package/docs/{INTEGRATION_STATUS_FINAL.md → integration/INTEGRATION_STATUS_FINAL.md} +0 -0
  112. /package/docs/{agentic-flow-agentdb-mcp-integration.md → integration/agentic-flow-agentdb-mcp-integration.md} +0 -0
  113. /package/docs/{phase-1-2-implementation-summary.md → integration/phase-1-2-implementation-summary.md} +0 -0
  114. /package/docs/{.github-release-issue-v2.7.33.md → releases/.github-release-issue-v2.7.33.md} +0 -0
  115. /package/docs/{RELEASE_NOTES_v2.7.15.md → releases/RELEASE_NOTES_v2.7.15.md} +0 -0
  116. /package/docs/{RELEASE_NOTES_v2.7.33.md → releases/RELEASE_NOTES_v2.7.33.md} +0 -0
  117. /package/docs/{RELEASE_READINESS_SUMMARY.md → releases/RELEASE_READINESS_SUMMARY.md} +0 -0
  118. /package/docs/{RELEASE_SUMMARY_v2.7.33.md → releases/RELEASE_SUMMARY_v2.7.33.md} +0 -0
  119. /package/docs/{V2.7.14_RELEASE_NOTES.md → releases/V2.7.14_RELEASE_NOTES.md} +0 -0
  120. /package/docs/{V2.7.25_RELEASE_NOTES.md → releases/V2.7.25_RELEASE_NOTES.md} +0 -0
  121. /package/docs/{V2.7.26_RELEASE_SUMMARY.md → releases/V2.7.26_RELEASE_SUMMARY.md} +0 -0
  122. /package/docs/{V2.7.27_RELEASE_NOTES.md → releases/V2.7.27_RELEASE_NOTES.md} +0 -0
  123. /package/docs/{V2.7.28_RELEASE_NOTES.md → releases/V2.7.28_RELEASE_NOTES.md} +0 -0
  124. /package/docs/{AGENTIC_FLOW_INTEGRATION_REVIEW.md → reviews/AGENTIC_FLOW_INTEGRATION_REVIEW.md} +0 -0
  125. /package/docs/{BRANCH_REVIEW_SUMMARY.md → reviews/BRANCH_REVIEW_SUMMARY.md} +0 -0
  126. /package/docs/{DEEP_CODE_REVIEW_v2.7.33.md → reviews/DEEP_CODE_REVIEW_v2.7.33.md} +0 -0
  127. /package/docs/{LATEST_LIBRARIES_REVIEW.md → reviews/LATEST_LIBRARIES_REVIEW.md} +0 -0
  128. /package/docs/{REGRESSION_TEST_REPORT_v2.7.33.md → testing/REGRESSION_TEST_REPORT_v2.7.33.md} +0 -0
  129. /package/docs/{V2.7.27_TEST_REPORT.md → testing/V2.7.27_TEST_REPORT.md} +0 -0
  130. /package/docs/{regression-analysis-phase-1-2.md → testing/regression-analysis-phase-1-2.md} +0 -0
  131. /package/docs/{TRANSFORMER_INITIALIZATION_ISSUE.md → troubleshooting/TRANSFORMER_INITIALIZATION_ISSUE.md} +0 -0
  132. /package/docs/{FIX_VERIFICATION_MEMORY_STATS.md → validation/FIX_VERIFICATION_MEMORY_STATS.md} +0 -0
  133. /package/docs/{TOOL_VALIDATION_REPORT.md → validation/TOOL_VALIDATION_REPORT.md} +0 -0
  134. /package/docs/{VALIDATION_REPORT_v2.7.1.md → validation/VALIDATION_REPORT_v2.7.1.md} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/coordination/load-balancer.ts"],"sourcesContent":["import {\n getErrorMessage,\n hasAgentLoad,\n hasAgentTask,\n hasWorkStealingData,\n} from '../utils/type-guards.js';\n/**\n * Advanced load balancing and work stealing implementation\n */\n\nimport { EventEmitter } from 'node:events';\nimport type { ILogger } from '../core/logger.js';\nimport type { IEventBus } from '../core/event-bus.js';\nimport type {\n AgentId,\n AgentState,\n TaskDefinition,\n TaskId,\n LoadBalancingStrategy,\n} from '../swarm/types.js';\nimport { WorkStealingCoordinator } from './work-stealing.js';\n\nexport interface LoadBalancerConfig {\n strategy: LoadBalancingStrategy;\n enableWorkStealing: boolean;\n stealThreshold: number;\n maxStealBatch: number;\n rebalanceInterval: number;\n loadSamplingInterval: number;\n affinityWeight: number;\n performanceWeight: number;\n loadWeight: number;\n latencyWeight: number;\n queueDepthThreshold: number;\n adaptiveThresholds: boolean;\n predictiveEnabled: boolean;\n debugMode: boolean;\n}\n\nexport interface AgentLoad {\n agentId: string;\n queueDepth: number;\n cpuUsage: number;\n memoryUsage: number;\n taskCount: number;\n averageResponseTime: number;\n throughput: number;\n lastUpdated: Date;\n capacity: number;\n utilization: number;\n efficiency: number;\n affinityScore: number;\n}\n\nexport interface LoadBalancingDecision {\n selectedAgent: AgentId;\n reason: string;\n confidence: number;\n alternatives: Array<{\n agent: AgentId;\n score: number;\n reason: string;\n }>;\n loadBefore: Record<string, number>;\n predictedLoadAfter: Record<string, number>;\n timestamp: Date;\n}\n\nexport interface WorkStealingOperation {\n id: string;\n sourceAgent: AgentId;\n targetAgent: AgentId;\n tasks: TaskId[];\n reason: string;\n status: 'planned' | 'executing' | 'completed' | 'failed';\n startTime: Date;\n endTime?: Date;\n metrics: {\n tasksStolen: number;\n loadReduction: number;\n latencyImprovement: number;\n };\n}\n\nexport interface LoadPrediction {\n agentId: string;\n currentLoad: number;\n predictedLoad: number;\n confidence: number;\n timeHorizon: number;\n factors: Record<string, number>;\n}\n\n/**\n * Advanced load balancing system with work stealing and predictive capabilities\n */\nexport class LoadBalancer extends EventEmitter {\n private logger: ILogger;\n private eventBus: IEventBus;\n private config: LoadBalancerConfig;\n private workStealer: WorkStealingCoordinator;\n\n // Load tracking\n private agentLoads = new Map<string, AgentLoad>();\n private loadHistory = new Map<string, Array<{ timestamp: Date; load: number }>>();\n private taskQueues = new Map<string, TaskDefinition[]>();\n\n // Monitoring and statistics\n private loadSamplingInterval?: NodeJS.Timeout;\n private rebalanceInterval?: NodeJS.Timeout;\n private decisions: LoadBalancingDecision[] = [];\n private stealOperations = new Map<string, WorkStealingOperation>();\n\n // Predictive modeling\n private loadPredictors = new Map<string, LoadPredictor>();\n private performanceBaselines = new Map<string, PerformanceBaseline>();\n\n constructor(config: Partial<LoadBalancerConfig>, logger: ILogger, eventBus: IEventBus) {\n super();\n this.logger = logger;\n this.eventBus = eventBus;\n\n this.config = {\n strategy: 'hybrid',\n enableWorkStealing: true,\n stealThreshold: 3,\n maxStealBatch: 5,\n rebalanceInterval: 10000,\n loadSamplingInterval: 5000,\n affinityWeight: 0.3,\n performanceWeight: 0.3,\n loadWeight: 0.25,\n latencyWeight: 0.15,\n queueDepthThreshold: 10,\n adaptiveThresholds: true,\n predictiveEnabled: true,\n debugMode: false,\n ...config,\n };\n\n this.workStealer = new WorkStealingCoordinator(\n {\n enabled: this.config.enableWorkStealing,\n stealThreshold: this.config.stealThreshold,\n maxStealBatch: this.config.maxStealBatch,\n stealInterval: this.config.rebalanceInterval,\n },\n this.eventBus,\n this.logger,\n );\n\n this.setupEventHandlers();\n }\n\n private setupEventHandlers(): void {\n this.eventBus.on('agent:load-update', (data) => {\n if (hasAgentLoad(data)) {\n this.updateAgentLoad(data.agentId, data.load);\n }\n });\n\n this.eventBus.on('task:queued', (data) => {\n if (hasAgentTask(data)) {\n this.updateTaskQueue(data.agentId, data.task, 'add');\n }\n });\n\n this.eventBus.on('task:started', (data) => {\n if (hasAgentTask(data)) {\n this.updateTaskQueue(data.agentId, data.task, 'remove');\n }\n });\n\n this.eventBus.on('workstealing:request', (data) => {\n if (hasWorkStealingData(data)) {\n this.executeWorkStealing(data.sourceAgent, data.targetAgent, data.taskCount);\n }\n });\n\n this.eventBus.on('agent:performance-update', (data) => {\n this.updatePerformanceBaseline(data.agentId, data.metrics);\n });\n }\n\n async initialize(): Promise<void> {\n this.logger.info('Initializing load balancer', {\n strategy: this.config.strategy,\n workStealing: this.config.enableWorkStealing,\n predictive: this.config.predictiveEnabled,\n });\n\n // Initialize work stealer\n await this.workStealer.initialize();\n\n // Start monitoring\n this.startLoadSampling();\n this.startRebalancing();\n\n this.emit('loadbalancer:initialized');\n }\n\n async shutdown(): Promise<void> {\n this.logger.info('Shutting down load balancer');\n\n // Stop monitoring\n if (this.loadSamplingInterval) clearInterval(this.loadSamplingInterval);\n if (this.rebalanceInterval) clearInterval(this.rebalanceInterval);\n\n // Shutdown work stealer\n await this.workStealer.shutdown();\n\n this.emit('loadbalancer:shutdown');\n }\n\n // === AGENT SELECTION ===\n\n async selectAgent(\n task: TaskDefinition,\n availableAgents: AgentState[],\n constraints?: {\n excludeAgents?: AgentId[];\n preferredAgents?: AgentId[];\n maxLoad?: number;\n requireCapabilities?: string[];\n },\n ): Promise<LoadBalancingDecision> {\n const startTime = Date.now();\n\n try {\n // Filter agents based on constraints\n let candidates = this.filterAgentsByConstraints(availableAgents, task, constraints);\n\n if (candidates.length === 0) {\n throw new Error('No suitable agents available for task');\n }\n\n // Apply selection strategy\n const decision = await this.applySelectionStrategy(task, candidates);\n\n // Record decision\n this.decisions.push(decision);\n\n // Keep only last 1000 decisions\n if (this.decisions.length > 1000) {\n this.decisions.shift();\n }\n\n const selectionTime = Date.now() - startTime;\n this.logger.debug('Agent selected', {\n taskId: task.id.id,\n selectedAgent: decision.selectedAgent.id,\n reason: decision.reason,\n confidence: decision.confidence,\n selectionTime,\n });\n\n this.emit('agent:selected', { task, decision, selectionTime });\n\n return decision;\n } catch (error) {\n this.logger.error('Agent selection failed', { taskId: task.id.id, error });\n throw error;\n }\n }\n\n private filterAgentsByConstraints(\n agents: AgentState[],\n task: TaskDefinition,\n constraints?: {\n excludeAgents?: AgentId[];\n preferredAgents?: AgentId[];\n maxLoad?: number;\n requireCapabilities?: string[];\n },\n ): AgentState[] {\n return agents.filter((agent) => {\n // Exclude specific agents\n if (constraints?.excludeAgents?.some((excluded) => excluded.id === agent.id.id)) {\n return false;\n }\n\n // Check maximum load\n const load = this.agentLoads.get(agent.id.id);\n if (constraints?.maxLoad && load && load.utilization > constraints.maxLoad) {\n return false;\n }\n\n // Check required capabilities\n if (constraints?.requireCapabilities) {\n const hasAllCapabilities = constraints.requireCapabilities.every(\n (cap) =>\n agent.capabilities.domains.includes(cap) ||\n agent.capabilities.tools.includes(cap) ||\n agent.capabilities.languages.includes(cap),\n );\n if (!hasAllCapabilities) {\n return false;\n }\n }\n\n // Check task type compatibility\n if (!this.isAgentCompatible(agent, task)) {\n return false;\n }\n\n return true;\n });\n }\n\n private async applySelectionStrategy(\n task: TaskDefinition,\n candidates: AgentState[],\n ): Promise<LoadBalancingDecision> {\n const scores = new Map<string, number>();\n const reasons = new Map<string, string>();\n const loadBefore: Record<string, number> = {};\n const predictedLoadAfter: Record<string, number> = {};\n\n // Calculate scores for each candidate\n for (const agent of candidates) {\n const agentId = agent.id.id;\n const load = this.agentLoads.get(agentId) || this.createDefaultLoad(agentId);\n\n loadBefore[agentId] = load.utilization;\n\n let score = 0;\n const scoreComponents: string[] = [];\n\n switch (this.config.strategy) {\n case 'load-based':\n score = this.calculateLoadScore(agent, load);\n scoreComponents.push(`load:${score.toFixed(2)}`);\n break;\n\n case 'performance-based':\n score = this.calculatePerformanceScore(agent, load);\n scoreComponents.push(`perf:${score.toFixed(2)}`);\n break;\n\n case 'capability-based':\n score = this.calculateCapabilityScore(agent, task);\n scoreComponents.push(`cap:${score.toFixed(2)}`);\n break;\n\n case 'affinity-based':\n score = this.calculateAffinityScore(agent, task);\n scoreComponents.push(`affinity:${score.toFixed(2)}`);\n break;\n\n case 'cost-based':\n score = this.calculateCostScore(agent, task);\n scoreComponents.push(`cost:${score.toFixed(2)}`);\n break;\n\n case 'hybrid':\n score = this.calculateHybridScore(agent, task, load);\n scoreComponents.push(`hybrid:${score.toFixed(2)}`);\n break;\n\n default:\n score = Math.random(); // Random fallback\n scoreComponents.push(`random:${score.toFixed(2)}`);\n }\n\n // Apply predictive modeling if enabled\n if (this.config.predictiveEnabled) {\n const prediction = this.predictLoad(agentId, task);\n const predictiveScore = this.calculatePredictiveScore(prediction);\n score = score * 0.7 + predictiveScore * 0.3;\n predictedLoadAfter[agentId] = prediction.predictedLoad;\n scoreComponents.push(`pred:${predictiveScore.toFixed(2)}`);\n } else {\n predictedLoadAfter[agentId] = load.utilization + 0.1; // Simple estimate\n }\n\n scores.set(agentId, score);\n reasons.set(agentId, scoreComponents.join(','));\n }\n\n // Select agent with highest score\n const sortedCandidates = candidates.sort((a, b) => {\n const scoreA = scores.get(a.id.id) || 0;\n const scoreB = scores.get(b.id.id) || 0;\n return scoreB - scoreA;\n });\n\n const selectedAgent = sortedCandidates[0];\n const selectedScore = scores.get(selectedAgent.id.id) || 0;\n const selectedReason = reasons.get(selectedAgent.id.id) || 'unknown';\n\n // Build alternatives list\n const alternatives = sortedCandidates.slice(1, 4).map((agent) => ({\n agent: agent.id,\n score: scores.get(agent.id.id) || 0,\n reason: reasons.get(agent.id.id) || 'unknown',\n }));\n\n // Calculate confidence based on score gap\n const secondBestScore = alternatives.length > 0 ? alternatives[0].score : 0;\n const confidence = Math.min(1, selectedScore - secondBestScore + 0.5);\n\n return {\n selectedAgent: selectedAgent.id,\n reason: selectedReason,\n confidence,\n alternatives,\n loadBefore,\n predictedLoadAfter,\n timestamp: new Date(),\n };\n }\n\n // === SCORING ALGORITHMS ===\n\n private calculateLoadScore(agent: AgentState, load: AgentLoad): number {\n // Higher score for lower load (inverted)\n return 1 - load.utilization;\n }\n\n private calculatePerformanceScore(agent: AgentState, load: AgentLoad): number {\n const baseline = this.performanceBaselines.get(agent.id.id);\n if (!baseline) return 0.5;\n\n // Combine throughput, efficiency, and response time\n const throughputScore = Math.min(1, load.throughput / baseline.expectedThroughput);\n const efficiencyScore = load.efficiency;\n const responseScore = Math.min(1, baseline.expectedResponseTime / load.averageResponseTime);\n\n return (throughputScore + efficiencyScore + responseScore) / 3;\n }\n\n private calculateCapabilityScore(agent: AgentState, task: TaskDefinition): number {\n let score = 0;\n let totalChecks = 0;\n\n // Check language compatibility\n if (task.requirements.capabilities.includes('coding')) {\n const hasLanguage = agent.capabilities.languages.some(\n (lang) => task.context.language === lang,\n );\n score += hasLanguage ? 1 : 0;\n totalChecks++;\n }\n\n // Check framework compatibility\n if (task.context.framework) {\n const hasFramework = agent.capabilities.frameworks.includes(task.context.framework);\n score += hasFramework ? 1 : 0;\n totalChecks++;\n }\n\n // Check domain expertise\n const domainMatch = agent.capabilities.domains.some(\n (domain) => task.type.includes(domain) || task.requirements.capabilities.includes(domain),\n );\n score += domainMatch ? 1 : 0;\n totalChecks++;\n\n // Check required tools\n const hasTools = task.requirements.tools.every((tool) =>\n agent.capabilities.tools.includes(tool),\n );\n score += hasTools ? 1 : 0;\n totalChecks++;\n\n return totalChecks > 0 ? score / totalChecks : 0;\n }\n\n private calculateAffinityScore(agent: AgentState, task: TaskDefinition): number {\n const load = this.agentLoads.get(agent.id.id);\n if (!load) return 0;\n\n return load.affinityScore || 0.5;\n }\n\n private calculateCostScore(agent: AgentState, task: TaskDefinition): number {\n // Simple cost model - could be enhanced\n const baseCost = 1.0;\n const performanceFactor = agent.capabilities.speed;\n const reliabilityFactor = agent.capabilities.reliability;\n\n const cost = baseCost / (performanceFactor * reliabilityFactor);\n return Math.max(0, 1 - cost / 2); // Normalize and invert\n }\n\n private calculateHybridScore(agent: AgentState, task: TaskDefinition, load: AgentLoad): number {\n const loadScore = this.calculateLoadScore(agent, load);\n const performanceScore = this.calculatePerformanceScore(agent, load);\n const capabilityScore = this.calculateCapabilityScore(agent, task);\n const affinityScore = this.calculateAffinityScore(agent, task);\n\n return (\n loadScore * this.config.loadWeight +\n performanceScore * this.config.performanceWeight +\n capabilityScore * this.config.affinityWeight +\n affinityScore * this.config.latencyWeight\n );\n }\n\n private calculatePredictiveScore(prediction: LoadPrediction): number {\n // Higher score for lower predicted load\n const loadScore = 1 - prediction.predictedLoad;\n const confidenceBonus = prediction.confidence * 0.2;\n return Math.min(1, loadScore + confidenceBonus);\n }\n\n // === WORK STEALING ===\n\n private async executeWorkStealing(\n sourceAgentId: string,\n targetAgentId: string,\n taskCount: number,\n ): Promise<void> {\n const operationId = `steal-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n const operation: WorkStealingOperation = {\n id: operationId,\n sourceAgent: { id: sourceAgentId, swarmId: 'default', type: 'coordinator', instance: 1 },\n targetAgent: { id: targetAgentId, swarmId: 'default', type: 'coordinator', instance: 1 },\n tasks: [],\n reason: 'load_imbalance',\n status: 'planned',\n startTime: new Date(),\n metrics: {\n tasksStolen: 0,\n loadReduction: 0,\n latencyImprovement: 0,\n },\n };\n\n this.stealOperations.set(operationId, operation);\n\n try {\n operation.status = 'executing';\n\n // Get source queue\n const sourceQueue = this.taskQueues.get(sourceAgentId) || [];\n if (sourceQueue.length === 0) {\n throw new Error('Source agent has no tasks to steal');\n }\n\n // Select tasks to steal (lowest priority first)\n const tasksToSteal = sourceQueue\n .sort((a, b) => (a.priority === b.priority ? 0 : a.priority === 'low' ? -1 : 1))\n .slice(0, Math.min(taskCount, this.config.maxStealBatch));\n\n // Remove tasks from source\n for (const task of tasksToSteal) {\n this.updateTaskQueue(sourceAgentId, task, 'remove');\n this.updateTaskQueue(targetAgentId, task, 'add');\n operation.tasks.push(task.id);\n }\n\n // Update metrics\n operation.metrics.tasksStolen = tasksToSteal.length;\n operation.metrics.loadReduction = this.calculateLoadReduction(\n sourceAgentId,\n tasksToSteal.length,\n );\n operation.status = 'completed';\n operation.endTime = new Date();\n\n this.logger.info('Work stealing completed', {\n operationId,\n sourceAgent: sourceAgentId,\n targetAgent: targetAgentId,\n tasksStolen: operation.metrics.tasksStolen,\n });\n\n this.emit('workstealing:completed', { operation });\n } catch (error) {\n operation.status = 'failed';\n operation.endTime = new Date();\n\n this.logger.error('Work stealing failed', {\n operationId,\n sourceAgent: sourceAgentId,\n targetAgent: targetAgentId,\n error,\n });\n\n this.emit('workstealing:failed', { operation, error });\n }\n }\n\n // === LOAD MONITORING ===\n\n private startLoadSampling(): void {\n this.loadSamplingInterval = setInterval(() => {\n this.sampleAgentLoads();\n }, this.config.loadSamplingInterval);\n\n this.logger.info('Started load sampling', {\n interval: this.config.loadSamplingInterval,\n });\n }\n\n private startRebalancing(): void {\n this.rebalanceInterval = setInterval(() => {\n this.performRebalancing();\n }, this.config.rebalanceInterval);\n\n this.logger.info('Started rebalancing', {\n interval: this.config.rebalanceInterval,\n });\n }\n\n private async sampleAgentLoads(): Promise<void> {\n // Sample current loads from all agents\n for (const [agentId, load] of this.agentLoads) {\n // Update load history\n const history = this.loadHistory.get(agentId) || [];\n history.push({ timestamp: new Date(), load: load.utilization });\n\n // Keep only last 100 samples\n if (history.length > 100) {\n history.shift();\n }\n\n this.loadHistory.set(agentId, history);\n\n // Update predictive models\n if (this.config.predictiveEnabled) {\n this.updateLoadPredictor(agentId, load);\n }\n }\n }\n\n private async performRebalancing(): Promise<void> {\n if (!this.config.enableWorkStealing) return;\n\n try {\n // Find overloaded and underloaded agents\n const loads = Array.from(this.agentLoads.entries());\n const overloaded = loads.filter(\n ([_, load]) => load.utilization > 0.8 && load.queueDepth > this.config.queueDepthThreshold,\n );\n const underloaded = loads.filter(\n ([_, load]) => load.utilization < 0.3 && load.queueDepth < 2,\n );\n\n if (overloaded.length === 0 || underloaded.length === 0) {\n return; // No rebalancing needed\n }\n\n // Perform work stealing\n for (const [overloadedId, overloadedLoad] of overloaded) {\n // Find best underloaded target\n const target = underloaded.sort((a, b) => a[1].utilization - b[1].utilization)[0];\n\n if (target) {\n const [targetId] = target;\n const tasksToSteal = Math.min(\n Math.floor((overloadedLoad.queueDepth - targetId.length) / 2),\n this.config.maxStealBatch,\n );\n\n if (tasksToSteal > 0) {\n await this.executeWorkStealing(overloadedId, targetId, tasksToSteal);\n }\n }\n }\n } catch (error) {\n this.logger.error('Rebalancing failed', error);\n }\n }\n\n // === PREDICTIVE MODELING ===\n\n private predictLoad(agentId: string, task: TaskDefinition): LoadPrediction {\n const predictor = this.loadPredictors.get(agentId);\n const currentLoad = this.agentLoads.get(agentId)?.utilization || 0;\n\n if (!predictor) {\n // Simple fallback prediction\n return {\n agentId,\n currentLoad,\n predictedLoad: Math.min(1, currentLoad + 0.1),\n confidence: 0.5,\n timeHorizon: 60000, // 1 minute\n factors: { task_complexity: 0.1 },\n };\n }\n\n return predictor.predict(task);\n }\n\n private updateLoadPredictor(agentId: string, load: AgentLoad): void {\n let predictor = this.loadPredictors.get(agentId);\n if (!predictor) {\n predictor = new LoadPredictor(agentId);\n this.loadPredictors.set(agentId, predictor);\n }\n\n predictor.update(load);\n }\n\n // === UTILITY METHODS ===\n\n private isAgentCompatible(agent: AgentState, task: TaskDefinition): boolean {\n // Check basic type compatibility\n const typeCompatible = this.checkTypeCompatibility(agent.type, task.type);\n if (!typeCompatible) return false;\n\n // Check capability requirements\n const hasRequiredCapabilities = task.requirements.capabilities.every((cap) => {\n return (\n agent.capabilities.domains.includes(cap) ||\n agent.capabilities.tools.includes(cap) ||\n agent.capabilities.languages.includes(cap)\n );\n });\n\n return hasRequiredCapabilities;\n }\n\n private checkTypeCompatibility(agentType: string, taskType: string): boolean {\n const compatibilityMap: Record<string, string[]> = {\n researcher: ['research', 'analysis', 'documentation'],\n coder: ['coding', 'testing', 'integration', 'deployment'],\n analyst: ['analysis', 'validation', 'review'],\n reviewer: ['review', 'validation', 'documentation'],\n coordinator: ['coordination', 'monitoring', 'management'],\n tester: ['testing', 'validation', 'integration'],\n specialist: ['custom', 'optimization', 'maintenance'],\n };\n\n const compatibleTypes = compatibilityMap[agentType] || [];\n return compatibleTypes.some((type) => taskType.includes(type));\n }\n\n private updateAgentLoad(agentId: string, loadData: Partial<AgentLoad>): void {\n const existing = this.agentLoads.get(agentId) || this.createDefaultLoad(agentId);\n const updated = { ...existing, ...loadData, lastUpdated: new Date() };\n\n // Recalculate utilization\n updated.utilization = this.calculateUtilization(updated);\n\n this.agentLoads.set(agentId, updated);\n }\n\n private updateTaskQueue(\n agentId: string,\n task: TaskDefinition,\n operation: 'add' | 'remove',\n ): void {\n const queue = this.taskQueues.get(agentId) || [];\n\n if (operation === 'add') {\n queue.push(task);\n } else {\n const index = queue.findIndex((t) => t.id.id === task.id.id);\n if (index >= 0) {\n queue.splice(index, 1);\n }\n }\n\n this.taskQueues.set(agentId, queue);\n\n // Update agent load\n this.updateAgentLoad(agentId, {\n queueDepth: queue.length,\n taskCount: queue.length,\n });\n }\n\n private updatePerformanceBaseline(agentId: string, metrics: any): void {\n const baseline = this.performanceBaselines.get(agentId) || {\n expectedThroughput: 10,\n expectedResponseTime: 5000,\n expectedQuality: 0.8,\n };\n\n // Update baseline with exponential moving average\n const alpha = 0.1;\n baseline.expectedThroughput =\n baseline.expectedThroughput * (1 - alpha) + metrics.throughput * alpha;\n baseline.expectedResponseTime =\n baseline.expectedResponseTime * (1 - alpha) + metrics.responseTime * alpha;\n\n this.performanceBaselines.set(agentId, baseline);\n }\n\n private calculateUtilization(load: AgentLoad): number {\n // Combine multiple factors to calculate overall utilization\n const queueFactor = Math.min(1, load.queueDepth / 10);\n const cpuFactor = load.cpuUsage / 100;\n const memoryFactor = load.memoryUsage / 100;\n const taskFactor = Math.min(1, load.taskCount / load.capacity);\n\n return (queueFactor + cpuFactor + memoryFactor + taskFactor) / 4;\n }\n\n private calculateLoadReduction(agentId: string, tasksRemoved: number): number {\n const load = this.agentLoads.get(agentId);\n if (!load) return 0;\n\n const oldUtilization = load.utilization;\n const newUtilization = this.calculateUtilization({\n ...load,\n queueDepth: load.queueDepth - tasksRemoved,\n taskCount: load.taskCount - tasksRemoved,\n });\n\n return oldUtilization - newUtilization;\n }\n\n private createDefaultLoad(agentId: string): AgentLoad {\n return {\n agentId,\n queueDepth: 0,\n cpuUsage: 0,\n memoryUsage: 0,\n taskCount: 0,\n averageResponseTime: 5000,\n throughput: 0,\n lastUpdated: new Date(),\n capacity: 10,\n utilization: 0,\n efficiency: 1.0,\n affinityScore: 0.5,\n };\n }\n\n // === PUBLIC API ===\n\n getAgentLoad(agentId: string): AgentLoad | undefined {\n return this.agentLoads.get(agentId);\n }\n\n getAllLoads(): AgentLoad[] {\n return Array.from(this.agentLoads.values());\n }\n\n getRecentDecisions(limit: number = 10): LoadBalancingDecision[] {\n return this.decisions.slice(-limit);\n }\n\n getStealOperations(): WorkStealingOperation[] {\n return Array.from(this.stealOperations.values());\n }\n\n getLoadStatistics(): {\n totalAgents: number;\n averageUtilization: number;\n overloadedAgents: number;\n underloadedAgents: number;\n totalStealOperations: number;\n successfulSteals: number;\n } {\n const loads = Array.from(this.agentLoads.values());\n const avgUtilization =\n loads.reduce((sum, load) => sum + load.utilization, 0) / loads.length || 0;\n const overloaded = loads.filter((load) => load.utilization > 0.8).length;\n const underloaded = loads.filter((load) => load.utilization < 0.3).length;\n const successfulSteals = Array.from(this.stealOperations.values()).filter(\n (op) => op.status === 'completed',\n ).length;\n\n return {\n totalAgents: loads.length,\n averageUtilization: avgUtilization,\n overloadedAgents: overloaded,\n underloadedAgents: underloaded,\n totalStealOperations: this.stealOperations.size,\n successfulSteals,\n };\n }\n\n // Force rebalance\n async forceRebalance(): Promise<void> {\n await this.performRebalancing();\n }\n}\n\n// === HELPER CLASSES ===\n\nclass LoadPredictor {\n private agentId: string;\n private history: Array<{ timestamp: Date; load: number }> = [];\n private model: SimpleLinearModel;\n\n constructor(agentId: string) {\n this.agentId = agentId;\n this.model = new SimpleLinearModel();\n }\n\n update(load: AgentLoad): void {\n this.history.push({ timestamp: new Date(), load: load.utilization });\n\n // Keep only last 50 samples\n if (this.history.length > 50) {\n this.history.shift();\n }\n\n // Update model if we have enough data\n if (this.history.length >= 10) {\n this.model.train(this.history);\n }\n }\n\n predict(task: TaskDefinition): LoadPrediction {\n const currentLoad = this.history.length > 0 ? this.history[this.history.length - 1].load : 0;\n\n let predictedLoad = currentLoad;\n let confidence = 0.5;\n\n if (this.history.length >= 10) {\n const prediction = this.model.predict();\n predictedLoad = prediction.value;\n confidence = prediction.confidence;\n }\n\n // Adjust for task complexity\n const taskComplexity = this.estimateTaskComplexity(task);\n predictedLoad = Math.min(1, predictedLoad + taskComplexity * 0.1);\n\n return {\n agentId: this.agentId,\n currentLoad,\n predictedLoad,\n confidence,\n timeHorizon: 60000,\n factors: {\n task_complexity: taskComplexity,\n historical_trend: predictedLoad - currentLoad,\n },\n };\n }\n\n private estimateTaskComplexity(task: TaskDefinition): number {\n // Simple complexity estimation\n let complexity = 0.5;\n\n if (task.requirements.estimatedDuration && task.requirements.estimatedDuration > 300000) {\n complexity += 0.3; // Long-running task\n }\n\n if (task.requirements.memoryRequired && task.requirements.memoryRequired > 512 * 1024 * 1024) {\n complexity += 0.2; // Memory-intensive\n }\n\n if (task.requirements.capabilities.length > 3) {\n complexity += 0.2; // Requires multiple capabilities\n }\n\n return Math.min(1, complexity);\n }\n}\n\nclass SimpleLinearModel {\n private slope = 0;\n private intercept = 0;\n private r2 = 0;\n\n train(data: Array<{ timestamp: Date; load: number }>): void {\n if (data.length < 2) return;\n\n // Convert timestamps to relative time points\n const startTime = data[0].timestamp.getTime();\n const points = data.map((point, index) => ({\n x: index, // Use index as x for simplicity\n y: point.load,\n }));\n\n // Calculate linear regression\n const n = points.length;\n const sumX = points.reduce((sum, p) => sum + p.x, 0);\n const sumY = points.reduce((sum, p) => sum + p.y, 0);\n const sumXY = points.reduce((sum, p) => sum + p.x * p.y, 0);\n const sumXX = points.reduce((sum, p) => sum + p.x * p.x, 0);\n\n this.slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);\n this.intercept = (sumY - this.slope * sumX) / n;\n\n // Calculate R²\n const meanY = sumY / n;\n const ssTotal = points.reduce((sum, p) => sum + Math.pow(p.y - meanY, 2), 0);\n const ssRes = points.reduce((sum, p) => {\n const predicted = this.slope * p.x + this.intercept;\n return sum + Math.pow(p.y - predicted, 2);\n }, 0);\n\n this.r2 = 1 - ssRes / ssTotal;\n }\n\n predict(): { value: number; confidence: number } {\n // Predict next value (x = n)\n const nextValue = this.slope * 1 + this.intercept; // Predict 1 step ahead\n const confidence = Math.max(0, this.r2); // Use R² as confidence\n\n return {\n value: Math.max(0, Math.min(1, nextValue)),\n confidence,\n };\n }\n}\n\ninterface PerformanceBaseline {\n expectedThroughput: number;\n expectedResponseTime: number;\n expectedQuality: number;\n}\n"],"names":["hasAgentLoad","hasAgentTask","hasWorkStealingData","EventEmitter","WorkStealingCoordinator","LoadBalancer","logger","eventBus","config","workStealer","agentLoads","Map","loadHistory","taskQueues","loadSamplingInterval","rebalanceInterval","decisions","stealOperations","loadPredictors","performanceBaselines","strategy","enableWorkStealing","stealThreshold","maxStealBatch","affinityWeight","performanceWeight","loadWeight","latencyWeight","queueDepthThreshold","adaptiveThresholds","predictiveEnabled","debugMode","enabled","stealInterval","setupEventHandlers","on","data","updateAgentLoad","agentId","load","updateTaskQueue","task","executeWorkStealing","sourceAgent","targetAgent","taskCount","updatePerformanceBaseline","metrics","initialize","info","workStealing","predictive","startLoadSampling","startRebalancing","emit","shutdown","clearInterval","selectAgent","availableAgents","constraints","startTime","Date","now","candidates","filterAgentsByConstraints","length","Error","decision","applySelectionStrategy","push","shift","selectionTime","debug","taskId","id","selectedAgent","reason","confidence","error","agents","filter","agent","excludeAgents","some","excluded","get","maxLoad","utilization","requireCapabilities","hasAllCapabilities","every","cap","capabilities","domains","includes","tools","languages","isAgentCompatible","scores","reasons","loadBefore","predictedLoadAfter","createDefaultLoad","score","scoreComponents","calculateLoadScore","toFixed","calculatePerformanceScore","calculateCapabilityScore","calculateAffinityScore","calculateCostScore","calculateHybridScore","Math","random","prediction","predictLoad","predictiveScore","calculatePredictiveScore","predictedLoad","set","join","sortedCandidates","sort","a","b","scoreA","scoreB","selectedScore","selectedReason","alternatives","slice","map","secondBestScore","min","timestamp","baseline","throughputScore","throughput","expectedThroughput","efficiencyScore","efficiency","responseScore","expectedResponseTime","averageResponseTime","totalChecks","requirements","hasLanguage","lang","context","language","framework","hasFramework","frameworks","domainMatch","domain","type","hasTools","tool","affinityScore","baseCost","performanceFactor","speed","reliabilityFactor","reliability","cost","max","loadScore","performanceScore","capabilityScore","confidenceBonus","sourceAgentId","targetAgentId","operationId","toString","operation","swarmId","instance","tasks","status","tasksStolen","loadReduction","latencyImprovement","sourceQueue","tasksToSteal","priority","calculateLoadReduction","endTime","setInterval","sampleAgentLoads","interval","performRebalancing","history","updateLoadPredictor","loads","Array","from","entries","overloaded","_","queueDepth","underloaded","overloadedId","overloadedLoad","target","targetId","floor","predictor","currentLoad","timeHorizon","factors","task_complexity","predict","LoadPredictor","update","typeCompatible","checkTypeCompatibility","hasRequiredCapabilities","agentType","taskType","compatibilityMap","researcher","coder","analyst","reviewer","coordinator","tester","specialist","compatibleTypes","loadData","existing","updated","lastUpdated","calculateUtilization","queue","index","findIndex","t","splice","expectedQuality","alpha","responseTime","queueFactor","cpuFactor","cpuUsage","memoryFactor","memoryUsage","taskFactor","capacity","tasksRemoved","oldUtilization","newUtilization","getAgentLoad","getAllLoads","values","getRecentDecisions","limit","getStealOperations","getLoadStatistics","avgUtilization","reduce","sum","successfulSteals","op","totalAgents","averageUtilization","overloadedAgents","underloadedAgents","totalStealOperations","size","forceRebalance","model","SimpleLinearModel","train","value","taskComplexity","estimateTaskComplexity","historical_trend","complexity","estimatedDuration","memoryRequired","slope","intercept","r2","getTime","points","point","x","y","n","sumX","p","sumY","sumXY","sumXX","meanY","ssTotal","pow","ssRes","predicted","nextValue"],"mappings":"AAA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AMG,QAAQb,OAAOzB,MAAM,CAAC,CAACC,KAAK8B;YAChC,MAAMQ,YAAY,IAAI,CAAClB,KAAK,GAAGU,EAAEJ,CAAC,GAAG,IAAI,CAACL,SAAS;YACnD,OAAOrB,MAAMpJ,KAAKwL,GAAG,CAACN,EAAEH,CAAC,GAAGW,WAAW;QACzC,GAAG;QAEH,IAAI,CAAChB,EAAE,GAAG,IAAIe,QAAQF;IACxB;IAEApF,UAAiD;QAE/C,MAAMwF,YAAY,IAAI,CAACnB,KAAK,GAAG,IAAI,IAAI,CAACC,SAAS;QACjD,MAAM5M,aAAamC,KAAKqD,GAAG,CAAC,GAAG,IAAI,CAACqH,EAAE;QAEtC,OAAO;YACLT,OAAOjK,KAAKqD,GAAG,CAAC,GAAGrD,KAAKqB,GAAG,CAAC,GAAGsK;YAC/B9N;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/coordination/load-balancer.ts"],"sourcesContent":["import {\n getErrorMessage,\n hasAgentLoad,\n hasAgentTask,\n hasWorkStealingData,\n} from '../utils/type-guards.js';\n/**\n * Advanced load balancing and work stealing implementation\n */\n\nimport { EventEmitter } from 'node:events';\nimport type { ILogger } from '../core/logger.js';\nimport type { IEventBus } from '../core/event-bus.js';\nimport type {\n AgentId,\n AgentState,\n TaskDefinition,\n TaskId,\n LoadBalancingStrategy,\n} from '../swarm/types.js';\nimport { WorkStealingCoordinator } from './work-stealing.js';\n\nexport interface LoadBalancerConfig {\n strategy: LoadBalancingStrategy;\n enableWorkStealing: boolean;\n stealThreshold: number;\n maxStealBatch: number;\n rebalanceInterval: number;\n loadSamplingInterval: number;\n affinityWeight: number;\n performanceWeight: number;\n loadWeight: number;\n latencyWeight: number;\n queueDepthThreshold: number;\n adaptiveThresholds: boolean;\n predictiveEnabled: boolean;\n debugMode: boolean;\n}\n\nexport interface AgentLoad {\n agentId: string;\n queueDepth: number;\n cpuUsage: number;\n memoryUsage: number;\n taskCount: number;\n averageResponseTime: number;\n throughput: number;\n lastUpdated: Date;\n capacity: number;\n utilization: number;\n efficiency: number;\n affinityScore: number;\n}\n\nexport interface LoadBalancingDecision {\n selectedAgent: AgentId;\n reason: string;\n confidence: number;\n alternatives: Array<{\n agent: AgentId;\n score: number;\n reason: string;\n }>;\n loadBefore: Record<string, number>;\n predictedLoadAfter: Record<string, number>;\n timestamp: Date;\n}\n\nexport interface WorkStealingOperation {\n id: string;\n sourceAgent: AgentId;\n targetAgent: AgentId;\n tasks: TaskId[];\n reason: string;\n status: 'planned' | 'executing' | 'completed' | 'failed';\n startTime: Date;\n endTime?: Date;\n metrics: {\n tasksStolen: number;\n loadReduction: number;\n latencyImprovement: number;\n };\n}\n\nexport interface LoadPrediction {\n agentId: string;\n currentLoad: number;\n predictedLoad: number;\n confidence: number;\n timeHorizon: number;\n factors: Record<string, number>;\n}\n\n/**\n * Advanced load balancing system with work stealing and predictive capabilities\n */\nexport class LoadBalancer extends EventEmitter {\n private logger: ILogger;\n private eventBus: IEventBus;\n private config: LoadBalancerConfig;\n private workStealer: WorkStealingCoordinator;\n\n // Load tracking\n private agentLoads = new Map<string, AgentLoad>();\n private loadHistory = new Map<string, Array<{ timestamp: Date; load: number }>>();\n private taskQueues = new Map<string, TaskDefinition[]>();\n\n // Monitoring and statistics\n private loadSamplingInterval?: NodeJS.Timeout;\n private rebalanceInterval?: NodeJS.Timeout;\n private decisions: LoadBalancingDecision[] = [];\n private stealOperations = new Map<string, WorkStealingOperation>();\n\n // Predictive modeling\n private loadPredictors = new Map<string, LoadPredictor>();\n private performanceBaselines = new Map<string, PerformanceBaseline>();\n\n constructor(config: Partial<LoadBalancerConfig>, logger: ILogger, eventBus: IEventBus) {\n super();\n this.logger = logger;\n this.eventBus = eventBus;\n\n this.config = {\n strategy: 'hybrid',\n enableWorkStealing: true,\n stealThreshold: 3,\n maxStealBatch: 5,\n rebalanceInterval: 10000,\n loadSamplingInterval: 5000,\n affinityWeight: 0.3,\n performanceWeight: 0.3,\n loadWeight: 0.25,\n latencyWeight: 0.15,\n queueDepthThreshold: 10,\n adaptiveThresholds: true,\n predictiveEnabled: true,\n debugMode: false,\n ...config,\n };\n\n this.workStealer = new WorkStealingCoordinator(\n {\n enabled: this.config.enableWorkStealing,\n stealThreshold: this.config.stealThreshold,\n maxStealBatch: this.config.maxStealBatch,\n stealInterval: this.config.rebalanceInterval,\n },\n this.eventBus,\n this.logger,\n );\n\n this.setupEventHandlers();\n }\n\n private setupEventHandlers(): void {\n this.eventBus.on('agent:load-update', (data) => {\n if (hasAgentLoad(data)) {\n this.updateAgentLoad(data.agentId, data.load);\n }\n });\n\n this.eventBus.on('task:queued', (data) => {\n if (hasAgentTask(data)) {\n this.updateTaskQueue(data.agentId, data.task, 'add');\n }\n });\n\n this.eventBus.on('task:started', (data) => {\n if (hasAgentTask(data)) {\n this.updateTaskQueue(data.agentId, data.task, 'remove');\n }\n });\n\n this.eventBus.on('workstealing:request', (data) => {\n if (hasWorkStealingData(data)) {\n this.executeWorkStealing(data.sourceAgent, data.targetAgent, data.taskCount);\n }\n });\n\n this.eventBus.on('agent:performance-update', (data) => {\n this.updatePerformanceBaseline(data.agentId, data.metrics);\n });\n }\n\n async initialize(): Promise<void> {\n this.logger.info('Initializing load balancer', {\n strategy: this.config.strategy,\n workStealing: this.config.enableWorkStealing,\n predictive: this.config.predictiveEnabled,\n });\n\n // Initialize work stealer\n await this.workStealer.initialize();\n\n // Start monitoring\n this.startLoadSampling();\n this.startRebalancing();\n\n this.emit('loadbalancer:initialized');\n }\n\n async shutdown(): Promise<void> {\n this.logger.info('Shutting down load balancer');\n\n // Stop monitoring\n if (this.loadSamplingInterval) clearInterval(this.loadSamplingInterval);\n if (this.rebalanceInterval) clearInterval(this.rebalanceInterval);\n\n // Shutdown work stealer\n await this.workStealer.shutdown();\n\n this.emit('loadbalancer:shutdown');\n }\n\n // === AGENT SELECTION ===\n\n async selectAgent(\n task: TaskDefinition,\n availableAgents: AgentState[],\n constraints?: {\n excludeAgents?: AgentId[];\n preferredAgents?: AgentId[];\n maxLoad?: number;\n requireCapabilities?: string[];\n },\n ): Promise<LoadBalancingDecision> {\n const startTime = Date.now();\n\n try {\n // Filter agents based on constraints\n const candidates = this.filterAgentsByConstraints(availableAgents, task, constraints);\n\n if (candidates.length === 0) {\n throw new Error('No suitable agents available for task');\n }\n\n // Apply selection strategy\n const decision = await this.applySelectionStrategy(task, candidates);\n\n // Record decision\n this.decisions.push(decision);\n\n // Keep only last 1000 decisions\n if (this.decisions.length > 1000) {\n this.decisions.shift();\n }\n\n const selectionTime = Date.now() - startTime;\n this.logger.debug('Agent selected', {\n taskId: task.id.id,\n selectedAgent: decision.selectedAgent.id,\n reason: decision.reason,\n confidence: decision.confidence,\n selectionTime,\n });\n\n this.emit('agent:selected', { task, decision, selectionTime });\n\n return decision;\n } catch (error) {\n this.logger.error('Agent selection failed', { taskId: task.id.id, error });\n throw error;\n }\n }\n\n private filterAgentsByConstraints(\n agents: AgentState[],\n task: TaskDefinition,\n constraints?: {\n excludeAgents?: AgentId[];\n preferredAgents?: AgentId[];\n maxLoad?: number;\n requireCapabilities?: string[];\n },\n ): AgentState[] {\n return agents.filter((agent) => {\n // Exclude specific agents\n if (constraints?.excludeAgents?.some((excluded) => excluded.id === agent.id.id)) {\n return false;\n }\n\n // Check maximum load\n const load = this.agentLoads.get(agent.id.id);\n if (constraints?.maxLoad && load && load.utilization > constraints.maxLoad) {\n return false;\n }\n\n // Check required capabilities\n if (constraints?.requireCapabilities) {\n const hasAllCapabilities = constraints.requireCapabilities.every(\n (cap) =>\n agent.capabilities.domains.includes(cap) ||\n agent.capabilities.tools.includes(cap) ||\n agent.capabilities.languages.includes(cap),\n );\n if (!hasAllCapabilities) {\n return false;\n }\n }\n\n // Check task type compatibility\n if (!this.isAgentCompatible(agent, task)) {\n return false;\n }\n\n return true;\n });\n }\n\n private async applySelectionStrategy(\n task: TaskDefinition,\n candidates: AgentState[],\n ): Promise<LoadBalancingDecision> {\n const scores = new Map<string, number>();\n const reasons = new Map<string, string>();\n const loadBefore: Record<string, number> = {};\n const predictedLoadAfter: Record<string, number> = {};\n\n // Calculate scores for each candidate\n for (const agent of candidates) {\n const agentId = agent.id.id;\n const load = this.agentLoads.get(agentId) || this.createDefaultLoad(agentId);\n\n loadBefore[agentId] = load.utilization;\n\n let score = 0;\n const scoreComponents: string[] = [];\n\n switch (this.config.strategy) {\n case 'load-based':\n score = this.calculateLoadScore(agent, load);\n scoreComponents.push(`load:${score.toFixed(2)}`);\n break;\n\n case 'performance-based':\n score = this.calculatePerformanceScore(agent, load);\n scoreComponents.push(`perf:${score.toFixed(2)}`);\n break;\n\n case 'capability-based':\n score = this.calculateCapabilityScore(agent, task);\n scoreComponents.push(`cap:${score.toFixed(2)}`);\n break;\n\n case 'affinity-based':\n score = this.calculateAffinityScore(agent, task);\n scoreComponents.push(`affinity:${score.toFixed(2)}`);\n break;\n\n case 'cost-based':\n score = this.calculateCostScore(agent, task);\n scoreComponents.push(`cost:${score.toFixed(2)}`);\n break;\n\n case 'hybrid':\n score = this.calculateHybridScore(agent, task, load);\n scoreComponents.push(`hybrid:${score.toFixed(2)}`);\n break;\n\n default:\n score = Math.random(); // Random fallback\n scoreComponents.push(`random:${score.toFixed(2)}`);\n }\n\n // Apply predictive modeling if enabled\n if (this.config.predictiveEnabled) {\n const prediction = this.predictLoad(agentId, task);\n const predictiveScore = this.calculatePredictiveScore(prediction);\n score = score * 0.7 + predictiveScore * 0.3;\n predictedLoadAfter[agentId] = prediction.predictedLoad;\n scoreComponents.push(`pred:${predictiveScore.toFixed(2)}`);\n } else {\n predictedLoadAfter[agentId] = load.utilization + 0.1; // Simple estimate\n }\n\n scores.set(agentId, score);\n reasons.set(agentId, scoreComponents.join(','));\n }\n\n // Select agent with highest score\n const sortedCandidates = candidates.sort((a, b) => {\n const scoreA = scores.get(a.id.id) || 0;\n const scoreB = scores.get(b.id.id) || 0;\n return scoreB - scoreA;\n });\n\n const selectedAgent = sortedCandidates[0];\n const selectedScore = scores.get(selectedAgent.id.id) || 0;\n const selectedReason = reasons.get(selectedAgent.id.id) || 'unknown';\n\n // Build alternatives list\n const alternatives = sortedCandidates.slice(1, 4).map((agent) => ({\n agent: agent.id,\n score: scores.get(agent.id.id) || 0,\n reason: reasons.get(agent.id.id) || 'unknown',\n }));\n\n // Calculate confidence based on score gap\n const secondBestScore = alternatives.length > 0 ? alternatives[0].score : 0;\n const confidence = Math.min(1, selectedScore - secondBestScore + 0.5);\n\n return {\n selectedAgent: selectedAgent.id,\n reason: selectedReason,\n confidence,\n alternatives,\n loadBefore,\n predictedLoadAfter,\n timestamp: new Date(),\n };\n }\n\n // === SCORING ALGORITHMS ===\n\n private calculateLoadScore(agent: AgentState, load: AgentLoad): number {\n // Higher score for lower load (inverted)\n return 1 - load.utilization;\n }\n\n private calculatePerformanceScore(agent: AgentState, load: AgentLoad): number {\n const baseline = this.performanceBaselines.get(agent.id.id);\n if (!baseline) return 0.5;\n\n // Combine throughput, efficiency, and response time\n const throughputScore = Math.min(1, load.throughput / baseline.expectedThroughput);\n const efficiencyScore = load.efficiency;\n const responseScore = Math.min(1, baseline.expectedResponseTime / load.averageResponseTime);\n\n return (throughputScore + efficiencyScore + responseScore) / 3;\n }\n\n private calculateCapabilityScore(agent: AgentState, task: TaskDefinition): number {\n let score = 0;\n let totalChecks = 0;\n\n // Check language compatibility\n if (task.requirements.capabilities.includes('coding')) {\n const hasLanguage = agent.capabilities.languages.some(\n (lang) => task.context.language === lang,\n );\n score += hasLanguage ? 1 : 0;\n totalChecks++;\n }\n\n // Check framework compatibility\n if (task.context.framework) {\n const hasFramework = agent.capabilities.frameworks.includes(task.context.framework);\n score += hasFramework ? 1 : 0;\n totalChecks++;\n }\n\n // Check domain expertise\n const domainMatch = agent.capabilities.domains.some(\n (domain) => task.type.includes(domain) || task.requirements.capabilities.includes(domain),\n );\n score += domainMatch ? 1 : 0;\n totalChecks++;\n\n // Check required tools\n const hasTools = task.requirements.tools.every((tool) =>\n agent.capabilities.tools.includes(tool),\n );\n score += hasTools ? 1 : 0;\n totalChecks++;\n\n return totalChecks > 0 ? score / totalChecks : 0;\n }\n\n private calculateAffinityScore(agent: AgentState, task: TaskDefinition): number {\n const load = this.agentLoads.get(agent.id.id);\n if (!load) return 0;\n\n return load.affinityScore || 0.5;\n }\n\n private calculateCostScore(agent: AgentState, task: TaskDefinition): number {\n // Simple cost model - could be enhanced\n const baseCost = 1.0;\n const performanceFactor = agent.capabilities.speed;\n const reliabilityFactor = agent.capabilities.reliability;\n\n const cost = baseCost / (performanceFactor * reliabilityFactor);\n return Math.max(0, 1 - cost / 2); // Normalize and invert\n }\n\n private calculateHybridScore(agent: AgentState, task: TaskDefinition, load: AgentLoad): number {\n const loadScore = this.calculateLoadScore(agent, load);\n const performanceScore = this.calculatePerformanceScore(agent, load);\n const capabilityScore = this.calculateCapabilityScore(agent, task);\n const affinityScore = this.calculateAffinityScore(agent, task);\n\n return (\n loadScore * this.config.loadWeight +\n performanceScore * this.config.performanceWeight +\n capabilityScore * this.config.affinityWeight +\n affinityScore * this.config.latencyWeight\n );\n }\n\n private calculatePredictiveScore(prediction: LoadPrediction): number {\n // Higher score for lower predicted load\n const loadScore = 1 - prediction.predictedLoad;\n const confidenceBonus = prediction.confidence * 0.2;\n return Math.min(1, loadScore + confidenceBonus);\n }\n\n // === WORK STEALING ===\n\n private async executeWorkStealing(\n sourceAgentId: string,\n targetAgentId: string,\n taskCount: number,\n ): Promise<void> {\n const operationId = `steal-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n\n const operation: WorkStealingOperation = {\n id: operationId,\n sourceAgent: { id: sourceAgentId, swarmId: 'default', type: 'coordinator', instance: 1 },\n targetAgent: { id: targetAgentId, swarmId: 'default', type: 'coordinator', instance: 1 },\n tasks: [],\n reason: 'load_imbalance',\n status: 'planned',\n startTime: new Date(),\n metrics: {\n tasksStolen: 0,\n loadReduction: 0,\n latencyImprovement: 0,\n },\n };\n\n this.stealOperations.set(operationId, operation);\n\n try {\n operation.status = 'executing';\n\n // Get source queue\n const sourceQueue = this.taskQueues.get(sourceAgentId) || [];\n if (sourceQueue.length === 0) {\n throw new Error('Source agent has no tasks to steal');\n }\n\n // Select tasks to steal (lowest priority first)\n const tasksToSteal = sourceQueue\n .sort((a, b) => (a.priority === b.priority ? 0 : a.priority === 'low' ? -1 : 1))\n .slice(0, Math.min(taskCount, this.config.maxStealBatch));\n\n // Remove tasks from source\n for (const task of tasksToSteal) {\n this.updateTaskQueue(sourceAgentId, task, 'remove');\n this.updateTaskQueue(targetAgentId, task, 'add');\n operation.tasks.push(task.id);\n }\n\n // Update metrics\n operation.metrics.tasksStolen = tasksToSteal.length;\n operation.metrics.loadReduction = this.calculateLoadReduction(\n sourceAgentId,\n tasksToSteal.length,\n );\n operation.status = 'completed';\n operation.endTime = new Date();\n\n this.logger.info('Work stealing completed', {\n operationId,\n sourceAgent: sourceAgentId,\n targetAgent: targetAgentId,\n tasksStolen: operation.metrics.tasksStolen,\n });\n\n this.emit('workstealing:completed', { operation });\n } catch (error) {\n operation.status = 'failed';\n operation.endTime = new Date();\n\n this.logger.error('Work stealing failed', {\n operationId,\n sourceAgent: sourceAgentId,\n targetAgent: targetAgentId,\n error,\n });\n\n this.emit('workstealing:failed', { operation, error });\n }\n }\n\n // === LOAD MONITORING ===\n\n private startLoadSampling(): void {\n this.loadSamplingInterval = setInterval(() => {\n this.sampleAgentLoads();\n }, this.config.loadSamplingInterval);\n\n this.logger.info('Started load sampling', {\n interval: this.config.loadSamplingInterval,\n });\n }\n\n private startRebalancing(): void {\n this.rebalanceInterval = setInterval(() => {\n this.performRebalancing();\n }, this.config.rebalanceInterval);\n\n this.logger.info('Started rebalancing', {\n interval: this.config.rebalanceInterval,\n });\n }\n\n private async sampleAgentLoads(): Promise<void> {\n // Sample current loads from all agents\n for (const [agentId, load] of this.agentLoads) {\n // Update load history\n const history = this.loadHistory.get(agentId) || [];\n history.push({ timestamp: new Date(), load: load.utilization });\n\n // Keep only last 100 samples\n if (history.length > 100) {\n history.shift();\n }\n\n this.loadHistory.set(agentId, history);\n\n // Update predictive models\n if (this.config.predictiveEnabled) {\n this.updateLoadPredictor(agentId, load);\n }\n }\n }\n\n private async performRebalancing(): Promise<void> {\n if (!this.config.enableWorkStealing) return;\n\n try {\n // Find overloaded and underloaded agents\n const loads = Array.from(this.agentLoads.entries());\n const overloaded = loads.filter(\n ([_, load]) => load.utilization > 0.8 && load.queueDepth > this.config.queueDepthThreshold,\n );\n const underloaded = loads.filter(\n ([_, load]) => load.utilization < 0.3 && load.queueDepth < 2,\n );\n\n if (overloaded.length === 0 || underloaded.length === 0) {\n return; // No rebalancing needed\n }\n\n // Perform work stealing\n for (const [overloadedId, overloadedLoad] of overloaded) {\n // Find best underloaded target\n const target = underloaded.sort((a, b) => a[1].utilization - b[1].utilization)[0];\n\n if (target) {\n const [targetId] = target;\n const tasksToSteal = Math.min(\n Math.floor((overloadedLoad.queueDepth - targetId.length) / 2),\n this.config.maxStealBatch,\n );\n\n if (tasksToSteal > 0) {\n await this.executeWorkStealing(overloadedId, targetId, tasksToSteal);\n }\n }\n }\n } catch (error) {\n this.logger.error('Rebalancing failed', error);\n }\n }\n\n // === PREDICTIVE MODELING ===\n\n private predictLoad(agentId: string, task: TaskDefinition): LoadPrediction {\n const predictor = this.loadPredictors.get(agentId);\n const currentLoad = this.agentLoads.get(agentId)?.utilization || 0;\n\n if (!predictor) {\n // Simple fallback prediction\n return {\n agentId,\n currentLoad,\n predictedLoad: Math.min(1, currentLoad + 0.1),\n confidence: 0.5,\n timeHorizon: 60000, // 1 minute\n factors: { task_complexity: 0.1 },\n };\n }\n\n return predictor.predict(task);\n }\n\n private updateLoadPredictor(agentId: string, load: AgentLoad): void {\n let predictor = this.loadPredictors.get(agentId);\n if (!predictor) {\n predictor = new LoadPredictor(agentId);\n this.loadPredictors.set(agentId, predictor);\n }\n\n predictor.update(load);\n }\n\n // === UTILITY METHODS ===\n\n private isAgentCompatible(agent: AgentState, task: TaskDefinition): boolean {\n // Check basic type compatibility\n const typeCompatible = this.checkTypeCompatibility(agent.type, task.type);\n if (!typeCompatible) return false;\n\n // Check capability requirements\n const hasRequiredCapabilities = task.requirements.capabilities.every((cap) => {\n return (\n agent.capabilities.domains.includes(cap) ||\n agent.capabilities.tools.includes(cap) ||\n agent.capabilities.languages.includes(cap)\n );\n });\n\n return hasRequiredCapabilities;\n }\n\n private checkTypeCompatibility(agentType: string, taskType: string): boolean {\n const compatibilityMap: Record<string, string[]> = {\n researcher: ['research', 'analysis', 'documentation'],\n coder: ['coding', 'testing', 'integration', 'deployment'],\n analyst: ['analysis', 'validation', 'review'],\n reviewer: ['review', 'validation', 'documentation'],\n coordinator: ['coordination', 'monitoring', 'management'],\n tester: ['testing', 'validation', 'integration'],\n specialist: ['custom', 'optimization', 'maintenance'],\n };\n\n const compatibleTypes = compatibilityMap[agentType] || [];\n return compatibleTypes.some((type) => taskType.includes(type));\n }\n\n private updateAgentLoad(agentId: string, loadData: Partial<AgentLoad>): void {\n const existing = this.agentLoads.get(agentId) || this.createDefaultLoad(agentId);\n const updated = { ...existing, ...loadData, lastUpdated: new Date() };\n\n // Recalculate utilization\n updated.utilization = this.calculateUtilization(updated);\n\n this.agentLoads.set(agentId, updated);\n }\n\n private updateTaskQueue(\n agentId: string,\n task: TaskDefinition,\n operation: 'add' | 'remove',\n ): void {\n const queue = this.taskQueues.get(agentId) || [];\n\n if (operation === 'add') {\n queue.push(task);\n } else {\n const index = queue.findIndex((t) => t.id.id === task.id.id);\n if (index >= 0) {\n queue.splice(index, 1);\n }\n }\n\n this.taskQueues.set(agentId, queue);\n\n // Update agent load\n this.updateAgentLoad(agentId, {\n queueDepth: queue.length,\n taskCount: queue.length,\n });\n }\n\n private updatePerformanceBaseline(agentId: string, metrics: any): void {\n const baseline = this.performanceBaselines.get(agentId) || {\n expectedThroughput: 10,\n expectedResponseTime: 5000,\n expectedQuality: 0.8,\n };\n\n // Update baseline with exponential moving average\n const alpha = 0.1;\n baseline.expectedThroughput =\n baseline.expectedThroughput * (1 - alpha) + metrics.throughput * alpha;\n baseline.expectedResponseTime =\n baseline.expectedResponseTime * (1 - alpha) + metrics.responseTime * alpha;\n\n this.performanceBaselines.set(agentId, baseline);\n }\n\n private calculateUtilization(load: AgentLoad): number {\n // Combine multiple factors to calculate overall utilization\n const queueFactor = Math.min(1, load.queueDepth / 10);\n const cpuFactor = load.cpuUsage / 100;\n const memoryFactor = load.memoryUsage / 100;\n const taskFactor = Math.min(1, load.taskCount / load.capacity);\n\n return (queueFactor + cpuFactor + memoryFactor + taskFactor) / 4;\n }\n\n private calculateLoadReduction(agentId: string, tasksRemoved: number): number {\n const load = this.agentLoads.get(agentId);\n if (!load) return 0;\n\n const oldUtilization = load.utilization;\n const newUtilization = this.calculateUtilization({\n ...load,\n queueDepth: load.queueDepth - tasksRemoved,\n taskCount: load.taskCount - tasksRemoved,\n });\n\n return oldUtilization - newUtilization;\n }\n\n private createDefaultLoad(agentId: string): AgentLoad {\n return {\n agentId,\n queueDepth: 0,\n cpuUsage: 0,\n memoryUsage: 0,\n taskCount: 0,\n averageResponseTime: 5000,\n throughput: 0,\n lastUpdated: new Date(),\n capacity: 10,\n utilization: 0,\n efficiency: 1.0,\n affinityScore: 0.5,\n };\n }\n\n // === PUBLIC API ===\n\n getAgentLoad(agentId: string): AgentLoad | undefined {\n return this.agentLoads.get(agentId);\n }\n\n getAllLoads(): AgentLoad[] {\n return Array.from(this.agentLoads.values());\n }\n\n getRecentDecisions(limit: number = 10): LoadBalancingDecision[] {\n return this.decisions.slice(-limit);\n }\n\n getStealOperations(): WorkStealingOperation[] {\n return Array.from(this.stealOperations.values());\n }\n\n getLoadStatistics(): {\n totalAgents: number;\n averageUtilization: number;\n overloadedAgents: number;\n underloadedAgents: number;\n totalStealOperations: number;\n successfulSteals: number;\n } {\n const loads = Array.from(this.agentLoads.values());\n const avgUtilization =\n loads.reduce((sum, load) => sum + load.utilization, 0) / loads.length || 0;\n const overloaded = loads.filter((load) => load.utilization > 0.8).length;\n const underloaded = loads.filter((load) => load.utilization < 0.3).length;\n const successfulSteals = Array.from(this.stealOperations.values()).filter(\n (op) => op.status === 'completed',\n ).length;\n\n return {\n totalAgents: loads.length,\n averageUtilization: avgUtilization,\n overloadedAgents: overloaded,\n underloadedAgents: underloaded,\n totalStealOperations: this.stealOperations.size,\n successfulSteals,\n };\n }\n\n // Force rebalance\n async forceRebalance(): Promise<void> {\n await this.performRebalancing();\n }\n}\n\n// === HELPER CLASSES ===\n\nclass LoadPredictor {\n private agentId: string;\n private history: Array<{ timestamp: Date; load: number }> = [];\n private model: SimpleLinearModel;\n\n constructor(agentId: string) {\n this.agentId = agentId;\n this.model = new SimpleLinearModel();\n }\n\n update(load: AgentLoad): void {\n this.history.push({ timestamp: new Date(), load: load.utilization });\n\n // Keep only last 50 samples\n if (this.history.length > 50) {\n this.history.shift();\n }\n\n // Update model if we have enough data\n if (this.history.length >= 10) {\n this.model.train(this.history);\n }\n }\n\n predict(task: TaskDefinition): LoadPrediction {\n const currentLoad = this.history.length > 0 ? this.history[this.history.length - 1].load : 0;\n\n let predictedLoad = currentLoad;\n let confidence = 0.5;\n\n if (this.history.length >= 10) {\n const prediction = this.model.predict();\n predictedLoad = prediction.value;\n confidence = prediction.confidence;\n }\n\n // Adjust for task complexity\n const taskComplexity = this.estimateTaskComplexity(task);\n predictedLoad = Math.min(1, predictedLoad + taskComplexity * 0.1);\n\n return {\n agentId: this.agentId,\n currentLoad,\n predictedLoad,\n confidence,\n timeHorizon: 60000,\n factors: {\n task_complexity: taskComplexity,\n historical_trend: predictedLoad - currentLoad,\n },\n };\n }\n\n private estimateTaskComplexity(task: TaskDefinition): number {\n // Simple complexity estimation\n let complexity = 0.5;\n\n if (task.requirements.estimatedDuration && task.requirements.estimatedDuration > 300000) {\n complexity += 0.3; // Long-running task\n }\n\n if (task.requirements.memoryRequired && task.requirements.memoryRequired > 512 * 1024 * 1024) {\n complexity += 0.2; // Memory-intensive\n }\n\n if (task.requirements.capabilities.length > 3) {\n complexity += 0.2; // Requires multiple capabilities\n }\n\n return Math.min(1, complexity);\n }\n}\n\nclass SimpleLinearModel {\n private slope = 0;\n private intercept = 0;\n private r2 = 0;\n\n train(data: Array<{ timestamp: Date; load: number }>): void {\n if (data.length < 2) return;\n\n // Convert timestamps to relative time points\n const startTime = data[0].timestamp.getTime();\n const points = data.map((point, index) => ({\n x: index, // Use index as x for simplicity\n y: point.load,\n }));\n\n // Calculate linear regression\n const n = points.length;\n const sumX = points.reduce((sum, p) => sum + p.x, 0);\n const sumY = points.reduce((sum, p) => sum + p.y, 0);\n const sumXY = points.reduce((sum, p) => sum + p.x * p.y, 0);\n const sumXX = points.reduce((sum, p) => sum + p.x * p.x, 0);\n\n this.slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);\n this.intercept = (sumY - this.slope * sumX) / n;\n\n // Calculate R²\n const meanY = sumY / n;\n const ssTotal = points.reduce((sum, p) => sum + Math.pow(p.y - meanY, 2), 0);\n const ssRes = points.reduce((sum, p) => {\n const predicted = this.slope * p.x + this.intercept;\n return sum + Math.pow(p.y - predicted, 2);\n }, 0);\n\n this.r2 = 1 - ssRes / ssTotal;\n }\n\n predict(): { value: number; confidence: number } {\n // Predict next value (x = n)\n const nextValue = this.slope * 1 + this.intercept; // Predict 1 step ahead\n const confidence = Math.max(0, this.r2); // Use R² as confidence\n\n return {\n value: Math.max(0, Math.min(1, nextValue)),\n confidence,\n };\n }\n}\n\ninterface PerformanceBaseline {\n expectedThroughput: number;\n expectedResponseTime: number;\n expectedQuality: number;\n}\n"],"names":["hasAgentLoad","hasAgentTask","hasWorkStealingData","EventEmitter","WorkStealingCoordinator","LoadBalancer","logger","eventBus","config","workStealer","agentLoads","Map","loadHistory","taskQueues","loadSamplingInterval","rebalanceInterval","decisions","stealOperations","loadPredictors","performanceBaselines","strategy","enableWorkStealing","stealThreshold","maxStealBatch","affinityWeight","performanceWeight","loadWeight","latencyWeight","queueDepthThreshold","adaptiveThresholds","predictiveEnabled","debugMode","enabled","stealInterval","setupEventHandlers","on","data","updateAgentLoad","agentId","load","updateTaskQueue","task","executeWorkStealing","sourceAgent","targetAgent","taskCount","updatePerformanceBaseline","metrics","initialize","info","workStealing","predictive","startLoadSampling","startRebalancing","emit","shutdown","clearInterval","selectAgent","availableAgents","constraints","startTime","Date","now","candidates","filterAgentsByConstraints","length","Error","decision","applySelectionStrategy","push","shift","selectionTime","debug","taskId","id","selectedAgent","reason","confidence","error","agents","filter","agent","excludeAgents","some","excluded","get","maxLoad","utilization","requireCapabilities","hasAllCapabilities","every","cap","capabilities","domains","includes","tools","languages","isAgentCompatible","scores","reasons","loadBefore","predictedLoadAfter","createDefaultLoad","score","scoreComponents","calculateLoadScore","toFixed","calculatePerformanceScore","calculateCapabilityScore","calculateAffinityScore","calculateCostScore","calculateHybridScore","Math","random","prediction","predictLoad","predictiveScore","calculatePredictiveScore","predictedLoad","set","join","sortedCandidates","sort","a","b","scoreA","scoreB","selectedScore","selectedReason","alternatives","slice","map","secondBestScore","min","timestamp","baseline","throughputScore","throughput","expectedThroughput","efficiencyScore","efficiency","responseScore","expectedResponseTime","averageResponseTime","totalChecks","requirements","hasLanguage","lang","context","language","framework","hasFramework","frameworks","domainMatch","domain","type","hasTools","tool","affinityScore","baseCost","performanceFactor","speed","reliabilityFactor","reliability","cost","max","loadScore","performanceScore","capabilityScore","confidenceBonus","sourceAgentId","targetAgentId","operationId","toString","operation","swarmId","instance","tasks","status","tasksStolen","loadReduction","latencyImprovement","sourceQueue","tasksToSteal","priority","calculateLoadReduction","endTime","setInterval","sampleAgentLoads","interval","performRebalancing","history","updateLoadPredictor","loads","Array","from","entries","overloaded","_","queueDepth","underloaded","overloadedId","overloadedLoad","target","targetId","floor","predictor","currentLoad","timeHorizon","factors","task_complexity","predict","LoadPredictor","update","typeCompatible","checkTypeCompatibility","hasRequiredCapabilities","agentType","taskType","compatibilityMap","researcher","coder","analyst","reviewer","coordinator","tester","specialist","compatibleTypes","loadData","existing","updated","lastUpdated","calculateUtilization","queue","index","findIndex","t","splice","expectedQuality","alpha","responseTime","queueFactor","cpuFactor","cpuUsage","memoryFactor","memoryUsage","taskFactor","capacity","tasksRemoved","oldUtilization","newUtilization","getAgentLoad","getAllLoads","values","getRecentDecisions","limit","getStealOperations","getLoadStatistics","avgUtilization","reduce","sum","successfulSteals","op","totalAgents","averageUtilization","overloadedAgents","underloadedAgents","totalStealOperations","size","forceRebalance","model","SimpleLinearModel","train","value","taskComplexity","estimateTaskComplexity","historical_trend","complexity","estimatedDuration","memoryRequired","slope","intercept","r2","getTime","points","point","x","y","n","sumX","p","sumY","sumXY","sumXX","meanY","ssTotal","pow","ssRes","predicted","nextValue"],"mappings":"AAAA,SAEEA,YAAY,EACZC,YAAY,EACZC,mBAAmB,QACd,0BAA0B;AAKjC,SAASC,YAAY,QAAQ,cAAc;AAU3C,SAASC,uBAAuB,QAAQ,qBAAqB;AA4E7D,OAAO,MAAMC,qBAAqBF;IACxBG,OAAgB;IAChBC,SAAoB;IACpBC,OAA2B;IAC3BC,YAAqC;IAGrCC,aAAa,IAAIC,MAAyB;IAC1CC,cAAc,IAAID,MAAwD;IAC1EE,aAAa,IAAIF,MAAgC;IAGjDG,qBAAsC;IACtCC,kBAAmC;IACnCC,YAAqC,EAAE,CAAC;IACxCC,kBAAkB,IAAIN,MAAqC;IAG3DO,iBAAiB,IAAIP,MAA6B;IAClDQ,uBAAuB,IAAIR,MAAmC;IAEtE,YAAYH,MAAmC,EAAEF,MAAe,EAAEC,QAAmB,CAAE;QACrF,KAAK;QACL,IAAI,CAACD,MAAM,GAAGA;QACd,IAAI,CAACC,QAAQ,GAAGA;QAEhB,IAAI,CAACC,MAAM,GAAG;YACZY,UAAU;YACVC,oBAAoB;YACpBC,gBAAgB;YAChBC,eAAe;YACfR,mBAAmB;YACnBD,sBAAsB;YACtBU,gBAAgB;YAChBC,mBAAmB;YACnBC,YAAY;YACZC,eAAe;YACfC,qBAAqB;YACrBC,oBAAoB;YACpBC,mBAAmB;YACnBC,WAAW;YACX,G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B,EAAEJ,CAAC,GAAGI,EAAEJ,CAAC,EAAE;QAEzD,IAAI,CAACN,KAAK,GAAG,AAACQ,CAAAA,IAAII,QAAQH,OAAOE,IAAG,IAAMH,CAAAA,IAAIK,QAAQJ,OAAOA,IAAG;QAChE,IAAI,CAACR,SAAS,GAAG,AAACU,CAAAA,OAAO,IAAI,CAACX,KAAK,GAAGS,IAAG,IAAKD;QAG9C,MAAMM,QAAQH,OAAOH;QACrB,MAAMO,UAAUX,OAAOzB,MAAM,CAAC,CAACC,KAAK8B,IAAM9B,MAAMpJ,KAAKwL,GAAG,CAACN,EAAEH,CAAC,GAAGO,OAAO,IAAI;QAC1E,MAAMG,QAAQb,OAAOzB,MAAM,CAAC,CAACC,KAAK8B;YAChC,MAAMQ,YAAY,IAAI,CAAClB,KAAK,GAAGU,EAAEJ,CAAC,GAAG,IAAI,CAACL,SAAS;YACnD,OAAOrB,MAAMpJ,KAAKwL,GAAG,CAACN,EAAEH,CAAC,GAAGW,WAAW;QACzC,GAAG;QAEH,IAAI,CAAChB,EAAE,GAAG,IAAIe,QAAQF;IACxB;IAEApF,UAAiD;QAE/C,MAAMwF,YAAY,IAAI,CAACnB,KAAK,GAAG,IAAI,IAAI,CAACC,SAAS;QACjD,MAAM5M,aAAamC,KAAKqD,GAAG,CAAC,GAAG,IAAI,CAACqH,EAAE;QAEtC,OAAO;YACLT,OAAOjK,KAAKqD,GAAG,CAAC,GAAGrD,KAAKqB,GAAG,CAAC,GAAGsK;YAC/B9N;QACF;IACF;AACF"}
@@ -5,29 +5,59 @@ export class DatabaseManager {
5
5
  dbType;
6
6
  dbPath;
7
7
  initialized = false;
8
+ retryCount = 0;
9
+ maxRetries = 3;
8
10
  constructor(dbType = 'sqlite', dbPath){
9
11
  this.dbType = dbType;
10
12
  this.dbPath = dbPath || this.getDefaultPath();
11
13
  if (this.dbType === 'sqlite') {
12
- try {
13
- this.provider = new SQLiteProvider(this.dbPath);
14
- } catch (error) {
15
- console.warn('SQLite not available, falling back to JSON storage:', error);
16
- this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));
17
- this.dbType = 'json';
18
- }
14
+ this.provider = this.initializeSQLiteWithRecovery();
19
15
  } else {
20
16
  this.provider = new JSONProvider(this.dbPath);
21
17
  }
22
18
  }
19
+ initializeSQLiteWithRecovery() {
20
+ try {
21
+ return new SQLiteProvider(this.dbPath);
22
+ } catch (error) {
23
+ const errorMsg = error instanceof Error ? error.message : String(error);
24
+ if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
25
+ console.warn('⚠️ SQLite initialization failed due to npm cache error');
26
+ console.warn(' Will attempt automatic recovery during initialize()');
27
+ } else {
28
+ console.warn('SQLite not available, falling back to JSON storage:', error);
29
+ }
30
+ this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));
31
+ this.dbType = 'json';
32
+ return this.provider;
33
+ }
34
+ }
23
35
  getDefaultPath() {
24
36
  const baseDir = path.join(process.cwd(), '.claude-flow');
25
37
  return this.dbType === 'sqlite' ? path.join(baseDir, 'database.sqlite') : path.join(baseDir, 'database.json');
26
38
  }
27
39
  async initialize() {
28
40
  await fs.ensureDir(path.dirname(this.dbPath));
29
- await this.provider.initialize();
30
- this.initialized = true;
41
+ try {
42
+ await this.provider.initialize();
43
+ this.initialized = true;
44
+ } catch (error) {
45
+ if (this.dbType === 'json') {
46
+ throw error;
47
+ }
48
+ const errorMsg = error instanceof Error ? error.message : String(error);
49
+ if (this.retryCount < this.maxRetries) {
50
+ console.warn(`⚠️ Database initialization failed (attempt ${this.retryCount + 1}/${this.maxRetries})`);
51
+ console.warn(` Error: ${errorMsg}`);
52
+ console.log('🔄 Switching to JSON storage as fallback...');
53
+ this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));
54
+ this.dbType = 'json';
55
+ this.retryCount++;
56
+ await this.initialize();
57
+ } else {
58
+ throw error;
59
+ }
60
+ }
31
61
  }
32
62
  async store(key, value, namespace = 'default') {
33
63
  if (!this.initialized) {
@@ -1 +1 @@
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,CAACN,QAAQ,GAAG,IAAIS,aAAa,IAAI,CAACP,MAAM,CAACQ,OAAO,CAAC,WAAW;gBAChE,IAAI,CAACT,MAAM,GAAG;YAChB;QACF,OAAO;YACL,IAAI,CAACD,QAAQ,GAAG,IAAIS,aAAa,IAAI,CAACP,MAAM;QAC9C;IACF;IAEQE,iBAAyB;QAC/B,MAAMO,UAAUb,KAAKc,IAAI,CAACC,QAAQC,GAAG,IAAI;QACzC,OAAO,IAAI,CA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ACS,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"}
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 private retryCount: number = 0;\n private maxRetries: number = 3;\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 this.provider = this.initializeSQLiteWithRecovery();\n } else {\n this.provider = new JSONProvider(this.dbPath);\n }\n }\n\n /**\n * Initialize SQLite with automatic error recovery\n */\n private initializeSQLiteWithRecovery(): IDatabaseProvider {\n try {\n return new SQLiteProvider(this.dbPath);\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n // Check if it's an npm cache error\n if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {\n console.warn('⚠️ SQLite initialization failed due to npm cache error');\n console.warn(' Will attempt automatic recovery during initialize()');\n } else {\n console.warn('SQLite not available, falling back to JSON storage:', error);\n }\n\n // Fallback to JSON for now\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n return this.provider;\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\n try {\n await this.provider.initialize();\n this.initialized = true;\n } catch (error) {\n // If JSON provider failed, just propagate the error\n if (this.dbType === 'json') {\n throw error;\n }\n\n // For SQLite errors, attempt recovery\n const errorMsg = error instanceof Error ? error.message : String(error);\n if (this.retryCount < this.maxRetries) {\n console.warn(`⚠️ Database initialization failed (attempt ${this.retryCount + 1}/${this.maxRetries})`);\n console.warn(` Error: ${errorMsg}`);\n\n // Attempt to recover by switching to JSON\n console.log('🔄 Switching to JSON storage as fallback...');\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n this.retryCount++;\n\n // Retry initialization with JSON provider\n await this.initialize();\n } else {\n throw error;\n }\n }\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","retryCount","maxRetries","getDefaultPath","initializeSQLiteWithRecovery","JSONProvider","SQLiteProvider","error","errorMsg","Error","message","String","includes","console","warn","replace","baseDir","join","process","cwd","initialize","ensureDir","dirname","log","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","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;IAC7BC,aAAqB,EAAE;IACvBC,aAAqB,EAAE;IAE/B,YAAYJ,SAA4B,QAAQ,EAAEC,MAAe,CAAE;QACjE,IAAI,CAACD,MAAM,GAAGA;QACd,IAAI,CAACC,MAAM,GAAGA,UAAU,IAAI,CAACI,cAAc;QAG3C,IAAI,IAAI,CAACL,MAAM,KAAK,UAAU;YAC5B,IAAI,CAACD,QAAQ,GAAG,IAAI,CAACO,4BAA4B;QACnD,OAAO;YACL,IAAI,CAACP,QAAQ,GAAG,IAAIQ,aAAa,IAAI,CAACN,MAAM;QAC9C;IACF;IAKQK,+BAAkD;QACxD,IAAI;YACF,OAAO,IAAIE,eAAe,IAAI,CAACP,MAAM;QACvC,EAAE,OAAOQ,OAAO;YACd,MAAMC,WAAWD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGC,OAAOJ;YAGjE,IAAIC,SAASI,QAAQ,CAAC,gBAAgBJ,SAASI,QAAQ,CAAC,mBAAmB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iC,OAAO;IACpB;IAEA,MAAcA,UAAyB;QACrC,IAAI;YACF,MAAMtE,GAAG2B,SAAS,CAAC1B,KAAK2B,OAAO,CAAC,IAAI,CAACvB,MAAM;YAC3C,MAAML,GAAGyE,SAAS,CAAC,IAAI,CAACpE,MAAM,EAAE,IAAI,CAACqC,IAAI,EAAE;gBAAEgC,QAAQ;YAAE;QACzD,EAAE,OAAO7D,OAAO;YACdM,QAAQN,KAAK,CAAC,oCAAoCA;QACpD;IACF;AACF"}
@@ -57,7 +57,7 @@ const FORMAT_PARSERS = {
57
57
  parse: (content)=>{
58
58
  const lines = content.split('\n');
59
59
  const result = {};
60
- let current = result;
60
+ const current = result;
61
61
  const stack = [
62
62
  result
63
63
  ];