agentic-flow 2.0.0-alpha → 2.0.1-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +320 -23
  2. package/agentic-flow/.claude/agents/base-template-generator.md +229 -3
  3. package/agentic-flow/.claude/agents/core/coder.md +212 -7
  4. package/agentic-flow/.claude/agents/core/planner.md +228 -7
  5. package/agentic-flow/.claude/agents/core/researcher.md +205 -10
  6. package/agentic-flow/.claude/agents/core/reviewer.md +216 -5
  7. package/agentic-flow/.claude/agents/core/tester.md +213 -3
  8. package/agentic-flow/.claude/agents/data/ml/data-ml-model.md +256 -5
  9. package/agentic-flow/.claude/agents/development/backend/dev-backend-api.md +209 -6
  10. package/agentic-flow/.claude/agents/documentation/api-docs/docs-api-openapi.md +185 -5
  11. package/agentic-flow/.claude/agents/github/code-review-swarm.md +307 -468
  12. package/agentic-flow/.claude/agents/github/issue-tracker.md +270 -13
  13. package/agentic-flow/.claude/agents/github/pr-manager.md +259 -12
  14. package/agentic-flow/.claude/agents/github/release-manager.md +253 -15
  15. package/agentic-flow/.claude/agents/github/workflow-automation.md +277 -9
  16. package/agentic-flow/.claude/agents/sona/sona-learning-optimizer.md +496 -0
  17. package/agentic-flow/.claude/agents/sparc/architecture.md +231 -4
  18. package/agentic-flow/.claude/agents/sparc/pseudocode.md +206 -4
  19. package/agentic-flow/.claude/agents/sparc/refinement.md +283 -6
  20. package/agentic-flow/.claude/agents/sparc/specification.md +205 -3
  21. package/agentic-flow/.claude/agents/swarm/adaptive-coordinator.md +731 -0
  22. package/agentic-flow/.claude/agents/swarm/hierarchical-coordinator.md +455 -1
  23. package/agentic-flow/.claude/agents/swarm/mesh-coordinator.md +571 -0
  24. package/agentic-flow/.claude/agents/templates/sparc-coordinator.md +336 -5
  25. package/agentic-flow/dist/cli/commands/sona-train.d.ts.map +1 -0
  26. package/agentic-flow/dist/cli/commands/sona-train.js +295 -0
  27. package/agentic-flow/dist/cli/commands/sona-train.js.map +1 -0
  28. package/agentic-flow/dist/cli/commands/sona.d.ts.map +1 -0
  29. package/agentic-flow/dist/cli/commands/sona.js +290 -0
  30. package/agentic-flow/dist/cli/commands/sona.js.map +1 -0
  31. package/agentic-flow/dist/core/agentdb-fast.d.ts.map +1 -0
  32. package/agentic-flow/dist/core/agentdb-fast.js +299 -0
  33. package/agentic-flow/dist/core/agentdb-fast.js.map +1 -0
  34. package/agentic-flow/dist/core/attention-fallbacks.d.ts.map +1 -0
  35. package/agentic-flow/dist/core/attention-fallbacks.js +321 -0
  36. package/agentic-flow/dist/core/attention-fallbacks.js.map +1 -0
  37. package/agentic-flow/dist/core/embedding-service.d.ts.map +1 -0
  38. package/agentic-flow/dist/core/embedding-service.js +370 -0
  39. package/agentic-flow/dist/core/embedding-service.js.map +1 -0
  40. package/agentic-flow/dist/core/gnn-wrapper.d.ts.map +1 -0
  41. package/agentic-flow/dist/core/gnn-wrapper.js +236 -0
  42. package/agentic-flow/dist/core/gnn-wrapper.js.map +1 -0
  43. package/agentic-flow/dist/core/index.d.ts.map +1 -1
  44. package/agentic-flow/dist/core/index.js +80 -3
  45. package/agentic-flow/dist/core/index.js.map +1 -1
  46. package/agentic-flow/dist/mcp/claudeFlowSdkServer.d.ts.map +1 -1
  47. package/agentic-flow/dist/mcp/claudeFlowSdkServer.js +109 -0
  48. package/agentic-flow/dist/mcp/claudeFlowSdkServer.js.map +1 -1
  49. package/agentic-flow/dist/mcp/tools/agent-booster-tools.d.ts.map +1 -0
  50. package/agentic-flow/dist/mcp/tools/agent-booster-tools.js +262 -0
  51. package/agentic-flow/dist/mcp/tools/agent-booster-tools.js.map +1 -0
  52. package/agentic-flow/dist/mcp/tools/sona-tools.d.ts.map +1 -0
  53. package/agentic-flow/dist/mcp/tools/sona-tools.js +560 -0
  54. package/agentic-flow/dist/mcp/tools/sona-tools.js.map +1 -0
  55. package/agentic-flow/dist/optimizations/agent-booster-migration.d.ts.map +1 -0
  56. package/agentic-flow/dist/optimizations/agent-booster-migration.js +323 -0
  57. package/agentic-flow/dist/optimizations/agent-booster-migration.js.map +1 -0
  58. package/agentic-flow/dist/optimizations/configuration-tuning.d.ts.map +1 -0
  59. package/agentic-flow/dist/optimizations/configuration-tuning.js +422 -0
  60. package/agentic-flow/dist/optimizations/configuration-tuning.js.map +1 -0
  61. package/agentic-flow/dist/optimizations/ruvector-backend.d.ts.map +1 -0
  62. package/agentic-flow/dist/optimizations/ruvector-backend.js +464 -0
  63. package/agentic-flow/dist/optimizations/ruvector-backend.js.map +1 -0
  64. package/agentic-flow/dist/services/embedding-service.d.ts.map +1 -0
  65. package/agentic-flow/dist/services/embedding-service.js +367 -0
  66. package/agentic-flow/dist/services/embedding-service.js.map +1 -0
  67. package/agentic-flow/dist/services/sona-agent-training.d.ts.map +1 -0
  68. package/agentic-flow/dist/services/sona-agent-training.js +382 -0
  69. package/agentic-flow/dist/services/sona-agent-training.js.map +1 -0
  70. package/agentic-flow/dist/services/sona-agentdb-integration.d.ts.map +1 -0
  71. package/agentic-flow/dist/services/sona-agentdb-integration.js +346 -0
  72. package/agentic-flow/dist/services/sona-agentdb-integration.js.map +1 -0
  73. package/agentic-flow/dist/services/sona-service.d.ts.map +1 -0
  74. package/agentic-flow/dist/services/sona-service.js +448 -0
  75. package/agentic-flow/dist/services/sona-service.js.map +1 -0
  76. package/agentic-flow/dist/services/sona-types.d.ts.map +1 -0
  77. package/agentic-flow/dist/services/sona-types.js +59 -0
  78. package/agentic-flow/dist/services/sona-types.js.map +1 -0
  79. package/docs/README.md +27 -2
  80. package/package.json +12 -2
  81. package/docs/AGENTIC_JUJUTSU_QUICKSTART.md +0 -491
