π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(swarm): use intersecting Byzantine quorums for every cluster size
Rudy Mizrahi Celeklia0c143d7c92d
diff --git a/v3/@claude-flow/swarm/__tests__/byzantine-quorum-size.test.ts b/v3/@claude-flow/swarm/__tests__/byzantine-quorum-size.test.tsnew file mode 100644index 0000000000..1f1d764c3b--- /dev/null+++ b/v3/@claude-flow/swarm/__tests__/byzantine-quorum-size.test.ts@@ -0,0 +1,86 @@+import { describe, it, expect } from 'vitest';+import { ByzantineConsensus, type ByzantineMessage } from '../src/consensus/byzantine.js';++function cluster(n: number, maxFaultyNodes?: number) {+ const bft = new ByzantineConsensus('node-0', { maxFaultyNodes });+ for (let i = 1; i < n; i++) bft.addNode(`node-${i}`);+ bft.electPrimary();+ return bft;+}+const approve = (voterId: string) => ({ voterId, approve: true, confidence: 1, timestamp: new Date() });++describe('Byzantine fault bounds and safe quorum (#3560)', () => {+ it.each([-1, 0.5, NaN, Infinity])('rejects invalid configured fault cap %s', cap => {+ expect(() => cluster(4, cap)).toThrow('maxFaultyNodes');+ });++ it.each(Array.from({ length: 10 }, (_, i) => i + 1))('accepts unanimous approval for n=%i', async n => {+ const bft = cluster(n);+ try {+ const proposal = await bft.propose({ decision: 'unanimous' });+ for (let i = 0; i < n; i++) await bft.vote(proposal.id, approve(`node-${i}`));+ expect(proposal.status).toBe('accepted');+ expect(bft.getMaxFaultyNodes()).toBe(Math.floor((n - 1) / 3));+ } finally { await bft.shutdown(); }+ });++ it('accepts two of three approvals with zero Byzantine faults', async () => {+ const bft = cluster(3);+ try {+ const proposal = await bft.propose({ decision: 'one-silent' });+ await bft.vote(proposal.id, approve('node-0'));+ expect(proposal.status).toBe('pending');+ await bft.vote(proposal.id, approve('node-1'));+ expect(proposal.status).toBe('accepted');+ expect(bft.canTolerate(1)).toBe(false);+ } finally { await bft.shutdown(); }+ });++ it('uses an intersecting quorum across n=1..100 and valid configured fault caps', async () => {+ for (let n = 1; n <= 100; n++) {+ const derived = Math.floor((n - 1) / 3);+ for (const cap of [undefined, 0, 1, derived + 2]) {+ const bft = cluster(n, cap);+ try {+ const f = cap === undefined ? derived : Math.min(derived, cap);+ const q = Math.floor((n + f) / 2) + 1;+ expect(bft.getMaxFaultyNodes()).toBe(f);+ expect(3 * f + 1).toBeLessThanOrEqual(n);+ expect(2 * q).toBeGreaterThanOrEqual(n + f + 1);+ expect(q).toBeLessThanOrEqual(n - f);+ const proposal = await bft.propose({ n, cap });+ for (let i = 0; i < q - 1; i++) await bft.vote(proposal.id, approve(`node-${i}`));+ if (q > 1) expect(proposal.status).toBe('pending');+ await bft.vote(proposal.id, approve(`node-${q - 1}`));+ expect(proposal.status).toBe('accepted');+ } finally { await bft.shutdown(); }+ }+ }+ });++ it.each([2, 3, 5, 6, 10])('applies the same safe threshold to prepare and commit messages for n=%i', async n => {+ const bft = cluster(n);+ const f = Math.floor((n - 1) / 3);+ const q = Math.floor((n + f) / 2) + 1;+ let pre: ByzantineMessage;+ bft.on('message.broadcast', (event: { message: ByzantineMessage }) => {+ if (event.message.type === 'pre-prepare') pre = event.message;+ });+ try {+ const proposal = await bft.propose({ decision: 'protocol-quorum' });+ const message = (type: 'prepare' | 'commit', i: number): ByzantineMessage => ({+ ...pre!, type, senderId: `node-${i}`,+ });+ // propose() self-prepares; q-2 peer prepares still cannot prepare.+ for (let i = 1; i < q - 1; i++) await bft.handlePrepare(message('prepare', i));+ expect(bft.getPreparedCount()).toBe(0);+ await bft.handlePrepare(message('prepare', q - 1));+ expect(bft.getPreparedCount()).toBe(1);+ // Completing prepare self-commits; q-2 peer commits still cannot accept.+ for (let i = 1; i < q - 1; i++) await bft.handleCommit(message('commit', i));+ expect(proposal.status).toBe('pending');+ await bft.handleCommit(message('commit', q - 1));+ expect(proposal.status).toBe('accepted');+ } finally { await bft.shutdown(); }+ });+});diff --git a/v3/@claude-flow/swarm/__tests__/byzantine-transport.test.ts b/v3/@claude-flow/swarm/__tests__/byzantine-transport.test.tsindex a230785d6b..1fa88ea8d1 100644--- a/v3/@claude-flow/swarm/__tests__/byzantine-transport.test.ts+++ b/v3/@claude-flow/swarm/__tests__/byzantine-transport.test.ts@@ -106,8 +106,8 @@ describe('ADR-095 G2 β BFT fault tolerance f derived from cluster size', () =>// byzantineF() is private; exercise it through the quorum behavior by// observing how many prepare messages are needed before a proposal goes// from 'pending' to 'accepted'. With n nodes, f = floor((n-1)/3),- // quorum = 2f+1.- function fFor(n: number): number { return Math.max(1, Math.floor((n - 1) / 3)); }+ // quorum = floor((n+f)/2)+1.+ function fFor(n: number): number { return Math.floor((n - 1) / 3); }it('4-node cluster β f=1 (need 3 prepares)', () => {expect(fFor(4)).toBe(1);@@ -124,7 +124,7 @@ describe('ADR-095 G2 β BFT fault tolerance f derived from cluster size', () =>// Add 9 peers β derived f would be floor(9/3)=3, but cap=1.for (let i = 2; i <= 10; i++) bft.addNode(`n${i}`, false);// We can't read byzantineF() directly; assert via the documented contract:- // a cap of 1 means quorum stays 2*1+1=3 even in a 10-node cluster.+ // a cap of 1 lowers f, while the 10-node quorum remains an intersecting majority.// (Behavioral assertion proxy β the cap is honored in the f computation.)expect((bft as unknown as { byzantineF: () => number }).byzantineF()).toBe(1);});@@ -137,11 +137,12 @@ describe('ADR-095 G2 β BFT fault tolerance f derived from cluster size', () =>expect((bft as unknown as { byzantineF: () => number }).byzantineF()).toBe(3);});- it('a 3-node cluster still gets f=1 (clamp floor)', () => {+ it('a 3-node cluster has f=0, matching its public fault bound', () => {const bft = new ByzantineConsensus('n1');bft.addNode('n2', false);bft.addNode('n3', false);- // floor((3-1)/3) = 0, clamped to 1 β degenerate but keeps the math sane.- expect((bft as unknown as { byzantineF: () => number }).byzantineF()).toBe(1);+ // No Byzantine fault is tolerable with fewer than four nodes.+ expect((bft as unknown as { byzantineF: () => number }).byzantineF()).toBe(0);+ expect(bft.getMaxFaultyNodes()).toBe(0);});});diff --git a/v3/@claude-flow/swarm/__tests__/consensus-failure-injection.test.ts b/v3/@claude-flow/swarm/__tests__/consensus-failure-injection.test.tsindex 0c8b19882d..891f10f581 100644--- a/v3/@claude-flow/swarm/__tests__/consensus-failure-injection.test.ts+++ b/v3/@claude-flow/swarm/__tests__/consensus-failure-injection.test.ts@@ -95,11 +95,19 @@ describe('ADR-095 G2 β BFT prepare/commit quorum under f-bounded faults', () =expect(achieved).toBe(false); // node + 3 = 4 < 5});- it('config.maxFaultyNodes caps f: 10-node cluster + cap 1 β 2f+1=3 reached with only 2 external commits', async () => {+ it('config.maxFaultyNodes caps f: 10-node cluster + cap 1 still rejects only 3 commit messages', async () => {const { achieved, f } = await injectQuorum({ peerCount: 9, maxFaultyNodes: 1, prepareSenders: ['s1', 's2'], commitSenders: ['s1', 's2'] });expect(f).toBe(1); // capped, not floor(9/3)=3+ expect(achieved).toBe(false);+ });++ it('10-node cluster + cap 1 reaches its six-message intersecting quorum', async () => {+ const senders = ['s1', 's2', 's3', 's4', 's5'];+ const { achieved, f } = await injectQuorum({ peerCount: 9, maxFaultyNodes: 1, prepareSenders: senders, commitSenders: senders });+ expect(f).toBe(1);expect(achieved).toBe(true);});+});// ---------------------------------------------------------------------------diff --git a/v3/@claude-flow/swarm/__tests__/consensus.test.ts b/v3/@claude-flow/swarm/__tests__/consensus.test.tsindex facf148aa1..87de3e5a33 100644--- a/v3/@claude-flow/swarm/__tests__/consensus.test.ts+++ b/v3/@claude-flow/swarm/__tests__/consensus.test.ts@@ -690,7 +690,7 @@ describe('Weighted Consensus (Dream Cycle 2026-08-24)', () => {// hang until awaitConsensus's own timeout/expiry path});await byzantine.initialize();- byzantine.addNode('primary', true);+ byzantine.electPrimary();byzantine.addNode('voter-a');byzantine.addNode('voter-b');byzantine.addNode('voter-c');@@ -716,7 +716,7 @@ describe('Weighted Consensus (Dream Cycle 2026-08-24)', () => {it('reproduces today\'s flat 2f+1 quorum exactly when no weights are supplied (regression guard)', async () => {const byzantine = createByzantineConsensus('primary', { maxFaultyNodes: 1 });await byzantine.initialize();- byzantine.addNode('primary', true);+ byzantine.electPrimary();byzantine.addNode('voter-a');byzantine.addNode('voter-b');byzantine.addNode('voter-c');diff --git a/v3/@claude-flow/swarm/src/consensus/byzantine.ts b/v3/@claude-flow/swarm/src/consensus/byzantine.tsindex 535ae6ffde..b4a347eb17 100644--- a/v3/@claude-flow/swarm/src/consensus/byzantine.ts+++ b/v3/@claude-flow/swarm/src/consensus/byzantine.ts@@ -62,6 +62,9 @@ export class ByzantineConsensus extends EventEmitter {constructor(nodeId: string, config: ByzantineConfig = {}) {super();+ if (config.maxFaultyNodes !== undefined && (!Number.isSafeInteger(config.maxFaultyNodes) || config.maxFaultyNodes < 0)) {+ throw new RangeError('maxFaultyNodes must be a non-negative safe integer');+ }this.config = {threshold: config.threshold ?? SWARM_CONSTANTS.DEFAULT_CONSENSUS_THRESHOLD,timeoutMs: config.timeoutMs ?? SWARM_CONSTANTS.DEFAULT_CONSENSUS_TIMEOUT_MS,@@ -158,11 +161,17 @@ export class ByzantineConsensus extends EventEmitter {*/private byzantineF(): number {const n = this.nodes.size + 1; // self + known peers- const derived = Math.max(1, Math.floor((n - 1) / 3));+ const derived = Math.floor((n - 1) / 3);const cap = this.config.maxFaultyNodes;return cap === undefined ? derived : Math.min(derived, cap);}+ /** Strictly intersecting quorum for every cluster size, including capped f. */+ private quorumSize(): number {+ const n = this.nodes.size + 1;+ return Math.floor((n + this.byzantineF()) / 2) + 1;+ }+electPrimary(): string {const nodeIds = [this.node.id, ...Array.from(this.nodes.keys())];const primaryIndex = this.node.viewNumber % nodeIds.length;@@ -233,7 +242,7 @@ export class ByzantineConsensus extends EventEmitter {// Dream Cycle 2026-08-24 (swarm): per-voter weight for weighted consensus,// clamped to [0,1]. The clamp is a hard safety invariant, not a style- // choice: byzantine.ts's f-faulty-node quorum (2f+1) assumes each vote+ // choice: byzantine.ts's f-faulty-node quorum assumes each vote// contributes at most one unit β an unclamped weight >1 would let a// single high-weight node satisfy quorum alone, defeating the BFT// guarantee. Missing weights/voter defaults to 1 (flat vote), reproducing@@ -252,9 +261,8 @@ export class ByzantineConsensus extends EventEmitter {proposal.votes.set(vote.voterId, vote);// Check consensus- const f = this.byzantineF();const n = this.nodes.size + 1;- const requiredVotes = 2 * f + 1;+ const requiredVotes = this.quorumSize();const castVotes = Array.from(proposal.votes.values());const approvingWeight = castVotes@@ -351,11 +359,11 @@ export class ByzantineConsensus extends EventEmitter {messages.push(message);}- // Check if prepared (2f + 1 prepare messages)- const f = this.byzantineF();+ // Check the same intersecting quorum used by vote().+ const requiredMessages = this.quorumSize();const prepareCount = messages.filter(m => m.type === 'prepare').length;- if (prepareCount >= 2 * f + 1) {+ if (prepareCount >= requiredMessages) {const proposalId = `bft_${message.viewNumber}_${message.sequenceNumber}`;this.node.preparedMessages.set(key, messages);@@ -388,10 +396,10 @@ export class ByzantineConsensus extends EventEmitter {// KNOWN LIMITATION (pre-existing, not fixed here, flagged by adversarial// review during dream-cycle 2026-08-24): this PBFT protocol-message commit// quorum is a second, fully separate acceptance path from vote()'s- // weighted tally below β it accepts on raw commit-message count (2f+1),- // with no concept of per-voter weight. Currently unreachable in this- // package's unit tests (no transport wired), but a deployment that wires- // real multi-node PBFT transport traffic would bypass weighted consensus+ // weighted tally below β it accepts on raw commit-message count at the same quorum size,+ // with no concept of per-voter weight. The protocol quorum is now covered+ // by direct message-handler tests; a deployment that wires real multi-node+ // PBFT transport traffic would still bypass weighted consensus// entirely via this path. "Weighted Byzantine consensus" governs the// vote() API only, not the underlying commit-message protocol.async handleCommit(message: ByzantineMessage): Promise<void> {@@ -410,11 +418,11 @@ export class ByzantineConsensus extends EventEmitter {messages.push(message);}- // Check if committed (2f + 1 commit messages)- const f = this.byzantineF();+ // Check the same intersecting quorum used by vote().+ const requiredMessages = this.quorumSize();const commitCount = messages.filter(m => m.type === 'commit').length;- if (commitCount >= 2 * f + 1) {+ if (commitCount >= requiredMessages) {const proposalId = `bft_${message.viewNumber}_${message.sequenceNumber}`;this.node.committedMessages.set(key, messages);@@ -526,8 +534,7 @@ export class ByzantineConsensus extends EventEmitter {}getMaxFaultyNodes(): number {- const n = this.nodes.size + 1;- return Math.floor((n - 1) / 3);+ return this.byzantineF();}canTolerate(faultyCount: number): boolean {