Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 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

dream(intelligence, evaluated): #3394 fix inverted EMA direction in EWCConsolidator.updateFisherFromConfidences() (ACCEPT) (#3395)

rUva91db6768ba5
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md
index 30b735af27..db6fb6c957 100644
--- a/docs/dream-cycle/LEDGER.md
+++ b/docs/dream-cycle/LEDGER.md
@@ -192,6 +192,10 @@ as a first-class, high-priority candidate, not a background note.
| 2026-09-10 | performance | `mmrRerank()` eagerly re-tokenized every remaining candidate's content on every MMR outer-loop pass (O(N×limit) `tokenize()` calls) — a pattern that predates and survived PR #3169's embedding-cosine wiring unchanged, even though the cosine branch made that tokenization mostly discarded work in the now-common all-embedded case; made lazy and cached per-candidate | #3265 | #3266 | yes | ACCEPT | `tokenize()` calls 400→0 (N=30/limit=20 corpus, stash-isolated: fails against real baseline, passes against candidate); wall-clock 5.88x faster (0.6745ms→0.1148ms mean), independently reproduced at 5.96x by an adversarial critic; selection output byte-identical to baseline across all-embedded/none/mixed/lambda-extreme scenarios; 473/474 full-suite both ways (1 pre-existing unrelated failure), `tsc` clean | 78c074ef... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232 merges), awaiting fresh CI as of 2026-09-14 |
| 2026-09-11 | security | `hive-mind_consensus` accepted votes from any caller-supplied `voterId` with no check against `state.workers` (a single caller could cross any strategy's quorum by voting under fabricated identities β€” a Sybil attack on consensus); fail-closed roster-membership check added. **Update (ruvnet review):** REJECTed the initial scoped fix on the caveat the adversarial critic had already disclosed (`hive-mind_join`/`leave` fully unauthenticated β€” the roster itself could be Sybil'd) plus a required-CI cold-install failure (`@claude-flow/security` missing a `prepare` script, so root `npm ci` never built its dist/). Both addressed same-session: `join`/`leave`/`vote` now capability-bound to a `hiveToken` minted by `hive-mind_init` (32-byte random, constant-time comparison, fail-closed β€” zero state change for denied calls, verified via a fresh state.json reload simulating restart; a same-machine-only token reader lets the CLI's own subcommands keep working without exposing the token over any MCP response); `@claude-flow/security`'s `package.json` gained a `prepare: npm run build` so root `npm ci` builds it automatically for every consumer, not just this CI job | #3290 | #3291 | yes | ACCEPT-scoped (post-review) | stash-isolated 2/3 fail baseline (forged votes silently accepted) β†’ 3/3 pass candidate; full `@claude-flow/cli` suite failures 46β†’28 after the CI fix (remainder pre-existing/unrelated); adversarial critic CONFIRMED-WITH-CAVEATS pre-review, both caveats closed post-review | 55d67b4a... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266 merges), awaiting fresh CI as of 2026-09-14 |
| 2026-09-12 | intelligence | `LocalReasoningBank.findSimilar()` overwrote every returned pattern's `confidence` (learned reliability) with the per-query cosine similarity score instead of the already-declared `PatternMatch.similarity` field, inverting `distillLearning()`'s "only distill from high-confidence matches" gate (it tested query-similarity, not reliability) and forcing `findSimilarPatterns()`'s public API into an unsafe cast that made `confidence`/`similarity` always identical; `findSimilar()` now preserves real `confidence` and returns `similarity` separately, with the one affected consumer (`memory-bridge.ts`'s search-ranking score) migrated accordingly | #3301 | #3302 | yes | ACCEPT | 4 new discriminating tests, baseline-fails/candidate-passes via stash isolation; full suite 90-vs-91-failed-files identical except the new test file; `tsc --noEmit` byte-identical (463 errors both ways); independent adversarial critique CONFIRMED, no blocking caveats | cb60b43b... | rebased onto main (post #3086/#3094/#3103/#3110/#3119/#3123/#3130/#3139/#3152/#3160/#3232/#3266/#3291 merges), awaiting fresh CI as of 2026-09-14 |
+
+**Note (2026-09-22):** rows for 2026-09-15 (performance, #3329/#3330), 09-16 (security, #3338/#3339), 09-17 (intelligence, #3349/#3350), 09-18 (memory, #3351/#3352), 09-19 (swarm, #3356/#3357), 09-20 (performance, #3377/#3378), and 09-21 (security, #3384/#3385) all ran (verified via `git ls-remote --heads origin "dream/*"` and `list_pull_requests`/`search_pull_requests`, not inferred β€” same "rows only reach `main` via PR merge" structural gap noted since 2026-08-19) but are not transcribed as rows here, to avoid another copy stuck on another unmerged branch. All 7 are OPEN/draft, all <14d old (none stale). Trailing-7-night merge rate since the 09-14/15 backlog sweep: 0/7 β€” worth watching but not yet actionable (no single night is stale, no repeated-direction pattern).
+
+| 2026-09-22 | intelligence | `EWCConsolidator.updateFisherFromConfidences()` (`ewc-consolidation.ts`, wired into production at `intelligence.ts:413` via #3110) ran its online-Fisher EMA backwards vs. its two sibling `globalFisher`-updating methods in the same class (`computeFisherMatrix()`, `recordGradient()`) β€” new batch got 99% weight, accumulated importance got 1%, discarding ~99% of accumulated Fisher on every `distillLearning()` pass and defeating EWC++'s anti-catastrophic-forgetting purpose; flagged as lead candidate by 09-21's scan finding, independently re-verified against the code and the EWC++ literature (Chaudhry et al. ECCV 2018, arXiv:1801.10112), fixed to match the sibling sites. **Update (ruvnet evidence-gate review, same session):** initial fix REJECTed pending lifecycle hardening β€” no guard against non-finite input, a no-op update still decayed/persisted Fisher, no validation on loaded persisted state, receipt bound the pre-session base commit not the candidate. All addressed: non-finite samples dropped before folding in; zero-sample updates leave state untouched; `loadFromDisk()` validates/quarantines a malformed `globalFisher`; witness rebound to the hardened candidate commit; 3 new regression tests confirmed via stash isolation; also verified against the compiled `dist/` output directly (not just vitest's transform) | #3394 | #3395 | yes | ACCEPT-scoped (post-review) | 5 EMA-direction/consistency tests + 3 hardening regression tests (non-finite-input drop, no-op-no-persist, corrupted-state quarantine), all baseline-fails/candidate-passes via stash isolation; independently reproduced by adversarial critic pre-review (CONFIRMED) and by ruvnet's evidence-gate review post-review (REJECT β†’ all items closed); full `@claude-flow/cli` suite byte-identical 96-file failure set throughout; `tsc --noEmit` byte-identical (463 errors) throughout | fc2088df... | 09-15..09-21 (7 nights) all still open/draft, none merged since the 09-14/15 backlog sweep, none stale |
**Note (2026-09-19):** 2026-09-15 (performance, #3329/#3330), 2026-09-16 (security, #3338/#3339), 2026-09-17 (intelligence, #3349/#3350), and 2026-09-18 (memory, #3351/#3352) all exist as real branches+issues+draft-PRs (verified via `mcp__github__search_pull_requests`, not inferred) but are not transcribed as rows here β€” same "ledger rows only reach `main` via PR merge" structural gap noted repeatedly since 2026-08-19/09-03/09-05/09-09. GitHub-verified fates for the trailing 7 nights before tonight's own row (via `mcp__github__pull_request_read`, `gh` CLI unavailable this session): #3302 (09-12) **MERGED**; #3291 (09-11) **MERGED**; #3266 (09-10) **MERGED**; #3330 (09-15) OPEN/draft 4d old; #3339 (09-16) OPEN/draft 3d old; #3350 (09-17) OPEN/draft 2d old; #3352 (09-18) OPEN/draft 1d old β€” none STALE. A large batch (18 dream PRs spanning 08-14..09-12) merged together on 2026-09-14. Swarm surface specifically: #3086 (08-24), #3123 (08-29), #3243 (09-09) β€” 3/3 merged, 100% historical rate.
| 2026-09-19 | swarm | `TopologyManager.createEdgesForNode()` mirrored a new node's edge onto its connection target only for `type === 'mesh'` β€” for hierarchical/centralized/hybrid, the queen/coordinator's own `connections`/`adjacencyList` permanently never gained any worker (not just transiently stale: neither `shouldRebalance()` nor any `rebalance*()` guard, which checks the worker's side instead of the leader's, could ever repair it); fixed by mirroring whenever the connection target already exists in the topology | #3356 | #3357 | yes | ACCEPT-scoped | baseline 3/3 new tests fail (`expected [] to include`), candidate 233/233 full-suite pass (was 230/230 pre-diff), `tsc` clean; independent adversarial critique CONFIRMED β€” disclosed caveat: no shipped caller of `getNeighbors()`/`findOptimalPath()` exists yet and `swarm-tools.ts`'s `getStatus()` has a separate pre-existing type-drift bug, so the repaired state is correct/live but not yet externally visible | 2cd2ea40... | 08-24..09-12 merge status above; 09-15..09-18 still open/draft, none stale |
**No-run gap (2026-09-13, 2026-09-14):** no branch/PR/issue exists for either date (verified via `git ls-remote --heads origin "dream/*"` and `search_pull_requests`, 2026-09-18). Tonight's automation SCAN confirms no in-repo cron/workflow drives this trigger, so the gap is genuinely unexplained from repo config, not a local misconfiguration β€” same open question as the 2026-08-20..23 gap.
diff --git a/docs/dream-cycle/dream-gist-2026-09-22.md b/docs/dream-cycle/dream-gist-2026-09-22.md
new file mode 100644
index 0000000000..a9600643cb
--- /dev/null
+++ b/docs/dream-cycle/dream-gist-2026-09-22.md
@@ -0,0 +1,77 @@
+# Intelligence SOTA Report β€” 2026-09-22
+
+TL;DR: Tonight's `intelligence` deep-dive fixes an inverted exponential-moving-average (EMA) direction in `EWCConsolidator.updateFisherFromConfidences()` (`v3/@claude-flow/cli/src/memory/ewc-consolidation.ts`), the Fisher-matrix update wired into production at `intelligence.ts:413` after every SONA `distillLearning()` pass. The buggy formula gave the new batch 99% weight and the accumulated Fisher signal only 1% (`alpha*old + (1-alpha)*new`, alpha=`fisherDecayRate`=0.01) β€” inverted vs. the two sibling `globalFisher`-updating sites in the same class (`computeFisherMatrix()`, `recordGradient()`), which correctly do `(1-decay)*old + decay*new`. This defeated EWC++'s single stated purpose ("prevents catastrophic forgetting... during continual learning") on this path: importance from many prior distill passes was wiped by the very next low-signal one. Flagged as tonight's lead candidate by yesterday's security-night scan (issue #3384), independently re-verified here by reading the code directly, and confirmed against the actual EWC++ literature by tonight's research.
+
+## What's New in 2026
+
+| Finding | Source | Confidence |
+|---|---|---|
+| EWC++'s standard online-Fisher update is a slow-moving EMA β€” small weight (~0.01) on the new batch, large weight on accumulated old Fisher β€” not a per-task snapshot | Chaudhry et al., "Riemannian Walk for Incremental Learning" (coined EWC++), ECCV 2018, arXiv:1801.10112 | A |
+| `F^t = Ξ±Β·F_current + (1-Ξ±)Β·F^(t-1)` is still the reference baseline in 2025 continual-learning work; small Ξ± belongs on the *current* term | "On the Computation of the Fisher Information in Continual Learning", arXiv:2502.11756 (2025) | A |
+| Online-EWC/EWC++ remains the benchmark being critiqued (for importance-estimation quality, not EMA direction) in the newest work | "Elastic Weight Consolidation Done Right for Continual Learning", CVPR 2026 | A |
+| No mainstream agent-memory framework implements an EWC++-style parameter-layer importance EMA; the field solves "protect important memories" at the record layer instead (LLM-assigned tags, recency re-ranking, temporal validity windows) | see Competitor Comparison | A/B |
+| Mem0's own maintainers are actively debating (unresolved) the exact problem EWC++ addresses β€” importance frozen at write time vs. needing dynamic, usage-weighted importance | github.com/mem0ai/mem0 issue #5330 | B |
+
+No 2026-dated source documents this specific EMA-inversion pattern β€” a project-local defect, not a literature failure mode. The case rests on the cited papers plus internal self-consistency: the same `fisherDecayRate` field has opposite effective semantics at this one call site vs. the other two in the identical class.
+
+## Ruflo Current Capability
+
+EWC++ lives in `v3/@claude-flow/cli/src/memory/ewc-consolidation.ts` (`EWCConsolidator`), wired into the intelligence pipeline's CONSOLIDATE stage via `intelligence.ts`'s `distillLearning()`. The 2026-08-27 dream cycle (#3110, unmerged) fixed a related-but-distinct bug: `distillLearning()` was calling `getPenalty([oldConf],[newConf])` (collapses to reading `globalFisher[0]` alone) instead of `computeConfidencePenalty()` (correctly averages the full 384-dim diagonal) β€” that fix is *why* `updateFisherFromConfidences()` has a live production caller at all. Tonight's bug is one level deeper: even with the correct read path wired in, the write path building `globalFisher` was discarding ~99% of what it had already learned on every call. Three `globalFisher`-mutating methods exist; two (`computeFisherMatrix`, `recordGradient`) use the correct EMA direction, the third (`updateFisherFromConfidences`, the only one reachable from production) used the inverted one. No existing test exercised it twice from non-zero state.
+
+## Competitor Comparison
+
+| Framework | Importance/forgetting mechanism | Layer | Source | Grade |
+|---|---|---|---|---|
+| CrewAI | "Cognitive Memory" (2026): LLM-assigned importance at write time; blended similarity/recency/importance retrieval; decay+pruning | Memory record | crewai.com blog, Mar 2026 | B |
+| Mem0 | "Memory Decay" (May 2026): search-time re-rank only (1.5x/0.3x boost/damp); importance otherwise frozen at write time (open issue) | Memory record | mem0.ai blog + GitHub #5330 | B |
+| Zep / Graphiti | Bi-temporal knowledge graph, 5 forgetting mechanisms (decay, TTL, LRU, semantic importance, temporal invalidation) on graph edges | KG edge | arXiv:2501.13956 | B |
+| Letta (MemGPT) | Agent-driven, non-systematic: agent judges importance and self-edits; eviction is plain FIFO, no decay function | Agent-judged | Letta vs. Hindsight comparison, 2026 | B |
+| LangGraph (core) | None native; community `langgraph-memory` add-on does LLM-assigned importance + composite ranking | Memory record | GitHub, Mar 2026 | C |
+| AutoGen / MS Agent Framework | None shipped; biologically-inspired forgetting is external research, not integrated | β€” | github.com/microsoft/autogen #7794 | B |
+| OpenAI Agents SDK | None β€” no persistent memory by default; forgetting is total at session end, delegated to third parties | β€” | OpenAI Agents SDK docs | A |
+
+No competitor implements anything structurally like EWC++'s online-Fisher-EMA at the parameter/weight layer β€” the field solves a retrieval/pruning problem (which record to keep) rather than a continual-learning problem (how much a learned signal should move). Genuine open gap, not solved-elsewhere: unresolved even inside a well-resourced competitor (Mem0 #5330). Ruflo's approach is more rigorous for its stated goal, but the rigor was undone by an operand-order bug in the one wired-to-production write path.
+
+## Hypothesis
+
+Given `EWCConsolidator.updateFisherFromConfidences()` using an inverted EMA (`alpha*old + (1-alpha)*new`, alpha=`fisherDecayRate`=0.01, new dominates), when corrected to `(1-decay)*old + decay*new` matching the two sibling sites and the standard online-EWC/EWC++ convention, then accumulated Fisher values should persist across subsequent low-signal calls (retain β‰₯90% after 5 near-zero-signal calls, vs. ~0.01^5β‰ˆ0 under the bug) rather than being ~99% overwritten each time, subject to: (1) `computeConfidencePenalty()`'s scalar-average semantics unchanged; (2) the two correct sites untouched; (3) `fisherDecayRate`'s default (0.01) and meaning preserved, no new config knob; (4) all existing EWC/intelligence tests green; (5) deterministic, $0 evaluation. Frozen before evaluation; not modified after.
+
+## Benchmarks
+
+No existing corpus targets this call path. A new deterministic test (`__tests__/ewc-fisher-ema-direction.test.ts`) was added: (a) establishes a high Fisher signal from one batch, applies 5 near-zero-signal batches, asserts β‰₯90% retention (correct EMA retains ~95.1% at decay=0.01; the bug retained ~1.7e-9); (b) cross-checks `updateFisherFromConfidences()` vs. `recordGradient()` for numerically identical output on equivalent inputs at decay=0.25, chosen to diverge sharply if mismatched.
+
+## Evaluation
+
+**evaluated: accepted.** Real evaluator: Vitest 4.1.8, deterministic, $0, zero LLM calls. Baseline-fails/candidate-passes isolated via `git stash` (both new tests fail against baseline with a >1e9x retention discrepancy and a 3x EMA mismatch; pass against candidate). Full `@claude-flow/cli` suite both ways: failed-file set byte-identical (96 pre-existing files, same unbuilt-dist class documented every prior night) β€” zero new failures, 155/155 in EWC-adjacent tests (153 pre-existing + 2 new). `tsc --noEmit`: 463 pre-existing errors, identical both ways, none in changed files.
+
+## Darwin Results
+
+Skipped: binary EMA-direction correctness fix, not a continuous parameter with a fitness gradient β€” same skip class as #3110/#3160/#3184/#3221/#3243/#3266/#3302/#3330/#3378/#3385. Future night: `fisherDecayRate` (default 0.01) is now a legitimate Darwin-explorable parameter β€” deliberately out of scope tonight to avoid widening the hypothesis after evaluation began.
+
+## SOTA Proof & Witness
+
+**Reward hack check** (manual checklist β€” no standalone reward-hack CLI reachable in this environment): test weakening β€” none, diff purely corrective/additive; gold-data tampering β€” N/A; cherry-picking β€” none; evaluator exploitation β€” none; cost hiding β€” none, $0 deterministic. Independently re-verified by the adversarial critic, who ran every item itself.
+
+**Adversarial critique**: independent critic (no access to this session's reasoning) re-derived the bug's correctness from the two sibling `globalFisher` sites itself, independently reproduced the stash-isolated fail/pass proof from a fresh `git stash`/`vitest run`/`git stash pop` cycle, reran the regression set (155/155), and checked the EMA math by hand. **Verdict: CONFIRMED**, no blocking issues. Two non-blocking notes: no NaN/Infinity guard added (matches pre-existing sibling style, not a new gap); pre-fix persisted `.swarm/ewc-fisher.json` state (none exists here) would carry over safely β€” `resetFisher()`/`clear()` exist as an escape hatch if ever needed.
+
+**Security review**: no security-sensitive surface β€” pure internal arithmetic on an ML importance signal, no user input, no auth/filesystem/network scope change beyond the pre-existing `saveToDisk()` path (unchanged).
+
+**Promotion gate** (advisory only β€” this session does not self-promote): evaluation_complete βœ“, effect_positive βœ“, significance_sufficient βœ“ (>1e9x retention discrepancy), no_material_regression βœ“ (byte-identical 96-file failure set, 463 tsc errors both ways), tests_green βœ“ (158/158 after hardening), reward_hack_clear βœ“, critic_clear βœ“, witness_valid βœ“ (below), receipt_reproducible βœ“. **VERDICT: ACCEPT** β€” recommended for human review, not self-promoted.
+
+**Post-review hardening** (ruvnet's evidence-gate REJECT on PR #3395, at head `1cc7231`): the EMA-direction fix itself was confirmed correct (retention 1.01e-8% β†’ 95.099% after 5 low-signal updates), but `updateFisherFromConfidences()` had no defenses against malformed runtime input or a corrupted persisted state file. Fixed same-session: non-finite embedding/confidence values now drop that sample instead of poisoning the shared accumulator; a batch where no sample contributes leaves `globalFisher` and disk state untouched (previously it still decayed and persisted a no-op); `loadFromDisk()` now validates the loaded Fisher array (exact dimensions, finite, non-negative) and quarantines (resets to zero) the whole array if invalid rather than silently resuming with corrupted entries. 3 new regression tests, each independently confirmed to fail against the pre-hardening code via `git stash` isolation. 158/158 EWC-adjacent tests, full-suite failed-file set still byte-identical (96 files), `tsc --noEmit` still byte-identical (463 errors). The witness below is rebound to this hardened candidate commit rather than the pre-session base commit, per the same review's finding that the original receipt didn't bind the candidate.
+
+| Field | Value |
+|---|---|
+| Candidate commit | `290959f99a3a019f25dd046a47512a2c35c7ea41` |
+| Gist SHA-256 (pre-witness content) | `b6b2cae23b1377263fe53c08d98f68a02de0b09a83c502bf467cc5fe9c9ac5f0` |
+| Witness stamp | `fc2088df4df6d1ba3a82a499d4f5ed77199af85241091262bcd9612695ebd507` |
+
+Verifier: fetch this gist from the branch, strip the witness table's filled values back to `PENDING`, SHA-256 it, concatenate with the candidate commit, SHA-256 again β€” must equal the stamp.
+
+## Recommended Next Steps
+
+1. **This fix**: human review and merge of the linked draft PR β€” small (~10 net lines, 1 source file + 1 new test file), one conceptual change, zero regressions.
+2. **`fisherDecayRate` tuning** (future `intelligence` night): direction is now correct, so Darwin has a real continuous parameter to explore β€” is 0.01 optimal, or does another value trade off responsiveness vs. forgetting-resistance better?
+3. **`mmrRerank()` redundant cosine recomputation** (`v3/@claude-flow/memory/src/smart-retrieval.ts:286-339`, newly found tonight, distinct from the already-fixed #3266 tokenization bug): recomputes similarity against all selected items every outer-loop pass, no running-max cache β€” good `memory`/`performance`-night candidate.
+4. **HNSW binary/scalar quantization dispatch** (`v3/@claude-flow/memory/src/hnsw-index.ts:1018-1153`, re-confirmed unfixed, same bug class as the fixed product-quantization case #3093/#3094): `distance()` still falls through to generic cosine/euclidean on packed vectors, zero recall coverage. Note: a real wasm-backed RaBitQ implementation now exists (`v3/@claude-flow/cli/src/memory/rabitq-index.ts`), just not wired into this function β€” the CLAUDE.md claim is stale, not fictional.
+5. **Plugin install permission/trust-level enforcement** (`v3/@claude-flow/cli/src/commands/plugins.ts:224-320` β†’ `plugins/manager.ts:149-221`, re-confirmed unfixed): `installFromNpm()` never checks declared `permissions`/`trustLevel` against `PluginStoreConfig`; `--verify` is parsed, unused, and has no checksum/signature to check against even if wired up. Good `capabilities`/security-night candidate.
diff --git a/v3/@claude-flow/cli/__tests__/ewc-fisher-ema-direction.test.ts b/v3/@claude-flow/cli/__tests__/ewc-fisher-ema-direction.test.ts
new file mode 100644
index 0000000000..d7ddbaed22
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ewc-fisher-ema-direction.test.ts
@@ -0,0 +1,187 @@
+/**
+ * Dream Cycle 2026-09-22 (intelligence surface).
+ *
+ * `EWCConsolidator.updateFisherFromConfidences()` (memory/ewc-consolidation.ts)
+ * is the Fisher-matrix update wired into production at
+ * `intelligence.ts:413`, called after every SONA `distillLearning()` pass
+ * (see `ewc-distill-confidence-gate.test.ts`, the 2026-08-27 fix that wired
+ * it in). Before this fix, its online-EMA update used
+ * `globalFisher[i] = alpha * globalFisher[i] + (1 - alpha) * currentFisher[i]`
+ * with `alpha = fisherDecayRate` (default 0.01) β€” the OLD accumulated value
+ * got the *small* coefficient (0.01) and the new batch got the *large* one
+ * (0.99), discarding ~99% of accumulated importance on every single call.
+ *
+ * This is inverted relative to the two sibling `globalFisher` EMA sites in
+ * the same class β€” `computeFisherMatrix()` and `recordGradient()` β€” which
+ * both correctly do `(1 - decay) * old + decay * new` (decay is the weight
+ * given to the *new* batch, so old dominates and Fisher decays slowly).
+ * It also contradicts the standard online-EWC/EWC++ update rule (Chaudhry
+ * et al., "Riemannian Walk for Incremental Learning", ECCV 2018,
+ * arXiv:1801.10112; confirmed still the reference baseline as of
+ * arXiv:2502.11756, 2025), which the file's own docstring describes
+ * correctly ("Uses online averaging: F_new = alpha * F_old + (1-alpha) *
+ * F_current") but the code did not implement to match ("alpha" is bound to
+ * the *decay* config value, which should carry small weight on old, not new).
+ *
+ * Net effect of the bug: EWC++'s entire purpose ("Prevents catastrophic
+ * forgetting of important patterns during continual learning", line 3 of
+ * ewc-consolidation.ts) was defeated for this call path β€” importance
+ * accumulated over many prior distill passes was wiped by the very next
+ * low-signal one.
+ */
+import { describe, expect, it } from 'vitest';
+
+describe('#dream-2026-09-22 EWCConsolidator.updateFisherFromConfidences EMA direction', () => {
+ it('retains most of a prior high-importance signal across several subsequent low-signal calls', async () => {
+ const { EWCConsolidator } = await import('../src/memory/ewc-consolidation.js');
+ const consolidator = new EWCConsolidator({
+ dimensions: 8,
+ fisherDecayRate: 0.01,
+ storagePath: '/tmp/ewc-ema-direction-test-a.json',
+ });
+
+ // One high-magnitude, high-confidence-delta batch establishes a strong
+ // Fisher signal (the "important pattern" EWC++ should protect).
+ consolidator.updateFisherFromConfidences([
+ { id: 'important', embedding: new Array(8).fill(10), oldConf: 0.5, newConf: 0.9 },
+ ]);
+ const fisherAfterFirst = consolidator.getConsolidationStats().avgFisherValue;
+ expect(fisherAfterFirst).toBeGreaterThan(0);
+
+ // Five subsequent near-zero-signal batches (as would happen on nights
+ // where little of note gets distilled) should barely erode it β€” a slow
+ // EMA with decay=0.01 retains (1-0.01)^5 β‰ˆ 95.1% of the original value.
+ for (let i = 0; i < 5; i++) {
+ consolidator.updateFisherFromConfidences([
+ { id: 'noise', embedding: new Array(8).fill(0.001), oldConf: 0.5, newConf: 0.51 },
+ ]);
+ }
+ const fisherAfterFiveNoisyCalls = consolidator.getConsolidationStats().avgFisherValue;
+
+ // Buggy behavior retained ~(0.01)^5 of the original (effectively zero);
+ // correct behavior retains ~95%. 0.9 is a safe discriminating threshold.
+ expect(fisherAfterFiveNoisyCalls).toBeGreaterThan(fisherAfterFirst * 0.9);
+ });
+
+ it('matches the EMA direction of the sibling recordGradient()/computeFisherMatrix() update sites', async () => {
+ const { EWCConsolidator } = await import('../src/memory/ewc-consolidation.js');
+
+ const viaConfidences = new EWCConsolidator({
+ dimensions: 4,
+ fisherDecayRate: 0.25,
+ storagePath: '/tmp/ewc-ema-direction-test-b.json',
+ });
+ const viaGradient = new EWCConsolidator({
+ dimensions: 4,
+ fisherDecayRate: 0.25,
+ storagePath: '/tmp/ewc-ema-direction-test-c.json',
+ });
+
+ // Same embedding/confidence-delta shape, fed through both update paths:
+ // recordGradient() takes a raw gradient vector directly, while
+ // updateFisherFromConfidences() scales the embedding by the confidence
+ // delta first β€” so use delta=1 to make the two proxies equivalent.
+ const embedding = [2, 2, 2, 2];
+ viaConfidences.updateFisherFromConfidences([
+ { id: 'p1', embedding, oldConf: 0, newConf: 1 },
+ ]);
+ viaGradient.recordGradient('p1', embedding, true);
+
+ const statsA = viaConfidences.getConsolidationStats();
+ const statsB = viaGradient.getConsolidationStats();
+
+ // Both start from an all-zero globalFisher and observe the same single
+ // gradient-proxy sample, so a matching EMA direction must produce the
+ // same post-update Fisher value; the (now-fixed) inverted direction
+ // would instead produce dramatically different avgFisherValue for the
+ // same decay rate and inputs whenever decay != 0.5.
+ expect(statsA.avgFisherValue).toBeCloseTo(statsB.avgFisherValue, 10);
+ });
+
+ // Post-review hardening (ruvnet, PR #3395): the EMA-direction fix above was
+ // confirmed correct, but the function had no defenses against malformed
+ // runtime input or a corrupted/incompatible persisted state file. Fixed
+ // fail-closed rather than adding a follow-up candidate.
+ it('drops a sample with non-finite embedding values instead of poisoning globalFisher', async () => {
+ const { EWCConsolidator } = await import('../src/memory/ewc-consolidation.js');
+ const consolidator = new EWCConsolidator({
+ dimensions: 4,
+ fisherDecayRate: 0.5,
+ storagePath: '/tmp/ewc-ema-hardening-test-a.json',
+ });
+
+ consolidator.updateFisherFromConfidences([
+ { id: 'good', embedding: [3, 3, 3, 3], oldConf: 0.2, newConf: 0.8 },
+ ]);
+ const beforeBad = consolidator.getConsolidationStats().avgFisherValue;
+
+ consolidator.updateFisherFromConfidences([
+ { id: 'nan-embedding', embedding: [NaN, 1, 1, 1], oldConf: 0.2, newConf: 0.8 },
+ { id: 'infinite-embedding', embedding: [Infinity, 1, 1, 1], oldConf: 0.2, newConf: 0.8 },
+ { id: 'nan-confidence', embedding: [1, 1, 1, 1], oldConf: NaN, newConf: 0.8 },
+ { id: 'infinite-confidence', embedding: [1, 1, 1, 1], oldConf: 0.2, newConf: Infinity },
+ ]);
+ const afterBad = consolidator.getConsolidationStats().avgFisherValue;
+
+ // Every entry in the second batch was malformed, so none contributed a
+ // sample -- globalFisher (and avgFisherValue) must be byte-identical to
+ // before, and in particular must not have become NaN.
+ expect(afterBad).toBe(beforeBad);
+ expect(Number.isFinite(afterBad)).toBe(true);
+ });
+
+ it('leaves globalFisher and persisted state untouched when no sample contributes (all deltas zero)', async () => {
+ const { EWCConsolidator } = await import('../src/memory/ewc-consolidation.js');
+ const storagePath = '/tmp/ewc-ema-hardening-test-b.json';
+ const fs = await import('node:fs');
+ if (fs.existsSync(storagePath)) fs.unlinkSync(storagePath);
+
+ const consolidator = new EWCConsolidator({
+ dimensions: 4,
+ fisherDecayRate: 0.5,
+ storagePath,
+ });
+
+ // No prior signal established, and this batch's only entry has a zero
+ // confidence delta -- sampleCount stays 0.
+ consolidator.updateFisherFromConfidences([
+ { id: 'no-op', embedding: [5, 5, 5, 5], oldConf: 0.5, newConf: 0.5 },
+ ]);
+
+ expect(consolidator.getConsolidationStats().avgFisherValue).toBe(0);
+ // A no-contributing-sample update must not persist -- it has nothing new
+ // to record and decaying accumulated importance toward an empty batch
+ // would defeat the same anti-forgetting purpose the EMA fix restores.
+ expect(fs.existsSync(storagePath)).toBe(false);
+ });
+
+ it('quarantines a corrupted persisted globalFisher on load instead of resuming from it', async () => {
+ const { EWCConsolidator } = await import('../src/memory/ewc-consolidation.js');
+ const fs = await import('node:fs');
+ const storagePath = '/tmp/ewc-ema-hardening-test-c.json';
+
+ fs.writeFileSync(
+ storagePath,
+ JSON.stringify({
+ version: '1.0.0',
+ config: { lambda: 0.4, dimensions: 4, fisherDecayRate: 0.01 },
+ // Corrupted: a non-finite value survived a lossy JSON round-trip as
+ // `null`, and one entry is negative (impossible for a real Fisher
+ // value, which is always a sum of squares).
+ globalFisher: [1.5, null, -2, 3],
+ patterns: [],
+ consolidationHistory: [],
+ savedAt: Date.now(),
+ }),
+ );
+
+ const consolidator = new EWCConsolidator({ dimensions: 4, storagePath });
+ await consolidator.initialize();
+
+ // The whole array is quarantined (not element-by-element patched) --
+ // resuming with a zeroed Fisher is a known-safe state; silently keeping
+ // 3 of 4 "plausible-looking" values from a file already proven corrupt
+ // is not.
+ expect(consolidator.getConsolidationStats().avgFisherValue).toBe(0);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts b/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
index df33112f07..039500495b 100644
--- a/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
+++ b/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
@@ -527,7 +527,13 @@ export class EWCConsolidator {
* Called by SONA after distillLearning to track which patterns
* are important and should be protected from forgetting.
*
- * Uses online averaging: F_new = alpha * F_old + (1-alpha) * F_current
+ * Uses online averaging: F_new = (1 - decay) * F_old + decay * F_current
+ * (same convention as computeFisherMatrix()/recordGradient() above: decay
+ * is the weight given to the new batch, so a small decay β€” the default,
+ * 0.01 β€” means the accumulated Fisher decays slowly and survives many
+ * subsequent low-signal calls, per the standard online-EWC/EWC++ update
+ * rule, e.g. Chaudhry et al., "Riemannian Walk for Incremental Learning",
+ * ECCV 2018, arXiv:1801.10112).
*
* @param confidenceChanges - Array of {id, embedding, oldConf, newConf}
*/
@@ -536,35 +542,58 @@ export class EWCConsolidator {
): void {
if (confidenceChanges.length === 0) return;
- const alpha = this.config.fisherDecayRate;
+ const decay = this.config.fisherDecayRate;
const currentFisher = new Array(this.config.dimensions).fill(0);
let sampleCount = 0;
for (const change of confidenceChanges) {
if (!change.embedding || change.embedding.length === 0) continue;
+ if (!Number.isFinite(change.oldConf) || !Number.isFinite(change.newConf)) continue;
const confDelta = Math.abs(change.newConf - change.oldConf);
if (confDelta === 0) continue;
- sampleCount++;
const len = Math.min(change.embedding.length, this.config.dimensions);
- // Squared gradient proxy: embedding scaled by confidence change magnitude
+ // Squared gradient proxy: embedding scaled by confidence change magnitude.
+ // Validate the whole sample before folding any of it in -- a single
+ // non-finite embedding dimension (NaN/Infinity) must not silently poison
+ // the shared accumulator for every other pattern in this batch.
+ const sampleFisher = new Array(len);
+ let sampleValid = true;
for (let i = 0; i < len; i++) {
const grad = change.embedding[i] * confDelta;
- currentFisher[i] += grad * grad;
+ const sq = grad * grad;
+ if (!Number.isFinite(sq)) {
+ sampleValid = false;
+ break;
+ }
+ sampleFisher[i] = sq;
}
- }
+ if (!sampleValid) continue;
- if (sampleCount > 0) {
- for (let i = 0; i < this.config.dimensions; i++) {
- currentFisher[i] /= sampleCount;
+ sampleCount++;
+ for (let i = 0; i < len; i++) {
+ currentFisher[i] += sampleFisher[i];
}
}
- // Online EMA: F_new = alpha * F_old + (1-alpha) * F_current
+ // No sample contributed usable signal (all filtered out, or every delta was
+ // zero): leave globalFisher and persisted state untouched rather than
+ // decaying accumulated importance toward an empty/no-op batch.
+ if (sampleCount === 0) return;
+
for (let i = 0; i < this.config.dimensions; i++) {
- this.globalFisher[i] = alpha * this.globalFisher[i] + (1 - alpha) * currentFisher[i];
+ currentFisher[i] /= sampleCount;
+ }
+
+ // Online EMA: F_new = (1 - decay) * F_old + decay * F_current
+ for (let i = 0; i < this.config.dimensions; i++) {
+ const next = (1 - decay) * this.globalFisher[i] + decay * currentFisher[i];
+ // Defensive: never let a non-finite result (e.g. from a corrupted prior
+ // globalFisher[i]) propagate into the live signal -- keep the last known
+ // finite value instead of poisoning it further.
+ this.globalFisher[i] = Number.isFinite(next) ? next : this.globalFisher[i];
}
this.saveToDisk();
@@ -614,6 +643,22 @@ export class EWCConsolidator {
// Private Methods
// ============================================================================
+ /**
+ * Validate a loaded globalFisher candidate before trusting it: must be an
+ * array of exactly `dimensions` finite, non-negative numbers. Fisher
+ * values are sums of squares (see computeFisherMatrix/recordGradient/
+ * updateFisherFromConfidences above), so a negative or non-finite entry
+ * means the persisted file is corrupted or from an incompatible layout,
+ * not a legitimate state to resume from.
+ */
+ private isValidFisherArray(value: unknown): value is number[] {
+ return (
+ Array.isArray(value) &&
+ value.length === this.config.dimensions &&
+ value.every((v) => typeof v === 'number' && Number.isFinite(v) && v >= 0)
+ );
+ }
+
/**
* Calculate importance score for a pattern based on usage
*/
@@ -725,8 +770,15 @@ export class EWCConsolidator {
throw new Error(`Unsupported state version: ${state.version}`);
}
- // Restore state
- this.globalFisher = state.globalFisher || new Array(this.config.dimensions).fill(0);
+ // Restore the Fisher matrix, quarantining anything malformed -- wrong
+ // length, non-numeric/non-finite entries (e.g. JSON's lossy NaN/Infinity
+ // -> null round-trip), or negative values (Fisher values are sums of
+ // squares and can never legitimately be negative) -- rather than
+ // silently absorbing corrupted or truncated state into live importance
+ // tracking on restart.
+ this.globalFisher = this.isValidFisherArray(state.globalFisher)
+ ? state.globalFisher
+ : new Array(this.config.dimensions).fill(0);
// Restore patterns
this.patterns.clear();