@@ -185,6 +185,577 @@ class TaskAuction:
185
185
  return self.award_task(task, winner[0])
186
186
  ```
187
187
 
188
+ ## 🧠 Advanced Attention Mechanisms (v2.0.0-alpha)
189
+
190
+ ### Multi-Head Attention for Peer-to-Peer Coordination
191
+
192
+ Mesh networks use **multi-head attention** for distributed consensus where all agents have equal influence:
193
+
194
+ ```typescript
195
+ import { AttentionService } from 'agentdb';
196
+
197
+ // Initialize attention service for mesh coordination
198
+ const attentionService = new AttentionService({
199
+ embeddingDim: 384,
200
+ runtime: 'napi' // 2.49x-7.47x faster
201
+ });
202
+
203
+ // Peer-to-peer mesh coordination with equal influence
204
+ class MeshCoordinator {
205
+ constructor(
206
+ private attentionService: AttentionService,
207
+ private numHeads: number = 8 // Multi-head attention heads
208
+ ) {}
209
+
210
+ /**
211
+ * Coordinate using multi-head attention for peer-to-peer consensus
212
+ * All agents have equal influence (no hierarchy)
213
+ */
214
+ async coordinatePeers(
215
+ peerOutputs: AgentOutput[]
216
+ ): Promise<CoordinationResult> {
217
+ // Convert outputs to embeddings
218
+ const embeddings = await this.outputsToEmbeddings(peerOutputs);
219
+
220
+ // Multi-head attention for peer consensus
221
+ const result = await this.attentionService.multiHeadAttention(
222
+ embeddings,
223
+ embeddings,
224
+ embeddings,
225
+ { numHeads: this.numHeads }
226
+ );
227
+
228
+ // Extract attention weights for each peer
229
+ const attentionWeights = this.extractAttentionWeights(result);
230
+
231
+ // Generate consensus with equal peer influence
232
+ const consensus = this.generatePeerConsensus(peerOutputs, attentionWeights);
233
+
234
+ return {
235
+ consensus,
236
+ attentionWeights,
237
+ topAgents: this.rankPeersByContribution(attentionWeights),
238
+ consensusStrength: this.calculateConsensusStrength(attentionWeights),
239
+ executionTimeMs: result.executionTimeMs,
240
+ memoryUsage: result.memoryUsage
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Byzantine Fault Tolerant coordination with attention-based voting
246
+ * Tolerates up to 33% malicious or failed nodes
247
+ */
248
+ async byzantineConsensus(
249
+ peerOutputs: AgentOutput[],
250
+ faultTolerance: number = 0.33
251
+ ): Promise<CoordinationResult> {
252
+ const embeddings = await this.outputsToEmbeddings(peerOutputs);
253
+
254
+ // Multi-head attention for Byzantine consensus
255
+ const result = await this.attentionService.multiHeadAttention(
256
+ embeddings,
257
+ embeddings,
258
+ embeddings,
259
+ { numHeads: this.numHeads }
260
+ );
261
+
262
+ const attentionWeights = this.extractAttentionWeights(result);
263
+
264
+ // Identify potential Byzantine nodes (outliers in attention)
265
+ const byzantineNodes = this.detectByzantineNodes(
266
+ attentionWeights,
267
+ faultTolerance
268
+ );
269
+
270
+ // Filter out Byzantine nodes
271
+ const trustworthyOutputs = peerOutputs.filter(
272
+ (_, idx) => !byzantineNodes.includes(idx)
273
+ );
274
+ const trustworthyWeights = attentionWeights.filter(
275
+ (_, idx) => !byzantineNodes.includes(idx)
276
+ );
277
+
278
+ // Generate consensus from trustworthy nodes
279
+ const consensus = this.generatePeerConsensus(
280
+ trustworthyOutputs,
281
+ trustworthyWeights
282
+ );
283
+
284
+ return {
285
+ consensus,
286
+ attentionWeights: trustworthyWeights,
287
+ topAgents: this.rankPeersByContribution(trustworthyWeights),
288
+ byzantineNodes,
289
+ consensusStrength: this.calculateConsensusStrength(trustworthyWeights),
290
+ executionTimeMs: result.executionTimeMs,
291
+ memoryUsage: result.memoryUsage
292
+ };
293
+ }
294
+
295
+ /**
296
+ * GraphRoPE: Topology-aware coordination for mesh networks
297
+ */
298
+ async topologyAwareCoordination(
299
+ peerOutputs: AgentOutput[],
300
+ networkTopology: MeshTopology
301
+ ): Promise<CoordinationResult> {
302
+ // Build graph representation of mesh network
303
+ const graphContext = this.buildMeshGraph(peerOutputs, networkTopology);
304
+
305
+ const embeddings = await this.outputsToEmbeddings(peerOutputs);
306
+
307
+ // Apply GraphRoPE for topology-aware position encoding
308
+ const positionEncodedEmbeddings = this.applyGraphRoPE(
309
+ embeddings,
310
+ graphContext
311
+ );
312
+
313
+ // Multi-head attention with topology awareness
314
+ const result = await this.attentionService.multiHeadAttention(
315
+ positionEncodedEmbeddings,
316
+ positionEncodedEmbeddings,
317
+ positionEncodedEmbeddings,
318
+ { numHeads: this.numHeads }
319
+ );
320
+
321
+ return this.processCoordinationResult(result, peerOutputs);
322
+ }
323
+
324
+ /**
325
+ * Gossip-based consensus with attention weighting
326
+ */
327
+ async gossipConsensus(
328
+ peerOutputs: AgentOutput[],
329
+ gossipRounds: number = 3
330
+ ): Promise<CoordinationResult> {
331
+ let currentEmbeddings = await this.outputsToEmbeddings(peerOutputs);
332
+
333
+ // Simulate gossip rounds with attention propagation
334
+ for (let round = 0; round < gossipRounds; round++) {
335
+ const result = await this.attentionService.multiHeadAttention(
336
+ currentEmbeddings,
337
+ currentEmbeddings,
338
+ currentEmbeddings,
339
+ { numHeads: this.numHeads }
340
+ );
341
+
342
+ // Update embeddings based on attention (information propagation)
343
+ currentEmbeddings = this.propagateGossip(
344
+ currentEmbeddings,
345
+ result.output
346
+ );
347
+ }
348
+
349
+ // Final consensus after gossip rounds
350
+ const finalResult = await this.attentionService.multiHeadAttention(
351
+ currentEmbeddings,
352
+ currentEmbeddings,
353
+ currentEmbeddings,
354
+ { numHeads: this.numHeads }
355
+ );
356
+
357
+ return this.processCoordinationResult(finalResult, peerOutputs);
358
+ }
359
+
360
+ /**
361
+ * Build mesh graph structure
362
+ */
363
+ private buildMeshGraph(
364
+ outputs: AgentOutput[],
365
+ topology: MeshTopology
366
+ ): GraphContext {
367
+ const nodes = outputs.map((_, idx) => idx);
368
+ const edges: [number, number][] = [];
369
+ const edgeWeights: number[] = [];
370
+
371
+ // Build edges based on mesh connectivity
372
+ topology.connections.forEach(([from, to, weight]) => {
373
+ edges.push([from, to]);
374
+ edgeWeights.push(weight || 1.0); // Equal weight by default
375
+ });
376
+
377
+ return {
378
+ nodes,
379
+ edges,
380
+ edgeWeights,
381
+ nodeLabels: outputs.map(o => o.agentType)
382
+ };
383
+ }
384
+
385
+ /**
386
+ * Apply GraphRoPE position embeddings for mesh topology
387
+ */
388
+ private applyGraphRoPE(
389
+ embeddings: number[][],
390
+ graphContext: GraphContext
391
+ ): number[][] {
392
+ return embeddings.map((emb, idx) => {
393
+ // Calculate centrality measures
394
+ const degree = this.calculateDegree(idx, graphContext);
395
+ const betweenness = this.calculateBetweenness(idx, graphContext);
396
+
397
+ // Position encoding based on network position
398
+ const positionEncoding = this.generateNetworkPositionEncoding(
399
+ emb.length,
400
+ degree,
401
+ betweenness
402
+ );
403
+
404
+ // Add position encoding to embedding
405
+ return emb.map((v, i) => v + positionEncoding[i] * 0.1);
406
+ });
407
+ }
408
+
409
+ private calculateDegree(nodeId: number, graph: GraphContext): number {
410
+ return graph.edges.filter(
411
+ ([from, to]) => from === nodeId || to === nodeId
412
+ ).length;
413
+ }
414
+
415
+ private calculateBetweenness(nodeId: number, graph: GraphContext): number {
416
+ // Simplified betweenness centrality
417
+ let betweenness = 0;
418
+ const n = graph.nodes.length;
419
+
420
+ for (let i = 0; i < n; i++) {
421
+ for (let j = i + 1; j < n; j++) {
422
+ if (i === nodeId || j === nodeId) continue;
423
+
424
+ const shortestPaths = this.findShortestPaths(i, j, graph);
425
+ const pathsThroughNode = shortestPaths.filter(path =>
426
+ path.includes(nodeId)
427
+ ).length;
428
+
429
+ if (shortestPaths.length > 0) {
430
+ betweenness += pathsThroughNode / shortestPaths.length;
431
+ }
432
+ }
433
+ }
434
+
435
+ return betweenness / ((n - 1) * (n - 2) / 2);
436
+ }
437
+
438
+ private findShortestPaths(
439
+ from: number,
440
+ to: number,
441
+ graph: GraphContext
442
+ ): number[][] {
443
+ // BFS to find all shortest paths
444
+ const queue: [number, number[]][] = [[from, [from]]];
445
+ const visited = new Set<number>();
446
+ const shortestPaths: number[][] = [];
447
+ let shortestLength = Infinity;
448
+
449
+ while (queue.length > 0) {
450
+ const [current, path] = queue.shift()!;
451
+
452
+ if (current === to) {
453
+ if (path.length <= shortestLength) {
454
+ shortestLength = path.length;
455
+ shortestPaths.push(path);
456
+ }
457
+ continue;
458
+ }
459
+
460
+ if (visited.has(current)) continue;
461
+ visited.add(current);
462
+
463
+ // Find neighbors
464
+ graph.edges.forEach(([edgeFrom, edgeTo]) => {
465
+ if (edgeFrom === current && !path.includes(edgeTo)) {
466
+ queue.push([edgeTo, [...path, edgeTo]]);
467
+ } else if (edgeTo === current && !path.includes(edgeFrom)) {
468
+ queue.push([edgeFrom, [...path, edgeFrom]]);
469
+ }
470
+ });
471
+ }
472
+
473
+ return shortestPaths.filter(p => p.length === shortestLength);
474
+ }
475
+
476
+ private generateNetworkPositionEncoding(
477
+ dim: number,
478
+ degree: number,
479
+ betweenness: number
480
+ ): number[] {
481
+ // Sinusoidal position encoding based on network centrality
482
+ return Array.from({ length: dim }, (_, i) => {
483
+ const freq = 1 / Math.pow(10000, i / dim);
484
+ return Math.sin(degree * freq) + Math.cos(betweenness * freq * 100);
485
+ });
486
+ }
487
+
488
+ /**
489
+ * Detect Byzantine (malicious/faulty) nodes using attention outliers
490
+ */
491
+ private detectByzantineNodes(
492
+ attentionWeights: number[],
493
+ faultTolerance: number
494
+ ): number[] {
495
+ // Calculate mean and standard deviation
496
+ const mean = attentionWeights.reduce((a, b) => a + b, 0) / attentionWeights.length;
497
+ const variance = attentionWeights.reduce(
498
+ (acc, w) => acc + Math.pow(w - mean, 2),
499
+ 0
500
+ ) / attentionWeights.length;
501
+ const stdDev = Math.sqrt(variance);
502
+
503
+ // Identify outliers (more than 2 std devs from mean)
504
+ const byzantine: number[] = [];
505
+ attentionWeights.forEach((weight, idx) => {
506
+ if (Math.abs(weight - mean) > 2 * stdDev) {
507
+ byzantine.push(idx);
508
+ }
509
+ });
510
+
511
+ // Ensure we don't exceed fault tolerance
512
+ const maxByzantine = Math.floor(attentionWeights.length * faultTolerance);
513
+ return byzantine.slice(0, maxByzantine);
514
+ }
515
+
516
+ /**
517
+ * Propagate information through gossip rounds
518
+ */
519
+ private propagateGossip(
520
+ embeddings: number[][],
521
+ attentionOutput: Float32Array
522
+ ): number[][] {
523
+ // Average embeddings weighted by attention
524
+ return embeddings.map((emb, idx) => {
525
+ const attentionStart = idx * emb.length;
526
+ const attentionSlice = Array.from(
527
+ attentionOutput.slice(attentionStart, attentionStart + emb.length)
528
+ );
529
+
530
+ return emb.map((v, i) => (v + attentionSlice[i]) / 2);
531
+ });
532
+ }
533
+
534
+ private async outputsToEmbeddings(
535
+ outputs: AgentOutput[]
536
+ ): Promise<number[][]> {
537
+ // Convert agent outputs to embeddings (simplified)
538
+ return outputs.map(output =>
539
+ Array.from({ length: 384 }, () => Math.random())
540
+ );
541
+ }
542
+
543
+ private extractAttentionWeights(result: any): number[] {
544
+ return Array.from(result.output.slice(0, result.output.length / 384));
545
+ }
546
+
547
+ private generatePeerConsensus(
548
+ outputs: AgentOutput[],
549
+ weights: number[]
550
+ ): string {
551
+ // Weighted voting consensus (all peers equal)
552
+ const weightedOutputs = outputs.map((output, idx) => ({
553
+ output: output.content,
554
+ weight: weights[idx]
555
+ }));
556
+
557
+ // Majority vote weighted by attention
558
+ const best = weightedOutputs.reduce((max, curr) =>
559
+ curr.weight > max.weight ? curr : max
560
+ );
561
+
562
+ return best.output;
563
+ }
564
+
565
+ private rankPeersByContribution(weights: number[]): AgentRanking[] {
566
+ return weights
567
+ .map((weight, idx) => ({ agentId: idx, contribution: weight }))
568
+ .sort((a, b) => b.contribution - a.contribution);
569
+ }
570
+
571
+ private calculateConsensusStrength(weights: number[]): number {
572
+ // Measure how strong the consensus is (lower variance = stronger)
573
+ const mean = weights.reduce((a, b) => a + b, 0) / weights.length;
574
+ const variance = weights.reduce(
575
+ (acc, w) => acc + Math.pow(w - mean, 2),
576
+ 0
577
+ ) / weights.length;
578
+
579
+ return 1 - Math.min(variance, 1); // 0-1, higher is stronger consensus
580
+ }
581
+
582
+ private processCoordinationResult(
583
+ result: any,
584
+ outputs: AgentOutput[]
585
+ ): CoordinationResult {
586
+ const weights = this.extractAttentionWeights(result);
587
+
588
+ return {
589
+ consensus: this.generatePeerConsensus(outputs, weights),
590
+ attentionWeights: weights,
591
+ topAgents: this.rankPeersByContribution(weights),
592
+ consensusStrength: this.calculateConsensusStrength(weights),
593
+ executionTimeMs: result.executionTimeMs,
594
+ memoryUsage: result.memoryUsage
595
+ };
596
+ }
597
+ }
598
+
599
+ // Type definitions
600
+ interface AgentOutput {
601
+ agentType: string;
602
+ content: string;
603
+ }
604
+
605
+ interface MeshTopology {
606
+ connections: [number, number, number?][]; // [from, to, weight?]
607
+ }
608
+
609
+ interface GraphContext {
610
+ nodes: number[];
611
+ edges: [number, number][];
612
+ edgeWeights: number[];
613
+ nodeLabels: string[];
614
+ }
615
+
616
+ interface CoordinationResult {
617
+ consensus: string;
618
+ attentionWeights: number[];
619
+ topAgents: AgentRanking[];
620
+ byzantineNodes?: number[];
621
+ consensusStrength: number;
622
+ executionTimeMs: number;
623
+ memoryUsage?: number;
624
+ }
625
+
626
+ interface AgentRanking {
627
+ agentId: number;
628
+ contribution: number;
629
+ }
630
+ ```
631
+
632
+ ### Usage Example: Mesh Peer Coordination
633
+
634
+ ```typescript
635
+ // Initialize mesh coordinator
636
+ const coordinator = new MeshCoordinator(attentionService, 8);
637
+
638
+ // Define mesh topology (all peers interconnected)
639
+ const meshTopology: MeshTopology = {
640
+ connections: [
641
+ [0, 1, 1.0], [0, 2, 1.0], [0, 3, 1.0],
642
+ [1, 2, 1.0], [1, 3, 1.0],
643
+ [2, 3, 1.0]
644
+ ]
645
+ };
646
+
647
+ // Peer agents (all equal influence)
648
+ const peerOutputs = [
649
+ {
650
+ agentType: 'coder-1',
651
+ content: 'Implement REST API with Express.js'
652
+ },
653
+ {
654
+ agentType: 'coder-2',
655
+ content: 'Use Fastify for better performance'
656
+ },
657
+ {
658
+ agentType: 'coder-3',
659
+ content: 'Express.js is more mature and well-documented'
660
+ },
661
+ {
662
+ agentType: 'coder-4',
663
+ content: 'Fastify has built-in validation and is faster'
664
+ }
665
+ ];
666
+
667
+ // Coordinate with multi-head attention (equal peer influence)
668
+ const result = await coordinator.coordinatePeers(peerOutputs);
669
+
670
+ console.log('Peer consensus:', result.consensus);
671
+ console.log('Consensus strength:', result.consensusStrength);
672
+ console.log('Top contributors:', result.topAgents.slice(0, 3));
673
+ console.log(`Processed in ${result.executionTimeMs}ms`);
674
+
675
+ // Byzantine fault-tolerant consensus
676
+ const bftResult = await coordinator.byzantineConsensus(peerOutputs, 0.33);
677
+ console.log('BFT consensus:', bftResult.consensus);
678
+ console.log('Byzantine nodes detected:', bftResult.byzantineNodes);
679
+ ```
680
+
681
+ ### Self-Learning Integration (ReasoningBank)
682
+
683
+ ```typescript
684
+ import { ReasoningBank } from 'agentdb';
685
+
686
+ class LearningMeshCoordinator extends MeshCoordinator {
687
+ constructor(
688
+ attentionService: AttentionService,
689
+ private reasoningBank: ReasoningBank,
690
+ numHeads: number = 8
691
+ ) {
692
+ super(attentionService, numHeads);
693
+ }
694
+
695
+ /**
696
+ * Learn from past peer coordination patterns
697
+ */
698
+ async coordinateWithLearning(
699
+ taskDescription: string,
700
+ peerOutputs: AgentOutput[]
701
+ ): Promise<CoordinationResult> {
702
+ // 1. Search for similar past mesh coordinations
703
+ const similarPatterns = await this.reasoningBank.searchPatterns({
704
+ task: taskDescription,
705
+ k: 5,
706
+ minReward: 0.8
707
+ });
708
+
709
+ if (similarPatterns.length > 0) {
710
+ console.log('📚 Learning from past peer coordinations:');
711
+ similarPatterns.forEach(pattern => {
712
+ console.log(`- ${pattern.task}: ${pattern.reward} consensus strength`);
713
+ });
714
+ }
715
+
716
+ // 2. Coordinate with multi-head attention
717
+ const result = await this.coordinatePeers(peerOutputs);
718
+
719
+ // 3. Calculate success metrics
720
+ const reward = result.consensusStrength;
721
+ const success = reward > 0.7;
722
+
723
+ // 4. Store learning pattern
724
+ await this.reasoningBank.storePattern({
725
+ sessionId: `mesh-${Date.now()}`,
726
+ task: taskDescription,
727
+ input: JSON.stringify({ peers: peerOutputs }),
728
+ output: result.consensus,
729
+ reward,
730
+ success,
731
+ critique: this.generateCritique(result),
732
+ tokensUsed: this.estimateTokens(result),
733
+ latencyMs: result.executionTimeMs
734
+ });
735
+
736
+ return result;
737
+ }
738
+
739
+ private generateCritique(result: CoordinationResult): string {
740
+ const critiques: string[] = [];
741
+
742
+ if (result.consensusStrength < 0.6) {
743
+ critiques.push('Weak consensus - peers have divergent opinions');
744
+ }
745
+
746
+ if (result.byzantineNodes && result.byzantineNodes.length > 0) {
747
+ critiques.push(`Detected ${result.byzantineNodes.length} Byzantine nodes`);
748
+ }
749
+
750
+ return critiques.join('; ') || 'Strong peer consensus achieved';
751
+ }
752
+
753
+ private estimateTokens(result: CoordinationResult): number {
754
+ return result.consensus.split(' ').length * 1.3;
755
+ }
756
+ }
757
+ ```
758
+
188
759
  ## MCP Tool Integration
189
760
 
190
761
  ### Network Management