π 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): #3928 MessageBus broadcast-retry re-queues under the real subscriber agentId, not the 'broadcast' sentinel
Claude86af231f6d0f
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex 75a2e124b5..6ae831521d 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -225,4 +225,7 @@ as a first-class, high-priority candidate, not a background note.**Note (2026-09-28):** verified via GitHub MCP tools (`gh` CLI unavailable this session, same FALLBACK-for-gist-only condition since 2026-09-17): a second bulk human-review pass landed 2026-09-26, closing most of the 09-15..09-22 backlog (spot-verified 2/2 as genuinely `merged:true` via `pull_request_read`, not trusting `search_pull_requests`'s own unreliable `merged` field per the 2026-09-21 note) β #3395 (09-22, intelligence) and several others now MERGED. Still OPEN/draft: #3339 (09-16, security, round-2 hive-mind auth, 811 lines β larger scope, human review pending) and #3476 (09-27, intelligence, `CLAUDE_FLOW_FISHER_DECAY` env override). Also observed: #3412 (`dream/2026-09-24-github-safe-artifact-parity`, MERGED 2026-09-26) β a real security fix for issue #3411, not a standard Dream Cycle DEEP/SCAN rotation, so not given its own ledger row. No branch/PR found for 2026-09-23, 2026-09-25, or 2026-09-26 β consistent with the recurring no-run-gap pattern (08-20..23, 09-13/14).+**Note (2026-10-09):** nights 2026-10-01 through 2026-10-08 all ran (real branches + issues + draft/closed PRs confirmed via `git ls-remote --heads origin "dream/*"` and `pull_request_read`/`list_pull_requests`, not inferred) but aren't transcribed as their own rows here β same "ledger rows only reach `main` via PR merge" structural gap noted since 2026-08-19. Fates: 10-01 security #3599 **MERGED** 2026-10-07; 10-02 intelligence #3622 open/draft; 10-03 memory #3650 open/draft; **10-04 (swarm) is a genuine no-run gap** (slot sequence skipped straight to 10-05); 10-05 performance #3754 **closed, not merged**; 10-06 security #3835 open/draft; 10-07 intelligence #3879 open/draft; 10-08 memory #3909 open/draft. Also newly confirmed merged since the last note: #3339 (09-16 security round 2) and #3539 (09-29 swarm), both 2026-10-07. Prior gist (10-08, memory) scored 9/10 (STEP 1.2: 2+2+2+2+0(1691 words, over the 1500-word cap)+1). pi.ruv.io read-only collective-memory check (STEP 2.1) unreachable this session (connection failure, HTTP status 000) β supplementary signal only, did not block.+| 2026-09-28 | memory | `mmrRerank()`'s embedding-cosine path (`smart-retrieval.ts`) recomputed max-similarity-to-selected against the *entire* selected set on every outer-loop pass (βO(candidatesΓselectedΒ²)), even after #3169/#3266 already made the Jaccard-fallback tokenization lazy β flagged grade-A by 2026-09-27's own memory scan (still-open #3476) and acted on directly tonight; replaced with a running per-candidate max-similarity cache (one new comparison per candidate per round, folded via `Math.max`, algebraically identical to recomputing the max from scratch) | #3516 | #3517 | yes | ACCEPT | byte-identical selection order across 5 scenarios (all/none/half-embedded, lambda extremes, a dedicated negative-cosine zero-floor case); wall-clock 686.5msβ<343.3ms (>2x, N=200/limit=100), stash-isolated baseline-fails/candidate-passes on this exact assertion; frozen-copy call-count comparison used instead of `vi.spyOn` after a debug test showed Vitest's ESM spy can't intercept same-module internal calls (flagged as a likely latent issue in the sibling 09-10 `tokenize()` call-count test, not fixed retroactively); 564/565 full `@claude-flow/memory` suite both ways (1 pre-existing environmental failure, unchanged), `tsc --noEmit` 0 errors both ways | 85e464a6... | 09-16 (#3339) still open/draft; 09-27 (#3476) still open/draft; 09-15..09-22 backlog mostly MERGED in a 2026-09-26 bulk review batch; no-run gap 09-23/09-25/09-26 |+| 2026-10-09 | swarm | `MessageBus.handleDeliveryError()`'s retry re-queue used the broadcast sentinel `message.to === 'broadcast'` as the queue key instead of the real subscriber `agentId` `enqueue()` had fanned the message out to β `processQueues()` skips any unsubscribed queue, so a failing broadcast subscriber's retries and eventual `message.failed` were silently dropped into an orphaned queue leaking until `shutdown()`; explicitly disclosed as a "KNOWN LIMITATION (pre-existing, not fixed here)" by the immediately-preceding #3562/#3563 rewrite, closed tonight by threading `subscription.agentId` through `deliverMessage()`β`handleDeliveryError()`βthe re-queue | #3928 | #3929 | yes | ACCEPT | 2 new discriminating tests, baseline-fails/candidate-passes via stash isolation (independently reproduced byte-identical by an adversarial critic's own stash/pop cycle); full `@claude-flow/swarm` suite 274/274β276/276 (+2 new), 0 regressions, `tsc --noEmit` clean both ways; healthy co-subscriber in the same broadcast unaffected (explicit regression guard); independent adversarial critique CONFIRMED, no blocking issues | 1b7e818e... | 10-01 #3599 MERGED 2026-10-07; 10-02..10-03/10-05..10-08 open/draft or closed-not-merged (see 2026-10-09 note above); 10-04 no-run gap; also newly confirmed MERGED this session: #3339 (09-16), #3539 (09-29) |diff --git a/docs/dream-cycle/dream-gist-2026-10-09.md b/docs/dream-cycle/dream-gist-2026-10-09.mdnew file mode 100644index 0000000000..6cb936b2f9--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-10-09.md@@ -0,0 +1,84 @@+# Swarm SOTA Report β 2026-10-09++TL;DR: In 2026, multi-agent orchestration research has shifted from "does consensus work" to "does it survive stochastic LLM voters" β AAAI 2026's confidence-weighted BFT (CP-WBFT) shows classic majority-vote BFT degrades badly under realistic LLM unreliability, while a March 2026 preprint shows a single Byzantine LLM agent can collapse textbook consensus entirely via liveness loss rather than corrupted values. Against that backdrop, tonight's own swarm package review found something more mundane but concretely fixable: `MessageBus`'s broadcast-retry path has been silently dropping failed deliveries to orphaned queue entries since the event-driven rewrite (#3562/#3563) that fixed its direct-message sibling β explicitly flagged as a "KNOWN LIMITATION (pre-existing, not fixed here)" comment in the shipped code, now closed. A second, independently confirmed dead-code finding (ruvector-integration SCAN: the code-graph analyzer's native-acceleration path calls API names that have never existed in the real `ruvector` package, across its entire pinned version range) is carried as a scanned-but-deferred candidate for a future night rather than bundled into tonight's patch.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| Confidence-weighted BFT (CP-WBFT) survives 85.7% Byzantine fault rates by weighting message credibility via probe-based scoring instead of flat majority vote | AAAI 2026 proceedings, arXiv:2511.10400 | A |+| RouteMoA: skipping pre-inference scoring in mixture-of-agents routing cuts cost 89.8% and latency 63.6% vs. scored routing at scale | ACL 2026 Long Papers | B |+| A single Byzantine LLM agent can collapse consensus success under a validity+liveness formalization β failures are dominated by liveness loss, not corrupted values, undercutting the assumption that textbook BFT math transfers to stochastic LLM voters | arXiv:2603.01213 (Mar 2026) | C |+| AdaptOrch: dynamic topology selection (parallel/sequential/hierarchical/hybrid) per task-dependency graph reportedly outweighs backbone model choice for system-level performance | arXiv:2602.16873 (Feb 2026) | C |+| MonoScale: familiarization tasks + contextual-bandit augmentation give a monotonic-improvement guarantee when onboarding new agents into a live pool (addresses "new agent tanks performance") | arXiv:2601.23219 | C |++No credible 2026 result found specifically combining CRDT+gossip+BFT for agent swarms β closest is a Dec-2025 position paper (arXiv:2512.03285) that is explicitly a research agenda, not evaluated results. Noted as a gap rather than padded.++## Ruflo Current Capability++`UnifiedSwarmCoordinator` (`v3/@claude-flow/swarm/src/unified-coordinator.ts`, 1931 lines) composes a `TopologyManager` (adjacency-list graph, O(1) queen/coordinator caches, symmetric edge mirroring), a per-domain `AgentPool` (acquire/release/scale with cooldown + health-check replacement), an event-driven `MessageBus` (Deque-backed priority queues, `scheduleProcessing()`), and a pluggable `ConsensusEngine` (raft/byzantine/gossip). Already fixed in recent nights (not re-proposed): MessageBus busy-poll (#3562/3563), spawnAgent pool.add() wiring (#3538/3539), topology edge-mirroring (#3356/3357), weighted-consensus trust tally, rebalanceHybrid one-directional edges, AgentPool heartbeat self-stamp, byzantine quorum sizing.++Tonight's finding sits one layer inside the already-fixed MessageBus rewrite: `handleDeliveryError()`'s retry re-queue used the broadcast sentinel `message.to === 'broadcast'` as a queue key instead of the real subscriber's `agentId` that `enqueue()` had actually fanned the message out to. Since `processQueues()` skips any queue with no matching subscription, a failing broadcast subscriber's retries β and eventual `message.failed` β were silently dropped into a queue nobody drains, leaking until `shutdown()`. The fix threads `subscription.agentId` through `deliverMessage()` β `handleDeliveryError()` β the re-queue, matching the already-correct direct-message path exactly.++## Competitor Comparison++| System | Topology/coordination | Dynamic pool & routing | Fault tolerance | Grade |+|---|---|---|---|---|+| LangGraph | supervisor / swarm (peer handoff) / hierarchical graph patterns | `create_handoff_tool` transfers control+state at runtime | Checkpointer resume, not quorum/consensus | B |+| Microsoft Agent Framework (AutoGen successor, GA Apr 2026) | sequential/concurrent/group-chat/handoff/Magentic (dynamic task ledger) | Magentic assigns open-ended sub-tasks from the ledger | No built-in consensus; durability from host runtime | B |+| CrewAI | sequential default; opt-in hierarchical (`manager_llm`); Flows adds event-driven routing | "Router Agent" pattern, not a core primitive | None documented; relies on LLM-call retries | B |+| OpenAI Agents SDK | Handoffs (single-agent-at-a-time transfer) + agents-as-tools; no branching/parallel | Triage agent picks a specialist | Guardrails/tracing, no consensus/HA | C |+| Temporal (workflow comparator) | Hand-built fan-out/fan-in, child workflows, sagas | Dynamic routing via signals/queries | Durable replay of persisted event history β closest analog to real fault tolerance | C |++None of these name Raft/Byzantine consensus as a headline feature the way ruflo's hive-mind does; Temporal's durable-replay model is the nearest real analog to fault tolerance, the rest lean on checkpoint-resume or plain retries.++**ruvector-integration SCAN note:** no competitor example found of a CI "contract test that diffs a native-wrapper's called method names against the real installed package's actual exports" β napi-rs/node-addon-api docs flag Rust snake_caseβJS camelCase export drift as a known risk, but an explicit startup self-test for it doesn't appear to be documented practice anywhere searched. LangChain.js's `faiss-node`/`hnswlib-node` integrations take the safer default: throw loudly when the native binding is missing, rather than silently degrading to a JS fallback β arguably the correct pattern ruflo's `graph-analyzer.ts` lacks.++## Hypothesis (frozen before evaluation)++Given a swarm using `MessageBus.broadcast()` where at least one subscriber's delivery callback throws, when `handleDeliveryError()`'s retry re-queue is changed to use the real subscriber's `agentId` (threaded through from `deliverMessage()`) instead of the literal string `'broadcast'`, then the failing subscriber should receive bounded retries up to `config.retryAttempts` and emit `message.failed` once exhausted β matching the already-correct direct-message path β subject to: zero change to happy-path (no-error) behavior, zero regression across the existing 274-test swarm suite, and a deterministic $0 Vitest evaluation.++## Benchmarks / Evaluation++Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls, against a freshly `pnpm install`-ed `v3/` workspace (not pre-built at session start).++- New test file `message-bus.broadcast-retry.test.ts` (2 tests): stash-isolated baseline (fix reverted, test kept) β both fail exactly as predicted (`badInvocations` 1 vs. expected 3; `getQueueDepth()` 1 vs. expected 0, i.e. the orphaned-queue leak). Candidate: both pass.+- Full `@claude-flow/swarm` suite: baseline 274/274 (17 files) β candidate 276/276 (18 files, +2 new), zero regressions.+- `tsc --noEmit`: clean, 0 errors, both ways.+- Healthy co-subscriber in the same broadcast delivers exactly once, unaffected by the sibling's failure β explicit regression guard in the new test.++## Darwin Results++Skipped β binary correctness/wiring fix (which queue key to re-queue under), no continuous or categorical parameter for Darwin's real interface (`npx ruvector harness darwin <config> --execute`, confirmed available v0.9.2) to search over. Same skip class as nearly every accepted fix since 2026-08-18 (#3110/.../#3909).++## SOTA Proof & Witness++See issue/PR for the full reward-hack checklist, adversarial critique, and security review. Witness stamp at the end of this file.++## Recommended Next Steps++1. **Wire the real `ruvector` npm package's `minCut`/`louvainCommunities`/`buildGraph` exports into `v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts`'s `loadRuVector()`** (currently checks for `ruvector.hooks_graph_mincut`/`ruvector.hooks_graph_cluster` and `@ruvector/wasm`'s `GraphAnalyzer` class, neither of which exists in any version of either real package β confirmed by downloading and inspecting `ruvector` 0.2.27 through 0.3.3 directly). Native-acceleration has been 100% dead code since introduction; a future `ruvector-integration` night should pick this up as its primary candidate.+2. **Add a CI contract test that imports the real `ruvector` package and asserts the exact method names `graph-analyzer.ts` expects actually exist** β would have caught tonight's #1 immediately and is cheap insurance against future API drift (no competitor precedent found for this pattern, but it's a clear gap).+3. **`AgentPool.updateAgentHeartbeat()` remains dead code** post the #3242/3243 fix that correctly stopped self-stamping β nothing in `v3/` currently calls it, so `replaceUnhealthyAgent()` only ever fires for genuinely-stale agents but no real agent's liveness is ever actually recorded via the pool's own API. Disclosed as a caveat in that PR, still unaddressed; candidate for a future `swarm` night once a concrete wiring path from `UnifiedSwarmCoordinator.handleHeartbeat()` is scoped.++## Scan Findings: ruview-integration++No real integration exists beyond a well-tested but **unwired** policy/schema module: `v3/@claude-flow/security/src/policy/product-plane.ts` defines a RuView product-plane profile (`RuViewSemanticObservationV1`, `validateRuViewSemanticObservation()`, privacy-ceiling P2/P3 enforcement) with substantive unit tests (`product-plane.test.ts`), but zero consumers anywhere in the codebase β no CLI command, MCP tool, or caller constructs or validates a real RuView observation. ADR-325 and ADR-326 (the design docs covering it) are both still **Proposed**. This is new-feature work (building a consumer), not a scoped bugfix, so it does not qualify as tonight's testable-tonight candidate β consistent with prior nights' findings on this surface.++## Scan Findings: ruvector-integration++See Recommended Next Steps #1-2. Independently confirmed by two separate reviews (this session's own package download + an independently-spawned architecture-reviewer agent reading the installed `ruvector` v0.2.41): `graph-analyzer.ts`'s `loadRuVector()` has never successfully loaded native acceleration since the file's introduction (`git log --follow` shows it was introduced whole, not regressed from a once-working state) β `analyzeMinCutBoundaries()`/`analyzeModuleCommunities()` always run the slower, approximate `fallbackMinCut`/`fallbackLouvain` JS implementations instead of the real package's exact Stoer-Wagner `minCut()` and `louvainCommunities()`. The existing test (`graph-analyzer.test.ts`'s `loadRuVector` describe block) doesn't catch this because its assertion (`result === null || typeof result === 'object'`) is trivially true either way, and its `@ruvector/wasm` mock (`{minCut, louvain}` as bare functions) doesn't match what the source code actually checks for (a `GraphAnalyzer` class with `.mincut()`/`.louvain()` methods) β so the mock never meaningfully exercises the real detection branch either.++## Competitors Reviewed++LangGraph, Microsoft Agent Framework (AutoGen successor), CrewAI, OpenAI Agents SDK, Temporal (coordination/topology); Qdrant, Weaviate, Milvus, LanceDB, LangChain.js `faiss-node`/`hnswlib-node` (native-fallback pattern, ruvector-integration scan).++## Witness++```+Session commit (STEP 0): 58e0ae7e14e68aab45a4127d6f42f567bbcfb328+Gist SHA-256 (pre-witness, this block's filled values stripped to PENDING): 3b02818262f559907245450201b00bb7742dc781270d60f3deea159fa568e1fc+Witness stamp: 1b7e818e917acd3925b622ec26d78632ab8c872dab78da3ecf97fb0da27d461c+```++Verifier: fetch this file from the branch, strip this block's filled values back to `PENDING`, SHA-256 the file, concatenate with the session commit above, SHA-256 again β must equal the witness stamp.diff --git a/v3/@claude-flow/swarm/__tests__/message-bus.broadcast-retry.test.ts b/v3/@claude-flow/swarm/__tests__/message-bus.broadcast-retry.test.tsnew file mode 100644index 0000000000..9222f4529d--- /dev/null+++ b/v3/@claude-flow/swarm/__tests__/message-bus.broadcast-retry.test.ts@@ -0,0 +1,100 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { MessageBus, createMessageBus } from '../src/message-bus.js';++// Covers the gap explicitly disclosed as a known limitation in message-bus.ts's+// handleDeliveryError() (introduced by #3562/#3563's event-driven rewrite): a+// broadcast message's retry re-queue used message.to ('broadcast') instead of+// the per-subscriber agentId enqueue() originally fanned the message out to,+// so a failing broadcast subscriber's retries β and eventual message.failed β+// were silently dropped into an orphaned, never-drained 'broadcast' queue.+describe('MessageBus - broadcast delivery retry accounting', () => {+ let bus: MessageBus;++ beforeEach(async () => {+ bus = createMessageBus({+ processingIntervalMs: 5,+ retryAttempts: 3,+ ackTimeoutMs: 1000,+ });+ await bus.initialize();+ });++ afterEach(async () => {+ await bus.shutdown();+ });++ it('bounds a failing broadcast subscriber at retryAttempts and emits message.failed, matching the direct-message path', async () => {+ let badInvocations = 0;+ let goodInvocations = 0;+ let failedEvents = 0;+ let retryEvents = 0;++ bus.on('message.failed', () => {+ failedEvents++;+ });+ bus.on('message.retry', () => {+ retryEvents++;+ });++ bus.subscribe('agent-bad', () => {+ badInvocations++;+ throw new Error('simulated handler crash');+ });+ bus.subscribe('agent-good', () => {+ goodInvocations++;+ });++ await bus.broadcast({+ type: 'direct',+ from: 'agent-sender',+ payload: { hello: 'world' },+ priority: 'normal',+ requiresAck: false,+ ttlMs: 60000,+ });++ // retryAttempts=3, processingIntervalMs=5ms β exhausting retries takes a+ // handful of ticks; this window is generous, not tight.+ await new Promise((resolve) => setTimeout(resolve, 500));++ // The failing subscriber must be retried up to the configured bound and+ // then emit message.failed β today it is delivered exactly once and then+ // silently dropped (retried into an orphaned 'broadcast' queue nobody+ // drains), so this assertion fails against the real baseline.+ expect(badInvocations).toBe(3);+ expect(retryEvents).toBe(2);+ expect(failedEvents).toBe(1);++ // The healthy subscriber in the same broadcast must be unaffected.+ expect(goodInvocations).toBe(1);++ // Counts must stay stable after the bound, not keep climbing or re-fire.+ await new Promise((resolve) => setTimeout(resolve, 300));++ expect(badInvocations).toBe(3);+ expect(retryEvents).toBe(2);+ expect(failedEvents).toBe(1);+ });++ it('does not leak an orphaned "broadcast"-keyed queue after retries resolve', async () => {+ bus.subscribe('agent-bad', () => {+ throw new Error('simulated handler crash');+ });++ await bus.broadcast({+ type: 'direct',+ from: 'agent-sender',+ payload: {},+ priority: 'normal',+ requiresAck: false,+ ttlMs: 60000,+ });++ await new Promise((resolve) => setTimeout(resolve, 500));++ // getQueueDepth() sums every live queue (not just subscribed ones) β a+ // stray 'broadcast'-keyed queue entry would otherwise sit unread forever+ // and inflate this past 0.+ expect(bus.getQueueDepth()).toBe(0);+ });+});diff --git a/v3/@claude-flow/swarm/src/message-bus.ts b/v3/@claude-flow/swarm/src/message-bus.tsindex fc039c1ee8..e698b6cd45 100644--- a/v3/@claude-flow/swarm/src/message-bus.ts+++ b/v3/@claude-flow/swarm/src/message-bus.ts@@ -546,11 +546,11 @@ export class MessageBus extends EventEmitter implements IMessageBus {to: subscription.agentId});} catch (error) {- this.handleDeliveryError(message, entry, error as Error);+ this.handleDeliveryError(message, entry, error as Error, subscription.agentId);}});} catch (error) {- this.handleDeliveryError(message, entry, error as Error);+ this.handleDeliveryError(message, entry, error as Error, subscription.agentId);}}@@ -565,7 +565,7 @@ export class MessageBus extends EventEmitter implements IMessageBus {this.emit('message.ack_failed', { messageId: message.id, error });}- private handleDeliveryError(message: Message, entry: MessageQueueEntry, error: Error): void {+ private handleDeliveryError(message: Message, entry: MessageQueueEntry, error: Error, subscriberAgentId: string): void {entry.attempts++;entry.lastAttemptAt = new Date();@@ -573,13 +573,12 @@ export class MessageBus extends EventEmitter implements IMessageBus {// Re-queue for retry, preserving the attempt count so it's bounded by// retryAttempts instead of resetting to 0 on every re-queue.//- // KNOWN LIMITATION (pre-existing, not fixed here): for a broadcast- // message, message.to stays the literal string 'broadcast' rather- // than the per-subscriber agentId enqueue() originally fanned out- // to, so this re-queues under a 'broadcast'-keyed queue nobody- // drains β a failing broadcast subscriber's retries (and eventual- // message.failed) are silently lost. Only the direct-message path- // is bounded by this fix.+ // Re-queue under the real subscriber's agentId, not message.to: for a+ // broadcast message, message.to is the literal string 'broadcast',+ // not any queue a subscription actually drains (enqueue() fanned the+ // original send out to each subscriber's own agentId-keyed queue), so+ // re-queuing under message.to would silently strand the retry in an+ // orphaned queue nobody processes.//// The re-queue itself is delayed (not just the dispatch) so the// backstop interval cannot pick the message up early either.@@ -589,7 +588,7 @@ export class MessageBus extends EventEmitter implements IMessageBus {if (this.isShutdown) {return;}- this.addToQueue(message.to, message, entry.attempts);+ this.addToQueue(subscriberAgentId, message, entry.attempts);this.scheduleProcessing();}, backoffMs);timer.unref?.();