diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md index 4a43a4d249..835b6bb694 100644 --- a/docs/dream-cycle/LEDGER.md +++ b/docs/dream-cycle/LEDGER.md @@ -288,6 +288,7 @@ as a first-class, high-priority candidate, not a background note. | 2026-11-14 | swarm | `ByzantineConsensus`/`GossipConsensus` missing the `setMaxListeners(0)` guard `RaftConsensus` already carries for its per-proposal `'consensus.achieved'` listener — carried forward/deferred since 2026-11-09 (~4.0/5), confirmed live by two independent research roles via direct reproduction (real `MaxListenersExceededWarning` captured under >10 concurrent proposals) + ruview-integration,ruvector-integration scan (ruview: confirmed stable/no-change with direct evidence; ruvector: new finding — `q-learning-router.ts` probes the wrong `@ruvector/*` package, real fix target identified but needs a native/JS-coexistence design decision, deferred) | #4988 | #4989 | yes | ACCEPT | 2 new discriminating tests, stash-isolated baseline fails 2/6 with a real captured `MaxListenersExceededWarning` for both classes → candidate 6/6 pass; full `@claude-flow/swarm` suite 382/382 (380+2 new), 0 regressions, `tsc --noEmit` clean both ways; independent adversarial critique (fresh context, independently re-ran stash isolation, 3x flakiness check, 50-concurrent-proposal stress test, grepped every other construction call site) CONFIRMED, no blocking issues; Darwin skipped (binary guard, no tunable parameter) | 0e31d2b1... | 11-08 #4910 CLOSED-not-merged; 11-09 #4908/#4927 MERGED; `dream/2026-11-10-hive-mind` #4937/#4938 MERGED; 11-11 #4960/#4961 MERGED; 11-02 #4659/#4660 still open/draft, 12d, approaching but not past the 14d stale threshold; 11-12/11-13 real pipelines confirmed (backfilled above), too recent to call fate. Prior gist (11-13, memory) scored 9/10 — same recurring <1500-word miss (1746 words tonight too, not trimmed — protecting research depth per STEP 0.6 v3.1 over the word-count point); 2+2+2+2+0+1 | **Note (2026-11-23):** direct verification tonight (`git ls-remote --heads origin "dream/*"` + `gh api search/issues` over 2026-11-19..22, both is:pr and is:issue, plus PR state checks on 2026-11-12/13/16/17/18) found: (1) a genuine 4-night no-run gap, **2026-11-19 through 11-22** — zero `dream/*` branches, zero `dream(...)` PRs, despite plenty of other repo activity those nights (releases 3.78.0→3.80.1); no in-repo cause found (checked for a workflow/scheduler/disabled-trigger artifact, found none). (2) PRs #4973 (11-12), #4983 (11-13), #5012 (11-17), #5034 (11-18) are individually `merged:false`/closed, but **not rejected** — their content (plus #4660/11-02 and two older PRs #4081/#3650) was folded into a human-driven integration PR **#5041, merged 2026-11-19T06:44:34Z** (operator comment on #5033 confirms the 11-18 fix landed via `89a00242b`). #4989 (11-14) and #5004 (11-16) merged directly/separately the same day. Net over the 10 most recent real dream-cycle nights with a PR: **0 genuinely rejected** — everything reaching evaluation either merged directly or was batch-integrated. Healthy-throughput signal, not a STEP-1.1 "zero of last 14 merged" trigger. | 2026-11-23 | memory | `ReasoningBank.detectContradictions()` (`v3/@claude-flow/neural/src/reasoning-bank.ts`) marks the lower-quality side of a contradicting memory pair `consolidated=true`, with an explicit "to exclude from retrieval" comment — but `retrieve()`/`retrieveByContent()` never checked that flag, so a self-judged-stale/contradicted memory kept being served into every future agent trajectory forever (consolidate()'s contradiction half was a no-op beyond a `getStats()` counter). Added a `.filter(c => !c.entry.consolidated)` / `.filter(e => !e.consolidated)` in both read paths; byte-identical for any entry never flagged. Independently found by two research roles (external-literature-driven Deep Researcher citing arXiv:2606.15903's "detected-but-not-enforced" failure class, and a pure-code Architecture Reviewer) before either saw the other's output. SCAN: plugins (`PluginStoreConfig`/`code-intelligence`/`ResourceLimits` dead-config findings confirmed still open; new finding — `EnhancedPluginRegistry.resolveConflict()`'s `namespace` strategy deletes the original owner key on first collision, so a 3rd colliding plugin silently reclaims the bare name, defeating the strategy for 3+-way collisions, deferred), automation (`hooks worker dispatch --priority` confirmed still dead; worker-fabricates-work anti-pattern confirmed still fixed; new finding — `DEFAULT_WORKERS` omits 5 of 12 documented worker types (`ultralearn`/`preload`/`deepdive`/`refactor`/`benchmark`), so dispatching them silently no-ops despite being advertised everywhere, deferred) | #5081 | #5082 | yes | ACCEPT | 2 new discriminating tests, stash-isolated baseline fails both exactly as predicted (1 control passes vacuously, 3/3 total); candidate 3/3 new, full `@claude-flow/neural` suite 184/184 (181 pre-existing + 3 new), `tsc --noEmit` clean both ways; independently reproduced byte-identical by a fresh-context adversarial critic, which also independently traced production-reachability (`index.ts`, 5 live MCP hook handlers, the `consolidate` background daemon) — verdict CONFIRMED, 2 non-blocking disclosed limitations (HNSW over-fetch-then-filter can under-return `k` if the over-fetched set is mostly consolidated; `usedHnsw` stats counted before the filter, cosmetic); Darwin skipped (binary guard, no tunable parameter, precedent 11-14); `harness mcp-scan`/`threat-model` MEDIUM(3)/0-high, byte-identical to baseline | 48c5020b... | See note above (11-19..22 genuine gap; 11-12/13/14/16/17/18 all real, 0 genuinely rejected — merged directly or via integration PR #5041). Prior gist (11-18, memory) scored 10/10 (2+2+2+2+1+1) — independently confirmed implemented on `main` via #5041 per the operator's own comment on #5033 | +| 2026-11-25 | performance | `AttentionCoordinator.computeAttentionScore()`'s `head?: number` param (`v3/@claude-flow/swarm/src/attention-coordinator.ts`) is never read in its body, so `multiHeadAttentionCoordination()`'s `numHeads=8` outer loop computed a byte-identical O(n²) cosine-similarity matrix 8 times and averaged 8 identical copies — a no-op. Deferred 2026-10-30 (scored 4.60/5) to keep that night's patch (same file's embedding memoization) to one conceptual change; picked up tonight. Fixed via a per-call flat `Float64Array`/`Uint8Array` memo cache indexed by `i*n+j`. **Disclosed negative result**: a string-keyed `Map` was tried first and measured *slower* than the 8x-redundant baseline at n≥400 (key-hashing cost exceeded the cheap cosine loop it replaced); switched to typed arrays, documented in-source. **Reachability correction** (disclosed, not reopening prior nights): `@claude-flow/swarm` is not a dependency of `@claude-flow/cli` or any of the 4 bundled release components — only `@claude-flow/testing` consumes it in-repo; fix is real and live within the package's own public API/tests and for direct npm consumers, but doesn't change the shipped CLI train's behavior today. SCAN: security (SSRF-via-DNS-rebind fix from 11-11 re-verified holding; new low-severity disclosed note — `getOrCreateEmbedding()`'s hash loop is uncapped-length, a minor single-call CPU-stall surface, not attacker-reachable today), hive-mind (`RaftConsensus.appendEntries()`'s legacy path still has zero log-contiguity check, confirmed unchanged since 11-10's disclosure — strong future hive-mind-DEEP candidate) | #5112 | #5113 | yes | ACCEPT | 7 new tests (2 discriminating via call-count/pair-uniqueness spies, 5 controls), stash-isolated baseline fails both discriminating tests exactly as predicted (exact 8x over-count: 200 vs 25 at n=5, 648 vs 81 at n=9) → candidate 7/7; full `@claude-flow/swarm` suite 389/389 (382+7 new), 0 regressions; `tsc --noEmit` 0 errors both ways; wall-clock (15-trial median, post-warmup) n=300 131.9ms→23.3ms (~5.7x), n=400 236.5ms→38.4ms (~6.2x); independently reproduced by a fresh-context adversarial critic (own stash/pop, own probe, own tsc/suite runs) — n=400 256.4ms→40.0ms (~6.4x, cross-validating this session's number) — verdict CONFIRMED, no blocking issues, 1 disclosed non-blocking caveat (the string-Map-slower claim wasn't independently re-run by the critic for lack of budget); `harness mcp-scan` MEDIUM(3)/0-high, byte-identical to baseline; Darwin skipped (binary guard, no tunable parameter, precedent 11-14/11-23/11-24) | ee0d1892... | 11-23 #5082 MERGED; 11-24 #5097 MERGED; 11-19..22 genuine no-run gap (already disclosed). Prior gist (11-24, swarm) scored 9/10 (2+2+2+2+1(1241 words)+0 — closes a 3rd-time-deferred dead-code finding, not a fresh discovery) | | 2026-11-24 | swarm | `QLearningRouter.initialize()`'s `@ruvector/core` native-engine probe (`v3/@claude-flow/cli/src/ruvector/q-learning-router.ts`) — deferred twice before (10-29, 11-14) under a "wrong package" framing — turns out to be one level deeper: `route()`/`update()` never read `this.ruvectorEngine` back at all, confirmed by 3 independent agents via full-class trace, so no package swap could ever have changed any routing decision; the only consumer anywhere is a cosmetic `route stats` CLI field. `@claude-flow/neural`'s real `createQLearning` confirmed API-incompatible (trajectory-batch vs. per-call string API) — not a same-night swap, closes the recurring thread as "design question, correctly deferred" rather than reopening a 3rd time. Removed the dead probe/field, documented why `useNative` stays permanently false. SCAN: ruview-integration (confirmed stable/no-change, independently re-verified against ADR-326 + product-plane.ts + the metaharness template list), ruvector-integration (no material change beyond the DEEP finding itself; quick sanity pass on tiny-dancer/learning-wasm/rabitq-wasm/mincut-bridge found nothing new) | #5096 | #5097 | yes | ACCEPT | 2 new tests (1 discriminating static source-guard — regex over the dead dynamic-import call, since `vitest.config.ts`'s `externalize-optional-deps` plugin prevents `vi.mock` from intercepting `@ruvector/*` dynamic imports, so a runtime spy can't discriminate here; 1 non-discriminating control proving route()/update() unaffected), stash-isolated baseline fails the discriminating test exactly as predicted → candidate 47/47; targeted related suite 437 passed/52 skipped vs baseline 435/52 (exactly +2, 0 regressions, 1 unrelated pre-existing failure identical both ways); `tsc --noEmit` 19 pre-existing errors byte-identical both ways, none in changed files; independent adversarial critique (fresh context, own stash/pop reproduction, own `require.resolve` check, own suite+tsc runs) CONFIRMED-WITH-CAVEATS — 1 non-blocking caveat (the static source-guard is a narrow regex, bypassable in principle by a differently-worded reintroduction, tracked not blocking); Darwin skipped (binary guard, no tunable parameter, precedent 11-14/11-23); `harness mcp-scan` 3 findings/0-high, byte-identical to baseline | c87edd85... | q-learning-router thread (10-29, 11-14) now closed as a correctly-deferred design question rather than reopened a 3rd time — see §1.1 duplicate-direction note above. Fate TBD next night. | **Note (2026-11-26):** 2026-11-25 (performance, `dream/2026-11-25-performance`, #5112/#5113) has no row below — confirmed via `list_pull_requests` that the branch and PR genuinely exist (PR OPEN/draft, unreviewed) — this is the same recurring STEP 25 live-append gap flagged by several prior nights' notes (11-12/13/16/17/18), not a new pipeline failure. Over the last 6 real nights with a PR: 11-16 #5004 MERGED, 11-17 #5012 CLOSED-not-merged, 11-18 #5034 CLOSED-not-merged, 11-23 #5082 MERGED, 11-24 #5097 MERGED, 11-25 #5113 OPEN. #5012/#5034 were both closed within 2 seconds of each other on 2026-11-19, near #5004's merge — looks like a human batch-review event, not evidence those candidates were wrong. Merge rate 3/6, not zero — no STEP 1.1 forced-small-patch trigger. | 2026-11-26 | security | `.harness/mcp-policy.json`'s `allowShell`/`allowNetwork`/`allowFileWrite:false` were purely decorative since the file was written — `policy-enforcer.ts` never read them, on the false premise (stated in both the policy's own `$comment` and the module's docstring) that shell/network/filesystem access isn't reachable from this MCP server's tool surface. Disclosed for 4 consecutive nights since 2026-10-26, never before tested — two independent research roles (Deep Researcher + Architecture Reviewer, neither saw the other's output) traced real counterexamples: `terminal_execute` (`execSync`), `http_fetch` (raw network), `hooks_fast-apply`/`hooks_codemod` (direct `writeFileSync`), all inside this MCP server's own handlers. Added a small, explicitly-traced `MCP_TOOL_CAPABILITY` table + `checkCapabilityAllowed()`, wired into `evaluateToolCall()`, denying those 4 tools when the matching flag is explicitly `false` and `RUFLO_MCP_ENFORCE_POLICY=1` is set; corrected the matching false claim in the policy file and the module docstring. Broader surface (`github-tools.ts`/`browser-tools.ts`/9 more `fetch(` files/22 more `writeFileSync` files) and the HTTP/WebSocket dispatcher (never calls this module at all) disclosed as follow-up, not fixed. SCAN: intelligence (`SONAManager`'s EWC-consolidation snapshot method implemented by only 2 of 5 SONA modes — `real-time`/`batch`/`edge` configure non-zero `ewcLambda` but never run `consolidateEWC()`, deferred), swarm (`ByzantineConsensus.handlePrePrepare()` never checks `senderId` matches the view's primary — any node's `pre-prepare` is accepted as legitimate, a PBFT leader-impersonation gap distinct from the known Raft `prevLogIndex` issue, deferred) | #5126 | #5127 | yes | ACCEPT | 12 new tests (full capability-table coverage, undefined/true-flag permissiveness, budget-isolation on denial, `memory_store` control), stash-isolated baseline fails to even load (`MCP_TOOL_CAPABILITY` undefined) → candidate 40/43 (3 pre-existing environmental failures, root-sandbox `/nonexistent-dir-xyz/` unwritable-path assumption false, reproduced identically on baseline); `tsc --noEmit` 534 pre-existing errors byte-identical both ways, 0 in changed files; independent adversarial critique (fresh context, own stash/pop reproduction, own `tsc`/mcp-scan runs, own reads of all 3 real call sites across `mcp-server.ts`/`bin/cli.js`/`bin/mcp-server.js` and all 4 tool files) CONFIRMED-WITH-CAVEATS — all non-blocking: (a) 4-tool table is narrow vs. the full traced surface, disclosed not silently safe; (c) new finding — capability denial skips budget but still forces a mandatory audit-log write, an un-rate-limited disk-write path under `auditLog:true`, tracked follow-up; (d) HTTP/WebSocket dispatcher still uncovered (pre-existing); Darwin skipped (binary guard, no tunable parameter, precedent 11-14/11-23/11-24/11-25); `harness mcp-scan`/`threat-model` MEDIUM(3)/0-high / clean, byte-identical to baseline | 29d887c8... | See note above (11-25 ledger-append gap confirmed cosmetic via `list_pull_requests`, not a pipeline failure). Prior gist (11-25, performance) scored 9/10 (2+2+2+2+1+0 — valid-looking witness, <1500 words, but a pickup of a previously-deferred 10-30 finding, not genuinely novel) | diff --git a/docs/dream-cycle/dream-gist-2026-11-25.md b/docs/dream-cycle/dream-gist-2026-11-25.md new file mode 100644 index 0000000000..f680025e57 --- /dev/null +++ b/docs/dream-cycle/dream-gist-2026-11-25.md @@ -0,0 +1,69 @@ +# Performance SOTA Report — 2026-11-25 + +TL;DR: `AttentionCoordinator.multiHeadAttentionCoordination()` (`v3/@claude-flow/swarm/src/attention-coordinator.ts`) ran a 2026-era "multi-head attention" loop whose per-head differentiator (`head: number`) was never actually read, so all 8 heads computed byte-identical O(n²) cosine-similarity scores and averaged 8 identical copies — pure wasted work. Fixed by memoizing each `(i,j)` pair's score once per call. Deferred twice: 10-30 scored it 4.60/5 and deliberately held it back to keep that night's patch to one conceptual change; tonight picks it up. A naive string-keyed cache was tried first and *measured slower* than the original bug at scale — a real, disclosed negative result folded into the final fix. + +## What's New in 2026 + +| Finding | Source | Confidence | +|---|---|---| +| Qdrant ships a `full_scan_threshold` (default 10,000) that brute-forces below that vector count instead of building HNSW | Qdrant official docs | A | +| "Representational Collapse in Multi-Agent LLM Committees" — mean pairwise cosine similarity 0.888 across 3-agent runs; diversity-weighted consensus beats self-consistency by ~3pp at −26% tokens | arXiv:2604.03809 (preprint) | B/C — single source, author discloses 1–3pt run variance | +| Multi-head dimension-splitting faults are a documented class of attention implementation bug (24% of surveyed faults) | arXiv:2508.04925 (survey) | B | +| "Multi-Head Attention Is a Multi-Player Game" — gradient descent itself can yield redundant/dead heads under training | arXiv:2602.00861 (Jan 2026) | B/C — tangential, a training-dynamics finding, not an implementation-defect match | + +No paper names "unused head-differentiation parameter causing 8x redundant computation" directly — the closest matches are a general dimension-splitting-fault taxonomy (B) and representational-collapse framing for *why* multi-agent output diversity matters (B/C). This is a correctness/implementation bug, not a researched-and-rejected design tradeoff. + +## Ruflo Current Capability + +`AttentionCoordinator` implements 6 coordination mechanisms over multiple agents' outputs (flash/multi-head/linear/hyperbolic/moe/graph-rope). `multiHeadAttentionCoordination()` is reachable via the public `coordinateAgents(outputs, 'multi-head')` API and exercised by its own package's tests, but — a correction worth disclosing plainly — `@claude-flow/swarm` is **not currently a dependency of `@claude-flow/cli`** or any of the four bundled release components (`security`, `codex`, `mcp`, `plugin-agent-federation`); its only in-repo consumer is `@claude-flow/testing`. So tonight's fix is real, live within the package's own public API and test suite (and reachable by anyone installing `@claude-flow/swarm` directly from npm), but it does not currently change behavior exercised by the shipped `ruflo`/`claude-flow` CLI train. Disclosing this now rather than carrying forward the more generous "every coordination mechanism calls it" framing some earlier nights used for this same file. + +## Competitor Comparison + +| Framework | Multi-output-weighting/attention mechanism? | Perf characteristics | Grade | +|---|---|---|---| +| LangGraph | No native one — reducers are generic merge functions; weighted aggregation is user-written | None documented (cost is whatever the custom reducer does) | C | +| AutoGen / AG2 | No — `GroupChatManager` selects ONE next speaker via an LLM call, doesn't blend multiple outputs | AG2 docs claim fewer LLM calls than alternatives (vendor-stated) | B/C | +| CrewAI | No — hierarchical manager delegates/validates, no scored blend of worker outputs | Independent write-ups report delegation-loop reliability issues (not a redundant-compute one) | C | +| OpenAI Agents SDK | No — handoffs transfer control to one target; combining sub-agent outputs is a known manual workaround (see GH issue #2056 on `openai-agents-python`) | Not perf-characterized; a documented gap | C | + +Why every row is "No": this is a real architectural split, not an oversight. LangGraph/AutoGen/CrewAI/OpenAI's SDK are all supervisor/handoff-pattern frameworks — each step picks ONE next actor rather than computing a weighted blend across simultaneous agent outputs. True weighted multi-agent-output attention shows up only in emerging academic work (e.g. ICLR 2026 "Graph-of-Agents", arXiv:2607.23678's adaptive attention orchestration) — a research-frontier pattern, not something competitors solved and declined to ship. That raises the bar for Ruflo's own implementation to be *correct*, since nothing else validates it by comparison. + +## Hypothesis + +> Given a call to `AttentionCoordinator.coordinateAgents(outputs, 'multi-head')` with `n` agent outputs, when `computeAttentionScore(i, j)` is memoized once per call (flat `Float64Array`/`Uint8Array` cache indexed by `i*n+j`, not a string-keyed `Map`) and reused across all 8 heads instead of recomputed per head, then `computeAttentionScore` call count should drop from `numHeads·n²` to `n²` and wall-clock latency should improve materially at n≥300, subject to: `attentionWeights`/`consensusOutput`/`confidence` output is unchanged (within floating-point tolerance) for every input, the cache is never reused across separate `coordinateAgents()` calls, and all other mechanisms (flash/linear/hyperbolic/moe/graph-rope) are untouched. + +## Benchmarks + +Vitest 4.1.8, `@claude-flow/swarm`, run directly against `src/` (package has no build-dependency on the monorepo's unbuilt `dist/` output). + +- **Call count** (deterministic, zero timing noise): baseline `numHeads·n²` exactly (e.g. n=20 → 3200 calls; n=100 → 80000); candidate `n²` exactly (n=20 → 400; n=100 → 10000) — an exact 8x reduction, independently stash-verified both directions. +- **Wall-clock** (median of 15 trials after JIT warmup, same sandbox, back-to-back stash/pop): n=300 baseline 131.9ms → candidate 23.3ms (~5.7x); n=400 baseline 236.5ms → candidate 38.4ms (~6.2x, min 228.4ms→36.1ms ~6.3x). At n≤100 the effect is swamped by sandbox scheduling/GC noise and is not a reliable signal — disclosed rather than cherry-picked. +- **Negative result, disclosed**: a first implementation used a string-keyed `Map` for the cache. At n≥400 this was measured *slower* than the original 8x-redundant baseline (per-pair template-string allocation + hashing cost more than `computeAttentionScore`'s own O(64)-float cosine loop, since `getOrCreateEmbedding()` is already memoized from 2026-10-30). Switched to index-addressed typed arrays, which eliminated the regression. Kept in-source as a code comment so this isn't rediscovered. + +## Evaluation + +7 new tests (2 discriminating via call-count/pair-uniqueness spies, 5 controls including a hand-computed ground-truth comparison and cross-mechanism sanity checks). Stash-isolated baseline: the 2 discriminating tests fail exactly as predicted (200 calls vs expected 25 at n=5; 648 pairs vs expected 81 at n=9 — i.e., exactly 8x over-count), the 5 controls pass vacuously either way. Candidate: 7/7 new, full `@claude-flow/swarm` suite 389/389 (382 pre-existing + 7 new), 0 regressions. `tsc --noEmit -p .`: 0 errors, both before and after. `harness mcp-scan .`: MEDIUM (3 findings, 0 high) — byte-identical to every recent night's baseline (candidate touches no `.claude/settings.json` or dependency manifest). Independently reproduced by a fresh-context adversarial critic (own stash/pop cycle, own throwaway probe): n=400 baseline median 256.4ms → candidate median 40.0ms (~6.4x), cross-validating this session's own 6.2x at the same n. Verdict: **CONFIRMED**, no blocking issues; one disclosed non-blocking caveat (the string-keyed-Map-is-slower claim above is plausible but was not independently re-run by the critic for lack of budget). + +## Darwin Results + +**Skipped — binary guard, no tunable parameter**, same precedent as 2026-11-14/11-23/11-24. The fix has a single discrete design choice (typed-array cache vs. string-keyed `Map`), already resolved by direct measurement above, not a continuous parameter space. + +## SOTA Proof & Witness + +``` +Session commit: f8a62a5f0ea4fa83b9fa7f5dc10acfe9ce0e8876 +Candidate commit: 07ce6dbf1b6cc38265ef0586ed692835577690f0 +Gist SHA-256 (pre-witness): c2ec634dc50819187b0ee1895157d6e67321934799ac6e8d9ffae8ee2c82ea20 +Witness stamp: ee0d1892be90e8d3ba60647ae232ca463705eaae8ac48ac75c9f5f1f3e259a22 +``` +Verifier: fetch this file from the branch, replace only the Gist SHA-256 and Witness stamp fields above with the literal text `PENDING` (Session/Candidate commit stay as-is — they were already fixed at hash time), SHA-256 the result, concatenate that hash with the Session commit value, SHA-256 again — must equal the Witness stamp. + +Evaluation receipt identity: `v3/@claude-flow/swarm/__tests__/attention-coordinator-multihead-memoization.test.ts` at the candidate commit. Flywheel evidence identity: issue #5112 + this gist + the independent adversarial critique described in the Evaluation section above. No Darwin lineage (skipped, binary guard). + +## Recommended Next Steps + +1. **AgentDB backend has no size-based brute-force bypass below the measured HNSW crossover** (N≈5k–20k per `v3/CLAUDE.md`'s own perf table) — `v3/@claude-flow/memory/src/agentdb-backend.ts`'s `searchWithAgentDB`. Confirmed still open tonight (grep of current `lines ~862-885`). Scored 4.50/5 — strongest next-night performance pick, deferred because the threshold is a judgment call (trades exactness vs. speed below crossover) rather than a byte-identical fix. +2. **Score-symmetry exploitation**: `computeAttentionScore(i,j) == computeAttentionScore(j,i)` exactly (cosine + symmetric confidence average), so tonight's fix still computes the full n×n matrix instead of the upper triangle — combining with tonight's fix would yield a further ~2x (combined ~16x total). Deferred to keep tonight's patch to one conceptual change; a clean, low-risk follow-up. +3. **`.harness/mcp-policy.json`'s false zero-shell/zero-network claim** remains open (4th consecutive disclosure since 10-26, still not re-raised as a fresh finding, flagged again only because this is now a multi-week-standing design question needing a human decision, not an oversight). + +**Security/hive-mind scan (disclosed, not implemented tonight):** security — SSRF-via-DNS-rebind fix (11-11) confirmed still holding; new low-severity hardening note: `getOrCreateEmbedding()`'s synthetic-hash loop is O(content.length) with no cap, a minor single-call CPU-stall surface for a pathologically large `AgentOutput.content` (not currently attacker-reachable in any call site). hive-mind — `RaftConsensus.appendEntries()`'s legacy path still has zero log-contiguity/prevLogIndex check (confirmed via direct code read, unchanged since 11-10's disclosure) — strong candidate for a future hive-mind-DEEP night. diff --git a/v3/@claude-flow/swarm/__tests__/attention-coordinator-multihead-memoization.test.ts b/v3/@claude-flow/swarm/__tests__/attention-coordinator-multihead-memoization.test.ts new file mode 100644 index 0000000000..b58e1805f1 --- /dev/null +++ b/v3/@claude-flow/swarm/__tests__/attention-coordinator-multihead-memoization.test.ts @@ -0,0 +1,131 @@ +/** + * AttentionCoordinator.multiHeadAttentionCoordination() redundant-head fix + * + * computeAttentionScore()'s `head` parameter is never read in its body, so + * every one of the numHeads=8 outer-loop iterations computed a byte-identical + * O(n^2) cosine-similarity matrix, then averaged 8 identical copies (a no-op). + * Fixed by memoizing each (i, j) pair's score once per + * multiHeadAttentionCoordination() call (flat typed-array cache, not a + * string-keyed Map — a string-keyed Map was measured slower than the + * original redundant loop at n>=400, since getOrCreateEmbedding() is already + * memoized and the per-pair cosine work is cheap relative to string-key + * hashing). Deferred 2026-10-30 (scored 4.60/5) to keep that night's patch to + * one conceptual change; picked up directly tonight. + */ + +import { describe, it, expect } from 'vitest'; +import { AttentionCoordinator, type AgentOutput } from '../src/attention-coordinator.js'; + +function makeOutputs(n: number, contentFn?: (i: number) => string): AgentOutput[] { + return Array.from({ length: n }, (_, i) => ({ + agentId: `agent-${i}`, + content: contentFn ? contentFn(i) : `agent ${i} output content for coordination test, varied length ${'x'.repeat(i % 7)}`, + confidence: 0.5 + (i % 5) / 10, + })); +} + +describe('AttentionCoordinator multi-head redundant-score memoization', () => { + it('[discriminating] computeAttentionScore is called exactly n^2 times, not numHeads*n^2', async () => { + for (const n of [5, 12, 23]) { + const coordinator = new AttentionCoordinator(); + let calls = 0; + const original = (coordinator as any).computeAttentionScore.bind(coordinator); + (coordinator as any).computeAttentionScore = (...args: unknown[]) => { + calls++; + return original(...args); + }; + + await coordinator.coordinateAgents(makeOutputs(n), 'multi-head'); + + expect(calls).toBe(n * n); + } + }); + + it('[discriminating] each unique (i, j) pair is scored exactly once per call', async () => { + const n = 9; + const coordinator = new AttentionCoordinator(); + const seenPairs: Array<[AgentOutput, AgentOutput]> = []; + const original = (coordinator as any).computeAttentionScore.bind(coordinator); + (coordinator as any).computeAttentionScore = (a: AgentOutput, b: AgentOutput) => { + seenPairs.push([a, b]); + return original(a, b); + }; + + const outputs = makeOutputs(n); + await coordinator.coordinateAgents(outputs, 'multi-head'); + + const pairKeys = new Set(seenPairs.map(([a, b]) => `${a.agentId},${b.agentId}`)); + expect(pairKeys.size).toBe(seenPairs.length); // no (i, j) pair repeats + expect(seenPairs.length).toBe(n * n); // every ordered pair, including i === j, covered once + }); + + it('[control] output is mathematically unaffected: equals a single (non-redundant) pass, not an average of 8 identical copies', async () => { + const n = 6; + const outputs = makeOutputs(n); + const coordinator = new AttentionCoordinator(); + + const result = await coordinator.coordinateAgents(outputs, 'multi-head'); + + // Ground truth: compute the single-head attention weights directly via + // the same private helper, bypassing the multi-head loop entirely. + const expectedWeights = outputs.map((_, i) => { + let sum = 0; + for (let j = 0; j < n; j++) { + sum += (coordinator as any).computeAttentionScore(outputs[i], outputs[j]); + } + return sum / n; + }); + + for (let i = 0; i < n; i++) { + expect(result.attentionWeights[i]).toBeCloseTo(expectedWeights[i], 10); + } + }); + + it('[control] output is stable and deterministic across repeated calls with equivalent inputs', async () => { + const outputs = makeOutputs(8); + + const run1 = await new AttentionCoordinator().coordinateAgents( + outputs.map((o) => ({ ...o })), + 'multi-head' + ); + const run2 = await new AttentionCoordinator().coordinateAgents( + outputs.map((o) => ({ ...o })), + 'multi-head' + ); + + expect(run1.attentionWeights).toEqual(run2.attentionWeights); + expect(run1.confidence).toBeCloseTo(run2.confidence, 10); + expect(run1.consensusOutput).toEqual(run2.consensusOutput); + }); + + it('[control] a fresh per-call cache does not leak state across separate coordinateAgents() calls', async () => { + const coordinator = new AttentionCoordinator(); + const first = makeOutputs(5, (i) => `first batch content ${i}`); + const second = makeOutputs(5, (i) => `completely different second batch content ${i}`); + + const r1 = await coordinator.coordinateAgents(first, 'multi-head'); + const r2 = await coordinator.coordinateAgents(second, 'multi-head'); + + expect(r1.attentionWeights).not.toEqual(r2.attentionWeights); + }); + + it('[control] other mechanisms (flash, linear, hyperbolic, graph-rope, moe) are untouched by this change', async () => { + const coordinator = new AttentionCoordinator(); + const outputs = makeOutputs(5); + + for (const mechanism of ['flash', 'linear', 'hyperbolic', 'graph-rope', 'moe'] as const) { + const result = await coordinator.coordinateAgents(outputs, mechanism); + expect(result.success).toBe(true); + expect(result.attentionWeights).toHaveLength(5); + } + }); + + it('[control] n=0 and n=1 edge cases do not throw', async () => { + const coordinator = new AttentionCoordinator(); + + await expect(coordinator.coordinateAgents([], 'multi-head')).resolves.toMatchObject({ success: true }); + await expect(coordinator.coordinateAgents(makeOutputs(1), 'multi-head')).resolves.toMatchObject({ + success: true, + }); + }); +}); diff --git a/v3/@claude-flow/swarm/src/attention-coordinator.ts b/v3/@claude-flow/swarm/src/attention-coordinator.ts index 2916c5866a..76a9e867cb 100644 --- a/v3/@claude-flow/swarm/src/attention-coordinator.ts +++ b/v3/@claude-flow/swarm/src/attention-coordinator.ts @@ -445,13 +445,40 @@ export class AttentionCoordinator extends EventEmitter { // Multi-head attention computation const headOutputs: number[][] = []; + // computeAttentionScore's `head` parameter is never read in its body, so + // every head's score for a given (i, j) pair is byte-identical — the + // numHeads-iteration outer loop below previously recomputed the same + // O(n^2) cosine-similarity matrix numHeads times for a result that's + // mathematically a no-op average of numHeads identical copies. Memoize + // each pair's score once per call (not across calls — fresh typed arrays + // per invocation, since inputs are fixed for the duration of this + // synchronous computation) and reuse it for every head, preserving the + // exact original summation/division arithmetic byte-for-byte. + // + // A string-keyed Map (`${i},${j}`) was tried first and measured SLOWER + // than the original 8x-redundant loop at n>=400: per-pair template- + // string allocation + hashing cost more than computeAttentionScore's own + // cheap O(headDim) cosine loop, since getOrCreateEmbedding() is already + // memoized (2026-10-30 fix). Flat index-addressed typed arrays avoid any + // string allocation or hashing, so the cache itself is cheaper than the + // work it replaces. + const pairScoreCache = new Float64Array(n * n); + const pairScoreSeen = new Uint8Array(n * n); + const getScore = (i: number, j: number): number => { + const idx = i * n + j; + if (!pairScoreSeen[idx]) { + pairScoreCache[idx] = this.computeAttentionScore(agentOutputs[i], agentOutputs[j]); + pairScoreSeen[idx] = 1; + } + return pairScoreCache[idx]; + }; + for (let h = 0; h < numHeads; h++) { const headWeights = new Array(n).fill(0); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { - const score = this.computeAttentionScore(agentOutputs[i], agentOutputs[j], h); - headWeights[i] += score; + headWeights[i] += getScore(i, j); } headWeights[i] /= n; }