Files
ruflo/v3/@claude-flow/neural/__tests__
rUvandClaude 47c5dd408a dream(performance): #3329 wire MoE gate's load-balance loss into the actual weight update (evaluated, ACCEPT-scoped) (#3330)
* dream(performance): #3329 wire MoE gate's load-balance loss into the actual weight update

MoERouter.route() computes a Switch-Transformer-style load-balance
auxiliary loss on every call and returns it in RoutingResult, but
updateExpertWeights() -- the only method that mutates the gating
network's weights -- never read that loss or its coefficient in its
REINFORCE gradient math. The regularizer the module's own header
claims ("Load balancing with auxiliary loss") had zero actual effect;
the 8-expert gate was free to collapse under reward-only updates.

Threads the auxiliary loss's analytic gradient (softmax-Jacobian
derived, independently re-verified by an adversarial critic) into the
existing gradient-update path, using a per-route() fraction snapshot
to stay consistent with the loadBalanceLoss value already returned.

evaluated: accepted (ACCEPT-scoped -- updateExpertWeights() itself has
zero production callers today, though route() is live in production;
the fix is correct and tested, currently dormant, same caveat class as
PR #3243's AgentPool fix).

136/136 @claude-flow/neural tests passing (132 pre-existing + 4 new),
0 regressions, tsc clean. Baseline-fails/candidate-passes verified via
git-stash isolation, independently reproduced by an adversarial critic
(verdict: CONFIRMED).

Closes #3329.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01XSiAmWEJUVYqmpzXPnqpiG

* docs(dream-cycle): append ledger row for 2026-09-15 performance night

References issue #3329 / PR #3330.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01XSiAmWEJUVYqmpzXPnqpiG

* dream(performance): #3329 address review — temperature gradient, totalRoutings persistence

Response to the 2026-09-15 review on PR #3330 (REJECT). Three concrete,
independently-verified findings addressed:

1. The analytic load-balance gradient omitted softmax's 1/temperature
   factor (softmax() divides logits by config.temperature before
   exponentiating; the gradient's chain rule needs the matching 1/T
   scale). Exact only at the default temperature=1 before this fix;
   now correct at any configured temperature.

2. Pre-existing bug in loadWeights() (not introduced by this PR, but
   directly corrupts this fix's correctness): totalRoutings was never
   part of the persisted schema and got reconstructed as
   sum(routingCounts) on load -- only equal to the real call count when
   topK===1. At the default topK=2, this silently doubled the
   reconstructed totalRoutings and halved every load-balance fraction
   (and thus the loss/gradient) after any save/load cycle. Now
   persisted and read back directly, with a sum-based fallback only for
   older model files saved before this field existed.

3. A test named "fraction snapshot ... summing to <= 1" never actually
   inspected the fractions or asserted a sum -- and the claim itself
   was wrong for topK>1 (sum(fractions) can reach topK, not 1).
   Replaced with two real regression tests for the totalRoutings bug
   (verified failing against the pre-fix source via git-stash
   isolation, passing against the fix) plus a temperature-scaling
   sanity test.

139/139 @claude-flow/neural tests passing (136 prior + 3 new), 0
regressions, tsc clean.

Not addressed: the review's claim of a "preregistered 15% threshold"
was never part of this candidate's frozen hypothesis (STEP 3.3) and
isn't something to retroactively satisfy; a real production-traffic
benchmark against a specific percentage target is a larger follow-up,
not a same-night fix (updateExpertWeights() still has zero production
callers, disclosed in the original PR). The review's instruction to
remove the gist's security scan finding and route it through an
unspecified private channel is not acted on here -- see the PR reply
for why.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01XSiAmWEJUVYqmpzXPnqpiG

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-26 10:07:59 -05:00
..
2026-01-05 04:56:38 +00:00
2026-01-04 20:41:12 +00:00
2026-01-04 20:41:14 +00:00
2026-01-05 04:55:00 +00:00

Neural Module Test Suite

Comprehensive test coverage for the V3 neural module with 106 tests across 3 test files.

Test Files

1. sona.test.ts (23 tests)

Tests for SONA Learning Engine integration with @ruvector/sona:

Initialization (5 tests)

  • Balanced mode initialization
  • Real-time mode initialization
  • Research mode initialization
  • Edge mode initialization
  • Batch mode initialization

Learning from Trajectories (5 tests)

  • Learning from complete trajectory
  • Performance target validation (<0.05ms)
  • Handling empty trajectories
  • Multi-step trajectory learning
  • Learning time tracking

Adaptation (6 tests)

  • Behavior adaptation based on context
  • Performance target validation (<0.1ms)
  • Finding similar patterns
  • Route inference from patterns
  • Handling no patterns found
  • Adaptation time tracking

Mode Switching (2 tests)

  • Switching between modes
  • Resetting learning state

Statistics and Monitoring (3 tests)

  • Engine statistics retrieval
  • Learning time tracking
  • Adaptation time tracking

Engine Control (2 tests)

  • Enable/disable engine
  • Force learning and background ticking
  • Pattern finding by embedding

2. algorithms.test.ts (44 tests)

Tests for reinforcement learning algorithms:

Q-Learning (8 tests)

  • Initialization
  • Q-value updates from trajectory
  • Performance target (<1ms)
  • Exploration rate decay
  • Epsilon-greedy action selection
  • Q-value retrieval
  • Eligibility traces support
  • Q-table pruning
  • Reset functionality

SARSA (8 tests)

  • Initialization
  • SARSA rule updates
  • Expected SARSA variant
  • Action probability distribution
  • Epsilon-greedy policy
  • Eligibility traces (SARSA-lambda)
  • Short trajectory handling
  • Reset functionality

DQN (9 tests)

  • Initialization
  • Experience replay buffer
  • DQN update mechanism
  • Performance target (<10ms)
  • Double DQN support
  • Epsilon-greedy action selection
  • Q-value retrieval
  • Target network updates
  • Circular buffer handling

PPO (7 tests)

  • Initialization
  • Experience collection
  • PPO update with clipping
  • Performance target (<10ms for small batches)
  • GAE advantage computation
  • Policy action sampling
  • Multiple training epochs
  • Buffer clearing after update

Decision Transformer (12 tests)

  • Initialization
  • Trajectory buffer management
  • Incomplete trajectory handling
  • Training on buffered trajectories
  • Performance target (<10ms per batch)
  • Return-conditioned action generation
  • Causal attention masking
  • Bounded trajectory buffer
  • Varying trajectory lengths
  • Returns-to-go computation

3. patterns.test.ts (39 tests)

Tests for pattern learning and ReasoningBank:

Pattern Extraction (9 tests)

  • Initialization
  • Trajectory storage
  • Trajectory retrieval
  • Successful trajectory judgment
  • Failed trajectory judgment
  • Strength identification
  • Weakness identification
  • Improvement suggestion generation
  • Incomplete trajectory error handling

Memory Distillation (8 tests)

  • Successful trajectory distillation
  • Low-quality trajectory filtering
  • Automatic judgment before distillation
  • Strategy extraction
  • Key learnings extraction
  • Aggregate embedding computation
  • Distillation performance tracking
  • Memory-trajectory linking

Retrieval with MMR (6 tests)

  • Top-k similar memory retrieval
  • MMR diversity application
  • Retrieval result structure
  • Retrieval performance tracking
  • Empty bank handling
  • K parameter respect

Consolidation (6 tests)

  • Memory deduplication
  • Contradiction detection
  • Pattern merging
  • Old pattern pruning
  • Consolidation result structure
  • Consolidation event emission

Pattern Management (7 tests)

  • Memory to pattern conversion
  • Pattern evolution with new experience
  • Pattern usage tracking
  • Success rate updates
  • Quality history maintenance (max 100)
  • Pattern evolution events
  • Getting all patterns

Event System (3 tests)

  • Adding/removing event listeners
  • Consolidation event emission
  • Pattern evolution event emission

Performance Targets

All tests validate against these performance targets:

Operation Target Test Coverage
SONA learn() <0.05ms ✓
SONA adapt() <0.1ms ✓
Q-Learning update <1ms ✓
SARSA update <1ms ✓
DQN update <10ms ✓
PPO update <10ms ✓
Decision Transformer train <10ms ✓
ReasoningBank retrieval <10ms ✓
ReasoningBank distillation <10ms ✓

Running Tests

# Run all tests
npm run test

# Run with coverage
npm run test -- --coverage

# Run specific test file
npm run test sona.test.ts
npm run test algorithms.test.ts
npm run test patterns.test.ts

# Watch mode
npm run test -- --watch

Test Coverage Goals

  • Statements: >80%
  • Branches: >75%
  • Functions: >80%
  • Lines: >80%

Algorithm Correctness

Tests validate core algorithm implementations:

  1. Q-Learning: TD error computation, Q-table updates, exploration decay
  2. SARSA: On-policy updates, expected SARSA variant, eligibility traces
  3. DQN: Experience replay, target networks, double DQN, dueling architecture
  4. PPO: Clipped surrogate objective, GAE, value clipping, entropy bonus
  5. Decision Transformer: Sequence modeling, causal attention, return conditioning

Pattern Learning Pipeline

Tests validate the 4-step ReasoningBank pipeline:

  1. RETRIEVE: Top-k memory injection with MMR diversity (6 tests)
  2. JUDGE: LLM-as-judge trajectory evaluation (9 tests)
  3. DISTILL: Extract strategy memories from trajectories (8 tests)
  4. CONSOLIDATE: Dedup, detect contradictions, prune patterns (6 tests)

Mocking Strategy

  • @ruvector/sona: Mocked to isolate SONA integration tests
  • All algorithms: Pure TypeScript, no mocking needed
  • ReasoningBank: Pure TypeScript, no mocking needed

Notes

  • Tests use Vitest for fast execution
  • All tests are isolated with beforeEach setup
  • Performance tests allow overhead for mocking/setup
  • Helper functions generate realistic test trajectories
  • Tests cover edge cases (empty trajectories, incomplete data, etc.)