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:

rUva6c4c1e1b08e
diff --git a/v3/__tests__/unit/security/credential-generator.test.ts b/v3/__tests__/unit/security/credential-generator.test.ts
new file mode 100644
index 0000000000..b5343df373
--- /dev/null
+++ b/v3/__tests__/unit/security/credential-generator.test.ts
@@ -0,0 +1,182 @@
+import { describe, it, expect } from 'vitest';
+import { CredentialGenerator } from '../../../security/credential-generator.js';
+
+describe('CredentialGenerator', () => {
+ describe('generatePassword', () => {
+ it('should generate passwords meeting complexity requirements', () => {
+ const generator = new CredentialGenerator();
+ const password = generator.generatePassword();
+
+ expect(password.length).toBeGreaterThanOrEqual(32);
+ expect(/[A-Z]/.test(password)).toBe(true);
+ expect(/[a-z]/.test(password)).toBe(true);
+ expect(/\d/.test(password)).toBe(true);
+ });
+
+ it('should generate unique passwords each time', () => {
+ const generator = new CredentialGenerator();
+ const passwords = new Set(Array.from({ length: 100 }, () => generator.generatePassword()));
+ expect(passwords.size).toBe(100);
+ });
+
+ it('should respect custom length parameter', () => {
+ const generator = new CredentialGenerator();
+ const password = generator.generatePassword(64);
+ expect(password.length).toBe(64);
+ });
+
+ it('should include special characters by default', () => {
+ const generator = new CredentialGenerator();
+ const password = generator.generatePassword();
+ expect(/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password)).toBe(true);
+ });
+ });
+
+ describe('generateApiKey', () => {
+ it('should generate API keys with prefix', () => {
+ const generator = new CredentialGenerator();
+ const key = generator.generateApiKey('test_');
+ expect(key.key.startsWith('test_')).toBe(true);
+ });
+
+ it('should generate API keys with default prefix', () => {
+ const generator = new CredentialGenerator();
+ const key = generator.generateApiKey();
+ expect(key.key.startsWith('cf_')).toBe(true);
+ });
+
+ it('should include keyId as UUID', () => {
+ const generator = new CredentialGenerator();
+ const key = generator.generateApiKey();
+ expect(key.keyId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i);
+ });
+
+ it('should include createdAt timestamp', () => {
+ const generator = new CredentialGenerator();
+ const before = new Date();
+ const key = generator.generateApiKey();
+ const after = new Date();
+ expect(key.createdAt.getTime()).toBeGreaterThanOrEqual(before.getTime());
+ expect(key.createdAt.getTime()).toBeLessThanOrEqual(after.getTime());
+ });
+
+ it('should generate unique keys each time', () => {
+ const generator = new CredentialGenerator();
+ const keys = new Set(Array.from({ length: 100 }, () => generator.generateApiKey().key));
+ expect(keys.size).toBe(100);
+ });
+ });
+
+ describe('generateSecret', () => {
+ it('should generate hex-encoded secrets', () => {
+ const generator = new CredentialGenerator();
+ const secret = generator.generateSecret();
+ expect(/^[0-9a-f]+$/i.test(secret)).toBe(true);
+ });
+
+ it('should generate secrets with default length', () => {
+ const generator = new CredentialGenerator();
+ const secret = generator.generateSecret();
+ expect(secret.length).toBe(64);
+ });
+
+ it('should generate secrets with custom length', () => {
+ const generator = new CredentialGenerator();
+ const secret = generator.generateSecret(128);
+ expect(secret.length).toBe(128);
+ });
+ });
+
+ describe('generateEncryptionKey', () => {
+ it('should generate 64-character hex key (32 bytes)', () => {
+ const generator = new CredentialGenerator();
+ const key = generator.generateEncryptionKey();
+ expect(key.length).toBe(64);
+ expect(/^[0-9a-f]+$/i.test(key)).toBe(true);
+ });
+ });
+
+ describe('generateInstallationCredentials', () => {
+ it('should generate complete credential set', () => {
+ const generator = new CredentialGenerator();
+ const creds = generator.generateInstallationCredentials();
+
+ expect(creds.adminPassword).toBeDefined();
+ expect(creds.servicePassword).toBeDefined();
+ expect(creds.jwtSecret).toBeDefined();
+ expect(creds.sessionSecret).toBeDefined();
+ expect(creds.encryptionKey).toBeDefined();
+ expect(creds.generatedAt).toBeInstanceOf(Date);
+ });
+
+ it('should set expiration when specified', () => {
+ const generator = new CredentialGenerator();
+ const creds = generator.generateInstallationCredentials(30);
+
+ expect(creds.expiresAt).toBeDefined();
+ const expectedExpiry = new Date(creds.generatedAt.getTime() + 30 * 24 * 60 * 60 * 1000);
+ expect(creds.expiresAt!.getTime()).toBeCloseTo(expectedExpiry.getTime(), -3);
+ });
+ });
+
+ describe('configuration validation', () => {
+ it('should reject password length below 16', () => {
+ expect(() => new CredentialGenerator({ passwordLength: 8 }))
+ .toThrow('Password length must be at least 16 characters');
+ });
+
+ it('should reject API key length below 32', () => {
+ expect(() => new CredentialGenerator({ apiKeyLength: 16 }))
+ .toThrow('API key length must be at least 32 characters');
+ });
+
+ it('should reject secret length below 32', () => {
+ expect(() => new CredentialGenerator({ secretLength: 16 }))
+ .toThrow('Secret length must be at least 32 characters');
+ });
+ });
+
+ describe('utility methods', () => {
+ it('should generate session tokens', () => {
+ const generator = new CredentialGenerator();
+ const token = generator.generateSessionToken();
+ expect(token.length).toBe(64);
+ });
+
+ it('should generate CSRF tokens', () => {
+ const generator = new CredentialGenerator();
+ const token = generator.generateCsrfToken();
+ expect(token).toBeDefined();
+ expect(token.length).toBeGreaterThan(0);
+ });
+
+ it('should generate nonces', () => {
+ const generator = new CredentialGenerator();
+ const nonce = generator.generateNonce();
+ expect(nonce.length).toBe(32);
+ expect(/^[0-9a-f]+$/i.test(nonce)).toBe(true);
+ });
+ });
+
+ describe('output generation', () => {
+ it('should create env script format', () => {
+ const generator = new CredentialGenerator();
+ const creds = generator.generateInstallationCredentials();
+ const script = generator.createEnvScript(creds);
+
+ expect(script).toContain('CLAUDE_FLOW_ADMIN_PASSWORD');
+ expect(script).toContain('CLAUDE_FLOW_JWT_SECRET');
+ expect(script).toContain('export');
+ });
+
+ it('should create JSON config format', () => {
+ const generator = new CredentialGenerator();
+ const creds = generator.generateInstallationCredentials();
+ const json = generator.createJsonConfig(creds);
+
+ const parsed = JSON.parse(json);
+ expect(parsed['claude-flow/admin-password']).toBeDefined();
+ expect(parsed['claude-flow/jwt-secret']).toBeDefined();
+ });
+ });
+});
diff --git a/v3/benchmarks/swarm/agent-coordination.bench.ts b/v3/benchmarks/swarm/agent-coordination.bench.ts
new file mode 100644
index 0000000000..a771b407a5
--- /dev/null
+++ b/v3/benchmarks/swarm/agent-coordination.bench.ts
@@ -0,0 +1,571 @@
+/**
+ * Agent Coordination Benchmark
+ *
+ * Target: <50ms for coordination operations
+ *
+ * Measures agent-to-agent coordination including message passing,
+ * state synchronization, and coordination patterns.
+ */
+
+import { benchmark, BenchmarkRunner, formatTime, meetsTarget } from '../framework/benchmark.js';
+
+// ============================================================================
+// Agent Types and Coordination
+// ============================================================================
+
+interface Agent {
+ id: string;
+ type: string;
+ status: 'idle' | 'busy' | 'waiting';
+ inbox: Message[];
+ outbox: Message[];
+}
+
+interface Message {
+ id: string;
+ from: string;
+ to: string;
+ type: 'request' | 'response' | 'broadcast' | 'heartbeat';
+ payload: unknown;
+ timestamp: number;
+}
+
+interface CoordinationResult {
+ success: boolean;
+ latency: number;
+ messagesExchanged: number;
+}
+
+/**
+ * Simple message broker for agent communication
+ */
+class MessageBroker {
+ private agents = new Map<string, Agent>();
+ private messageQueue: Message[] = [];
+
+ register(agent: Agent): void {
+ this.agents.set(agent.id, agent);
+ }
+
+ send(message: Message): void {
+ this.messageQueue.push(message);
+ const recipient = this.agents.get(message.to);
+ if (recipient) {
+ recipient.inbox.push(message);
+ }
+ }
+
+ broadcast(from: string, type: string, payload: unknown): void {
+ for (const [id, agent] of this.agents) {
+ if (id !== from) {
+ const message: Message = {
+ id: `msg-${Date.now()}-${Math.random()}`,
+ from,
+ to: id,
+ type: 'broadcast',
+ payload,
+ timestamp: Date.now(),
+ };
+ agent.inbox.push(message);
+ this.messageQueue.push(message);
+ }
+ }
+ }
+
+ processMessage(agentId: string): Message | undefined {
+ const agent = this.agents.get(agentId);
+ if (agent && agent.inbox.length > 0) {
+ return agent.inbox.shift();
+ }
+ return undefined;
+ }
+
+ get totalMessages(): number {
+ return this.messageQueue.length;
+ }
+}
+
+/**
+ * Hierarchical coordinator for multi-agent orchestration
+ */
+class HierarchicalCoordinator {
+ private queen: Agent;
+ private workers: Agent[] = [];
+ private broker: MessageBroker;
+
+ constructor(numWorkers: number) {
+ this.broker = new MessageBroker();
+
+ this.queen = {
+ id: 'queen',
+ type: 'coordinator',
+ status: 'idle',
+ inbox: [],
+ outbox: [],
+ };
+ this.broker.register(this.queen);
+
+ for (let i = 0; i < numWorkers; i++) {
+ const worker: Agent = {
+ id: `worker-${i}`,
+ type: 'worker',
+ status: 'idle',
+ inbox: [],
+ outbox: [],
+ };
+ this.workers.push(worker);
+ this.broker.register(worker);
+ }
+ }
+
+ async delegateTask(task: unknown): Promise<CoordinationResult> {
+ const startTime = performance.now();
+ let messagesExchanged = 0;
+
+ // Queen broadcasts task
+ this.broker.broadcast(this.queen.id, 'task', task);
+ messagesExchanged += this.workers.length;
+
+ // Workers acknowledge
+ for (const worker of this.workers) {
+ const ack: Message = {
+ id: `ack-${Date.now()}`,
+ from: worker.id,
+ to: this.queen.id,
+ type: 'response',
+ payload: { status: 'accepted' },
+ timestamp: Date.now(),
+ };
+ this.broker.send(ack);
+ messagesExchanged++;
+ }
+
+ // Process acknowledgments
+ while (this.queen.inbox.length > 0) {
+ this.broker.processMessage(this.queen.id);
+ }
+
+ return {
+ success: true,
+ latency: performance.now() - startTime,
+ messagesExchanged,
+ };
+ }
+
+ async gatherResults(): Promise<CoordinationResult> {
+ const startTime = performance.now();
+ let messagesExchanged = 0;
+
+ // Request results from all workers
+ for (const worker of this.workers) {
+ const request: Message = {
+ id: `req-${Date.now()}`,
+ from: this.queen.id,
+ to: worker.id,
+ type: 'request',
+ payload: { action: 'getResults' },
+ timestamp: Date.now(),
+ };
+ this.broker.send(request);
+ messagesExchanged++;
+ }
+
+ // Workers send results
+ for (const worker of this.workers) {
+ this.broker.processMessage(worker.id);
+ const response: Message = {
+ id: `res-${Date.now()}`,
+ from: worker.id,
+ to: this.queen.id,
+ type: 'response',
+ payload: { results: ['data'] },
+ timestamp: Date.now(),
+ };
+ this.broker.send(response);
+ messagesExchanged++;
+ }
+
+ // Queen processes all results
+ while (this.queen.inbox.length > 0) {
+ this.broker.processMessage(this.queen.id);
+ }
+
+ return {
+ success: true,
+ latency: performance.now() - startTime,
+ messagesExchanged,
+ };
+ }
+
+ get workerCount(): number {
+ return this.workers.length;
+ }
+}
+
+/**
+ * Mesh coordinator for peer-to-peer communication
+ */
+class MeshCoordinator {
+ private agents: Agent[] = [];
+ private broker: MessageBroker;
+
+ constructor(numAgents: number) {
+ this.broker = new MessageBroker();
+
+ for (let i = 0; i < numAgents; i++) {
+ const agent: Agent = {
+ id: `mesh-agent-${i}`,
+ type: 'peer',
+ status: 'idle',
+ inbox: [],
+ outbox: [],
+ };
+ this.agents.push(agent);
+ this.broker.register(agent);
+ }
+ }
+
+ async gossip(originId: number, data: unknown): Promise<CoordinationResult> {
+ const startTime = performance.now();
+ let messagesExchanged = 0;
+
+ const visited = new Set<string>();
+ const queue: string[] = [this.agents[originId]!.id];
+ visited.add(this.agents[originId]!.id);
+
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+
+ // Send to 2-3 random peers
+ const numPeers = Math.min(3, this.agents.length - visited.size);
+ const peers = this.agents
+ .filter((a) => !visited.has(a.id))
+ .slice(0, numPeers);
+
+ for (const peer of peers) {
+ const message: Message = {
+ id: `gossip-${Date.now()}`,
+ from: current,
+ to: peer.id,
+ type: 'broadcast',
+ payload: data,
+ timestamp: Date.now(),
+ };
+ this.broker.send(message);
+ messagesExchanged++;
+ visited.add(peer.id);
+ queue.push(peer.id);
+ }
+ }
+
+ return {
+ success: visited.size === this.agents.length,
+ latency: performance.now() - startTime,
+ messagesExchanged,
+ };
+ }
+
+ get agentCount(): number {
+ return this.agents.length;
+ }
+}
+
+// ============================================================================
+// Benchmark Suite
+// ============================================================================
+
+export async function runAgentCoordinationBenchmarks(): Promise<void> {
+ const runner = new BenchmarkRunner('Agent Coordination');
+
+ console.log('\n--- Agent Coordination Benchmarks ---\n');
+
+ // Benchmark 1: Create Message Broker
+ const brokerCreateResult = await runner.run(
+ 'create-message-broker',
+ async () => {
+ const broker = new MessageBroker();
+ void broker;
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Create Message Broker: ${formatTime(brokerCreateResult.mean)}`);
+
+ // Benchmark 2: Register Agent
+ const broker = new MessageBroker();
+
+ const registerResult = await runner.run(
+ 'register-agent',
+ async () => {
+ const agent: Agent = {
+ id: `agent-${Date.now()}`,
+ type: 'worker',
+ status: 'idle',
+ inbox: [],
+ outbox: [],
+ };
+ broker.register(agent);
+ },
+ { iterations: 5000 }
+ );
+
+ console.log(`Register Agent: ${formatTime(registerResult.mean)}`);
+
+ // Benchmark 3: Send Single Message
+ const sender: Agent = { id: 'sender', type: 'worker', status: 'idle', inbox: [], outbox: [] };
+ const receiver: Agent = { id: 'receiver', type: 'worker', status: 'idle', inbox: [], outbox: [] };
+ broker.register(sender);
+ broker.register(receiver);
+
+ const sendMessageResult = await runner.run(
+ 'send-message',
+ async () => {
+ const message: Message = {
+ id: `msg-${Date.now()}`,
+ from: 'sender',
+ to: 'receiver',
+ type: 'request',
+ payload: { data: 'test' },
+ timestamp: Date.now(),
+ };
+ broker.send(message);
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Send Message: ${formatTime(sendMessageResult.mean)}`);
+
+ // Benchmark 4: Hierarchical Coordination - 5 Workers
+ const hierCoord5 = new HierarchicalCoordinator(5);
+
+ const hierDelegate5Result = await runner.run(
+ 'hierarchical-delegate-5-workers',
+ async () => {
+ await hierCoord5.delegateTask({ action: 'process', data: [1, 2, 3] });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Hierarchical Delegate (5 workers): ${formatTime(hierDelegate5Result.mean)}`);
+ const coordTarget = meetsTarget('agent-coordination', hierDelegate5Result.mean);
+ console.log(` Target (<50ms): ${coordTarget.met ? 'PASS' : 'FAIL'}`);
+
+ // Benchmark 5: Hierarchical Coordination - 15 Workers
+ const hierCoord15 = new HierarchicalCoordinator(15);
+
+ const hierDelegate15Result = await runner.run(
+ 'hierarchical-delegate-15-workers',
+ async () => {
+ await hierCoord15.delegateTask({ action: 'process', data: [1, 2, 3] });
+ },
+ { iterations: 200 }
+ );
+
+ console.log(`Hierarchical Delegate (15 workers): ${formatTime(hierDelegate15Result.mean)}`);
+
+ // Benchmark 6: Gather Results - 5 Workers
+ const gather5Result = await runner.run(
+ 'hierarchical-gather-5-workers',
+ async () => {
+ await hierCoord5.gatherResults();
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Hierarchical Gather (5 workers): ${formatTime(gather5Result.mean)}`);
+
+ // Benchmark 7: Gather Results - 15 Workers
+ const gather15Result = await runner.run(
+ 'hierarchical-gather-15-workers',
+ async () => {
+ await hierCoord15.gatherResults();
+ },
+ { iterations: 200 }
+ );
+
+ console.log(`Hierarchical Gather (15 workers): ${formatTime(gather15Result.mean)}`);
+
+ // Benchmark 8: Mesh Gossip - 10 Peers
+ const meshCoord10 = new MeshCoordinator(10);
+
+ const gossip10Result = await runner.run(
+ 'mesh-gossip-10-peers',
+ async () => {
+ await meshCoord10.gossip(0, { data: 'gossip message' });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Mesh Gossip (10 peers): ${formatTime(gossip10Result.mean)}`);
+
+ // Benchmark 9: Mesh Gossip - 50 Peers
+ const meshCoord50 = new MeshCoordinator(50);
+
+ const gossip50Result = await runner.run(
+ 'mesh-gossip-50-peers',
+ async () => {
+ await meshCoord50.gossip(0, { data: 'gossip message' });
+ },
+ { iterations: 100 }
+ );
+
+ console.log(`Mesh Gossip (50 peers): ${formatTime(gossip50Result.mean)}`);
+
+ // Benchmark 10: Full Coordination Cycle
+ const hierCoordFull = new HierarchicalCoordinator(10);
+
+ const fullCycleResult = await runner.run(
+ 'full-coordination-cycle',
+ async () => {
+ await hierCoordFull.delegateTask({ action: 'compute' });
+ await hierCoordFull.gatherResults();
+ },
+ { iterations: 200 }
+ );
+
+ console.log(`Full Coordination Cycle (10 workers): ${formatTime(fullCycleResult.mean)}`);
+
+ // Summary
+ console.log('\n--- Summary ---');
+ console.log(`Message passing: ${formatTime(sendMessageResult.mean)}`);
+ console.log(`5-worker coordination: ${formatTime(hierDelegate5Result.mean)}`);
+ console.log(`15-worker coordination: ${formatTime(hierDelegate15Result.mean)}`);
+ console.log(`Gossip (10 peers): ${formatTime(gossip10Result.mean)}`);
+ console.log(`Gossip (50 peers): ${formatTime(gossip50Result.mean)}`);
+ console.log(`\nScaling: 5->15 workers = ${(hierDelegate15Result.mean / hierDelegate5Result.mean).toFixed(2)}x`);
+ console.log(`Scaling: 10->50 peers = ${(gossip50Result.mean / gossip10Result.mean).toFixed(2)}x`);
+
+ // Print full results
+ runner.printResults();
+}
+
+// ============================================================================
+// Agent Coordination Optimization Strategies
+// ============================================================================
+
+export const coordinationOptimizations = {
+ /**
+ * Message batching
+ */
+ messageBatching: {
+ description: 'Batch multiple messages to reduce overhead',
+ expectedImprovement: '3-5x',
+ implementation: `
+ class BatchedBroker {
+ private batch: Message[] = [];
+ private batchSize = 100;
+
+ send(message: Message): void {
+ this.batch.push(message);
+ if (this.batch.length >= this.batchSize) {
+ this.flush();
+ }
+ }
+
+ private flush(): void {
+ for (const msg of this.batch) {
+ this.deliver(msg);
+ }
+ this.batch = [];
+ }
+ }
+ `,
+ },
+
+ /**
+ * Zero-copy messaging
+ */
+ zeroCopyMessaging: {
+ description: 'Share references instead of copying data',
+ expectedImprovement: '2-4x for large payloads',
+ implementation: `
+ interface SharedMessage {
+ id: string;
+ payload: SharedArrayBuffer;
+ }
+
+ function createSharedMessage(data: Uint8Array): SharedMessage {
+ const sab = new SharedArrayBuffer(data.length);
+ const view = new Uint8Array(sab);
+ view.set(data);
+ return { id: generateId(), payload: sab };
+ }
+ `,
+ },
+
+ /**
+ * Hierarchical aggregation
+ */
+ hierarchicalAggregation: {
+ description: 'Aggregate results in tree structure to reduce queen load',
+ expectedImprovement: 'O(log n) instead of O(n)',
+ implementation: `
+ class HierarchicalAggregator {
+ async aggregate(workers: Agent[]): Promise<Result> {
+ // Create tree of aggregators
+ const levels = Math.ceil(Math.log2(workers.length));
+ let current = workers.map(w => w.result);
+
+ for (let level = 0; level < levels; level++) {
+ const next = [];
+ for (let i = 0; i < current.length; i += 2) {
+ next.push(this.combine(current[i], current[i + 1]));
+ }
+ current = next;
+ }
+
+ return current[0];
+ }
+ }
+ `,
+ },
+
+ /**
+ * Async message processing
+ */
+ asyncProcessing: {
+ description: 'Process messages asynchronously with backpressure',
+ expectedImprovement: '2-3x throughput',
+ implementation: `
+ class AsyncBroker {
+ private queue = new AsyncQueue<Message>();
+
+ async process(): Promise<void> {
+ while (true) {
+ const messages = await this.queue.dequeue(100); // Batch up to 100
+ await Promise.all(messages.map(m => this.handle(m)));
+ }
+ }
+ }
+ `,
+ },
+
+ /**
+ * Local-first coordination
+ */
+ localFirstCoordination: {
+ description: 'Process locally when possible, coordinate only when needed',
+ expectedImprovement: '5-10x for local operations',
+ implementation: `
+ class LocalFirstCoordinator {
+ canProcessLocally(task: Task): boolean {
+ return task.dependencies.every(d => this.hasLocal(d));
+ }
+
+ async execute(task: Task): Promise<Result> {
+ if (this.canProcessLocally(task)) {
+ return this.executeLocal(task);
+ }
+ return this.executeDistributed(task);
+ }
+ }
+ `,
+ },
+};
+
+// Run if executed directly
+if (import.meta.url === `file://${process.argv[1]}`) {
+ runAgentCoordinationBenchmarks().catch(console.error);
+}
+
+export default runAgentCoordinationBenchmarks;
diff --git a/v3/benchmarks/swarm/consensus-latency.bench.ts b/v3/benchmarks/swarm/consensus-latency.bench.ts
new file mode 100644
index 0000000000..f5fcdcca5f
--- /dev/null
+++ b/v3/benchmarks/swarm/consensus-latency.bench.ts
@@ -0,0 +1,613 @@
+/**
+ * Consensus Latency Benchmark
+ *
+ * Target: <100ms (5x faster than current ~500ms)
+ *
+ * Measures the time to achieve consensus among multiple agents
+ * using various consensus protocols.
+ */
+
+import { benchmark, BenchmarkRunner, formatTime, meetsTarget } from '../framework/benchmark.js';
+
+// ============================================================================
+// Consensus Types
+// ============================================================================
+
+interface Vote {
+ agentId: string;
+ value: unknown;
+ timestamp: number;
+}
+
+interface ConsensusResult {
+ achieved: boolean;
+ value: unknown;
+ votes: Vote[];
+ rounds: number;
+ latency: number;
+}
+
+interface Agent {
+ id: string;
+ vote: (proposal: unknown) => Vote;
+ receive: (votes: Vote[]) => void;
+}
+
+// ============================================================================
+// Consensus Implementations
+// ============================================================================
+
+/**
+ * Simple majority voting
+ */
+class MajorityVoting {
+ private agents: Agent[] = [];
+
+ constructor(numAgents: number) {
+ for (let i = 0; i < numAgents; i++) {
+ this.agents.push({
+ id: `agent-${i}`,
+ vote: (proposal) => ({
+ agentId: `agent-${i}`,
+ value: proposal,
+ timestamp: Date.now(),
+ }),
+ receive: () => {},
+ });
+ }
+ }
+
+ async achieve(proposal: unknown): Promise<ConsensusResult> {
+ const startTime = performance.now();
+
+ // Collect votes
+ const votes = this.agents.map((agent) => agent.vote(proposal));
+
+ // Count votes
+ const voteCounts = new Map<string, number>();
+ for (const vote of votes) {
+ const key = JSON.stringify(vote.value);
+ voteCounts.set(key, (voteCounts.get(key) || 0) + 1);
+ }
+
+ // Find majority
+ const threshold = Math.floor(this.agents.length / 2) + 1;
+ let consensusValue: unknown = null;
+ let achieved = false;
+
+ for (const [value, count] of voteCounts) {
+ if (count >= threshold) {
+ consensusValue = JSON.parse(value);
+ achieved = true;
+ break;
+ }
+ }
+
+ return {
+ achieved,
+ value: consensusValue,
+ votes,
+ rounds: 1,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ get agentCount(): number {
+ return this.agents.length;
+ }
+}
+
+/**
+ * Two-phase commit protocol
+ */
+class TwoPhaseCommit {
+ private coordinator: string;
+ private participants: string[];
+ private preparedVotes = new Map<string, boolean>();
+
+ constructor(numParticipants: number) {
+ this.coordinator = 'coordinator';
+ this.participants = Array.from({ length: numParticipants }, (_, i) => `participant-${i}`);
+ }
+
+ async commit(transaction: unknown): Promise<ConsensusResult> {
+ const startTime = performance.now();
+ const votes: Vote[] = [];
+ let rounds = 0;
+
+ // Phase 1: Prepare
+ rounds++;
+ const prepareVotes = this.participants.map((p) => {
+ const vote: Vote = {
+ agentId: p,
+ value: { phase: 'prepare', ready: Math.random() > 0.1 }, // 90% success rate
+ timestamp: Date.now(),
+ };
+ votes.push(vote);
+ return vote;
+ });
+
+ const allPrepared = prepareVotes.every(
+ (v) => (v.value as { ready: boolean }).ready
+ );
+
+ if (!allPrepared) {
+ // Abort
+ rounds++;
+ return {
+ achieved: false,
+ value: null,
+ votes,
+ rounds,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ // Phase 2: Commit
+ rounds++;
+ const commitVotes = this.participants.map((p) => {
+ const vote: Vote = {
+ agentId: p,
+ value: { phase: 'commit', committed: true },
+ timestamp: Date.now(),
+ };
+ votes.push(vote);
+ return vote;
+ });
+
+ void commitVotes;
+
+ return {
+ achieved: true,
+ value: transaction,
+ votes,
+ rounds,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ get participantCount(): number {
+ return this.participants.length;
+ }
+}
+
+/**
+ * Raft-like leader election
+ */
+class RaftConsensus {
+ private nodes: Array<{
+ id: string;
+ term: number;
+ votedFor: string | null;
+ state: 'follower' | 'candidate' | 'leader';
+ }>;
+
+ constructor(numNodes: number) {
+ this.nodes = Array.from({ length: numNodes }, (_, i) => ({
+ id: `node-${i}`,
+ term: 0,
+ votedFor: null,
+ state: 'follower' as const,
+ }));
+ }
+
+ async electLeader(): Promise<ConsensusResult> {
+ const startTime = performance.now();
+ const votes: Vote[] = [];
+ let rounds = 0;
+
+ // Timeout and start election
+ const candidateIdx = Math.floor(Math.random() * this.nodes.length);
+ const candidate = this.nodes[candidateIdx]!;
+ candidate.state = 'candidate';
+ candidate.term++;
+ candidate.votedFor = candidate.id;
+
+ rounds++;
+
+ // Request votes from all nodes
+ let votesReceived = 1; // Vote for self
+
+ for (let i = 0; i < this.nodes.length; i++) {
+ if (i === candidateIdx) continue;
+
+ const node = this.nodes[i]!;
+ const grantVote =
+ node.term < candidate.term &&
+ (node.votedFor === null || node.votedFor === candidate.id);
+
+ if (grantVote) {
+ node.votedFor = candidate.id;
+ node.term = candidate.term;
+ votesReceived++;
+ }
+
+ votes.push({
+ agentId: node.id,
+ value: { grantVote, term: node.term },
+ timestamp: Date.now(),
+ });
+ }
+
+ const majority = Math.floor(this.nodes.length / 2) + 1;
+ const achieved = votesReceived >= majority;
+
+ if (achieved) {
+ candidate.state = 'leader';
+ } else {
+ candidate.state = 'follower';
+ }
+
+ return {
+ achieved,
+ value: achieved ? candidate.id : null,
+ votes,
+ rounds,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ get nodeCount(): number {
+ return this.nodes.length;
+ }
+}
+
+/**
+ * Byzantine Fault Tolerant consensus (simplified PBFT)
+ */
+class BFTConsensus {
+ private replicas: Array<{
+ id: string;
+ byzantine: boolean;
+ }>;
+ private f: number; // Max byzantine faults tolerated
+
+ constructor(numReplicas: number, byzantineCount: number = 0) {
+ this.replicas = Array.from({ length: numReplicas }, (_, i) => ({
+ id: `replica-${i}`,
+ byzantine: i < byzantineCount,
+ }));
+ this.f = Math.floor((numReplicas - 1) / 3);
+ }
+
+ async agree(proposal: unknown): Promise<ConsensusResult> {
+ const startTime = performance.now();
+ const votes: Vote[] = [];
+ let rounds = 0;
+
+ // Pre-prepare phase
+ rounds++;
+ const preprepareVotes = this.replicas.map((r) => ({
+ agentId: r.id,
+ value: { phase: 'preprepare', proposal: r.byzantine ? 'bad' : proposal },
+ timestamp: Date.now(),
+ }));
+ votes.push(...preprepareVotes);
+
+ // Prepare phase
+ rounds++;
+ const prepareVotes = this.replicas.map((r) => ({
+ agentId: r.id,
+ value: { phase: 'prepare', ready: !r.byzantine },
+ timestamp: Date.now(),
+ }));
+ votes.push(...prepareVotes);
+
+ const prepareCount = prepareVotes.filter(
+ (v) => (v.value as { ready: boolean }).ready
+ ).length;
+
+ // Need 2f + 1 prepare messages
+ if (prepareCount < 2 * this.f + 1) {
+ return {
+ achieved: false,
+ value: null,
+ votes,
+ rounds,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ // Commit phase
+ rounds++;
+ const commitVotes = this.replicas.map((r) => ({
+ agentId: r.id,
+ value: { phase: 'commit', committed: !r.byzantine },
+ timestamp: Date.now(),
+ }));
+ votes.push(...commitVotes);
+
+ const commitCount = commitVotes.filter(
+ (v) => (v.value as { committed: boolean }).committed
+ ).length;
+
+ const achieved = commitCount >= 2 * this.f + 1;
+
+ return {
+ achieved,
+ value: achieved ? proposal : null,
+ votes,
+ rounds,
+ latency: performance.now() - startTime,
+ };
+ }
+
+ get replicaCount(): number {
+ return this.replicas.length;
+ }
+}
+
+// ============================================================================
+// Benchmark Suite
+// ============================================================================
+
+export async function runConsensusLatencyBenchmarks(): Promise<void> {
+ const runner = new BenchmarkRunner('Consensus Latency');
+
+ console.log('\n--- Consensus Latency Benchmarks ---\n');
+
+ // Benchmark 1: Majority Voting - 5 Agents
+ const majority5 = new MajorityVoting(5);
+
+ const majority5Result = await runner.run(
+ 'majority-voting-5-agents',
+ async () => {
+ await majority5.achieve({ action: 'approve', value: 42 });
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Majority Voting (5 agents): ${formatTime(majority5Result.mean)}`);
+ const consensusTarget = meetsTarget('consensus-latency', majority5Result.mean);
+ console.log(` Target (<100ms): ${consensusTarget.met ? 'PASS' : 'FAIL'}`);
+
+ // Benchmark 2: Majority Voting - 15 Agents
+ const majority15 = new MajorityVoting(15);
+
+ const majority15Result = await runner.run(
+ 'majority-voting-15-agents',
+ async () => {
+ await majority15.achieve({ action: 'approve', value: 42 });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Majority Voting (15 agents): ${formatTime(majority15Result.mean)}`);
+
+ // Benchmark 3: Two-Phase Commit - 5 Participants
+ const tpc5 = new TwoPhaseCommit(5);
+
+ const tpc5Result = await runner.run(
+ 'two-phase-commit-5',
+ async () => {
+ await tpc5.commit({ txId: 'tx-123', data: 'test' });
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Two-Phase Commit (5 participants): ${formatTime(tpc5Result.mean)}`);
+
+ // Benchmark 4: Two-Phase Commit - 15 Participants
+ const tpc15 = new TwoPhaseCommit(15);
+
+ const tpc15Result = await runner.run(
+ 'two-phase-commit-15',
+ async () => {
+ await tpc15.commit({ txId: 'tx-123', data: 'test' });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Two-Phase Commit (15 participants): ${formatTime(tpc15Result.mean)}`);
+
+ // Benchmark 5: Raft Leader Election - 5 Nodes
+ const raft5 = new RaftConsensus(5);
+
+ const raft5Result = await runner.run(
+ 'raft-election-5-nodes',
+ async () => {
+ await raft5.electLeader();
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Raft Election (5 nodes): ${formatTime(raft5Result.mean)}`);
+
+ // Benchmark 6: Raft Leader Election - 15 Nodes
+ const raft15 = new RaftConsensus(15);
+
+ const raft15Result = await runner.run(
+ 'raft-election-15-nodes',
+ async () => {
+ await raft15.electLeader();
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Raft Election (15 nodes): ${formatTime(raft15Result.mean)}`);
+
+ // Benchmark 7: BFT Consensus - 4 Replicas (f=1)
+ const bft4 = new BFTConsensus(4, 0);
+
+ const bft4Result = await runner.run(
+ 'bft-consensus-4-replicas',
+ async () => {
+ await bft4.agree({ decision: 'commit' });
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`BFT Consensus (4 replicas, f=1): ${formatTime(bft4Result.mean)}`);
+
+ // Benchmark 8: BFT Consensus - 7 Replicas (f=2)
+ const bft7 = new BFTConsensus(7, 0);
+
+ const bft7Result = await runner.run(
+ 'bft-consensus-7-replicas',
+ async () => {
+ await bft7.agree({ decision: 'commit' });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`BFT Consensus (7 replicas, f=2): ${formatTime(bft7Result.mean)}`);
+
+ // Benchmark 9: BFT with Byzantine Nodes
+ const bft7byz = new BFTConsensus(7, 2);
+
+ const bft7byzResult = await runner.run(
+ 'bft-consensus-7-with-2-byzantine',
+ async () => {
+ await bft7byz.agree({ decision: 'commit' });
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`BFT (7 replicas, 2 byzantine): ${formatTime(bft7byzResult.mean)}`);
+
+ // Benchmark 10: Multiple Consensus Rounds
+ const multiRoundResult = await runner.run(
+ 'multiple-consensus-rounds-10',
+ async () => {
+ for (let i = 0; i < 10; i++) {
+ await majority5.achieve({ round: i });
+ }
+ },
+ { iterations: 100 }
+ );
+
+ console.log(`10 Consensus Rounds: ${formatTime(multiRoundResult.mean)}`);
+
+ // Summary
+ console.log('\n--- Summary ---');
+ console.log(`Majority (5): ${formatTime(majority5Result.mean)}`);
+ console.log(`Majority (15): ${formatTime(majority15Result.mean)}`);
+ console.log(`2PC (5): ${formatTime(tpc5Result.mean)}`);
+ console.log(`Raft (5): ${formatTime(raft5Result.mean)}`);
+ console.log(`BFT (4): ${formatTime(bft4Result.mean)}`);
+ console.log(`\nScaling factors:`);
+ console.log(` Majority 5->15: ${(majority15Result.mean / majority5Result.mean).toFixed(2)}x`);
+ console.log(` 2PC 5->15: ${(tpc15Result.mean / tpc5Result.mean).toFixed(2)}x`);
+ console.log(` Raft 5->15: ${(raft15Result.mean / raft5Result.mean).toFixed(2)}x`);
+
+ // Print full results
+ runner.printResults();
+}
+
+// ============================================================================
+// Consensus Optimization Strategies
+// ============================================================================
+
+export const consensusOptimizations = {
+ /**
+ * Parallel vote collection
+ */
+ parallelVoteCollection: {
+ description: 'Collect votes from all agents in parallel',
+ expectedImprovement: 'O(1) instead of O(n)',
+ implementation: `
+ async function collectVotes(agents: Agent[], proposal: unknown): Promise<Vote[]> {
+ return Promise.all(agents.map(agent => agent.vote(proposal)));
+ }
+ `,
+ },
+
+ /**
+ * Early termination
+ */
+ earlyTermination: {
+ description: 'Terminate early when majority is achieved',
+ expectedImprovement: '30-50%',
+ implementation: `
+ async function earlyMajority(agents: Agent[], proposal: unknown): Promise<Vote[]> {
+ const majority = Math.floor(agents.length / 2) + 1;
+ const votes: Vote[] = [];
+
+ for (const agent of agents) {
+ votes.push(await agent.vote(proposal));
+ const count = countAgreement(votes);
+ if (count >= majority) break;
+ }
+
+ return votes;
+ }
+ `,
+ },
+
+ /**
+ * Pipelining phases
+ */
+ pipelining: {
+ description: 'Pipeline consensus phases for multiple proposals',
+ expectedImprovement: '2-3x throughput',
+ implementation: `
+ class PipelinedConsensus {
+ private phases = ['prepare', 'accept', 'commit'];
+ private inflight = new Map<string, number>();
+
+ async propose(proposal: unknown): Promise<void> {
+ const id = generateId();
+ this.inflight.set(id, 0);
+
+ // Start next phase as soon as previous completes
+ for (const phase of this.phases) {
+ await this.executePhase(id, phase);
+ this.inflight.set(id, this.inflight.get(id)! + 1);
+ }
+ }
+ }
+ `,
+ },
+
+ /**
+ * Speculative execution
+ */
+ speculativeExecution: {
+ description: 'Speculatively execute while waiting for consensus',
+ expectedImprovement: '50-70% latency reduction',
+ implementation: `
+ async function speculativeConsensus(proposal: unknown): Promise<Result> {
+ const [consensusResult, executionResult] = await Promise.all([
+ achieveConsensus(proposal),
+ speculativelyExecute(proposal),
+ ]);
+
+ if (consensusResult.achieved) {
+ return executionResult;
+ }
+
+ return rollback(executionResult);
+ }
+ `,
+ },
+
+ /**
+ * Hierarchical consensus
+ */
+ hierarchicalConsensus: {
+ description: 'Achieve consensus in smaller groups first',
+ expectedImprovement: 'O(log n) rounds',
+ implementation: `
+ async function hierarchicalConsensus(agents: Agent[]): Promise<Vote[]> {
+ const groupSize = 5;
+ const groups = chunkArray(agents, groupSize);
+
+ // First level: consensus within groups
+ const groupResults = await Promise.all(
+ groups.map(group => achieveConsensus(group))
+ );
+
+ // Second level: consensus among group leaders
+ const leaders = groupResults.map(r => r.leader);
+ return achieveConsensus(leaders);
+ }
+ `,
+ },
+};
+
+// Run if executed directly
+if (import.meta.url === `file://${process.argv[1]}`) {
+ runConsensusLatencyBenchmarks().catch(console.error);
+}
+
+export default runConsensusLatencyBenchmarks;
diff --git a/v3/benchmarks/swarm/message-throughput.bench.ts b/v3/benchmarks/swarm/message-throughput.bench.ts
new file mode 100644
index 0000000000..c1ad238d41
--- /dev/null
+++ b/v3/benchmarks/swarm/message-throughput.bench.ts
@@ -0,0 +1,568 @@
+/**
+ * Message Throughput Benchmark
+ *
+ * Target: <0.1ms per message
+ *
+ * Measures message passing throughput between agents including
+ * serialization, routing, and delivery.
+ */
+
+import { benchmark, BenchmarkRunner, formatTime, meetsTarget } from '../framework/benchmark.js';
+
+// ============================================================================
+// Message Types
+// ============================================================================
+
+interface Message {
+ id: string;
+ type: string;
+ from: string;
+ to: string;
+ payload: unknown;
+ timestamp: number;
+ headers?: Record<string, string>;
+}
+
+interface MessageStats {
+ sent: number;
+ received: number;
+ dropped: number;
+ latencySum: number;
+}
+
+// ============================================================================
+// Message Channel Implementations
+// ============================================================================
+
+/**
+ * Simple synchronous message channel
+ */
+class SyncChannel {
+ private handlers = new Map<string, (msg: Message) => void>();
+ private stats: MessageStats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+
+ subscribe(agentId: string, handler: (msg: Message) => void): void {
+ this.handlers.set(agentId, handler);
+ }
+
+ send(message: Message): boolean {
+ this.stats.sent++;
+ const handler = this.handlers.get(message.to);
+ if (handler) {
+ handler(message);
+ this.stats.received++;
+ this.stats.latencySum += Date.now() - message.timestamp;
+ return true;
+ }
+ this.stats.dropped++;
+ return false;
+ }
+
+ getStats(): MessageStats {
+ return { ...this.stats };
+ }
+
+ reset(): void {
+ this.stats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+ }
+}
+
+/**
+ * Async message queue with buffering
+ */
+class AsyncMessageQueue {
+ private queues = new Map<string, Message[]>();
+ private stats: MessageStats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+ private maxQueueSize = 1000;
+
+ enqueue(message: Message): boolean {
+ this.stats.sent++;
+
+ let queue = this.queues.get(message.to);
+ if (!queue) {
+ queue = [];
+ this.queues.set(message.to, queue);
+ }
+
+ if (queue.length >= this.maxQueueSize) {
+ this.stats.dropped++;
+ return false;
+ }
+
+ queue.push(message);
+ return true;
+ }
+
+ dequeue(agentId: string): Message | undefined {
+ const queue = this.queues.get(agentId);
+ if (queue && queue.length > 0) {
+ const message = queue.shift()!;
+ this.stats.received++;
+ this.stats.latencySum += Date.now() - message.timestamp;
+ return message;
+ }
+ return undefined;
+ }
+
+ dequeueAll(agentId: string): Message[] {
+ const queue = this.queues.get(agentId) || [];
+ this.queues.set(agentId, []);
+ this.stats.received += queue.length;
+ for (const msg of queue) {
+ this.stats.latencySum += Date.now() - msg.timestamp;
+ }
+ return queue;
+ }
+
+ getStats(): MessageStats {
+ return { ...this.stats };
+ }
+
+ reset(): void {
+ this.queues.clear();
+ this.stats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+ }
+}
+
+/**
+ * Pub/Sub message broker
+ */
+class PubSubBroker {
+ private topics = new Map<string, Set<string>>();
+ private handlers = new Map<string, (msg: Message) => void>();
+ private stats: MessageStats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+
+ subscribe(agentId: string, topic: string, handler: (msg: Message) => void): void {
+ if (!this.topics.has(topic)) {
+ this.topics.set(topic, new Set());
+ }
+ this.topics.get(topic)!.add(agentId);
+ this.handlers.set(`${agentId}:${topic}`, handler);
+ }
+
+ publish(topic: string, message: Message): number {
+ const subscribers = this.topics.get(topic);
+ if (!subscribers) return 0;
+
+ let delivered = 0;
+ for (const agentId of subscribers) {
+ this.stats.sent++;
+ const handler = this.handlers.get(`${agentId}:${topic}`);
+ if (handler) {
+ handler({ ...message, to: agentId });
+ this.stats.received++;
+ this.stats.latencySum += Date.now() - message.timestamp;
+ delivered++;
+ }
+ }
+
+ return delivered;
+ }
+
+ getStats(): MessageStats {
+ return { ...this.stats };
+ }
+
+ reset(): void {
+ this.stats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+ }
+}
+
+/**
+ * Batched message channel
+ */
+class BatchedChannel {
+ private batch: Message[] = [];
+ private handlers = new Map<string, (msgs: Message[]) => void>();
+ private batchSize = 100;
+ private stats: MessageStats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+
+ subscribe(agentId: string, handler: (msgs: Message[]) => void): void {
+ this.handlers.set(agentId, handler);
+ }
+
+ send(message: Message): void {
+ this.stats.sent++;
+ this.batch.push(message);
+
+ if (this.batch.length >= this.batchSize) {
+ this.flush();
+ }
+ }
+
+ flush(): void {
+ // Group messages by recipient
+ const byRecipient = new Map<string, Message[]>();
+ for (const msg of this.batch) {
+ if (!byRecipient.has(msg.to)) {
+ byRecipient.set(msg.to, []);
+ }
+ byRecipient.get(msg.to)!.push(msg);
+ }
+
+ // Deliver to each recipient
+ for (const [agentId, messages] of byRecipient) {
+ const handler = this.handlers.get(agentId);
+ if (handler) {
+ handler(messages);
+ this.stats.received += messages.length;
+ for (const msg of messages) {
+ this.stats.latencySum += Date.now() - msg.timestamp;
+ }
+ } else {
+ this.stats.dropped += messages.length;
+ }
+ }
+
+ this.batch = [];
+ }
+
+ getStats(): MessageStats {
+ return { ...this.stats };
+ }
+
+ reset(): void {
+ this.batch = [];
+ this.stats = { sent: 0, received: 0, dropped: 0, latencySum: 0 };
+ }
+}
+
+// ============================================================================
+// Helper Functions
+// ============================================================================
+
+function createMessage(from: string, to: string, payload: unknown): Message {
+ return {
+ id: `msg-${Date.now()}-${Math.random().toString(36).slice(2)}`,
+ type: 'data',
+ from,
+ to,
+ payload,
+ timestamp: Date.now(),
+ };
+}
+
+// ============================================================================
+// Benchmark Suite
+// ============================================================================
+
+export async function runMessageThroughputBenchmarks(): Promise<void> {
+ const runner = new BenchmarkRunner('Message Throughput');
+
+ console.log('\n--- Message Throughput Benchmarks ---\n');
+
+ // Setup channels
+ const syncChannel = new SyncChannel();
+ const asyncQueue = new AsyncMessageQueue();
+ const pubsub = new PubSubBroker();
+ const batchedChannel = new BatchedChannel();
+
+ // Register handlers
+ for (let i = 0; i < 100; i++) {
+ syncChannel.subscribe(`agent-${i}`, () => {});
+ batchedChannel.subscribe(`agent-${i}`, () => {});
+ }
+ for (let i = 0; i < 100; i++) {
+ pubsub.subscribe(`agent-${i}`, 'broadcast', () => {});
+ }
+
+ // Benchmark 1: Single Message - Sync Channel
+ const syncSingleResult = await runner.run(
+ 'sync-channel-single-message',
+ async () => {
+ const msg = createMessage('sender', 'agent-0', { data: 'test' });
+ syncChannel.send(msg);
+ },
+ { iterations: 100000 }
+ );
+
+ console.log(`Sync Channel (single): ${formatTime(syncSingleResult.mean)}`);
+ const throughputTarget = meetsTarget('message-throughput', syncSingleResult.mean);
+ console.log(` Target (<0.1ms): ${throughputTarget.met ? 'PASS' : 'FAIL'}`);
+
+ // Benchmark 2: Message Batch - Sync Channel (100 messages)
+ const syncBatchResult = await runner.run(
+ 'sync-channel-100-messages',
+ async () => {
+ for (let i = 0; i < 100; i++) {
+ const msg = createMessage('sender', `agent-${i}`, { data: i });
+ syncChannel.send(msg);
+ }
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Sync Channel (100 messages): ${formatTime(syncBatchResult.mean)}`);
+ console.log(` Per message: ${formatTime(syncBatchResult.mean / 100)}`);
+
+ // Benchmark 3: Async Queue - Enqueue
+ const asyncEnqueueResult = await runner.run(
+ 'async-queue-enqueue',
+ async () => {
+ const msg = createMessage('sender', 'agent-0', { data: 'test' });
+ asyncQueue.enqueue(msg);
+ },
+ { iterations: 100000 }
+ );
+
+ console.log(`Async Queue (enqueue): ${formatTime(asyncEnqueueResult.mean)}`);
+
+ // Benchmark 4: Async Queue - Dequeue
+ // Pre-populate queue
+ for (let i = 0; i < 10000; i++) {
+ asyncQueue.enqueue(createMessage('sender', 'agent-0', { data: i }));
+ }
+
+ const asyncDequeueResult = await runner.run(
+ 'async-queue-dequeue',
+ async () => {
+ asyncQueue.dequeue('agent-0');
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Async Queue (dequeue): ${formatTime(asyncDequeueResult.mean)}`);
+
+ // Benchmark 5: Async Queue - Batch Dequeue
+ asyncQueue.reset();
+ for (let i = 0; i < 100; i++) {
+ asyncQueue.enqueue(createMessage('sender', 'agent-1', { data: i }));
+ }
+
+ const asyncBatchDequeueResult = await runner.run(
+ 'async-queue-batch-dequeue',
+ async () => {
+ asyncQueue.dequeueAll('agent-1');
+ // Refill for next iteration
+ for (let i = 0; i < 100; i++) {
+ asyncQueue.enqueue(createMessage('sender', 'agent-1', { data: i }));
+ }
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Async Queue (batch dequeue 100): ${formatTime(asyncBatchDequeueResult.mean)}`);
+
+ // Benchmark 6: Pub/Sub - Single Publish
+ const pubsubSingleResult = await runner.run(
+ 'pubsub-single-publish',
+ async () => {
+ const msg = createMessage('publisher', '', { event: 'test' });
+ pubsub.publish('broadcast', msg);
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Pub/Sub (to 100 subscribers): ${formatTime(pubsubSingleResult.mean)}`);
+ console.log(` Per subscriber: ${formatTime(pubsubSingleResult.mean / 100)}`);
+
+ // Benchmark 7: Batched Channel - Single Message
+ const batchedSingleResult = await runner.run(
+ 'batched-channel-single',
+ async () => {
+ const msg = createMessage('sender', 'agent-0', { data: 'test' });
+ batchedChannel.send(msg);
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Batched Channel (single, no flush): ${formatTime(batchedSingleResult.mean)}`);
+
+ // Benchmark 8: Batched Channel - Full Batch + Flush
+ batchedChannel.reset();
+
+ const batchedFlushResult = await runner.run(
+ 'batched-channel-flush-100',
+ async () => {
+ for (let i = 0; i < 100; i++) {
+ batchedChannel.send(createMessage('sender', `agent-${i}`, { data: i }));
+ }
+ batchedChannel.flush();
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Batched Channel (100 + flush): ${formatTime(batchedFlushResult.mean)}`);
+ console.log(` Per message: ${formatTime(batchedFlushResult.mean / 100)}`);
+
+ // Benchmark 9: Message Serialization
+ const serializationResult = await runner.run(
+ 'message-serialization',
+ async () => {
+ const msg = createMessage('sender', 'receiver', {
+ data: Array.from({ length: 100 }, (_, i) => i),
+ nested: { level1: { level2: { value: 42 } } },
+ });
+ JSON.stringify(msg);
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Message Serialization: ${formatTime(serializationResult.mean)}`);
+
+ // Benchmark 10: Message Deserialization
+ const msgJson = JSON.stringify(
+ createMessage('sender', 'receiver', {
+ data: Array.from({ length: 100 }, (_, i) => i),
+ })
+ );
+
+ const deserializationResult = await runner.run(
+ 'message-deserialization',
+ async () => {
+ JSON.parse(msgJson);
+ },
+ { iterations: 10000 }
+ );
+
+ console.log(`Message Deserialization: ${formatTime(deserializationResult.mean)}`);
+
+ // Benchmark 11: High Throughput Test (1000 messages)
+ syncChannel.reset();
+
+ const highThroughputResult = await runner.run(
+ 'high-throughput-1000-messages',
+ async () => {
+ for (let i = 0; i < 1000; i++) {
+ const msg = createMessage('sender', `agent-${i % 100}`, { seq: i });
+ syncChannel.send(msg);
+ }
+ },
+ { iterations: 100 }
+ );
+
+ console.log(`High Throughput (1000 messages): ${formatTime(highThroughputResult.mean)}`);
+ console.log(` Throughput: ${(1000 / highThroughputResult.mean * 1000).toFixed(0)} msg/sec`);
+
+ // Summary
+ console.log('\n--- Summary ---');
+ console.log(`Single message: ${formatTime(syncSingleResult.mean)}`);
+ console.log(`Batch (100): ${formatTime(syncBatchResult.mean)} (${formatTime(syncBatchResult.mean / 100)}/msg)`);
+ console.log(`Pub/Sub (100 subs): ${formatTime(pubsubSingleResult.mean)}`);
+ console.log(`Serialization: ${formatTime(serializationResult.mean)}`);
+ console.log(`\nThroughput: ${(1000 / highThroughputResult.mean * 1000).toFixed(0)} messages/sec`);
+
+ // Print full results
+ runner.printResults();
+}
+
+// ============================================================================
+// Message Throughput Optimization Strategies
+// ============================================================================
+
+export const messageOptimizations = {
+ /**
+ * Zero-copy messaging
+ */
+ zeroCopy: {
+ description: 'Use SharedArrayBuffer to avoid copying message data',
+ expectedImprovement: '3-5x for large messages',
+ implementation: `
+ class ZeroCopyChannel {
+ send(data: Uint8Array): void {
+ const sab = new SharedArrayBuffer(data.length);
+ new Uint8Array(sab).set(data);
+ this.deliverReference(sab);
+ }
+ }
+ `,
+ },
+
+ /**
+ * Message batching
+ */
+ messageBatching: {
+ description: 'Batch multiple messages to amortize overhead',
+ expectedImprovement: '5-10x throughput',
+ implementation: `
+ class BatchedSender {
+ private batch: Message[] = [];
+ private batchSize = 100;
+
+ send(msg: Message): void {
+ this.batch.push(msg);
+ if (this.batch.length >= this.batchSize) {
+ this.flush();
+ }
+ }
+
+ private flush(): void {
+ this.transport.sendBatch(this.batch);
+ this.batch = [];
+ }
+ }
+ `,
+ },
+
+ /**
+ * Binary serialization
+ */
+ binarySerialization: {
+ description: 'Use binary format instead of JSON',
+ expectedImprovement: '2-4x serialization speed',
+ implementation: `
+ import msgpack from '@msgpack/msgpack';
+
+ function serialize(msg: Message): Uint8Array {
+ return msgpack.encode(msg);
+ }
+
+ function deserialize(data: Uint8Array): Message {
+ return msgpack.decode(data) as Message;
+ }
+ `,
+ },
+
+ /**
+ * Connection pooling
+ */
+ connectionPooling: {
+ description: 'Reuse connections for message delivery',
+ expectedImprovement: '10-20x for remote messaging',
+ implementation: `
+ class ConnectionPool {
+ private pool: Connection[] = [];
+
+ async getConnection(target: string): Promise<Connection> {
+ const cached = this.pool.find(c => c.target === target && c.idle);
+ if (cached) {
+ cached.idle = false;
+ return cached;
+ }
+ return this.createConnection(target);
+ }
+ }
+ `,
+ },
+
+ /**
+ * Priority queuing
+ */
+ priorityQueuing: {
+ description: 'Process high-priority messages first',
+ expectedImprovement: 'Lower latency for critical messages',
+ implementation: `
+ class PriorityQueue {
+ private high: Message[] = [];
+ private normal: Message[] = [];
+ private low: Message[] = [];
+
+ enqueue(msg: Message): void {
+ const queue = this.getQueue(msg.priority);
+ queue.push(msg);
+ }
+
+ dequeue(): Message | undefined {
+ return this.high.shift() || this.normal.shift() || this.low.shift();
+ }
+ }
+ `,
+ },
+};
+
+// Run if executed directly
+if (import.meta.url === `file://${process.argv[1]}`) {
+ runMessageThroughputBenchmarks().catch(console.error);
+}
+
+export default runMessageThroughputBenchmarks;
diff --git a/v3/benchmarks/swarm/task-decomposition.bench.ts b/v3/benchmarks/swarm/task-decomposition.bench.ts
new file mode 100644
index 0000000000..ef2ec39823
--- /dev/null
+++ b/v3/benchmarks/swarm/task-decomposition.bench.ts
@@ -0,0 +1,545 @@
+/**
+ * Task Decomposition Benchmark
+ *
+ * Target: <20ms for task decomposition
+ *
+ * Measures the time to decompose complex tasks into subtasks
+ * for parallel execution by multiple agents.
+ */
+
+import { benchmark, BenchmarkRunner, formatTime, meetsTarget } from '../framework/benchmark.js';
+
+// ============================================================================
+// Task Types
+// ============================================================================
+
+interface Task {
+ id: string;
+ type: string;
+ description: string;
+ priority: number;
+ dependencies: string[];
+ estimatedDuration: number;
+ assignedTo?: string;
+}
+
+interface SubTask extends Task {
+ parentId: string;
+ order: number;
+}
+
+interface TaskGraph {
+ tasks: Map<string, Task>;
+ edges: Map<string, string[]>; // task -> dependencies
+}
+
+interface DecompositionResult {
+ subtasks: SubTask[];
+ parallelGroups: SubTask[][];
+ criticalPath: string[];
+ estimatedTotalTime: number;
+}
+
+// ============================================================================
+// Task Decomposition Strategies
+// ============================================================================
+
+/**
+ * Simple linear decomposition
+ */
+function linearDecompose(task: Task, numParts: number): SubTask[] {
+ const subtasks: SubTask[] = [];
+
+ for (let i = 0; i < numParts; i++) {
+ subtasks.push({
+ id: `${task.id}-part-${i}`,
+ parentId: task.id,
+ type: task.type,
+ description: `Part ${i + 1} of ${task.description}`,
+ priority: task.priority,
+ dependencies: i > 0 ? [`${task.id}-part-${i - 1}`] : task.dependencies,
+ estimatedDuration: task.estimatedDuration / numParts,
+ order: i,
+ });
+ }
+
+ return subtasks;
+}
+
+/**
+ * Parallel decomposition (all subtasks independent)
+ */
+function parallelDecompose(task: Task, numParts: number): SubTask[] {
+ const subtasks: SubTask[] = [];
+
+ for (let i = 0; i < numParts; i++) {
+ subtasks.push({
+ id: `${task.id}-parallel-${i}`,
+ parentId: task.id,
+ type: task.type,
+ description: `Parallel chunk ${i + 1} of ${task.description}`,
+ priority: task.priority,
+ dependencies: task.dependencies, // All depend only on parent's deps
+ estimatedDuration: task.estimatedDuration / numParts,
+ order: i,
+ });
+ }
+
+ return subtasks;
+}
+
+/**
+ * DAG-based decomposition with topological sort
+ */
+function dagDecompose(tasks: Task[]): DecompositionResult {
+ const graph: TaskGraph = {
+ tasks: new Map(tasks.map((t) => [t.id, t])),
+ edges: new Map(tasks.map((t) => [t.id, t.dependencies])),
+ };
+
+ // Topological sort using Kahn's algorithm
+ const inDegree = new Map<string, number>();
+ for (const task of tasks) {
+ inDegree.set(task.id, 0);
+ }
+
+ for (const [, deps] of graph.edges) {
+ for (const dep of deps) {
+ inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
+ }
+ }
+
+ const queue: string[] = [];
+ for (const [id, degree] of inDegree) {
+ if (degree === 0) {
+ queue.push(id);
+ }
+ }
+
+ const sorted: string[] = [];
+ const parallelGroups: SubTask[][] = [];
+
+ while (queue.length > 0) {
+ // All tasks in current queue can run in parallel
+ const currentGroup: SubTask[] = [];
+ const nextQueue: string[] = [];
+
+ for (const taskId of queue) {
+ const task = graph.tasks.get(taskId)!;
+ currentGroup.push({
+ ...task,
+ parentId: 'root',
+ order: sorted.length,
+ });
+ sorted.push(taskId);
+
+ // Reduce in-degree of dependent tasks
+ for (const [depId, deps] of graph.edges) {
+ if (deps.includes(taskId)) {
+ const newDegree = (inDegree.get(depId) || 1) - 1;
+ inDegree.set(depId, newDegree);
+ if (newDegree === 0) {
+ nextQueue.push(depId);
+ }
+ }
+ }
+ }
+
+ if (currentGroup.length > 0) {
+ parallelGroups.push(currentGroup);
+ }
+ queue.length = 0;
+ queue.push(...nextQueue);
+ }
+
+ // Find critical path
+ const criticalPath = findCriticalPath(tasks, sorted);
+
+ // Calculate estimated total time (parallel execution)
+ const estimatedTotalTime = parallelGroups.reduce(
+ (total, group) => total + Math.max(...group.map((t) => t.estimatedDuration)),
+ 0
+ );
+
+ return {
+ subtasks: parallelGroups.flat(),
+ parallelGroups,
+ criticalPath,
+ estimatedTotalTime,
+ };
+}
+
+/**
+ * Find critical path in task graph
+ */
+function findCriticalPath(tasks: Task[], sorted: string[]): string[] {
+ const taskMap = new Map(tasks.map((t) => [t.id, t]));
+ const longestPath = new Map<string, number>();
+ const predecessor = new Map<string, string>();
+
+ for (const taskId of sorted) {
+ const task = taskMap.get(taskId)!;
+ let maxPredDuration = 0;
+ let maxPredId = '';
+
+ for (const depId of task.dependencies) {
+ const predDuration = longestPath.get(depId) || 0;
+ if (predDuration > maxPredDuration) {
+ maxPredDuration = predDuration;
+ maxPredId = depId;
+ }
+ }
+
+ longestPath.set(taskId, maxPredDuration + task.estimatedDuration);
+ if (maxPredId) {
+ predecessor.set(taskId, maxPredId);
+ }
+ }
+
+ // Find task with longest path
+ let maxTask = '';
+ let maxDuration = 0;
+ for (const [taskId, duration] of longestPath) {
+ if (duration > maxDuration) {
+ maxDuration = duration;
+ maxTask = taskId;
+ }
+ }
+
+ // Reconstruct path
+ const path: string[] = [];
+ let current = maxTask;
+ while (current) {
+ path.unshift(current);
+ current = predecessor.get(current) || '';
+ }
+
+ return path;
+}
+
+/**
+ * SPARC-based decomposition
+ */
+function sparcDecompose(task: Task): SubTask[] {
+ const phases = [
+ { name: 'specification', ratio: 0.1 },
+ { name: 'pseudocode', ratio: 0.15 },
+ { name: 'architecture', ratio: 0.2 },
+ { name: 'refinement', ratio: 0.4 },
+ { name: 'completion', ratio: 0.15 },
+ ];
+
+ const subtasks: SubTask[] = [];
+ let prevId = '';
+
+ for (let i = 0; i < phases.length; i++) {
+ const phase = phases[i]!;
+ const subtask: SubTask = {
+ id: `${task.id}-${phase.name}`,
+ parentId: task.id,
+ type: phase.name,
+ description: `${phase.name.charAt(0).toUpperCase() + phase.name.slice(1)} for ${task.description}`,
+ priority: task.priority,
+ dependencies: prevId ? [prevId] : task.dependencies,
+ estimatedDuration: task.estimatedDuration * phase.ratio,
+ order: i,
+ };
+ subtasks.push(subtask);
+ prevId = subtask.id;
+ }
+
+ return subtasks;
+}
+
+// ============================================================================
+// Benchmark Suite
+// ============================================================================
+
+export async function runTaskDecompositionBenchmarks(): Promise<void> {
+ const runner = new BenchmarkRunner('Task Decomposition');
+
+ console.log('\n--- Task Decomposition Benchmarks ---\n');
+
+ // Create sample tasks
+ const sampleTask: Task = {
+ id: 'task-1',
+ type: 'development',
+ description: 'Implement user authentication',
+ priority: 1,
+ dependencies: [],
+ estimatedDuration: 100,
+ };
+
+ const complexTasks: Task[] = Array.from({ length: 50 }, (_, i) => ({
+ id: `task-${i}`,
+ type: 'development',
+ description: `Task ${i}`,
+ priority: Math.floor(Math.random() * 10),
+ dependencies: i > 0 ? [`task-${Math.floor(Math.random() * i)}`] : [],
+ estimatedDuration: 10 + Math.random() * 90,
+ }));
+
+ // Benchmark 1: Linear Decomposition
+ const linearResult = await runner.run(
+ 'linear-decompose-10',
+ async () => {
+ linearDecompose(sampleTask, 10);
+ },
+ { iterations: 5000 }
+ );
+
+ console.log(`Linear Decompose (10 parts): ${formatTime(linearResult.mean)}`);
+ const decomposeTarget = meetsTarget('task-decomposition', linearResult.mean);
+ console.log(` Target (<20ms): ${decomposeTarget.met ? 'PASS' : 'FAIL'}`);
+
+ // Benchmark 2: Parallel Decomposition
+ const parallelResult = await runner.run(
+ 'parallel-decompose-10',
+ async () => {
+ parallelDecompose(sampleTask, 10);
+ },
+ { iterations: 5000 }
+ );
+
+ console.log(`Parallel Decompose (10 parts): ${formatTime(parallelResult.mean)}`);
+
+ // Benchmark 3: SPARC Decomposition
+ const sparcResult = await runner.run(
+ 'sparc-decompose',
+ async () => {
+ sparcDecompose(sampleTask);
+ },
+ { iterations: 5000 }
+ );
+
+ console.log(`SPARC Decompose (5 phases): ${formatTime(sparcResult.mean)}`);
+
+ // Benchmark 4: DAG Decomposition - Small (10 tasks)
+ const smallTasks = complexTasks.slice(0, 10);
+
+ const dagSmallResult = await runner.run(
+ 'dag-decompose-10-tasks',
+ async () => {
+ dagDecompose(smallTasks);
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`DAG Decompose (10 tasks): ${formatTime(dagSmallResult.mean)}`);
+
+ // Benchmark 5: DAG Decomposition - Medium (50 tasks)
+ const dagMediumResult = await runner.run(
+ 'dag-decompose-50-tasks',
+ async () => {
+ dagDecompose(complexTasks);
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`DAG Decompose (50 tasks): ${formatTime(dagMediumResult.mean)}`);
+
+ // Benchmark 6: Critical Path Finding
+ const sorted = complexTasks.map((t) => t.id);
+
+ const criticalPathResult = await runner.run(
+ 'find-critical-path-50',
+ async () => {
+ findCriticalPath(complexTasks, sorted);
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Find Critical Path (50 tasks): ${formatTime(criticalPathResult.mean)}`);
+
+ // Benchmark 7: Large Decomposition (100 subtasks)
+ const largeLinearResult = await runner.run(
+ 'linear-decompose-100',
+ async () => {
+ linearDecompose(sampleTask, 100);
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Linear Decompose (100 parts): ${formatTime(largeLinearResult.mean)}`);
+
+ // Benchmark 8: Nested Decomposition
+ const nestedResult = await runner.run(
+ 'nested-decompose',
+ async () => {
+ // First level
+ const level1 = parallelDecompose(sampleTask, 5);
+ // Second level - decompose each part
+ const level2: SubTask[] = [];
+ for (const subtask of level1) {
+ level2.push(...linearDecompose(subtask, 4));
+ }
+ },
+ { iterations: 1000 }
+ );
+
+ console.log(`Nested Decompose (5x4=20): ${formatTime(nestedResult.mean)}`);
+
+ // Benchmark 9: Task Prioritization
+ const prioritizeResult = await runner.run(
+ 'task-prioritization-50',
+ async () => {
+ const sorted = [...complexTasks].sort((a, b) => b.priority - a.priority);
+ void sorted;
+ },
+ { iterations: 5000 }
+ );
+
+ console.log(`Task Prioritization (50 tasks): ${formatTime(prioritizeResult.mean)}`);
+
+ // Benchmark 10: Dependency Resolution
+ const dependencyResult = await runner.run(
+ 'dependency-resolution-50',
+ async () => {
+ const resolved = new Set<string>();
+ const pending = [...complexTasks];
+
+ while (pending.length > 0) {
+ const ready = pending.filter((t) =>
+ t.dependencies.every((d) => resolved.has(d))
+ );
+ for (const task of ready) {
+ resolved.add(task.id);
+ const idx = pending.indexOf(task);
+ if (idx >= 0) pending.splice(idx, 1);
+ }
+ if (ready.length === 0) break; // Circular dependency
+ }
+ },
+ { iterations: 500 }
+ );
+
+ console.log(`Dependency Resolution (50 tasks): ${formatTime(dependencyResult.mean)}`);
+
+ // Summary
+ console.log('\n--- Summary ---');
+ console.log(`Simple decomposition: ${formatTime(linearResult.mean)}`);
+ console.log(`SPARC decomposition: ${formatTime(sparcResult.mean)}`);
+ console.log(`DAG (10 tasks): ${formatTime(dagSmallResult.mean)}`);
+ console.log(`DAG (50 tasks): ${formatTime(dagMediumResult.mean)}`);
+ console.log(`\nScaling: 10->50 tasks = ${(dagMediumResult.mean / dagSmallResult.mean).toFixed(2)}x`);
+ console.log(`Per-task cost (50): ${formatTime(dagMediumResult.mean / 50)}`);
+
+ // Print full results
+ runner.printResults();
+}
+
+// ============================================================================
+// Task Decomposition Optimization Strategies
+// ============================================================================
+
+export const decompositionOptimizations = {
+ /**
+ * Cached dependency graph
+ */
+ cachedDependencyGraph: {
+ description: 'Cache computed dependency graphs for reuse',
+ expectedImprovement: '5-10x for repeated operations',
+ implementation: `
+ class CachedTaskGraph {
+ private graphCache = new Map<string, TaskGraph>();
+
+ getGraph(taskId: string): TaskGraph {
+ if (!this.graphCache.has(taskId)) {
+ this.graphCache.set(taskId, this.buildGraph(taskId));
+ }
+ return this.graphCache.get(taskId)!;
+ }
+ }
+ `,
+ },
+
+ /**
+ * Incremental decomposition
+ */
+ incrementalDecomposition: {
+ description: 'Decompose tasks incrementally as needed',
+ expectedImprovement: '2-3x for large task sets',
+ implementation: `
+ class IncrementalDecomposer {
+ private decomposed = new Map<string, SubTask[]>();
+
+ decomposeOnDemand(task: Task, depth: number): SubTask[] {
+ if (depth === 0) return [this.toSubTask(task)];
+
+ if (!this.decomposed.has(task.id)) {
+ const subtasks = this.decompose(task);
+ this.decomposed.set(task.id, subtasks);
+ }
+
+ return this.decomposed.get(task.id)!.flatMap(
+ st => this.decomposeOnDemand(st, depth - 1)
+ );
+ }
+ }
+ `,
+ },
+
+ /**
+ * Parallel decomposition processing
+ */
+ parallelProcessing: {
+ description: 'Decompose independent branches in parallel',
+ expectedImprovement: '2-4x on multi-core systems',
+ implementation: `
+ async function parallelDecompose(tasks: Task[]): Promise<SubTask[]> {
+ const independentGroups = findIndependentGroups(tasks);
+ const results = await Promise.all(
+ independentGroups.map(group => decompose(group))
+ );
+ return results.flat();
+ }
+ `,
+ },
+
+ /**
+ * Template-based decomposition
+ */
+ templateDecomposition: {
+ description: 'Use pre-defined templates for common task types',
+ expectedImprovement: '10x for known task types',
+ implementation: `
+ const templates = new Map<string, DecompositionTemplate>();
+
+ templates.set('feature', {
+ phases: ['design', 'implement', 'test', 'document'],
+ ratios: [0.1, 0.5, 0.3, 0.1],
+ });
+
+ function templateDecompose(task: Task): SubTask[] {
+ const template = templates.get(task.type);
+ if (template) {
+ return applyTemplate(task, template);
+ }
+ return defaultDecompose(task);
+ }
+ `,
+ },
+
+ /**
+ * Heuristic-based splitting
+ */
+ heuristicSplitting: {
+ description: 'Use heuristics to determine optimal split points',
+ expectedImprovement: '20-30% better parallelism',
+ implementation: `
+ function heuristicSplit(task: Task): number {
+ // Based on task complexity, type, and available workers
+ const baseChunks = Math.ceil(task.estimatedDuration / 30);
+ const maxChunks = Math.min(baseChunks, availableWorkers);
+ return Math.max(1, maxChunks);
+ }
+ `,
+ },
+};
+
+// Run if executed directly
+if (import.meta.url === `file://${process.argv[1]}`) {
+ runTaskDecompositionBenchmarks().catch(console.error);
+}
+
+export default runTaskDecompositionBenchmarks;
diff --git a/v3/integration/agentic-flow-bridge.ts b/v3/integration/agentic-flow-bridge.ts
index 028739d956..de4cc4a356 100644
--- a/v3/integration/agentic-flow-bridge.ts
+++ b/v3/integration/agentic-flow-bridge.ts
@@ -149,6 +149,10 @@ export class AgenticFlowBridge extends EventEmitter {
this.runtimeInfo = await this.detectRuntime();
this.logDebug('Runtime detected', this.runtimeInfo);
+ // ADR-001: Attempt to load agentic-flow@alpha dynamically
+ // This enables deep integration and code deduplication
+ await this.connectToAgenticFlow();
+
// Initialize SDK bridge first (required for version negotiation)
this.sdk = new SDKBridge({
targetVersion: 'alpha',
@@ -161,15 +165,23 @@ export class AgenticFlowBridge extends EventEmitter {
this.updateComponentHealth('sdk', 'healthy');
// Initialize SONA adapter if enabled
+ // Pass agentic-flow reference for delegation when available
if (this.config.features.enableSONA) {
this.sona = new SONAAdapter(this.config.sona);
+ if (this.agenticFlowCore) {
+ this.sona.setAgenticFlowReference(this.agenticFlowCore.sona);
+ }
await this.sona.initialize();
this.updateComponentHealth('sona', 'healthy');
}
// Initialize Attention coordinator if enabled
+ // Pass agentic-flow reference for delegation when available
if (this.config.features.enableFlashAttention) {
this.attention = new AttentionCoordinator(this.config.attention);
+ if (this.agenticFlowCore) {
+ this.attention.setAgenticFlowReference(this.agenticFlowCore.attention);
+ }
await this.attention.initialize();
this.updateComponentHealth('attention', 'healthy');
}
@@ -179,7 +191,8 @@ export class AgenticFlowBridge extends EventEmitter {
const duration = Date.now() - startTime;
this.emit('initialized', {
duration,
- components: this.getConnectedComponents()
+ components: this.getConnectedComponents(),
+ agenticFlowConnected: this.agenticFlowAvailable,
});
this.logDebug(`Initialization complete in ${duration}ms`);
@@ -189,6 +202,67 @@ export class AgenticFlowBridge extends EventEmitter {
}
}
+ /**
+ * Connect to agentic-flow@alpha package dynamically
+ *
+ * This implements ADR-001: Adopt agentic-flow as Core Foundation
+ * When agentic-flow is available, components delegate to it for:
+ * - SONA learning (eliminating duplicate pattern storage)
+ * - Flash Attention (using native optimized implementations)
+ * - AgentDB (leveraging 150x-12,500x faster HNSW search)
+ *
+ * If agentic-flow is not installed, falls back to local implementations
+ * to maintain backward compatibility.
+ */
+ private async connectToAgenticFlow(): Promise<void> {
+ try {
+ // Dynamic import to handle optional dependency
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const agenticFlowModule = await import('agentic-flow').catch(() => null);
+
+ if (agenticFlowModule && typeof agenticFlowModule.createAgenticFlow === 'function') {
+ const factory = agenticFlowModule.createAgenticFlow as AgenticFlowFactory;
+
+ this.agenticFlowCore = await factory({
+ sona: this.config.sona,
+ attention: this.config.attention,
+ agentdb: this.config.agentdb,
+ });
+
+ this.agenticFlowAvailable = true;
+ this.updateComponentHealth('agentic-flow', 'healthy');
+
+ this.emit('agentic-flow:connected', {
+ version: this.agenticFlowCore.version,
+ features: {
+ sona: true,
+ attention: true,
+ agentdb: true,
+ },
+ });
+
+ this.logDebug('Connected to agentic-flow', {
+ version: this.agenticFlowCore.version,
+ });
+ } else {
+ // Package not found or doesn't export expected factory
+ this.agenticFlowAvailable = false;
+ this.emit('agentic-flow:fallback', {
+ reason: 'package not found or incompatible',
+ });
+ this.logDebug('agentic-flow not available, using local implementations');
+ }
+ } catch (error) {
+ // Fallback to local implementation if agentic-flow fails to load
+ this.agenticFlowAvailable = false;
+ this.emit('agentic-flow:fallback', {
+ reason: 'initialization error',
+ error: (error as Error).message,
+ });
+ this.logDebug('agentic-flow initialization failed, using fallback', error);
+ }
+ }
+
/**
* Reconfigure the bridge with new settings
*/
diff --git a/v3/package.json b/v3/package.json
new file mode 100644
index 0000000000..68fb5dc0db
--- /dev/null
+++ b/v3/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "@claude-flow/v3",
+ "version": "3.0.0-alpha.1",
+ "type": "module",
+ "description": "V3 Claude Flow - Next Generation Security & Performance",
+ "main": "index.ts",
+ "scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:coverage": "vitest run --coverage",
+ "test:security": "vitest run __tests__/unit/security/",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "bcrypt": "^5.1.1",
+ "zod": "^3.22.0"
+ },
+ "devDependencies": {
+ "@types/bcrypt": "^5.0.2",
+ "@types/node": "^20.0.0",
+ "typescript": "^5.3.0",
+ "vitest": "^1.0.0",
+ "@vitest/coverage-v8": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}