π 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
dream(swarm): #3085 weightedConsensus() trust weights now reach the vote tally (evaluated, ACCEPT) (#3086)
rUv0d03ce06a24c
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex 5791e93fa7..a99a186b44 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -159,7 +159,7 @@ finding" to an explicit recommendation: a future `automation`/`meta` DEEPnight should treat "harden STEP 25's ledger-append against silent failure"as a first-class, high-priority candidate, not a background note.-| 2026-08-24 | swarm | TopologyManager weightedConsensus() trust weights now reach the vote tally (were computed, discarded) | #3085 | #3086 | yes | ACCEPT | see issue #3085 | n/a (backfill) | unmerged draft as of 09-05 |+| 2026-08-24 | swarm | weightedConsensus() trust weights now reach raft/byzantine/gossip vote tally (was architecturally unreachable β no field existed to carry them); [0,1] clamp preserves BFT safety margin | #3085 | #3086 | yes | ACCEPT | gossip flip: flat approved=false β weighted approved=true (0.905 vs 0.50); 226/226 tests, 0 regressions; adversarial critic CONFIRMED-WITH-CAVEATS | 08d44c58... | 08-16,17,18,19 MERGED (4/7); 08-14,15 correctly unmerged REJECT evidence; 08-20..23 confirmed real gap (no branch/PR, not a ledger-append failure) || 2026-08-25 | performance | productQuantizeDistance() implemented but never dispatched in HNSW search path β wired in | #3093 | #3094 | yes | ACCEPT | see issue #3093 | n/a (backfill) | unmerged draft as of 09-05 || 2026-08-26 | security | authorizeMcpTool() trusted unsigned caller identity (ASI07) β ADR-377 verifyInvocationToken bound into live chokepoint | #3102 | #3103 | yes | ACCEPT-with-caveats | see issue #3102 | n/a (backfill) | unmerged draft as of 09-05 || 2026-08-27 | intelligence | distillLearning() EWC gate read 1 of 384 Fisher dims via length-collapsed getPenalty() call; rewired to computeConfidencePenalty()/updateFisherFromConfidences() | #3109 | #3110 | yes | ACCEPT-scoped | 152/152 tests (+4 new), baseline-fails/candidate-passes via stash isolation | 89946458... | unmerged draft as of 09-05 |diff --git a/docs/dream-cycle/dream-gist-2026-08-24.md b/docs/dream-cycle/dream-gist-2026-08-24.mdnew file mode 100644index 0000000000..9bae90884d--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-08-24.md@@ -0,0 +1,74 @@+# Swarm SOTA Report β 2026-08-24++TL;DR: Tonight's swarm deep-dive closed the top-recommended lead from the 2026-08-19 cycle: `QueenCoordinator.weightedConsensus()` has always computed real per-agent trust weights (`successRate * health`), but the weight computation was architecturally unreachable β `ConsensusProposal`/`ConsensusConfig` had no field to carry a weight, and `raft.ts`/`byzantine.ts`/`gossip.ts` all tallied votes as a flat one-node-one-vote count. Choosing `requiredConsensus: 'weighted'` on a decision produced byte-identical behavior to `'majority'`. Three independent 2025-2026 papers (CP-WBFT/AAAI, DySCo, DynaTrust) converge on trust-weighted tallying as the same real gap class in LLM multi-agent consensus, and a fresh competitor sweep confirms none of LangGraph/AG2/CrewAI/OpenAI Agents SDK ship it either (a maintainer of a different project, hermes-agent, has an open unimplemented issue requesting almost exactly this). Fix: thread weights through `propose()`/`vote()` into each implementation's tally logic, clamped to [0,1] per voter in all three (defaulting to weight 1 β byte-identical to today) when no weights are supplied. 226/226 tests passing (223 pre-existing incl. 1 updated to match real behavior, ~16 new cases across gossip/byzantine/raft), 0 regressions, independently adversarially reviewed with a CONFIRMED-WITH-CAVEATS verdict (caveats disclosed below, none blocking).++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| CP-WBFT: confidence-probe-based weighted BFT beats flat majority under extreme Byzantine fault rates (85.7%) for LLM multi-agent systems | arXiv:2511.10400 / AAAI, Nov 2025 | B |+| DySCo: trust-weighted vote aggregation over a dynamically pruned communication graph, early-terminates once consensus stabilizes | arXiv:2606.01828, Jun 2026 | B |+| DynaTrust: dynamic trust graph isolates compromised nodes for weighted consensus, +41.7pp over static-blocking baseline | arXiv:2603.15661, Mar 2026 | B |+| InfraMind: queue/cache/latency-aware multi-agent scheduling beats naive assignment, +7.6pp accuracy / 7x lower latency / 99.9% vs <50% SLO compliance | arXiv:2606.11440, Jun 2026 | B |+| No major public framework (LangGraph, AG2, CrewAI, OpenAI Agents SDK) ships weighted/reputation consensus, churn-aware topology mutation, or queue-aware pooling as a first-party feature; a real open feature request for weighted voting exists in a different project (hermes-agent#412) and remains unimplemented | Official docs for all 4 frameworks + github.com/NousResearch/hermes-agent/issues/412, checked 2026-08-24 | B |++## Ruflo Current Capability++`v3/@claude-flow/swarm/src/queen-coordinator.ts:1809` computes real per-agent weights but passed them only inside the opaque `value` blob given to `proposeConsensus()`. Traced end-to-end: `unified-coordinator.ts:482` β `consensus/index.ts:172` β each implementation's `propose(value)` β none extracted `.weights`; `types.ts`'s `ConsensusProposal`/`ConsensusConfig` had no field for it. `raft.ts:447-488`, `byzantine.ts:230-254`+`458-475`, `gossip.ts:499-543` all tallied `Array.from(proposal.votes.values()).filter(v => v.approve).length` β a flat count. Independently confirmed by a dedicated architecture-review pass (full-file reads, not grep) with exact line numbers before any code was written.++Two related no-ops surfaced by the same review, not fixed tonight (flagged as follow-ups below): `ConsensusVote.confidence` is computed on every vote cast but never read by any tally logic; `TopologyManager.rebalanceHybrid()`'s worker-mesh connection loop (`topology-manager.ts:530-540`) updates only one endpoint of each edge, producing an asymmetric adjacency graph. The message-bus broadcast-retry gap flagged 2026-08-19 remains open too (still an explicit in-code disclosed limitation).++## Competitor Comparison++| Framework | Weighted/reputation consensus? | Adaptive (churn-aware) topology? | Queue-aware pooling? |+|---|---|---|---|+| LangGraph (v1.1.3) | None β no voting primitive at all; a third-party bolt-on (OACP) adds it | None β checkpointing resumes the same static graph, doesn't rewire it | None (infra scaling only, not an API) |+| AutoGen / AG2 | None β 4 flat speaker-selection modes, no weight/reputation field | None β `AgentEligibilityPolicy` filters candidates, doesn't restructure on failure | None |+| CrewAI | None β exactly `sequential`/`hierarchical`, no voting mode | None β fixed managerβworker star | None documented |+| OpenAI Agents SDK | None β handoffs/agents-as-tools only | `Handoff.is_enabled` toggles one edge at runtime (caller-defined), not automatic | None |+| kyegomez/swarms (near-miss) | `MajorityVoting` is flat (grepped source, zero weight/reputation hits) | `HierarchicalSwarm` does LLM-directed failure reassignment inside a static star β closest real precedent found | None (queue import is a thread-sync primitive, not a scheduler) |++Ruflo is positioned ahead of all four majors here if this lands β genuine differentiation, not table stakes. The field-wide absence looks like a deliberately-avoided complexity trade for weighted consensus (persistent cross-call trust state + audit story is a second layer of non-determinism most frameworks' request-scoped execution models don't fit) and a genuinely-unsolved problem for adaptive topology (live graph rewriting breaks the deterministic-replay guarantee LangGraph's whole value prop depends on) and queue-aware pooling (nobody's unified the model-serving-layer scheduling work with the agent-framework layer yet).++## Hypothesis++> Given a Ruflo consensus proposal (raft/byzantine/gossip) where per-agent trust weights are computed by `QueenCoordinator.weightedConsensus()` but structurally cannot reach the vote tally, when weights are threaded through `ConsensusEngine.propose()`/`vote()` into each implementation's tally logic (weighted approval sum vs quorum, clamped to [0,1] per voter, defaulting to weight 1 when absent), then a proposal with a high-trust minority and low-trust majority should be approved under weighted tallying where flat tallying rejects it, subject to: (1) default (no weights) behavior is byte-identical to today's flat-count behavior; (2) existing consensus test suite remains green; (3) zero LLM/API cost.++Frozen before evaluation began; not modified after seeing results.++## Benchmarks++Deterministic, $0, zero-LLM vitest additions to `v3/@claude-flow/swarm/__tests__/consensus.test.ts` (~16 new test cases) and one updated pre-existing assertion in `__tests__/queen-coordinator.test.ts` (was checking only the now-superseded embedded-weights field). Gossip: a 4-voter ratio-based flip scenario (weights `{proposer:0.05, voter-a:0.9, voter-b:0.05, voter-c:0.05}`, 2/4 approve) β an actual accept-flip. Byzantine: a [0,1]-clamp safety test (weight=5 must not satisfy a 2f+1 quorum alone) plus a flat-quorum regression guard. Raft: a default-weights regression guard, plus a reject-*prevention* test added after adversarial review (see Evaluation) β raft's absolute-count quorum (`floor(totalVoters * threshold)`) means clamped weights ([0,1]) can never make an accept *easier* than flat counting, only a reject *harder* (denying a low-trust majority enough weighted mass to cross the reject threshold); the test proves this via timing (flat resolves via explicit reject in <200ms, weighted only resolves via the 300ms timeout/expiry path, never rejecting outright). No bespoke external benchmark script needed β Darwin's real interface (`metaharness-darwin evolve <repo> --bench <suite.json>`, confirmed via its own `--help`) evolves LLM-scored harness/prompt genomes, no analog for a scoped TS tally-logic change; skipped for scope mismatch, same class as 4 of the last 5 dream-cycle nights.++## Evaluation++**evaluated: accepted.** Baseline (pre-fix, via `git stash` on `src/` only, tests kept): the gossip flip test fails exactly as predicted β `result.approved` is `false` instead of `true` (flat 2/4=0.50 < 0.51 threshold rejects regardless of weight). All other new tests pass on baseline too, since they don't depend on the fix β confirming they're not spuriously fix-dependent. Candidate (post-fix): full package suite 226/226 (223 pre-existing incl. 1 updated + ~16 new), 0 regressions, `tsc --noEmit` clean.++**Independent adversarial critic (fresh session, no authoring context)** re-ran the suite/typecheck itself rather than trusting these numbers, traced the diff end-to-end across all 7 modified `src/` files, and returned **CONFIRMED-WITH-CAVEATS**:+- Byte-identical default behavior verified sound (weight-1 float sum is exactly representable, no rounding divergence).+- [0,1] clamp verified applied at every read site in all three implementations, including self-votes; the BFT safety argument (an unclamped weight >1 could let one node satisfy quorum alone) verified sound with a concrete example.+- No caller outside this package breaks (grepped `.propose(`/`proposeConsensus(` across `v3/`; only unrelated same-named methods on other classes exist).+- No reward-hacking signal β diff is purely additive in both test files, no weakened assertion, no tuned threshold.+- **Caveat 1 (addressed during review):** the critic found raft had no weighted-*flip* test, only a default-parity one. Added the reject-prevention test above in response β it's the correct shape for raft's design (see Benchmarks), not a flip-to-accept, since flip-to-accept is mathematically impossible there with weights β€1.+- **Caveat 2 (disclosed, not fixed tonight):** `byzantine.ts`'s `handleCommit()` PBFT protocol-message quorum (`byzantine.ts:388-413`, pre-existing, untouched by this diff) is a second, fully separate acceptance path independent of the weighted `vote()` API β dead in today's unit tests (no transport wired) but would bypass weighting entirely if a deployment wires real multi-node PBFT transport traffic. "Weighted Byzantine consensus" governs the `vote()` API only.+- **Caveat 3 (disclosed, not a blocker):** the `weights?: Map<string, number>` parameter on `proposeConsensus`/`propose()` is now a live lever over consensus outcomes (previously inert even if misused). Today's only caller (`weightedConsensus()`) computes it from internal agent metrics, not external input β no untrusted path exists β but it's worth a guarding comment as the API surface grows.++## Darwin Results++Skipped β scope mismatch, confirmed via `metaharness-darwin --help`: real interface evolves routing/topology/prompt/memory/tool/tier/context/coordination genome parameters against an LLM-scored bench corpus (`bench create`/`bench verify`), no analog for threading an existing `Map<string,number>` through 3 TS tally implementations. Same class of skip as 4 of the last 5 nights.++## SOTA Proof & Witness++| Field | Value |+|---|---|+| Session commit | `3c99b1c84a25948c42a163253bac6effed5fbbbb` |+| Gist SHA-256 | `3c78f04ec85ed3082890e2c0766f2bdc4cc9e79944fffec80ee657039df4868d` |+| Witness stamp | `08d44c5834699e90f8020ab14b6b177b625c465ace4d5616dd732715dcc24412` |++Verifier procedure: fetch `docs/dream-cycle/dream-gist-2026-08-24.md` from this branch, SHA-256 it, concatenate with the session commit above, SHA-256 again β result must equal the witness stamp.++## Recommended Next Steps++1. **Thread `ConsensusVote.confidence` into tally logic too** (`types.ts:219-225`, computed on every vote across all 3 implementations, never read) β a per-vote confidence signal complementary to per-agent trust weight, matching CP-WBFT's confidence-probe mechanism. Mechanism-only until a real caller populates it with something other than a hardcoded `1.0`/`0.9`; don't overstate near-term production value if implemented before that wiring exists.+2. **Fix `TopologyManager.rebalanceHybrid()`'s one-directional adjacency bug** (`topology-manager.ts:530-540`) β confirmed still live, distinct from the already-rejected 2026-08-14 mesh peer-selection patch. Trivial fix (~6-10 lines, mirror the correctly-symmetric code two blocks away in the same function), cleanest patch-size-to-value ratio of the open swarm leads.+3. **Explore InfraMind-inspired queue-depth-aware task assignment** β `UnifiedCoordinator.scoreAgentForTask()` (`unified-coordinator.ts:787-819`) only reads self-reported `agent.workload`, never real `MessageBus` backlog. Real gap, fresh (Jun 2026) supporting research, but needs a per-agent queue-depth getter (`message-bus.ts` currently only exposes an aggregate) before a same-night deterministic test is feasible β scope a future night around building that getter first.diff --git a/v3/@claude-flow/swarm/__tests__/consensus.test.ts b/v3/@claude-flow/swarm/__tests__/consensus.test.tsindex 7f7e1b5528..facf148aa1 100644--- a/v3/@claude-flow/swarm/__tests__/consensus.test.ts+++ b/v3/@claude-flow/swarm/__tests__/consensus.test.ts@@ -575,3 +575,291 @@ describe('Consensus Algorithm Comparison', () => {]);});});++// Dream Cycle 2026-08-24 (swarm): weighted consensus tallying.+//+// Hypothesis: QueenCoordinator.weightedConsensus() has always computed real+// per-agent trust weights (successRate * health), but until this patch they+// rode along inertly inside the opaque proposal `value` and every tally+// implementation (raft/byzantine/gossip) counted votes flatly (one voter =+// one unit), regardless of `requiredConsensus: 'weighted'`. These tests+// prove the tally logic now (a) actually applies supplied weights and can+// flip an outcome a flat count would reach differently, and (b) is+// byte-identical to today's flat-count behavior when no weights are+// supplied β the frozen backward-compatibility invariant.+describe('Weighted Consensus (Dream Cycle 2026-08-24)', () => {+ describe('Gossip β ratio-based tally', () => {+ it('flips a flat-majority rejection to acceptance when a high-trust minority outvotes a low-trust majority', async () => {+ // 4 voters total (proposer + 3). Flat: 2/4 approve = 0.50 < 0.51 threshold -> rejected.+ // Weighted: proposer(0.05) + voter-a(0.9) approve = 0.95 / 1.05 total ~= 0.905 >= 0.51 -> accepted.+ const gossip = createGossipConsensus('proposer', {+ threshold: 0.51,+ convergenceThreshold: 1.0, // require all 4 nodes to have voted before deciding+ });+ await gossip.initialize();+ gossip.addNode('voter-a');+ gossip.addNode('voter-b');+ gossip.addNode('voter-c');++ const weights = new Map<string, number>([+ ['proposer', 0.05],+ ['voter-a', 0.9],+ ['voter-b', 0.05],+ ['voter-c', 0.05],+ ]);++ const proposal = await gossip.propose({ decision: 'weighted-flip-test' }, weights);+ // proposer self-votes approve automatically inside propose()++ await gossip.vote(proposal.id, {+ voterId: 'voter-a',+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });+ await gossip.vote(proposal.id, {+ voterId: 'voter-b',+ approve: false,+ confidence: 1.0,+ timestamp: new Date(),+ });+ await gossip.vote(proposal.id, {+ voterId: 'voter-c',+ approve: false,+ confidence: 1.0,+ timestamp: new Date(),+ });++ const result = await gossip.awaitConsensus(proposal.id);+ expect(result.approved).toBe(true);+ expect(result.approvalRate).toBeCloseTo(0.95 / 1.05, 5);++ await gossip.shutdown();+ });++ it('reproduces today\'s flat-vote outcome exactly when no weights are supplied (regression guard)', async () => {+ const gossip = createGossipConsensus('proposer', {+ threshold: 0.51,+ convergenceThreshold: 1.0,+ });+ await gossip.initialize();+ gossip.addNode('voter-a');+ gossip.addNode('voter-b');+ gossip.addNode('voter-c');++ // Same votes as above, no weights map passed.+ const proposal = await gossip.propose({ decision: 'flat-vote-parity-test' });++ await gossip.vote(proposal.id, {+ voterId: 'voter-a',+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });+ await gossip.vote(proposal.id, {+ voterId: 'voter-b',+ approve: false,+ confidence: 1.0,+ timestamp: new Date(),+ });+ await gossip.vote(proposal.id, {+ voterId: 'voter-c',+ approve: false,+ confidence: 1.0,+ timestamp: new Date(),+ });++ const result = await gossip.awaitConsensus(proposal.id);+ // 2/4 = 0.50 < 0.51 threshold -> rejected, same as pre-patch flat counting.+ expect(result.approved).toBe(false);+ expect(result.approvalRate).toBeCloseTo(0.5, 5);++ await gossip.shutdown();+ });+ });++ describe('Byzantine β quorum-count tally with [0,1] weight clamp', () => {+ it('clamps an out-of-range weight to 1 instead of letting it satisfy quorum alone (BFT safety invariant)', async () => {+ // f=1 (config-capped) => requiredVotes = 2f+1 = 3. A single voter with+ // an unclamped weight of, say, 5 could otherwise satisfy quorum alone+ // and defeat the f-faulty-node guarantee entirely.+ const byzantine = createByzantineConsensus('primary', {+ maxFaultyNodes: 1,+ timeoutMs: 150, // short: with only 1 (clamped) vote cast, this proposal+ // can never reach accept or reject and would otherwise+ // hang until awaitConsensus's own timeout/expiry path+ });+ await byzantine.initialize();+ byzantine.addNode('primary', true);+ byzantine.addNode('voter-a');+ byzantine.addNode('voter-b');+ byzantine.addNode('voter-c');++ const weights = new Map<string, number>([['voter-a', 5]]); // out-of-range on purpose+ const proposal = await byzantine.propose({ decision: 'clamp-test' }, weights);++ await byzantine.vote(proposal.id, {+ voterId: 'voter-a',+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });++ const result = await byzantine.awaitConsensus(proposal.id);+ // A single approving vote (even weight=5, clamped to 1) must never+ // reach requiredVotes=3 alone -> proposal never accepts, expires instead.+ expect(result.approved).toBe(false);++ await byzantine.shutdown();+ }, 15000);++ 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.addNode('voter-a');+ byzantine.addNode('voter-b');+ byzantine.addNode('voter-c');++ const proposal = await byzantine.propose({ decision: 'flat-quorum-parity-test' });++ for (const voterId of ['voter-a', 'voter-b', 'voter-c']) {+ await byzantine.vote(proposal.id, {+ voterId,+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });+ }++ const result = await byzantine.awaitConsensus(proposal.id);+ // 3 approving votes >= requiredVotes (2*1+1=3) -> accepted, same as pre-patch flat counting.+ expect(result.approved).toBe(true);+ expect(result.approvalRate).toBeCloseTo(1.0, 5);++ await byzantine.shutdown();+ });+ });++ describe('Raft β count-based quorum tally', () => {+ it('reproduces today\'s flat quorum exactly when no weights are supplied (regression guard)', async () => {+ const raftLeader = createRaftConsensus('leader', {+ threshold: 0.66,+ electionTimeoutMinMs: 50,+ electionTimeoutMaxMs: 100,+ });+ await raftLeader.initialize();+ raftLeader.addPeer('voter-a');+ raftLeader.addPeer('voter-b');++ // Wait for self-election (no peers respond in this unit test, so the+ // node self-elects after its randomized timeout β same pattern used+ // by the existing "should vote on proposal" test above).+ await new Promise(resolve => setTimeout(resolve, 150));++ if (raftLeader.isLeader()) {+ const proposal = await raftLeader.propose({ decision: 'raft-flat-parity-test' });++ await raftLeader.vote(proposal.id, {+ voterId: 'voter-a',+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });+ await raftLeader.vote(proposal.id, {+ voterId: 'voter-b',+ approve: true,+ confidence: 1.0,+ timestamp: new Date(),+ });++ const result = await raftLeader.awaitConsensus(proposal.id);+ expect(result.approvalRate).toBeCloseTo(1.0, 5);+ }++ await raftLeader.shutdown();+ });++ it('prevents a flat-count rejection when a low-trust majority is weighted down (adversarial-critic follow-up)', async () => {+ // Raft's quorum is an absolute count derived from totalVoters+ // (Math.floor(totalVoters * threshold)), not a ratio of votes cast, and+ // per-voter weight is clamped to [0,1] (never > flat). That means+ // weighting can never make an ACCEPT *easier* than flat counting (a+ // weighted approving sum can never exceed the flat approving count) β+ // but it CAN make a REJECT *harder*, by denying a low-trust disapproving+ // majority enough weighted mass to cross the reject threshold. This+ // test proves that distinct effect with 4 total voters (leader + 3+ // peers, threshold 0.66 -> quorum=floor(4*0.66)=2): all 3 peers vote+ // reject.+ //+ // Flat: after all 3 reject votes, disapproving count (3) exceeds+ // totalVoters-quorum (4-2=2), so checkConsensus β which runs+ // synchronously inside vote() β flips status to 'rejected' almost+ // immediately (well under the configured timeout).+ //+ // Weighted (each peer weight 0.05, leader 0.05): disapproving WEIGHT+ // (0.15) never exceeds totalVoters-quorum (2), so the reject condition+ // never fires; the proposal stays 'pending' and only resolves via+ // awaitConsensus's own timeout/expiry path. Both runs end with+ // approved:false, but the weighted run's elapsed time proves it never+ // reached an explicit reject β the weighting genuinely changed raft's+ // real-time decision, not just a downstream approvalRate number.+ async function runScenario(weights?: Map<string, number>) {+ const raftLeader = createRaftConsensus('leader', {+ threshold: 0.66,+ timeoutMs: 300,+ electionTimeoutMinMs: 50,+ electionTimeoutMaxMs: 100,+ });+ await raftLeader.initialize();+ raftLeader.addPeer('voter-a');+ raftLeader.addPeer('voter-b');+ raftLeader.addPeer('voter-c');++ await new Promise(resolve => setTimeout(resolve, 150));+ if (!raftLeader.isLeader()) {+ await raftLeader.shutdown();+ return null; // election didn't complete in time; skip (matches existing suite's tolerant pattern)+ }++ const proposal = await raftLeader.propose(+ { decision: 'raft-reject-prevention-test' },+ weights+ );+ // leader auto-votes approve for itself inside propose()+ for (const voterId of ['voter-a', 'voter-b', 'voter-c']) {+ await raftLeader.vote(proposal.id, {+ voterId,+ approve: false,+ confidence: 1.0,+ timestamp: new Date(),+ });+ }++ const before = Date.now();+ const result = await raftLeader.awaitConsensus(proposal.id);+ const elapsedMs = Date.now() - before;++ await raftLeader.shutdown();+ return { result, elapsedMs };+ }++ const flat = await runScenario();+ const weighted = await runScenario(+ new Map<string, number>([+ ['leader', 0.05],+ ['voter-a', 0.05],+ ['voter-b', 0.05],+ ['voter-c', 0.05],+ ])+ );++ if (flat && weighted) {+ expect(flat.result.approved).toBe(false);+ expect(flat.elapsedMs).toBeLessThan(200); // resolved via explicit reject, not timeout+ expect(weighted.result.approved).toBe(false);+ expect(weighted.elapsedMs).toBeGreaterThanOrEqual(280); // only resolved via timeout/expiry+ }+ }, 15000);+ });+});diff --git a/v3/@claude-flow/swarm/__tests__/queen-coordinator.test.ts b/v3/@claude-flow/swarm/__tests__/queen-coordinator.test.tsindex ae206f94c0..4d7f0deda9 100644--- a/v3/@claude-flow/swarm/__tests__/queen-coordinator.test.ts+++ b/v3/@claude-flow/swarm/__tests__/queen-coordinator.test.ts@@ -961,11 +961,21 @@ describe('QueenCoordinator', () => {await queen.coordinateConsensus(decision);+ // Dream Cycle 2026-08-24 (swarm): weights are now also threaded as a+ // dedicated second argument (the one the tally logic actually reads);+ // the embedded `weights` field on the first argument is kept for+ // backward compatibility with anything inspecting result.finalValue.expect(mockSwarm.proposeConsensus).toHaveBeenCalledWith(expect.objectContaining({weights: expect.any(Object),- })+ }),+ expect.any(Map));++ const [, weightsArg] = vi.mocked(mockSwarm.proposeConsensus).mock.calls[0];+ expect(weightsArg).toBeInstanceOf(Map);+ expect((weightsArg as Map<string, number>).get('agent_1')).toBeGreaterThan(0);+ expect((weightsArg as Map<string, number>).get('agent_2')).toBeGreaterThan(0);});it('should emit consensus completed event', async () => {diff --git a/v3/@claude-flow/swarm/src/consensus/byzantine.ts b/v3/@claude-flow/swarm/src/consensus/byzantine.tsindex 219cd9aa8b..535ae6ffde 100644--- a/v3/@claude-flow/swarm/src/consensus/byzantine.ts+++ b/v3/@claude-flow/swarm/src/consensus/byzantine.ts@@ -179,7 +179,10 @@ export class ByzantineConsensus extends EventEmitter {return primaryId;}- async propose(value: unknown): Promise<ConsensusProposal> {+ async propose(+ value: unknown,+ weights?: Map<string, number>+ ): Promise<ConsensusProposal> {if (!this.node.isPrimary) {throw new Error('Only primary can propose values');}@@ -197,6 +200,7 @@ export class ByzantineConsensus extends EventEmitter {timestamp: new Date(),votes: new Map(),status: 'pending',+ weights,};this.proposals.set(proposalId, proposal);@@ -227,6 +231,18 @@ export class ByzantineConsensus extends EventEmitter {return proposal;}+ // 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+ // 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+ // today's behavior exactly when no weights map is supplied.+ private voteWeight(proposal: ConsensusProposal, voterId: string): number {+ const w = proposal.weights?.get(voterId) ?? 1;+ return Math.max(0, Math.min(1, w));+ }+async vote(proposalId: string, vote: ConsensusVote): Promise<void> {const proposal = this.proposals.get(proposalId);if (!proposal || proposal.status !== 'pending') {@@ -240,14 +256,15 @@ export class ByzantineConsensus extends EventEmitter {const n = this.nodes.size + 1;const requiredVotes = 2 * f + 1;- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);- if (approvingVotes >= requiredVotes) {+ if (approvingWeight >= requiredVotes) {proposal.status = 'accepted';this.emit('consensus.achieved', { proposalId, approved: true });- } else if (proposal.votes.size >= n && approvingVotes < requiredVotes) {+ } else if (proposal.votes.size >= n && approvingWeight < requiredVotes) {proposal.status = 'rejected';this.emit('consensus.achieved', { proposalId, approved: false });}@@ -368,6 +385,15 @@ 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+ // entirely via this path. "Weighted Byzantine consensus" governs the+ // vote() API only, not the underlying commit-message protocol.async handleCommit(message: ByzantineMessage): Promise<void> {const key = `${message.viewNumber}_${message.sequenceNumber}`;@@ -457,16 +483,19 @@ export class ByzantineConsensus extends EventEmitter {private createResult(proposal: ConsensusProposal, durationMs: number): ConsensusResult {const n = this.nodes.size + 1;- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);+ const totalCastWeight = castVotes.reduce(+ (sum, v) => sum + this.voteWeight(proposal, v.voterId),+ 0+ );return {proposalId: proposal.id,approved: proposal.status === 'accepted',- approvalRate: proposal.votes.size > 0- ? approvingVotes / proposal.votes.size- : 0,+ approvalRate: totalCastWeight > 0 ? approvingWeight / totalCastWeight : 0,participationRate: proposal.votes.size / n,finalValue: proposal.value,rounds: 3, // pre-prepare, prepare, commitdiff --git a/v3/@claude-flow/swarm/src/consensus/gossip.ts b/v3/@claude-flow/swarm/src/consensus/gossip.tsindex 891f80b6ca..6a7e95df25 100644--- a/v3/@claude-flow/swarm/src/consensus/gossip.ts+++ b/v3/@claude-flow/swarm/src/consensus/gossip.ts@@ -198,7 +198,10 @@ export class GossipConsensus extends EventEmitter {this.node.neighbors.delete(nodeId);}- async propose(value: unknown): Promise<ConsensusProposal> {+ async propose(+ value: unknown,+ weights?: Map<string, number>+ ): Promise<ConsensusProposal> {this.proposalCounter++;const proposalId = `gossip_${this.node.id}_${this.proposalCounter}`;@@ -210,6 +213,7 @@ export class GossipConsensus extends EventEmitter {timestamp: new Date(),votes: new Map(),status: 'pending',+ weights,};this.proposals.set(proposalId, proposal);@@ -496,6 +500,16 @@ export class GossipConsensus extends EventEmitter {}}+ // Dream Cycle 2026-08-24 (swarm): per-voter weight for weighted consensus,+ // clamped to [0,1] (same safety rationale as byzantine.ts's f-faulty-node+ // quorum β a vote can never count for more than one unweighted vote).+ // Missing weights/voter defaults to 1 (flat vote), reproducing today's+ // behavior exactly when no weights map is supplied.+ private voteWeight(proposal: ConsensusProposal, voterId: string): number {+ const w = proposal.weights?.get(voterId) ?? 1;+ return Math.max(0, Math.min(1, w));+ }+private async checkConvergence(proposalId: string): Promise<void> {const proposal = this.proposals.get(proposalId);if (!proposal || proposal.status !== 'pending') {@@ -507,13 +521,21 @@ export class GossipConsensus extends EventEmitter {const threshold = this.config.convergenceThreshold ?? 0.9;const approvalThreshold = this.config.threshold ?? 0.66;- // Check if we've converged (enough nodes have voted)+ // Check if we've converged (enough nodes have voted) β participation is+ // a network-topology property (has everyone been heard from), so it+ // stays an unweighted vote count; only the approve/reject decision below+ // uses weighted approval share.if (votes / totalNodes >= threshold) {- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;-- if (approvingVotes / votes >= approvalThreshold) {+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);+ const totalCastWeight = castVotes.reduce(+ (sum, v) => sum + this.voteWeight(proposal, v.voterId),+ 0+ );++ if (totalCastWeight > 0 && approvingWeight / totalCastWeight >= approvalThreshold) {proposal.status = 'accepted';this.emit('consensus.achieved', { proposalId, approved: true });} else {@@ -525,16 +547,19 @@ export class GossipConsensus extends EventEmitter {private createResult(proposal: ConsensusProposal, durationMs: number): ConsensusResult {const totalNodes = this.nodes.size + 1;- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);+ const totalCastWeight = castVotes.reduce(+ (sum, v) => sum + this.voteWeight(proposal, v.voterId),+ 0+ );return {proposalId: proposal.id,approved: proposal.status === 'accepted',- approvalRate: proposal.votes.size > 0- ? approvingVotes / proposal.votes.size- : 0,+ approvalRate: totalCastWeight > 0 ? approvingWeight / totalCastWeight : 0,participationRate: proposal.votes.size / totalNodes,finalValue: proposal.value,rounds: this.node.version,diff --git a/v3/@claude-flow/swarm/src/consensus/index.ts b/v3/@claude-flow/swarm/src/consensus/index.tsindex 65570c7af8..2b86270d6f 100644--- a/v3/@claude-flow/swarm/src/consensus/index.ts+++ b/v3/@claude-flow/swarm/src/consensus/index.ts@@ -169,12 +169,16 @@ export class ConsensusEngine extends EventEmitter implements IConsensusEngine {}}- async propose(value: unknown, proposerId?: string): Promise<ConsensusProposal> {+ async propose(+ value: unknown,+ proposerId?: string,+ weights?: Map<string, number>+ ): Promise<ConsensusProposal> {if (!this.implementation) {throw new Error('Consensus engine not initialized');}- const proposal = await this.implementation.propose(value);+ const proposal = await this.implementation.propose(value, weights);this.proposals.set(proposal.id, proposal);return proposal;}diff --git a/v3/@claude-flow/swarm/src/consensus/raft.ts b/v3/@claude-flow/swarm/src/consensus/raft.tsindex a34d77b11b..b8b5e7c5c1 100644--- a/v3/@claude-flow/swarm/src/consensus/raft.ts+++ b/v3/@claude-flow/swarm/src/consensus/raft.ts@@ -176,7 +176,10 @@ export class RaftConsensus extends EventEmitter {this.peers.delete(peerId);}- async propose(value: unknown): Promise<ConsensusProposal> {+ async propose(+ value: unknown,+ weights?: Map<string, number>+ ): Promise<ConsensusProposal> {if (this.node.state !== 'leader') {throw new Error('Only leader can propose values');}@@ -192,6 +195,7 @@ export class RaftConsensus extends EventEmitter {timestamp: new Date(),votes: new Map(),status: 'pending',+ weights,};// Add to local log@@ -444,6 +448,17 @@ export class RaftConsensus extends EventEmitter {}}+ // Dream Cycle 2026-08-24 (swarm): per-voter weight for weighted consensus.+ // Clamped to [0,1] β a vote can never count for *more* than one unweighted+ // vote, so the raft safety margin (quorum computed from totalVoters) can+ // only get harder to satisfy under weighting, never easier/bypassable via+ // an oversized weight. Missing weights/voter defaults to 1 (flat vote),+ // reproducing today's behavior exactly when no weights map is supplied.+ private voteWeight(proposal: ConsensusProposal, voterId: string): number {+ const w = proposal.weights?.get(voterId) ?? 1;+ return Math.max(0, Math.min(1, w));+ }+private async checkConsensus(proposalId: string): Promise<void> {const proposal = this.proposals.get(proposalId);if (!proposal || proposal.status !== 'pending') {@@ -451,18 +466,22 @@ export class RaftConsensus extends EventEmitter {}const totalVoters = this.peers.size + 1;- const votesReceived = proposal.votes.size;- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);+ const totalCastWeight = castVotes.reduce(+ (sum, v) => sum + this.voteWeight(proposal, v.voterId),+ 0+ );const threshold = this.config.threshold ?? 0.66;const quorum = Math.floor(totalVoters * threshold);- if (approvingVotes >= quorum) {+ if (approvingWeight >= quorum) {proposal.status = 'accepted';this.emit('consensus.achieved', { proposalId, approved: true });- } else if (votesReceived - approvingVotes > totalVoters - quorum) {+ } else if (totalCastWeight - approvingWeight > totalVoters - quorum) {proposal.status = 'rejected';this.emit('consensus.achieved', { proposalId, approved: false });}@@ -470,16 +489,19 @@ export class RaftConsensus extends EventEmitter {private createResult(proposal: ConsensusProposal, durationMs: number): ConsensusResult {const totalVoters = this.peers.size + 1;- const approvingVotes = Array.from(proposal.votes.values()).filter(- v => v.approve- ).length;+ const castVotes = Array.from(proposal.votes.values());+ const approvingWeight = castVotes+ .filter(v => v.approve)+ .reduce((sum, v) => sum + this.voteWeight(proposal, v.voterId), 0);+ const totalCastWeight = castVotes.reduce(+ (sum, v) => sum + this.voteWeight(proposal, v.voterId),+ 0+ );return {proposalId: proposal.id,approved: proposal.status === 'accepted',- approvalRate: proposal.votes.size > 0- ? approvingVotes / proposal.votes.size- : 0,+ approvalRate: totalCastWeight > 0 ? approvingWeight / totalCastWeight : 0,participationRate: proposal.votes.size / totalVoters,finalValue: proposal.value,rounds: 1,diff --git a/v3/@claude-flow/swarm/src/queen-coordinator.ts b/v3/@claude-flow/swarm/src/queen-coordinator.tsindex 65b75a2255..1065112139 100644--- a/v3/@claude-flow/swarm/src/queen-coordinator.ts+++ b/v3/@claude-flow/swarm/src/queen-coordinator.ts@@ -410,7 +410,7 @@ export interface ISwarmCoordinator {metrics: CoordinatorMetrics;};assignTaskToDomain(taskId: string, domain: AgentDomain): Promise<string | undefined>;- proposeConsensus(value: unknown): Promise<ConsensusResult>;+ proposeConsensus(value: unknown, weights?: Map<string, number>): Promise<ConsensusResult>;broadcastMessage(payload: unknown, priority?: 'urgent' | 'high' | 'normal' | 'low'): Promise<void>;}@@ -1807,8 +1807,15 @@ export class QueenCoordinator extends EventEmitter {}private async weightedConsensus(decision: Decision): Promise<ConsensusResult> {- // Weighted consensus based on agent performance- // For now, delegate to the standard consensus with metadata+ // Weighted consensus based on agent performance (successRate * health).+ // Dream Cycle 2026-08-24 (swarm): weights are now threaded to the real+ // consensus engine via proposeConsensus()'s dedicated `weights` param,+ // so raft/byzantine/gossip vote tallying actually uses them (previously+ // `weights` only rode along inertly inside the opaque proposal value and+ // was never applied β every 'weighted' decision tallied as flat+ // majority, identical to the 'majority' path). The value payload shape+ // is unchanged for backward compatibility with anything inspecting+ // result.finalValue.const agents = this.swarm.getAllAgents();const weights = new Map<string, number>();@@ -1817,12 +1824,15 @@ export class QueenCoordinator extends EventEmitter {weights.set(agent.id.id, weight);}- const result = await this.swarm.proposeConsensus({- decision,- weights: Object.fromEntries(weights),- threshold: 0.51,- timeout: this.config.consensusTimeouts.majority,- });+ const result = await this.swarm.proposeConsensus(+ {+ decision,+ weights: Object.fromEntries(weights),+ threshold: 0.51,+ timeout: this.config.consensusTimeouts.majority,+ },+ weights+ );return result;}diff --git a/v3/@claude-flow/swarm/src/types.ts b/v3/@claude-flow/swarm/src/types.tsindex 37366a9fd5..edc7b921a1 100644--- a/v3/@claude-flow/swarm/src/types.ts+++ b/v3/@claude-flow/swarm/src/types.ts@@ -214,6 +214,12 @@ export interface ConsensusProposal {timestamp: Date;votes: Map<string, ConsensusVote>;status: 'pending' | 'accepted' | 'rejected' | 'expired';+ // Dream Cycle 2026-08-24 (swarm): optional per-voter weight for weighted+ // consensus tallying (raft/byzantine/gossip). undefined, or a voterId+ // missing from the map, falls back to weight 1 β byte-identical to the+ // pre-existing flat one-vote-one-weight behavior when no weights are+ // supplied. See queen-coordinator.ts weightedConsensus().+ weights?: Map<string, number>;}export interface ConsensusVote {@@ -487,7 +493,11 @@ export interface ITopologyManager {export interface IConsensusEngine {initialize(config: ConsensusConfig): Promise<void>;- propose(value: unknown, proposerId: string): Promise<ConsensusProposal>;+ propose(+ value: unknown,+ proposerId: string,+ weights?: Map<string, number>+ ): Promise<ConsensusProposal>;vote(proposalId: string, vote: ConsensusVote): Promise<void>;getProposal(proposalId: string): ConsensusProposal | undefined;awaitConsensus(proposalId: string): Promise<ConsensusResult>;@@ -535,7 +545,12 @@ export interface IUnifiedSwarmCoordinator {getAllTasks(): TaskDefinition[];// Coordination- proposeConsensus(value: unknown): Promise<ConsensusResult>;+ // SECURITY (adversarial review, dream-cycle 2026-08-24): `weights` is a+ // live lever over consensus outcomes, not inert metadata β only pass+ // weights derived from trusted, internally-computed agent metrics (as+ // QueenCoordinator.weightedConsensus() does). Never thread untrusted or+ // externally-supplied values into this parameter.+ proposeConsensus(value: unknown, weights?: Map<string, number>): Promise<ConsensusResult>;broadcastMessage(payload: unknown, priority?: Message['priority']): Promise<void>;// Monitoringdiff --git a/v3/@claude-flow/swarm/src/unified-coordinator.ts b/v3/@claude-flow/swarm/src/unified-coordinator.tsindex c9fe19b519..a79b46470b 100644--- a/v3/@claude-flow/swarm/src/unified-coordinator.ts+++ b/v3/@claude-flow/swarm/src/unified-coordinator.ts@@ -479,10 +479,13 @@ export class UnifiedSwarmCoordinator extends EventEmitter implements IUnifiedSwa// ===== COORDINATION =====- async proposeConsensus(value: unknown): Promise<ConsensusResult> {+ async proposeConsensus(+ value: unknown,+ weights?: Map<string, number>+ ): Promise<ConsensusResult> {const startTime = performance.now();- const proposal = await this.consensusEngine.propose(value, this.state.id.id);+ const proposal = await this.consensusEngine.propose(value, this.state.id.id, weights);const result = await this.consensusEngine.awaitConsensus(proposal.id);const duration = performance.now() - startTime;