Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUv59ea39543184
diff --git a/v3/@claude-flow/shared/src/events/projections.ts b/v3/@claude-flow/shared/src/events/projections.ts
new file mode 100644
index 0000000000..ad0e17b6a6
--- /dev/null
+++ b/v3/@claude-flow/shared/src/events/projections.ts
@@ -0,0 +1,561 @@
+/**
+ * Event Projections for Read Models (ADR-007)
+ *
+ * Build read models from domain events using projections.
+ * Projections listen to events and maintain queryable state.
+ *
+ * Implemented Projections:
+ * - AgentStateProjection - Current state of all agents
+ * - TaskHistoryProjection - Complete task execution history
+ * - MemoryIndexProjection - Memory access patterns and index
+ *
+ * @module v3/shared/events/projections
+ */
+
+import { EventEmitter } from 'node:events';
+import { DomainEvent } from './domain-events.js';
+import { EventStore } from './event-store.js';
+import { AgentId, TaskId, AgentStatus, TaskStatus } from '../types.js';
+
+// =============================================================================
+// Projection Base Class
+// =============================================================================
+
+export abstract class Projection extends EventEmitter {
+ protected initialized: boolean = false;
+
+ constructor(protected eventStore: EventStore) {
+ super();
+ }
+
+ /**
+ * Initialize the projection by replaying events
+ */
+ async initialize(): Promise<void> {
+ if (this.initialized) return;
+
+ // Replay all events to build current state
+ for await (const event of this.eventStore.replay()) {
+ await this.handle(event);
+ }
+
+ this.initialized = true;
+ this.emit('initialized');
+ }
+
+ /**
+ * Handle a domain event
+ */
+ abstract handle(event: DomainEvent): Promise<void>;
+
+ /**
+ * Reset the projection state
+ */
+ abstract reset(): void;
+}
+
+// =============================================================================
+// Agent State Projection
+// =============================================================================
+
+export interface AgentProjectionState {
+ id: AgentId;
+ role: string;
+ domain: string;
+ status: AgentStatus;
+ currentTask: TaskId | null;
+ completedTasks: TaskId[];
+ failedTasks: TaskId[];
+ totalTaskDuration: number;
+ taskCount: number;
+ errorCount: number;
+ spawnedAt: number;
+ startedAt: number | null;
+ stoppedAt: number | null;
+ lastActivityAt: number;
+}
+
+export class AgentStateProjection extends Projection {
+ private agents: Map<AgentId, AgentProjectionState> = new Map();
+
+ /**
+ * Get state for a specific agent
+ */
+ getAgent(agentId: AgentId): AgentProjectionState | null {
+ return this.agents.get(agentId) || null;
+ }
+
+ /**
+ * Get all agents
+ */
+ getAllAgents(): AgentProjectionState[] {
+ return Array.from(this.agents.values());
+ }
+
+ /**
+ * Get agents by status
+ */
+ getAgentsByStatus(status: AgentStatus): AgentProjectionState[] {
+ return this.getAllAgents().filter((agent) => agent.status === status);
+ }
+
+ /**
+ * Get agents by domain
+ */
+ getAgentsByDomain(domain: string): AgentProjectionState[] {
+ return this.getAllAgents().filter((agent) => agent.domain === domain);
+ }
+
+ /**
+ * Get active agent count
+ */
+ getActiveAgentCount(): number {
+ return this.getAgentsByStatus('active').length;
+ }
+
+ async handle(event: DomainEvent): Promise<void> {
+ switch (event.type) {
+ case 'agent:spawned':
+ this.handleAgentSpawned(event);
+ break;
+ case 'agent:started':
+ this.handleAgentStarted(event);
+ break;
+ case 'agent:stopped':
+ this.handleAgentStopped(event);
+ break;
+ case 'agent:failed':
+ this.handleAgentFailed(event);
+ break;
+ case 'agent:status-changed':
+ this.handleAgentStatusChanged(event);
+ break;
+ case 'agent:task-assigned':
+ this.handleAgentTaskAssigned(event);
+ break;
+ case 'agent:task-completed':
+ this.handleAgentTaskCompleted(event);
+ break;
+ }
+ }
+
+ reset(): void {
+ this.agents.clear();
+ this.emit('reset');
+ }
+
+ private handleAgentSpawned(event: DomainEvent): void {
+ const { agentId, role, domain } = event.payload;
+
+ this.agents.set(agentId as AgentId, {
+ id: agentId as AgentId,
+ role: role as string,
+ domain: domain as string,
+ status: 'idle',
+ currentTask: null,
+ completedTasks: [],
+ failedTasks: [],
+ totalTaskDuration: 0,
+ taskCount: 0,
+ errorCount: 0,
+ spawnedAt: event.timestamp,
+ startedAt: null,
+ stoppedAt: null,
+ lastActivityAt: event.timestamp,
+ });
+
+ this.emit('agent:spawned', { agentId });
+ }
+
+ private handleAgentStarted(event: DomainEvent): void {
+ const { agentId } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.status = 'active';
+ agent.startedAt = event.timestamp;
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:started', { agentId });
+ }
+ }
+
+ private handleAgentStopped(event: DomainEvent): void {
+ const { agentId } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.status = 'completed';
+ agent.stoppedAt = event.timestamp;
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:stopped', { agentId });
+ }
+ }
+
+ private handleAgentFailed(event: DomainEvent): void {
+ const { agentId } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.status = 'error';
+ agent.errorCount++;
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:failed', { agentId });
+ }
+ }
+
+ private handleAgentStatusChanged(event: DomainEvent): void {
+ const { agentId, newStatus } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.status = newStatus as AgentStatus;
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:status-changed', { agentId, status: newStatus });
+ }
+ }
+
+ private handleAgentTaskAssigned(event: DomainEvent): void {
+ const { agentId, taskId } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.currentTask = taskId as TaskId;
+ agent.status = 'active';
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:task-assigned', { agentId, taskId });
+ }
+ }
+
+ private handleAgentTaskCompleted(event: DomainEvent): void {
+ const { agentId, taskId, duration } = event.payload;
+ const agent = this.agents.get(agentId as AgentId);
+
+ if (agent) {
+ agent.completedTasks.push(taskId as TaskId);
+ agent.currentTask = null;
+ agent.taskCount++;
+ agent.totalTaskDuration += (duration as number) || 0;
+ agent.status = 'idle';
+ agent.lastActivityAt = event.timestamp;
+ this.emit('agent:task-completed', { agentId, taskId });
+ }
+ }
+}
+
+// =============================================================================
+// Task History Projection
+// =============================================================================
+
+export interface TaskProjectionState {
+ id: TaskId;
+ type: string;
+ title: string;
+ status: TaskStatus;
+ priority: string;
+ assignedAgent: AgentId | null;
+ dependencies: TaskId[];
+ blockedBy: TaskId[];
+ createdAt: number;
+ startedAt: number | null;
+ completedAt: number | null;
+ failedAt: number | null;
+ duration: number | null;
+ result: unknown;
+ error: string | null;
+ retryCount: number;
+}
+
+export class TaskHistoryProjection extends Projection {
+ private tasks: Map<TaskId, TaskProjectionState> = new Map();
+
+ /**
+ * Get task by ID
+ */
+ getTask(taskId: TaskId): TaskProjectionState | null {
+ return this.tasks.get(taskId) || null;
+ }
+
+ /**
+ * Get all tasks
+ */
+ getAllTasks(): TaskProjectionState[] {
+ return Array.from(this.tasks.values());
+ }
+
+ /**
+ * Get tasks by status
+ */
+ getTasksByStatus(status: TaskStatus): TaskProjectionState[] {
+ return this.getAllTasks().filter((task) => task.status === status);
+ }
+
+ /**
+ * Get tasks by agent
+ */
+ getTasksByAgent(agentId: AgentId): TaskProjectionState[] {
+ return this.getAllTasks().filter((task) => task.assignedAgent === agentId);
+ }
+
+ /**
+ * Get completed task count
+ */
+ getCompletedTaskCount(): number {
+ return this.getTasksByStatus('completed').length;
+ }
+
+ /**
+ * Get average task duration
+ */
+ getAverageTaskDuration(): number {
+ const completed = this.getTasksByStatus('completed').filter((t) => t.duration !== null);
+
+ if (completed.length === 0) return 0;
+
+ const total = completed.reduce((sum, task) => sum + (task.duration || 0), 0);
+ return total / completed.length;
+ }
+
+ async handle(event: DomainEvent): Promise<void> {
+ switch (event.type) {
+ case 'task:created':
+ this.handleTaskCreated(event);
+ break;
+ case 'task:queued':
+ this.handleTaskQueued(event);
+ break;
+ case 'task:started':
+ this.handleTaskStarted(event);
+ break;
+ case 'task:completed':
+ this.handleTaskCompleted(event);
+ break;
+ case 'task:failed':
+ this.handleTaskFailed(event);
+ break;
+ case 'task:blocked':
+ this.handleTaskBlocked(event);
+ break;
+ }
+ }
+
+ reset(): void {
+ this.tasks.clear();
+ this.emit('reset');
+ }
+
+ private handleTaskCreated(event: DomainEvent): void {
+ const { taskId, taskType, title, priority, dependencies } = event.payload;
+
+ this.tasks.set(taskId as TaskId, {
+ id: taskId as TaskId,
+ type: taskType as string,
+ title: title as string,
+ status: 'pending',
+ priority: priority as string,
+ assignedAgent: null,
+ dependencies: (dependencies as TaskId[]) || [],
+ blockedBy: [],
+ createdAt: event.timestamp,
+ startedAt: null,
+ completedAt: null,
+ failedAt: null,
+ duration: null,
+ result: null,
+ error: null,
+ retryCount: 0,
+ });
+
+ this.emit('task:created', { taskId });
+ }
+
+ private handleTaskQueued(event: DomainEvent): void {
+ const { taskId } = event.payload;
+ const task = this.tasks.get(taskId as TaskId);
+
+ if (task) {
+ task.status = 'queued';
+ this.emit('task:queued', { taskId });
+ }
+ }
+
+ private handleTaskStarted(event: DomainEvent): void {
+ const { taskId, agentId } = event.payload;
+ const task = this.tasks.get(taskId as TaskId);
+
+ if (task) {
+ task.status = 'in-progress';
+ task.assignedAgent = agentId as AgentId;
+ task.startedAt = event.timestamp;
+ this.emit('task:started', { taskId, agentId });
+ }
+ }
+
+ private handleTaskCompleted(event: DomainEvent): void {
+ const { taskId, result, duration } = event.payload;
+ const task = this.tasks.get(taskId as TaskId);
+
+ if (task) {
+ task.status = 'completed';
+ task.completedAt = event.timestamp;
+ task.duration = (duration as number) || (task.startedAt ? event.timestamp - task.startedAt : null);
+ task.result = result;
+ this.emit('task:completed', { taskId });
+ }
+ }
+
+ private handleTaskFailed(event: DomainEvent): void {
+ const { taskId, error, retryCount } = event.payload;
+ const task = this.tasks.get(taskId as TaskId);
+
+ if (task) {
+ task.status = 'failed';
+ task.failedAt = event.timestamp;
+ task.error = error as string;
+ task.retryCount = retryCount as number;
+ this.emit('task:failed', { taskId });
+ }
+ }
+
+ private handleTaskBlocked(event: DomainEvent): void {
+ const { taskId, blockedBy } = event.payload;
+ const task = this.tasks.get(taskId as TaskId);
+
+ if (task) {
+ task.status = 'blocked';
+ task.blockedBy = blockedBy as TaskId[];
+ this.emit('task:blocked', { taskId, blockedBy });
+ }
+ }
+}
+
+// =============================================================================
+// Memory Index Projection
+// =============================================================================
+
+export interface MemoryProjectionState {
+ id: string;
+ namespace: string;
+ key: string;
+ type: string;
+ size: number;
+ accessCount: number;
+ storedAt: number;
+ lastAccessedAt: number;
+ deletedAt: number | null;
+ isDeleted: boolean;
+}
+
+export class MemoryIndexProjection extends Projection {
+ private memories: Map<string, MemoryProjectionState> = new Map();
+
+ /**
+ * Get memory by ID
+ */
+ getMemory(memoryId: string): MemoryProjectionState | null {
+ return this.memories.get(memoryId) || null;
+ }
+
+ /**
+ * Get all active memories (not deleted)
+ */
+ getActiveMemories(): MemoryProjectionState[] {
+ return Array.from(this.memories.values()).filter((m) => !m.isDeleted);
+ }
+
+ /**
+ * Get memories by namespace
+ */
+ getMemoriesByNamespace(namespace: string): MemoryProjectionState[] {
+ return this.getActiveMemories().filter((m) => m.namespace === namespace);
+ }
+
+ /**
+ * Get most accessed memories
+ */
+ getMostAccessedMemories(limit: number = 10): MemoryProjectionState[] {
+ return this.getActiveMemories()
+ .sort((a, b) => b.accessCount - a.accessCount)
+ .slice(0, limit);
+ }
+
+ /**
+ * Get total memory size by namespace
+ */
+ getTotalSizeByNamespace(namespace: string): number {
+ return this.getMemoriesByNamespace(namespace).reduce((sum, m) => sum + m.size, 0);
+ }
+
+ async handle(event: DomainEvent): Promise<void> {
+ switch (event.type) {
+ case 'memory:stored':
+ this.handleMemoryStored(event);
+ break;
+ case 'memory:retrieved':
+ this.handleMemoryRetrieved(event);
+ break;
+ case 'memory:deleted':
+ this.handleMemoryDeleted(event);
+ break;
+ case 'memory:expired':
+ this.handleMemoryExpired(event);
+ break;
+ }
+ }
+
+ reset(): void {
+ this.memories.clear();
+ this.emit('reset');
+ }
+
+ private handleMemoryStored(event: DomainEvent): void {
+ const { memoryId, namespace, key, memoryType, size } = event.payload;
+
+ this.memories.set(memoryId as string, {
+ id: memoryId as string,
+ namespace: namespace as string,
+ key: key as string,
+ type: memoryType as string,
+ size: (size as number) || 0,
+ accessCount: 0,
+ storedAt: event.timestamp,
+ lastAccessedAt: event.timestamp,
+ deletedAt: null,
+ isDeleted: false,
+ });
+
+ this.emit('memory:stored', { memoryId });
+ }
+
+ private handleMemoryRetrieved(event: DomainEvent): void {
+ const { memoryId, accessCount } = event.payload;
+ const memory = this.memories.get(memoryId as string);
+
+ if (memory && !memory.isDeleted) {
+ memory.accessCount = accessCount as number;
+ memory.lastAccessedAt = event.timestamp;
+ this.emit('memory:retrieved', { memoryId });
+ }
+ }
+
+ private handleMemoryDeleted(event: DomainEvent): void {
+ const { memoryId } = event.payload;
+ const memory = this.memories.get(memoryId as string);
+
+ if (memory) {
+ memory.isDeleted = true;
+ memory.deletedAt = event.timestamp;
+ this.emit('memory:deleted', { memoryId });
+ }
+ }
+
+ private handleMemoryExpired(event: DomainEvent): void {
+ const { memoryId } = event.payload;
+ const memory = this.memories.get(memoryId as string);
+
+ if (memory) {
+ memory.isDeleted = true;
+ memory.deletedAt = event.timestamp;
+ this.emit('memory:expired', { memoryId });
+ }
+ }
+}
diff --git a/v3/CLEANUP-REPORT.md b/v3/CLEANUP-REPORT.md
index b9a81d4b59..e4eaba841b 100644
--- a/v3/CLEANUP-REPORT.md
+++ b/v3/CLEANUP-REPORT.md
@@ -1,7 +1,8 @@
# V3 Dead Code Cleanup Report
**Date:** 2026-01-04
-**Status:** Pre-execution Analysis
+**Status:** COMPLETED
+**Execution Time:** 2026-01-04 (Automated Cleanup)
## Executive Summary
diff --git a/v3/__tests__/integration/mcp-integration.test.ts b/v3/__tests__/integration/mcp-integration.test.ts
new file mode 100644
index 0000000000..4f27db3423
--- /dev/null
+++ b/v3/__tests__/integration/mcp-integration.test.ts
@@ -0,0 +1,421 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { MCPServer } from '../../src/infrastructure/mcp/MCPServer';
+import { AgentTools } from '../../src/infrastructure/mcp/tools/AgentTools';
+import { MemoryTools } from '../../src/infrastructure/mcp/tools/MemoryTools';
+import { ConfigTools } from '../../src/infrastructure/mcp/tools/ConfigTools';
+import { SwarmCoordinator } from '../../src/coordination/application/SwarmCoordinator';
+import { HybridBackend } from '../../src/memory/infrastructure/HybridBackend';
+
+describe('MCP Tools Integration Tests', () => {
+ let mcpServer: MCPServer;
+ let agentTools: AgentTools;
+ let memoryTools: MemoryTools;
+ let configTools: ConfigTools;
+ let coordinator: SwarmCoordinator;
+ let memoryBackend: HybridBackend;
+
+ beforeEach(async () => {
+ memoryBackend = {
+ store: vi.fn(),
+ retrieve: vi.fn(),
+ query: vi.fn().mockResolvedValue([]),
+ vectorSearch: vi.fn().mockResolvedValue([]),
+ initialize: vi.fn(),
+ close: vi.fn()
+ } as any;
+
+ coordinator = {
+ spawnAgent: vi.fn(),
+ listAgents: vi.fn().mockResolvedValue([]),
+ terminateAgent: vi.fn(),
+ getAgentMetrics: vi.fn(),
+ initialize: vi.fn(),
+ shutdown: vi.fn()
+ } as any;
+
+ agentTools = new AgentTools(coordinator);
+ memoryTools = new MemoryTools(memoryBackend);
+ configTools = new ConfigTools();
+
+ mcpServer = new MCPServer({
+ tools: [agentTools, memoryTools, configTools]
+ });
+
+ await mcpServer.start();
+ });
+
+ afterEach(async () => {
+ await mcpServer.stop();
+ });
+
+ it('should spawn agent via MCP agent tools', async () => {
+ const mockAgent = {
+ id: 'mcp-agent-1',
+ type: 'coder',
+ status: 'active',
+ capabilities: ['code', 'refactor']
+ };
+
+ (coordinator.spawnAgent as any).mockResolvedValue(mockAgent);
+
+ const result = await agentTools.execute('agent_spawn', {
+ id: 'mcp-agent-1',
+ type: 'coder',
+ capabilities: ['code', 'refactor']
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.agent.id).toBe('mcp-agent-1');
+ expect(coordinator.spawnAgent).toHaveBeenCalledWith({
+ id: 'mcp-agent-1',
+ type: 'coder',
+ capabilities: ['code', 'refactor']
+ });
+ });
+
+ it('should list agents via MCP agent tools', async () => {
+ const mockAgents = [
+ { id: 'agent-1', type: 'coder', status: 'active' },
+ { id: 'agent-2', type: 'tester', status: 'active' },
+ { id: 'agent-3', type: 'reviewer', status: 'idle' }
+ ];
+
+ (coordinator.listAgents as any).mockResolvedValue(mockAgents);
+
+ const result = await agentTools.execute('agent_list', {});
+
+ expect(result.success).toBe(true);
+ expect(result.agents).toHaveLength(3);
+ expect(result.agents[0].id).toBe('agent-1');
+ });
+
+ it('should terminate agent via MCP agent tools', async () => {
+ (coordinator.terminateAgent as any).mockResolvedValue({ success: true });
+
+ const result = await agentTools.execute('agent_terminate', {
+ agentId: 'agent-to-kill'
+ });
+
+ expect(result.success).toBe(true);
+ expect(coordinator.terminateAgent).toHaveBeenCalledWith('agent-to-kill');
+ });
+
+ it('should get agent metrics via MCP agent tools', async () => {
+ const mockMetrics = {
+ agentId: 'metrics-agent',
+ tasksCompleted: 10,
+ averageExecutionTime: 250,
+ successRate: 0.95,
+ health: 'healthy'
+ };
+
+ (coordinator.getAgentMetrics as any).mockResolvedValue(mockMetrics);
+
+ const result = await agentTools.execute('agent_metrics', {
+ agentId: 'metrics-agent'
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.metrics.tasksCompleted).toBe(10);
+ expect(result.metrics.successRate).toBe(0.95);
+ });
+
+ it('should store memory via MCP memory tools', async () => {
+ const memory = {
+ id: 'mcp-mem-1',
+ agentId: 'agent-1',
+ content: 'Test memory from MCP',
+ type: 'task',
+ timestamp: Date.now()
+ };
+
+ (memoryBackend.store as any).mockResolvedValue(memory);
+
+ const result = await memoryTools.execute('memory_store', memory);
+
+ expect(result.success).toBe(true);
+ expect(memoryBackend.store).toHaveBeenCalledWith(memory);
+ });
+
+ it('should search memory via MCP memory tools', async () => {
+ const mockMemories = [
+ { id: '1', agentId: 'agent-1', content: 'Memory 1', type: 'task', timestamp: Date.now() },
+ { id: '2', agentId: 'agent-1', content: 'Memory 2', type: 'context', timestamp: Date.now() }
+ ];
+
+ (memoryBackend.query as any).mockResolvedValue(mockMemories);
+
+ const result = await memoryTools.execute('memory_search', {
+ agentId: 'agent-1',
+ type: 'task'
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.memories).toHaveLength(2);
+ expect(memoryBackend.query).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ type: 'task'
+ });
+ });
+
+ it('should perform vector search via MCP memory tools', async () => {
+ const mockResults = [
+ {
+ id: 'vec-1',
+ agentId: 'agent-1',
+ content: 'Similar content',
+ similarity: 0.95,
+ timestamp: Date.now()
+ },
+ {
+ id: 'vec-2',
+ agentId: 'agent-1',
+ content: 'Another similar',
+ similarity: 0.87,
+ timestamp: Date.now()
+ }
+ ];
+
+ (memoryBackend.vectorSearch as any).mockResolvedValue(mockResults);
+
+ const queryEmbedding = new Array(384).fill(0).map(() => Math.random());
+
+ const result = await memoryTools.execute('memory_vector_search', {
+ embedding: queryEmbedding,
+ k: 5
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.results).toHaveLength(2);
+ expect(result.results[0].similarity).toBeGreaterThan(0.9);
+ });
+
+ it('should load config via MCP config tools', async () => {
+ const mockConfig = {
+ swarm: {
+ topology: 'hierarchical',
+ maxAgents: 10
+ },
+ memory: {
+ backend: 'hybrid',
+ ttl: 3600000
+ },
+ performance: {
+ flashAttention: true,
+ targetSpeedup: '2.49x-7.47x'
+ }
+ };
+
+ vi.spyOn(configTools, 'loadConfig').mockResolvedValue(mockConfig);
+
+ const result = await configTools.execute('config_load', {
+ path: './config/v3.json'
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.config.swarm.topology).toBe('hierarchical');
+ expect(result.config.performance.flashAttention).toBe(true);
+ });
+
+ it('should save config via MCP config tools', async () => {
+ const config = {
+ swarm: { topology: 'mesh' },
+ memory: { backend: 'agentdb' }
+ };
+
+ vi.spyOn(configTools, 'saveConfig').mockResolvedValue({ success: true });
+
+ const result = await configTools.execute('config_save', {
+ path: './config/custom.json',
+ config
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should validate config via MCP config tools', async () => {
+ const invalidConfig = {
+ swarm: { topology: 'invalid-topology' },
+ memory: { backend: 'unknown' }
+ };
+
+ const result = await configTools.execute('config_validate', {
+ config: invalidConfig
+ });
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toBeDefined();
+ expect(result.errors.length).toBeGreaterThan(0);
+ });
+
+ it('should handle MCP tool execution errors gracefully', async () => {
+ (coordinator.spawnAgent as any).mockRejectedValue(new Error('Spawn failed'));
+
+ const result = await agentTools.execute('agent_spawn', {
+ id: 'failing-agent',
+ type: 'coder'
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBeDefined();
+ expect(result.error).toContain('Spawn failed');
+ });
+
+ it('should support chained MCP tool operations', async () => {
+ // Spawn agent
+ const mockAgent = { id: 'chain-agent', type: 'coder', status: 'active' };
+ (coordinator.spawnAgent as any).mockResolvedValue(mockAgent);
+
+ const spawnResult = await agentTools.execute('agent_spawn', {
+ id: 'chain-agent',
+ type: 'coder'
+ });
+
+ expect(spawnResult.success).toBe(true);
+
+ // Store memory for the agent
+ const memory = {
+ id: 'chain-mem',
+ agentId: 'chain-agent',
+ content: 'Agent spawned',
+ type: 'event',
+ timestamp: Date.now()
+ };
+
+ (memoryBackend.store as any).mockResolvedValue(memory);
+
+ const storeResult = await memoryTools.execute('memory_store', memory);
+
+ expect(storeResult.success).toBe(true);
+
+ // Retrieve memories
+ (memoryBackend.query as any).mockResolvedValue([memory]);
+
+ const searchResult = await memoryTools.execute('memory_search', {
+ agentId: 'chain-agent'
+ });
+
+ expect(searchResult.success).toBe(true);
+ expect(searchResult.memories).toHaveLength(1);
+ });
+
+ it('should handle concurrent MCP tool requests', async () => {
+ const mockAgents = Array.from({ length: 5 }, (_, i) => ({
+ id: `concurrent-agent-${i}`,
+ type: 'coder',
+ status: 'active'
+ }));
+
+ (coordinator.spawnAgent as any).mockImplementation(async (config) => ({
+ id: config.id,
+ type: config.type,
+ status: 'active'
+ }));
+
+ const requests = mockAgents.map(agent =>
+ agentTools.execute('agent_spawn', {
+ id: agent.id,
+ type: agent.type
+ })
+ );
+
+ const results = await Promise.all(requests);
+
+ expect(results).toHaveLength(5);
+ expect(results.every(r => r.success)).toBe(true);
+ });
+
+ it('should provide MCP tool introspection', async () => {
+ const tools = mcpServer.listTools();
+
+ expect(tools.length).toBeGreaterThan(0);
+
+ const agentSpawnTool = tools.find(t => t.name === 'agent_spawn');
+ expect(agentSpawnTool).toBeDefined();
+ expect(agentSpawnTool?.parameters).toBeDefined();
+ expect(agentSpawnTool?.description).toBeDefined();
+
+ const memoryStoreTool = tools.find(t => t.name === 'memory_store');
+ expect(memoryStoreTool).toBeDefined();
+
+ const configLoadTool = tools.find(t => t.name === 'config_load');
+ expect(configLoadTool).toBeDefined();
+ });
+
+ it('should support MCP tool parameter validation', async () => {
+ const invalidParams = {
+ id: '', // Invalid: empty ID
+ type: 'invalid-type', // Invalid: unknown type
+ capabilities: 'not-an-array' // Invalid: should be array
+ };
+
+ const result = await agentTools.execute('agent_spawn', invalidParams as any);
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('validation');
+ });
+
+ it('should integrate all MCP tools in workflow', async () => {
+ // 1. Load configuration
+ const mockConfig = {
+ swarm: { topology: 'hierarchical', maxAgents: 5 },
+ memory: { backend: 'hybrid' }
+ };
+ vi.spyOn(configTools, 'loadConfig').mockResolvedValue(mockConfig);
+
+ const configResult = await configTools.execute('config_load', {
+ path: './config/v3.json'
+ });
+ expect(configResult.success).toBe(true);
+
+ // 2. Spawn agents based on config
+ (coordinator.spawnAgent as any).mockImplementation(async (config) => ({
+ id: config.id,
+ type: config.type,
+ status: 'active'
+ }));
+
+ const agentResult = await agentTools.execute('agent_spawn', {
+ id: 'workflow-agent',
+ type: 'coder'
+ });
+ expect(agentResult.success).toBe(true);
+
+ // 3. Store agent spawn event in memory
+ (memoryBackend.store as any).mockResolvedValue({
+ id: 'event-1',
+ agentId: 'workflow-agent',
+ content: 'Agent spawned',
+ type: 'event',
+ timestamp: Date.now()
+ });
+
+ const memoryResult = await memoryTools.execute('memory_store', {
+ id: 'event-1',
+ agentId: 'workflow-agent',
+ content: 'Agent spawned',
+ type: 'event',
+ timestamp: Date.now()
+ });
+ expect(memoryResult.success).toBe(true);
+
+ // 4. Retrieve agent metrics
+ (coordinator.getAgentMetrics as any).mockResolvedValue({
+ agentId: 'workflow-agent',
+ tasksCompleted: 0,
+ successRate: 1.0,
+ health: 'healthy'
+ });
+
+ const metricsResult = await agentTools.execute('agent_metrics', {
+ agentId: 'workflow-agent'
+ });
+ expect(metricsResult.success).toBe(true);
+
+ // Verify complete workflow
+ expect(configResult.config).toBeDefined();
+ expect(agentResult.agent).toBeDefined();
+ expect(memoryResult.success).toBe(true);
+ expect(metricsResult.metrics).toBeDefined();
+ });
+});