diff --git a/v3/neural/algorithms/decision-transformer.ts b/v3/neural/algorithms/decision-transformer.ts new file mode 100644 index 0000000000..2987df5842 --- /dev/null +++ b/v3/neural/algorithms/decision-transformer.ts @@ -0,0 +1,521 @@ +/** + * Decision Transformer + * + * Implements sequence modeling approach for RL: + * - Trajectory as sequence: (s, a, R, s, a, R, ...) + * - Return-conditioned generation + * - Causal transformer attention + * - Offline RL from trajectories + * + * Performance Target: <10ms per forward pass + */ + +import type { + DecisionTransformerConfig, + Trajectory, + TrajectoryStep, +} from '../types.js'; + +/** + * Default Decision Transformer configuration + */ +export const DEFAULT_DT_CONFIG: DecisionTransformerConfig = { + algorithm: 'decision-transformer', + learningRate: 0.0001, + gamma: 0.99, + entropyCoef: 0, + valueLossCoef: 0, + maxGradNorm: 1.0, + epochs: 1, + miniBatchSize: 64, + contextLength: 20, + numHeads: 4, + numLayers: 2, + hiddenDim: 64, + embeddingDim: 32, + dropout: 0.1, +}; + +/** + * Sequence entry for transformer + */ +interface SequenceEntry { + returnToGo: number; + state: Float32Array; + action: number; + timestep: number; +} + +/** + * Decision Transformer Implementation + */ +export class DecisionTransformer { + private config: DecisionTransformerConfig; + + // Embeddings + private stateEmbed: Float32Array; + private actionEmbed: Float32Array; + private returnEmbed: Float32Array; + private posEmbed: Float32Array; + + // Transformer layers (simplified) + private attentionWeights: Float32Array[][]; + private ffnWeights: Float32Array[][]; + + // Output head + private actionHead: Float32Array; + + // Training buffer + private trajectoryBuffer: Trajectory[] = []; + + // Dimensions + private stateDim = 768; + private numActions = 4; + + // Statistics + private updateCount = 0; + private avgLoss = 0; + + constructor(config: Partial = {}) { + this.config = { ...DEFAULT_DT_CONFIG, ...config }; + + // Initialize embeddings + this.stateEmbed = this.initEmbedding(this.stateDim, this.config.embeddingDim); + this.actionEmbed = this.initEmbedding(this.numActions, this.config.embeddingDim); + this.returnEmbed = this.initEmbedding(1, this.config.embeddingDim); + this.posEmbed = this.initEmbedding(this.config.contextLength * 3, this.config.embeddingDim); + + // Initialize transformer layers + this.attentionWeights = []; + this.ffnWeights = []; + + for (let l = 0; l < this.config.numLayers; l++) { + // Attention: Q, K, V, O projections + this.attentionWeights.push([ + this.initWeight(this.config.embeddingDim, this.config.hiddenDim), // Q + this.initWeight(this.config.embeddingDim, this.config.hiddenDim), // K + this.initWeight(this.config.embeddingDim, this.config.hiddenDim), // V + this.initWeight(this.config.hiddenDim, this.config.embeddingDim), // O + ]); + + // FFN: up and down projections + this.ffnWeights.push([ + this.initWeight(this.config.embeddingDim, this.config.hiddenDim * 4), + this.initWeight(this.config.hiddenDim * 4, this.config.embeddingDim), + ]); + } + + // Action prediction head + this.actionHead = this.initWeight(this.config.embeddingDim, this.numActions); + } + + /** + * Add trajectory for training + */ + addTrajectory(trajectory: Trajectory): void { + if (trajectory.isComplete && trajectory.steps.length > 0) { + this.trajectoryBuffer.push(trajectory); + + // Keep buffer bounded + if (this.trajectoryBuffer.length > 1000) { + this.trajectoryBuffer = this.trajectoryBuffer.slice(-1000); + } + } + } + + /** + * Train on buffered trajectories + * Target: <10ms per batch + */ + train(): { loss: number; accuracy: number } { + const startTime = performance.now(); + + if (this.trajectoryBuffer.length === 0) { + return { loss: 0, accuracy: 0 }; + } + + // Sample mini-batch of trajectories + const batchSize = Math.min(this.config.miniBatchSize, this.trajectoryBuffer.length); + const batch: Trajectory[] = []; + + for (let i = 0; i < batchSize; i++) { + const idx = Math.floor(Math.random() * this.trajectoryBuffer.length); + batch.push(this.trajectoryBuffer[idx]); + } + + let totalLoss = 0; + let correct = 0; + let total = 0; + + for (const trajectory of batch) { + // Create sequence from trajectory + const sequence = this.createSequence(trajectory); + + if (sequence.length < 2) continue; + + // Forward pass and compute loss + for (let t = 1; t < sequence.length; t++) { + // Use context up to position t + const context = sequence.slice(Math.max(0, t - this.config.contextLength), t); + const target = sequence[t]; + + // Predict action + const predicted = this.forward(context); + const predictedAction = this.argmax(predicted); + + // Cross-entropy loss + const loss = -Math.log(predicted[target.action] + 1e-8); + totalLoss += loss; + + if (predictedAction === target.action) { + correct++; + } + total++; + + // Gradient update (simplified) + this.updateWeights(context, target.action, predicted); + } + } + + this.updateCount++; + this.avgLoss = total > 0 ? totalLoss / total : 0; + + const elapsed = performance.now() - startTime; + if (elapsed > 10) { + console.warn(`DT training exceeded target: ${elapsed.toFixed(2)}ms > 10ms`); + } + + return { + loss: this.avgLoss, + accuracy: total > 0 ? correct / total : 0, + }; + } + + /** + * Get action conditioned on target return + */ + getAction( + states: Float32Array[], + actions: number[], + targetReturn: number + ): number { + // Build sequence + const sequence: SequenceEntry[] = []; + let returnToGo = targetReturn; + + for (let i = 0; i < states.length; i++) { + sequence.push({ + returnToGo, + state: states[i], + action: actions[i] ?? 0, + timestep: i, + }); + + // Decrease return-to-go by estimated reward + if (i > 0) { + returnToGo -= 0.1; // Placeholder for actual reward + } + } + + // Forward pass + const logits = this.forward(sequence); + return this.argmax(logits); + } + + /** + * Forward pass through transformer + */ + forward(sequence: SequenceEntry[]): Float32Array { + // Embed sequence elements + const seqLen = Math.min(sequence.length, this.config.contextLength); + const embedDim = this.config.embeddingDim; + + // Initialize hidden states (simplified: stack all modalities) + const hidden = new Float32Array(seqLen * 3 * embedDim); + + for (let t = 0; t < seqLen; t++) { + const entry = sequence[sequence.length - seqLen + t]; + const baseIdx = t * 3 * embedDim; + + // Embed return + for (let d = 0; d < embedDim; d++) { + hidden[baseIdx + d] = entry.returnToGo * this.returnEmbed[d]; + } + + // Embed state + for (let d = 0; d < embedDim; d++) { + let stateSum = 0; + for (let s = 0; s < Math.min(entry.state.length, this.stateDim); s++) { + stateSum += entry.state[s] * this.stateEmbed[s * embedDim + d]; + } + hidden[baseIdx + embedDim + d] = stateSum; + } + + // Embed action + for (let d = 0; d < embedDim; d++) { + hidden[baseIdx + 2 * embedDim + d] = this.actionEmbed[entry.action * embedDim + d]; + } + + // Add positional embedding + for (let d = 0; d < 3 * embedDim; d++) { + hidden[baseIdx + d] += this.posEmbed[t * 3 * embedDim + d] || 0; + } + } + + // Apply transformer layers + for (let l = 0; l < this.config.numLayers; l++) { + hidden.set(this.transformerLayer(hidden, seqLen * 3, l)); + } + + // Extract last state position embedding for action prediction + const lastStateIdx = (seqLen * 3 - 2) * embedDim; + const lastState = hidden.slice(lastStateIdx, lastStateIdx + embedDim); + + // Action prediction + const logits = new Float32Array(this.numActions); + for (let a = 0; a < this.numActions; a++) { + let sum = 0; + for (let d = 0; d < embedDim; d++) { + sum += lastState[d] * this.actionHead[d * this.numActions + a]; + } + logits[a] = sum; + } + + return this.softmax(logits); + } + + /** + * Get statistics + */ + getStats(): Record { + return { + updateCount: this.updateCount, + bufferSize: this.trajectoryBuffer.length, + avgLoss: this.avgLoss, + contextLength: this.config.contextLength, + numLayers: this.config.numLayers, + }; + } + + // ========================================================================== + // Private Methods + // ========================================================================== + + private initEmbedding(inputDim: number, outputDim: number): Float32Array { + const embed = new Float32Array(inputDim * outputDim); + const scale = Math.sqrt(2 / inputDim); + for (let i = 0; i < embed.length; i++) { + embed[i] = (Math.random() - 0.5) * scale; + } + return embed; + } + + private initWeight(inputDim: number, outputDim: number): Float32Array { + const weight = new Float32Array(inputDim * outputDim); + const scale = Math.sqrt(2 / inputDim); + for (let i = 0; i < weight.length; i++) { + weight[i] = (Math.random() - 0.5) * scale; + } + return weight; + } + + private createSequence(trajectory: Trajectory): SequenceEntry[] { + const sequence: SequenceEntry[] = []; + + // Compute returns-to-go + const rewards = trajectory.steps.map(s => s.reward); + const returnsToGo = new Array(rewards.length).fill(0); + let cumReturn = 0; + + for (let t = rewards.length - 1; t >= 0; t--) { + cumReturn = rewards[t] + this.config.gamma * cumReturn; + returnsToGo[t] = cumReturn; + } + + // Create sequence entries + for (let t = 0; t < trajectory.steps.length; t++) { + sequence.push({ + returnToGo: returnsToGo[t], + state: trajectory.steps[t].stateAfter, + action: this.hashAction(trajectory.steps[t].action), + timestep: t, + }); + } + + return sequence; + } + + private transformerLayer( + hidden: Float32Array, + seqLen: number, + layerIdx: number + ): Float32Array { + const embedDim = this.config.embeddingDim; + const hiddenDim = this.config.hiddenDim; + const numHeads = this.config.numHeads; + const headDim = hiddenDim / numHeads; + + const output = new Float32Array(hidden.length); + + // Self-attention (simplified causal) + const [Wq, Wk, Wv, Wo] = this.attentionWeights[layerIdx]; + + // Compute Q, K, V for all positions + const Q = new Float32Array(seqLen * hiddenDim); + const K = new Float32Array(seqLen * hiddenDim); + const V = new Float32Array(seqLen * hiddenDim); + + for (let pos = 0; pos < seqLen; pos++) { + for (let h = 0; h < hiddenDim; h++) { + let qSum = 0, kSum = 0, vSum = 0; + for (let d = 0; d < embedDim; d++) { + const hiddenVal = hidden[pos * embedDim + d]; + qSum += hiddenVal * Wq[d * hiddenDim + h]; + kSum += hiddenVal * Wk[d * hiddenDim + h]; + vSum += hiddenVal * Wv[d * hiddenDim + h]; + } + Q[pos * hiddenDim + h] = qSum; + K[pos * hiddenDim + h] = kSum; + V[pos * hiddenDim + h] = vSum; + } + } + + // Causal attention + for (let pos = 0; pos < seqLen; pos++) { + // Compute attention scores for current position + const scores = new Float32Array(pos + 1); + for (let k = 0; k <= pos; k++) { + let score = 0; + for (let h = 0; h < hiddenDim; h++) { + score += Q[pos * hiddenDim + h] * K[k * hiddenDim + h]; + } + scores[k] = score / Math.sqrt(headDim); + } + + // Softmax + const maxScore = Math.max(...scores); + let sumExp = 0; + for (let k = 0; k <= pos; k++) { + scores[k] = Math.exp(scores[k] - maxScore); + sumExp += scores[k]; + } + for (let k = 0; k <= pos; k++) { + scores[k] /= sumExp; + } + + // Weighted sum of values + const attnOut = new Float32Array(hiddenDim); + for (let k = 0; k <= pos; k++) { + for (let h = 0; h < hiddenDim; h++) { + attnOut[h] += scores[k] * V[k * hiddenDim + h]; + } + } + + // Output projection + for (let d = 0; d < embedDim; d++) { + let sum = hidden[pos * embedDim + d]; // Residual + for (let h = 0; h < hiddenDim; h++) { + sum += attnOut[h] * Wo[h * embedDim + d]; + } + output[pos * embedDim + d] = sum; + } + } + + // FFN with residual + const [Wup, Wdown] = this.ffnWeights[layerIdx]; + const ffnHiddenDim = hiddenDim * 4; + + for (let pos = 0; pos < seqLen; pos++) { + // Up projection + GELU + const ffnHidden = new Float32Array(ffnHiddenDim); + for (let h = 0; h < ffnHiddenDim; h++) { + let sum = 0; + for (let d = 0; d < embedDim; d++) { + sum += output[pos * embedDim + d] * Wup[d * ffnHiddenDim + h]; + } + // GELU approximation + ffnHidden[h] = sum * 0.5 * (1 + Math.tanh(0.7978845608 * (sum + 0.044715 * sum * sum * sum))); + } + + // Down projection + for (let d = 0; d < embedDim; d++) { + let sum = output[pos * embedDim + d]; // Residual + for (let h = 0; h < ffnHiddenDim; h++) { + sum += ffnHidden[h] * Wdown[h * embedDim + d]; + } + output[pos * embedDim + d] = sum; + } + } + + return output; + } + + private updateWeights( + context: SequenceEntry[], + targetAction: number, + predicted: Float32Array + ): void { + // Simplified gradient update for action head + const lr = this.config.learningRate; + const embedDim = this.config.embeddingDim; + + // Gradient of cross-entropy + const grad = new Float32Array(this.numActions); + for (let a = 0; a < this.numActions; a++) { + grad[a] = predicted[a] - (a === targetAction ? 1 : 0); + } + + // Update action head (simplified) + for (let d = 0; d < embedDim; d++) { + for (let a = 0; a < this.numActions; a++) { + this.actionHead[d * this.numActions + a] -= lr * grad[a] * 0.1; + } + } + } + + private softmax(logits: Float32Array): Float32Array { + const max = Math.max(...logits); + const exps = new Float32Array(logits.length); + let sum = 0; + + for (let i = 0; i < logits.length; i++) { + exps[i] = Math.exp(logits[i] - max); + sum += exps[i]; + } + + for (let i = 0; i < exps.length; i++) { + exps[i] /= sum; + } + + return exps; + } + + private argmax(values: Float32Array): number { + let maxIdx = 0; + let maxVal = values[0]; + for (let i = 1; i < values.length; i++) { + if (values[i] > maxVal) { + maxVal = values[i]; + maxIdx = i; + } + } + return maxIdx; + } + + private hashAction(action: string): number { + let hash = 0; + for (let i = 0; i < action.length; i++) { + hash = (hash * 31 + action.charCodeAt(i)) % this.numActions; + } + return hash; + } +} + +/** + * Factory function + */ +export function createDecisionTransformer( + config?: Partial +): DecisionTransformer { + return new DecisionTransformer(config); +} diff --git a/v3/swarm/unified-coordinator.ts b/v3/swarm/unified-coordinator.ts index 4b49cb57d9..342d3f995b 100644 --- a/v3/swarm/unified-coordinator.ts +++ b/v3/swarm/unified-coordinator.ts @@ -1083,6 +1083,476 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa getAgentPool(type: AgentType): AgentPool | undefined { return this.agentPools.get(type); } + + // ============================================================================= + // DOMAIN-BASED TASK ROUTING (15-Agent Hierarchy Support) + // ============================================================================= + + /** + * Assign a task to a specific domain + * Routes the task to the most suitable agent within that domain + */ + async assignTaskToDomain(taskId: string, domain: AgentDomain): Promise { + const startTime = performance.now(); + const task = this.state.tasks.get(taskId); + + if (!task) { + throw new Error(`Task ${taskId} not found`); + } + + const pool = this.domainPools.get(domain); + if (!pool) { + throw new Error(`Domain pool ${domain} not found`); + } + + // Try to acquire an agent from the domain pool + const agent = await pool.acquire(); + if (!agent) { + // Add to domain queue if no agents available + const queue = this.domainTaskQueues.get(domain) || []; + queue.push(taskId); + this.domainTaskQueues.set(domain, queue); + task.status = 'queued'; + + this.emitEvent('task.queued', { + taskId, + domain, + queuePosition: queue.length, + reason: 'no_available_agents' + }); + + return undefined; + } + + // Update task + task.status = 'assigned'; + task.assignedTo = agent.id; + task.startedAt = new Date(); + + // Track assignment + const assignment: TaskAssignment = { + taskId, + domain, + agentId: agent.id.id, + priority: task.priority, + assignedAt: new Date(), + }; + this.taskAssignments.set(taskId, assignment); + + // Notify agent via message bus + await this.messageBus.send({ + type: 'task_assign', + from: this.state.id.id, + to: agent.id.id, + payload: { taskId, task, domain }, + priority: this.mapTaskPriorityToMessagePriority(task.priority), + requiresAck: true, + ttlMs: this.config.taskTimeoutMs, + }); + + const duration = performance.now() - startTime; + this.recordCoordinationLatency(duration); + + this.emitEvent('task.assigned', { + taskId, + agentId: agent.id.id, + domain, + assignmentDurationMs: duration, + }); + + return agent.id.id; + } + + /** + * Get all agents belonging to a specific domain + */ + getAgentsByDomain(domain: AgentDomain): AgentState[] { + const agents: AgentState[] = []; + for (const [agentId, agentDomain] of this.agentDomainMap) { + if (agentDomain === domain) { + const agent = this.state.agents.get(agentId); + if (agent) { + agents.push(agent); + } + } + } + return agents; + } + + /** + * Execute multiple tasks in parallel across different domains + * This is the key method for achieving >85% agent utilization + */ + async executeParallel(tasks: Array<{ + task: Omit; + domain: AgentDomain; + }>): Promise { + const startTime = performance.now(); + const executionPromises: Promise[] = []; + + // Submit all tasks first + const taskIds: Array<{ taskId: string; domain: AgentDomain }> = []; + for (const { task, domain } of tasks) { + const taskId = await this.submitTask(task); + taskIds.push({ taskId, domain }); + } + + // Execute all tasks in parallel across domains + for (const { taskId, domain } of taskIds) { + const promise = this.executeTaskInDomain(taskId, domain); + executionPromises.push(promise); + } + + // Wait for all tasks to complete (with individual error handling) + const settledResults = await Promise.allSettled(executionPromises); + + const results: ParallelExecutionResult[] = []; + for (let i = 0; i < settledResults.length; i++) { + const result = settledResults[i]; + const { taskId, domain } = taskIds[i]; + + if (result.status === 'fulfilled') { + results.push(result.value); + } else { + results.push({ + taskId, + domain, + success: false, + error: result.reason instanceof Error ? result.reason : new Error(String(result.reason)), + durationMs: performance.now() - startTime, + }); + } + } + + this.emitEvent('parallel.execution.completed', { + totalTasks: tasks.length, + successful: results.filter(r => r.success).length, + failed: results.filter(r => !r.success).length, + totalDurationMs: performance.now() - startTime, + }); + + return results; + } + + private async executeTaskInDomain(taskId: string, domain: AgentDomain): Promise { + const startTime = performance.now(); + + try { + // Assign to domain + const agentId = await this.assignTaskToDomain(taskId, domain); + if (!agentId) { + // Task was queued, wait for it to be assigned and complete + return await this.waitForQueuedTask(taskId, domain, startTime); + } + + // Wait for completion + const result = await this.waitForTaskCompletion(taskId, this.config.taskTimeoutMs); + + return { + taskId, + domain, + success: result.status === 'completed', + result: result.output, + durationMs: performance.now() - startTime, + }; + } catch (error) { + return { + taskId, + domain, + success: false, + error: error instanceof Error ? error : new Error(String(error)), + durationMs: performance.now() - startTime, + }; + } + } + + private async waitForQueuedTask( + taskId: string, + domain: AgentDomain, + startTime: number + ): Promise { + return new Promise((resolve) => { + const checkInterval = setInterval(() => { + const task = this.state.tasks.get(taskId); + if (!task) { + clearInterval(checkInterval); + resolve({ + taskId, + domain, + success: false, + error: new Error(`Task ${taskId} not found`), + durationMs: performance.now() - startTime, + }); + return; + } + + if (task.status === 'completed') { + clearInterval(checkInterval); + resolve({ + taskId, + domain, + success: true, + result: task.output, + durationMs: performance.now() - startTime, + }); + } else if (task.status === 'failed' || task.status === 'cancelled' || task.status === 'timeout') { + clearInterval(checkInterval); + resolve({ + taskId, + domain, + success: false, + error: new Error(`Task ${task.status}`), + durationMs: performance.now() - startTime, + }); + } + }, 100); + + // Timeout after configured duration + setTimeout(() => { + clearInterval(checkInterval); + const task = this.state.tasks.get(taskId); + if (task && task.status !== 'completed') { + task.status = 'timeout'; + } + resolve({ + taskId, + domain, + success: false, + error: new Error('Task timed out'), + durationMs: performance.now() - startTime, + }); + }, this.config.taskTimeoutMs); + }); + } + + private async waitForTaskCompletion(taskId: string, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const checkInterval = setInterval(() => { + const task = this.state.tasks.get(taskId); + if (!task) { + clearInterval(checkInterval); + reject(new Error(`Task ${taskId} not found`)); + return; + } + + if (task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled') { + clearInterval(checkInterval); + resolve(task); + } + }, 100); + + setTimeout(() => { + clearInterval(checkInterval); + const task = this.state.tasks.get(taskId); + if (task) { + task.status = 'timeout'; + task.completedAt = new Date(); + resolve(task); + } else { + reject(new Error(`Task ${taskId} timed out`)); + } + }, timeoutMs); + }); + } + + /** + * Get the current status of all domains + */ + getStatus(): { + swarmId: SwarmId; + status: SwarmStatus; + topology: TopologyType; + domains: DomainStatus[]; + metrics: CoordinatorMetrics; + } { + const domains: DomainStatus[] = []; + + for (const [domain, config] of this.domainConfigs) { + const pool = this.domainPools.get(domain); + const stats = pool?.getPoolStats(); + const queue = this.domainTaskQueues.get(domain) || []; + + const completedTasks = Array.from(this.taskAssignments.values()) + .filter(a => a.domain === domain) + .map(a => this.state.tasks.get(a.taskId)) + .filter(t => t?.status === 'completed') + .length; + + domains.push({ + name: domain, + agentCount: stats?.total ?? 0, + availableAgents: stats?.available ?? 0, + busyAgents: stats?.busy ?? 0, + tasksQueued: queue.length, + tasksCompleted: completedTasks, + }); + } + + return { + swarmId: this.state.id, + status: this.state.status, + topology: this.config.topology.type, + domains, + metrics: this.getMetrics(), + }; + } + + /** + * Register an agent and automatically assign it to the appropriate domain + * based on its agent number (1-15) + */ + async registerAgentWithDomain( + agentData: Omit, + agentNumber: number + ): Promise<{ agentId: string; domain: AgentDomain }> { + // First register the agent normally + const agentId = await this.registerAgent(agentData); + + // Determine domain based on agent number + const domain = this.getAgentDomain(agentNumber); + + // Add to domain tracking + this.agentDomainMap.set(agentId, domain); + + // Add to domain pool + const pool = this.domainPools.get(domain); + const agent = this.state.agents.get(agentId); + if (pool && agent) { + await pool.add(agent); + } + + this.emitEvent('agent.domain_assigned', { + agentId, + agentNumber, + domain, + }); + + return { agentId, domain }; + } + + /** + * Get the domain for a given agent number (1-15) + */ + getAgentDomain(agentNumber: number): AgentDomain { + for (const [domain, config] of this.domainConfigs) { + if (config.agentNumbers.includes(agentNumber)) { + return domain; + } + } + return 'core'; // Default to core domain + } + + /** + * Spawn the full 15-agent hierarchy + * Returns a map of agent numbers to their IDs and domains + */ + async spawnFullHierarchy(): Promise> { + const results = new Map(); + + for (const [domain, config] of this.domainConfigs) { + for (const agentNumber of config.agentNumbers) { + const agentType = this.domainToAgentType(domain); + + const agentData: Omit = { + name: `${domain}-agent-${agentNumber}`, + type: agentType, + status: 'idle', + capabilities: this.createDomainCapabilities(domain), + metrics: this.createDefaultAgentMetrics(), + workload: 0, + health: 1.0, + lastHeartbeat: new Date(), + topologyRole: domain === 'queen' ? 'queen' : 'worker', + connections: [], + }; + + const result = await this.registerAgentWithDomain(agentData, agentNumber); + results.set(agentNumber, result); + } + } + + this.emitEvent('hierarchy.spawned', { + totalAgents: results.size, + domains: Array.from(this.domainConfigs.keys()), + }); + + return results; + } + + private createDomainCapabilities(domain: AgentDomain): AgentCapabilities { + const domainConfig = this.domainConfigs.get(domain); + const capabilities = domainConfig?.capabilities || []; + + return { + codeGeneration: domain === 'core' || domain === 'integration', + codeReview: domain === 'security' || domain === 'core', + testing: domain === 'support' || domain === 'security', + documentation: true, + research: true, + analysis: true, + coordination: domain === 'queen', + languages: ['typescript', 'javascript', 'python'], + frameworks: ['node', 'react', 'vitest'], + domains: capabilities, + tools: ['git', 'npm', 'editor', 'claude'], + maxConcurrentTasks: domain === 'queen' ? 1 : 3, + maxMemoryUsage: 512 * 1024 * 1024, + maxExecutionTime: SWARM_CONSTANTS.DEFAULT_TASK_TIMEOUT_MS, + reliability: 0.95, + speed: 1.0, + quality: 0.9, + }; + } + + private createDefaultAgentMetrics(): AgentMetrics { + return { + tasksCompleted: 0, + tasksFailed: 0, + averageExecutionTime: 0, + successRate: 1.0, + cpuUsage: 0, + memoryUsage: 0, + messagesProcessed: 0, + lastActivity: new Date(), + responseTime: 0, + health: 1.0, + }; + } + + /** + * Get the domain pool for a specific domain + */ + getDomainPool(domain: AgentDomain): AgentPool | undefined { + return this.domainPools.get(domain); + } + + /** + * Get all domain configurations + */ + getDomainConfigs(): Map { + return new Map(this.domainConfigs); + } + + /** + * Release an agent back to its domain pool after task completion + */ + async releaseAgentToDomain(agentId: string): Promise { + const domain = this.agentDomainMap.get(agentId); + if (!domain) return; + + const pool = this.domainPools.get(domain); + if (pool) { + await pool.release(agentId); + } + + // Check if there are queued tasks for this domain + const queue = this.domainTaskQueues.get(domain) || []; + if (queue.length > 0) { + const nextTaskId = queue.shift()!; + this.domainTaskQueues.set(domain, queue); + await this.assignTaskToDomain(nextTaskId, domain); + } + } } export function createUnifiedSwarmCoordinator(