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

feat(intelligence): per-task bandit priors (ADR-142) + honest EWC/HNSW/MicroLoRA labeling (3.10.9) (#2231)

rUv313f2f88e0d1
diff --git a/docs/reviews/intelligence-system-audit-2026-05-29.md b/docs/reviews/intelligence-system-audit-2026-05-29.md
index 9eab84316e..64d57a4ca8 100644
--- a/docs/reviews/intelligence-system-audit-2026-05-29.md
+++ b/docs/reviews/intelligence-system-audit-2026-05-29.md
@@ -110,3 +110,12 @@ What does **not** hold up is the **performance-multiplier marketing**: the HNSW
- **EWC++ "Fisher information" is a proxy** (`|w|`/`embeddingΒ²`, not gradient curvature) β€” functional regularizer; relabeling vs. real gradient-Fisher is a design decision, deferred.
- **Bandit priors global-per-model, not per-task** β€” making them per-task changes the **persisted state schema** (`priors` β†’ per-task-bucket map), so it needs an ADR + migration, not a patch. Deferred to a dedicated change.
- **Embedding ONNX broken without native `sharp`** β€” now *observable* (3.10.7 `backend:mock`); a sharp-free transformers path / bundled binary is the real fix, deferred.
+
+### Shipped in v3.10.9
+- βœ… **Per-task bandit priors** (ADR-142) β€” Beta priors now keyed by complexity bucket (low/med/high) instead of global-per-model, so failures on one task type no longer suppress a model for all types. Backward-compatible schema migration (v1 flat β†’ seed all buckets). Proven by a per-bucket isolation test.
+- βœ… **EWC++ "Fisher" honesty** β€” header doc now states `F_i` is a heuristic embedding-importance proxy (`embedding_i^2`), not true gradient-curvature Fisher.
+- βœ… **HNSW backend label honesty** β€” `getStatus().backend` relabeled: `ruvector-native` (the healthy fast path) vs `ruvector-stub-search-disabled`. `isWasm()===true` means the broken stub (search returns []), NOT acceleration β€” so a regression into it is now visible instead of mistaken for a faster mode.
+
+### Re-confirmed NOT fixable here (honest ceilings)
+- **WASM-accelerated HNSW** β€” there is NO WASM HNSW build in the installed stack (`ruvector`'s `isWasm()` flags the do-nothing stub). Native NAPI is already the fastest backend; measured ~1.9x–6.5x at N=20k (recall ~0.9), and "150x-12,500x" is unreachable here (would need N in the millions / a different build). `wasmAccelerated:false` is the correct, healthy state. No code change can raise this ceiling; docs already state it honestly.
+- **WASM MicroLoRA `apply()`** β€” empirically still inert AFTER the `applyUpdates()` flush (measured maxAbsDelta = 0 after 200 adapts in `@ruvector/[email protected]`). The genuine signature bug (the wrapper passed a `Float32Array` where the runtime wants a scalar learning rate) is fixed, but inference output does not change. We deliberately do NOT synthesize a gradient from the scalar quality signal to make output "move" β€” that would be a fabricated signal (the same class of dishonesty as the Flash `Math.random` metric). MicroLoRA adaptation is documented as a no-op on inference until the WASM backend flushes B or a caller supplies real gradients. Routing to the real JS `LoraAdapter` is possible but only legitimate with real gradients, not scalar-quality.
diff --git a/package-lock.json b/package-lock.json
index 3026bce16b..3a67c2702e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "claude-flow",
- "version": "3.10.8",
+ "version": "3.10.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-flow",
- "version": "3.10.8",
+ "version": "3.10.9",
"license": "MIT",
"dependencies": {
"@claude-flow/cli-core": "^3.7.0-alpha.5",
diff --git a/package.json b/package.json
index c310d4c32e..710a8b76d2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.10.8",
+ "version": "3.10.9",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
diff --git a/ruflo/package.json b/ruflo/package.json
index dbea299eb8..f942cedcf7 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.10.8",
+ "version": "3.10.9",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/v3/@claude-flow/cli/__tests__/router-bandit.test.ts b/v3/@claude-flow/cli/__tests__/router-bandit.test.ts
index cbfd2ab604..d95a694871 100644
--- a/v3/@claude-flow/cli/__tests__/router-bandit.test.ts
+++ b/v3/@claude-flow/cli/__tests__/router-bandit.test.ts
@@ -1,10 +1,12 @@
/**
- * Thompson sampling bandit β€” convergence tests for the cost-adjusted router.
+ * Thompson sampling bandit β€” convergence + per-bucket isolation tests.
*
* What this proves: given an environment where Haiku is the right answer for
- * low-complexity tasks (matching the live observation that avg complexity is
- * ~0.30 but the deterministic router picks Opus 77% of the time), the bandit
- * converges to Haiku within ~50 trials and shifts the distribution decisively.
+ * low-complexity tasks, the bandit converges to Haiku and shifts the
+ * distribution decisively. As of ADR-142 the priors are keyed by complexity
+ * bucket (low/med/high), so outcomes on one task type no longer suppress a
+ * model for all task types β€” the tests below assert that isolation and that
+ * old flat-shaped state files migrate forward losslessly.
*
* The test environment is a deterministic outcome simulator β€” we know which
* model is "right" for a synthetic task and feed that back via recordOutcome.
@@ -13,7 +15,7 @@
*/
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
-import { rmSync, mkdtempSync } from 'node:fs';
+import { rmSync, mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ModelRouter } from '../src/ruvector/model-router.js';
@@ -32,14 +34,25 @@ function cleanupTempCwd(): void {
rmSync(tmpDir, { recursive: true, force: true });
}
-/**
- * Synthetic outcome oracle. Models reality where:
- * - Haiku has 80% success on simple tasks (complexity < 0.4)
- * - Sonnet has 80% success on medium tasks (0.4–0.7)
- * - Opus has 80% success on complex tasks (> 0.7)
- * - Wrong-tier on simple β†’ Opus succeeds anyway but we score it as
- * "escalated" for the bandit (cost-suboptimal even when correct).
- */
+/** The complexity bucket a task maps to β€” mirrors model-router's bands so the
+ * test queries the exact bucket recordOutcome wrote to. */
+function bucketOf(router: ModelRouter, task: string): 'low' | 'med' | 'high' {
+ const s = router.analyzeComplexity(task).score;
+ return s < 0.4 ? 'low' : s < 0.7 ? 'med' : 'high';
+}
+
+/** Sum Ξ±/Ξ² across all three buckets per model β€” recovers the total Bernoulli
+ * accounting regardless of which bucket each task landed in. Baseline is
+ * {alpha:3,beta:3} per model (3 buckets Γ— uniform {1,1}). */
+function aggregatePriors(router: ModelRouter) {
+ const b = router.getBucketedPriors();
+ const sum = (m: 'haiku' | 'sonnet' | 'opus') => ({
+ alpha: b.low[m].alpha + b.med[m].alpha + b.high[m].alpha,
+ beta: b.low[m].beta + b.med[m].beta + b.high[m].beta,
+ });
+ return { haiku: sum('haiku'), sonnet: sum('sonnet'), opus: sum('opus') };
+}
+
function syntheticOutcome(
model: 'haiku' | 'sonnet' | 'opus',
complexity: number,
@@ -47,32 +60,33 @@ function syntheticOutcome(
): 'success' | 'failure' | 'escalated' {
const optimal = complexity < 0.4 ? 'haiku' : complexity < 0.7 ? 'sonnet' : 'opus';
if (model === optimal) return rng() < 0.8 ? 'success' : 'failure';
- // Bigger model on smaller task: succeeds but counts as "escalated"
- // (cost-suboptimal). Smaller model on bigger task: high failure rate.
const tierGap = ['haiku', 'sonnet', 'opus'].indexOf(model)
- ['haiku', 'sonnet', 'opus'].indexOf(optimal);
if (tierGap > 0) return rng() < 0.7 ? 'escalated' : 'success';
return rng() < 0.3 ? 'success' : 'failure';
}
-describe('ModelRouter β€” Thompson sampling bandit (#1772)', () => {
+describe('ModelRouter β€” Thompson sampling bandit (#1772, ADR-142 bucketed)', () => {
beforeEach(setupTempCwd);
afterEach(cleanupTempCwd);
- it('starts with uniform Beta(1,1) priors on every model', () => {
+ it('starts with uniform Beta(1,1) priors in every bucket', () => {
const router = new ModelRouter();
- const priors = router.getBanditPriors();
- expect(priors.haiku).toEqual({ alpha: 1, beta: 1 });
- expect(priors.sonnet).toEqual({ alpha: 1, beta: 1 });
- expect(priors.opus).toEqual({ alpha: 1, beta: 1 });
+ const b = router.getBucketedPriors();
+ for (const bucket of ['low', 'med', 'high'] as const) {
+ expect(b[bucket].haiku).toEqual({ alpha: 1, beta: 1 });
+ expect(b[bucket].sonnet).toEqual({ alpha: 1, beta: 1 });
+ expect(b[bucket].opus).toEqual({ alpha: 1, beta: 1 });
+ }
});
- it('updates priors via cost-adjusted Bernoulli on recordOutcome', () => {
+ it('updates priors via cost-adjusted Bernoulli on recordOutcome (within one bucket)', () => {
const router = new ModelRouter();
- router.recordOutcome('simple task', 'haiku', 'success'); // reward 1.0 β†’ Ξ± += 1
- router.recordOutcome('simple task', 'opus', 'success'); // reward 0.4 β†’ Ξ± += 0.4
- router.recordOutcome('failure case', 'haiku', 'failure'); // reward 0 β†’ Ξ² += 1
- const p = router.getBanditPriors();
+ const task = 'simple task'; // all updates land in this task's bucket
+ router.recordOutcome(task, 'haiku', 'success'); // reward 1.0 β†’ Ξ± += 1
+ router.recordOutcome(task, 'opus', 'success'); // reward 0.4 β†’ Ξ± += 0.4
+ router.recordOutcome(task, 'haiku', 'failure'); // reward 0 β†’ Ξ² += 1
+ const p = router.getBanditPriors(bucketOf(router, task));
expect(p.haiku.alpha).toBeCloseTo(2.0, 5);
expect(p.haiku.beta).toBeCloseTo(2.0, 5);
expect(p.opus.alpha).toBeCloseTo(1.4, 5);
@@ -83,7 +97,7 @@ describe('ModelRouter β€” Thompson sampling bandit (#1772)', () => {
const router = new ModelRouter();
router.recordOutcome('t', 'sonnet', 'escalated'); // reward 0.1
router.recordOutcome('t', 'haiku', 'escalated'); // reward 0.0
- const p = router.getBanditPriors();
+ const p = router.getBanditPriors(bucketOf(router, 't'));
expect(p.sonnet.alpha).toBeCloseTo(1.1, 5);
expect(p.sonnet.beta).toBeCloseTo(1.9, 5);
expect(p.haiku.alpha).toBeCloseTo(1.0, 5);
@@ -93,21 +107,47 @@ describe('ModelRouter β€” Thompson sampling bandit (#1772)', () => {
it('persists and reloads priors across router instances', () => {
const router1 = new ModelRouter();
for (let i = 0; i < 10; i++) router1.recordOutcome('t', 'haiku', 'success');
- const before = router1.getBanditPriors();
- expect(before.haiku.alpha).toBeCloseTo(11, 5);
+ const bucket = bucketOf(router1, 't');
+ expect(router1.getBanditPriors(bucket).haiku.alpha).toBeCloseTo(11, 5);
const router2 = new ModelRouter(); // reads from same .swarm/model-router-state.json
- const after = router2.getBanditPriors();
+ const after = router2.getBanditPriors(bucket);
expect(after.haiku.alpha).toBeCloseTo(11, 5);
expect(after.haiku.beta).toBeCloseTo(1, 5);
});
+ it('ADR-142: per-bucket isolation β€” failures on one task type do not move another bucket', () => {
+ const router = new ModelRouter();
+ const easy = 'fix a typo'; // low bucket
+ const hard = 'architect a distributed byzantine consensus system with sharding'; // high bucket
+ const easyB = bucketOf(router, easy);
+ const hardB = bucketOf(router, hard);
+ expect(easyB).not.toBe(hardB); // sanity: they really are different buckets
+
+ for (let i = 0; i < 8; i++) router.recordOutcome(easy, 'haiku', 'failure');
+ // haiku is hammered in the easy bucket but untouched in the hard bucket.
+ expect(router.getBanditPriors(easyB).haiku.beta).toBeCloseTo(9, 5);
+ expect(router.getBanditPriors(hardB).haiku).toEqual({ alpha: 1, beta: 1 });
+ });
+
+ it('ADR-142: migrates a flat v1 state file by seeding all buckets', () => {
+ mkdirSync(join(tmpDir, '.swarm'), { recursive: true });
+ writeFileSync(join(tmpDir, '.swarm', 'model-router-state.json'), JSON.stringify({
+ totalDecisions: 5,
+ priors: {
+ haiku: { alpha: 9, beta: 2 }, sonnet: { alpha: 1, beta: 1 },
+ opus: { alpha: 1, beta: 1 }, inherit: { alpha: 1, beta: 1 },
+ },
+ }));
+ const router = new ModelRouter();
+ expect(router.getBanditPriors('low').haiku).toEqual({ alpha: 9, beta: 2 });
+ expect(router.getBanditPriors('high').haiku).toEqual({ alpha: 9, beta: 2 }); // seeded
+ });
+
it('converges toward Haiku on a low-complexity workload (~50 trials)', async () => {
const router = new ModelRouter();
- // Simulated workload matching live: avg complexity 0.3, deterministic seed
let seed = 0x1234567;
const rng = () => {
- // mulberry32 β€” deterministic, fine for testing
seed |= 0;
seed = (seed + 0x6D2B79F5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
@@ -128,31 +168,21 @@ describe('ModelRouter β€” Thompson sampling bandit (#1772)', () => {
router.recordOutcome(task, r.model, outcome);
}
- const priors = router.getBanditPriors();
- // Bandit should have learned Haiku is the right tier here.
- // Ξ±/(Ξ±+Ξ²) is the posterior mean β€” Haiku should be highest.
+ const priors = aggregatePriors(router);
const meanHaiku = priors.haiku.alpha / (priors.haiku.alpha + priors.haiku.beta);
- const meanSonnet = priors.sonnet.alpha / (priors.sonnet.alpha + priors.sonnet.beta);
const meanOpus = priors.opus.alpha / (priors.opus.alpha + priors.opus.beta);
-
expect(meanHaiku).toBeGreaterThan(meanOpus);
- expect(meanHaiku).toBeGreaterThan(0.4); // Haiku is winning
- // Distribution should also reflect the shift over the course of the run
expect(haikuPicked).toBeGreaterThan(opusPicked);
}, 30_000);
- it('does not lock in early β€” bandit explores enough to recover from a bad initial draw', async () => {
- // Even if Thompson sampling picks a bad arm first, repeated outcomes
- // should pull it back. Simulate: Haiku is always "right" but the first
- // 5 random samples happen to favor Opus. After 100 trials, posterior
- // mean for Haiku should still dominate.
+ it('does not lock in early β€” recovers from a bad initial draw', async () => {
const router = new ModelRouter();
for (let i = 0; i < 100; i++) {
const r = await router.route(`task ${i}`);
const outcome = r.model === 'haiku' ? 'success' : 'escalated';
router.recordOutcome(`task ${i}`, r.model, outcome);
}
- const priors = router.getBanditPriors();
+ const priors = aggregatePriors(router);
const meanHaiku = priors.haiku.alpha / (priors.haiku.alpha + priors.haiku.beta);
const meanOpus = priors.opus.alpha / (priors.opus.alpha + priors.opus.beta);
expect(meanHaiku).toBeGreaterThan(meanOpus);
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index c408646f23..44743f2f1e 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.10.8",
+ "version": "3.10.9",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
diff --git a/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts b/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
index 62c86df1eb..df33112f07 100644
--- a/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
+++ b/v3/@claude-flow/cli/src/memory/ewc-consolidation.ts
@@ -18,6 +18,16 @@
* - Selective consolidation based on pattern importance
* - Persistent storage in .swarm/ewc-fisher.json
*
+ * IMPLEMENTATION NOTE (honesty β€” see docs/reviews/intelligence-system-audit-2026-05-29.md):
+ * The penalty math above is real, but `F_i` here is NOT true Fisher information
+ * (the expectation of squared log-likelihood gradients). There are no model
+ * gradients in this pattern-memory context, so `F_i` is a HEURISTIC IMPORTANCE
+ * PROXY: accumulated squared embedding magnitude per dimension
+ * (`F_i += embedding_i^2`, see computeFisherMatrix). It protects high-magnitude
+ * embedding dimensions during consolidation β€” a reasonable importance signal β€”
+ * but "Fisher information" overstates it; read `F_i` as "embedding-importance
+ * weight", not gradient curvature.
+ *
* @module v3/cli/memory/ewc-consolidation
*/
diff --git a/v3/@claude-flow/cli/src/ruvector/model-router.ts b/v3/@claude-flow/cli/src/ruvector/model-router.ts
index b282e5746f..d2a0c4e8e7 100644
--- a/v3/@claude-flow/cli/src/ruvector/model-router.ts
+++ b/v3/@claude-flow/cli/src/ruvector/model-router.ts
@@ -177,6 +177,23 @@ const BANDIT_REWARDS: Record<ClaudeModel, Record<'success' | 'failure' | 'escala
/**
* Router state for persistence
*/
+/**
+ * Complexity bucket for per-task bandit priors. Bands mirror
+ * MODEL_CAPABILITIES.maxComplexity (haiku 0.4, sonnet 0.7) so the taxonomy
+ * isn't arbitrary. Keying priors by bucket fixes the global-bandit defect where
+ * failures on one task type suppressed a model for ALL task types (audit
+ * docs/reviews/intelligence-system-audit-2026-05-29.md; see ADR-142).
+ */
+export type ComplexityBucket = 'low' | 'med' | 'high';
+
+function complexityBucket(score: number): ComplexityBucket {
+ if (score < 0.4) return 'low'; // haiku territory
+ if (score < 0.7) return 'med'; // sonnet territory
+ return 'high'; // opus territory
+}
+
+type BucketedPriors = Record<ComplexityBucket, Record<ClaudeModel, BetaPrior>>;
+
interface RouterState {
totalDecisions: number;
modelDistribution: Record<ClaudeModel, number>;
@@ -191,12 +208,16 @@ interface RouterState {
outcome: 'success' | 'failure' | 'escalated';
timestamp: string;
}>;
+ /** Persisted-schema version. v2 = per-bucket priors (ADR-142). */
+ version?: number;
/**
- * Beta(Ξ±, Ξ²) priors per model β€” populated by recordOutcome via Thompson
- * sampling. Defaults to {alpha:1,beta:1} (uniform). After ~50 outcomes
- * these converge so the router auto-corrects against tier overuse.
+ * Beta(Ξ±, Ξ²) priors per complexity bucket per model β€” populated by
+ * recordOutcome via Thompson sampling. Defaults to {alpha:1,beta:1}
+ * (uniform). Keyed by bucket so e.g. haiku failures on hard tasks don't
+ * suppress haiku for easy tasks. Old flat per-model files migrate forward
+ * (see migratePriors).
*/
- priors?: Record<ClaudeModel, BetaPrior>;
+ priors?: BucketedPriors;
}
// ============================================================================
@@ -266,6 +287,40 @@ function defaultBanditPriors(): Record<ClaudeModel, BetaPrior> {
};
}
+/** Uniform priors for every complexity bucket (cold start). */
+function defaultBucketedPriors(): BucketedPriors {
+ return { low: defaultBanditPriors(), med: defaultBanditPriors(), high: defaultBanditPriors() };
+}
+
+function clonePriors(p: Record<ClaudeModel, BetaPrior>): Record<ClaudeModel, BetaPrior> {
+ return { haiku: { ...p.haiku }, sonnet: { ...p.sonnet }, opus: { ...p.opus }, inherit: { ...p.inherit } };
+}
+
+/**
+ * Forward-migrate a persisted `priors` field of any layout to the bucketed
+ * shape, never throwing (ADR-142):
+ * - missing/garbage β†’ fresh uniform buckets
+ * - already bucketed (has `low.haiku`) β†’ kept, backfilling any missing bucket
+ * - flat per-model (v1 bandit) β†’ seed ALL buckets from it (lossless: prior
+ * learning becomes a shared starting point that then diverges per bucket)
+ */
+function migratePriors(p: unknown): BucketedPriors {
+ if (!p || typeof p !== 'object') return defaultBucketedPriors();
+ const obj = p as Record<string, any>;
+ if (obj.low && typeof obj.low === 'object' && obj.low.haiku) {
+ return {
+ low: obj.low,
+ med: obj.med ?? clonePriors(obj.low),
+ high: obj.high ?? clonePriors(obj.low),
+ };
+ }
+ if (obj.haiku && typeof obj.haiku.alpha === 'number') {
+ const flat = obj as Record<ClaudeModel, BetaPrior>;
+ return { low: clonePriors(flat), med: clonePriors(flat), high: clonePriors(flat) };
+ }
+ return defaultBucketedPriors();
+}
+
// ============================================================================
// Default Configuration
// ============================================================================
@@ -514,8 +569,10 @@ export class ModelRouter {
scores: Record<ClaudeModel, number>,
complexityScore: number
): { model: ClaudeModel; confidence: number; uncertainty: number } {
- // Thompson sampling: combine deterministic score with bandit posterior
- const priors = this.state.priors ?? defaultBanditPriors();
+ // Thompson sampling: combine deterministic score with bandit posterior,
+ // keyed by complexity bucket (ADR-142) so learning is task-type-local.
+ const bucketed = this.state.priors ?? defaultBucketedPriors();
+ const priors = bucketed[complexityBucket(complexityScore)] ?? defaultBanditPriors();
const sampledScores: Record<ClaudeModel, number> = {
haiku: scores.haiku * sampleBeta(priors.haiku.alpha, priors.haiku.beta),
sonnet: scores.sonnet * sampleBeta(priors.sonnet.alpha, priors.sonnet.beta),
@@ -611,11 +668,17 @@ export class ModelRouter {
this.consecutiveFailures[model] = 0;
}
- // Track in history
+ // Re-derive this task's complexity bucket from the task string (the MCP
+ // outcome payload carries no complexity), using the SAME analyzeComplexity
+ // path route() uses so record-time and select-time buckets match.
+ const taskScore = this.analyzeComplexity(task).score;
+ const bucket = complexityBucket(taskScore);
+
+ // Track in history (record THIS task's score, not the running average)
this.state.learningHistory.push({
task: task.slice(0, 100),
model,
- complexity: this.state.avgComplexity,
+ complexity: taskScore,
outcome,
timestamp: new Date().toISOString(),
});
@@ -632,10 +695,11 @@ export class ModelRouter {
// Thompson sampling update (#1772): cost-adjusted Bernoulli reward.
// Haiku-success > Sonnet-success > Opus-success (Opus on simple tasks
// is wasteful even when correct). Failure/escalation always Ξ²++.
- if (!this.state.priors) this.state.priors = defaultBanditPriors();
+ if (!this.state.priors) this.state.priors = defaultBucketedPriors();
+ const bp = this.state.priors[bucket] ?? (this.state.priors[bucket] = defaultBanditPriors());
const reward = BANDIT_REWARDS[model]?.[outcome] ?? 0.5;
- this.state.priors[model].alpha += reward;
- this.state.priors[model].beta += 1 - reward;
+ bp[model].alpha += reward;
+ bp[model].beta += 1 - reward;
this.saveState();
}
@@ -673,17 +737,20 @@ export class ModelRouter {
circuitBreakerTrips: 0,
lastUpdated: new Date().toISOString(),
learningHistory: [],
- priors: defaultBanditPriors(),
+ version: 2,
+ priors: defaultBucketedPriors(),
};
try {
const fullPath = join(process.cwd(), this.config.statePath);
if (existsSync(fullPath)) {
const data = readFileSync(fullPath, 'utf-8');
- const loaded = JSON.parse(data) as Partial<RouterState>;
- // Backfill priors for state files written by pre-bandit cli versions.
- if (!loaded.priors) loaded.priors = defaultBanditPriors();
- return { ...defaultState, ...loaded };
+ const loaded = JSON.parse(data) as Partial<RouterState> & { priors?: unknown };
+ // ADR-142: forward-migrate priors of ANY layout (missing / flat v1 /
+ // already-bucketed) to the bucketed shape without data loss or throwing.
+ loaded.priors = migratePriors(loaded.priors);
+ loaded.version = 2;
+ return { ...defaultState, ...(loaded as Partial<RouterState>) };
}
} catch {
// Ignore load errors
@@ -721,7 +788,8 @@ export class ModelRouter {
circuitBreakerTrips: 0,
lastUpdated: new Date().toISOString(),
learningHistory: [],
- priors: defaultBanditPriors(),
+ version: 2,
+ priors: defaultBucketedPriors(),
};
this.consecutiveFailures = { haiku: 0, sonnet: 0, opus: 0, inherit: 0 };
this.decisionCount = 0;
@@ -733,8 +801,9 @@ export class ModelRouter {
* dashboards, and the pending hooks_intelligence_stats integration that
* surfaces convergence in the dashboard. Returns a copy.
*/
- getBanditPriors(): Record<ClaudeModel, BetaPrior> {
- const p = this.state.priors ?? defaultBanditPriors();
+ getBanditPriors(bucket: ComplexityBucket = 'med'): Record<ClaudeModel, BetaPrior> {
+ const bucketed = this.state.priors ?? defaultBucketedPriors();
+ const p = bucketed[bucket] ?? defaultBanditPriors();
return {
haiku: { ...p.haiku },
sonnet: { ...p.sonnet },
@@ -742,6 +811,16 @@ export class ModelRouter {
inherit: { ...p.inherit },
};
}
+
+ /** All bucketed priors (copy) β€” for dashboards/tests. */
+ getBucketedPriors(): BucketedPriors {
+ const b = this.state.priors ?? defaultBucketedPriors();
+ return {
+ low: clonePriors(b.low ?? defaultBanditPriors()),
+ med: clonePriors(b.med ?? defaultBanditPriors()),
+ high: clonePriors(b.high ?? defaultBanditPriors()),
+ };
+ }
}
// ============================================================================
diff --git a/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts b/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts
index 6a2906450b..4b953c7d90 100644
--- a/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts
+++ b/v3/@claude-flow/cli/src/ruvector/ruvllm-wasm.ts
@@ -259,7 +259,7 @@ export async function createSonaInstant(config: SonaConfig = {}): Promise<{
export async function createMicroLora(config: MicroLoraConfig): Promise<{
apply: (input: Float32Array) => Float32Array;
adapt: (quality: number, learningRate?: number, success?: boolean) => void;
- applyUpdates: (gradients: Float32Array) => void;
+ applyUpdates: (learningRate?: number) => void;
stats: () => string;
reset: () => void;
toJson: () => string;
@@ -287,9 +287,21 @@ export async function createMicroLora(config: MicroLoraConfig): Promise<{
try { (feedback as any).success = success; } catch { /* v2.0.2 quirk */ }
const input = new Float32Array(Math.max(config.inputDim, MICROLORA_WASM_MIN_DIM));
lora.adapt(input, feedback);
+ // Flush accumulated gradients. HONEST CAVEAT (audit
+ // docs/reviews/intelligence-system-audit-2026-05-29.md): even WITH this
+ // flush, the shipped @ruvector/[email protected] MicroLoraWasm.apply()
+ // output is empirically UNCHANGED (measured maxAbsDelta = 0 after 200
+ // adapts). MicroLoRA adaptation is therefore effectively a no-op on
+ // inference with this WASM backend. We do NOT synthesize a fake gradient
+ // from the scalar quality to make output "move" β€” that would be a
+ // fabricated signal. Real adaptation needs the WASM backend to flush B,
+ // or a caller supplying real gradients.
+ lora.applyUpdates(learningRate as unknown as Float32Array);
},
- applyUpdates(gradients: Float32Array): void {
- lora.applyUpdates(gradients);
+ applyUpdates(learningRate = 0.01): void {
+ // WASM runtime signature is applyUpdates(learning_rate: number); the
+ // shipped .d.ts mistypes it as Float32Array, hence the cast.
+ lora.applyUpdates(learningRate as unknown as Float32Array);
},
stats(): string {
return lora.toJson();
diff --git a/v3/@claude-flow/cli/src/ruvector/vector-db.ts b/v3/@claude-flow/cli/src/ruvector/vector-db.ts
index 9b857808bb..f83f43c582 100644
--- a/v3/@claude-flow/cli/src/ruvector/vector-db.ts
+++ b/v3/@claude-flow/cli/src/ruvector/vector-db.ts
@@ -335,7 +335,7 @@ export function computeSimilarity(a: Float32Array, b: Float32Array): number {
export function getStatus(): {
available: boolean;
wasmAccelerated: boolean;
- backend: 'ruvector-wasm' | 'ruvector' | 'fallback';
+ backend: 'ruvector-stub-search-disabled' | 'ruvector-native' | 'fallback';
} {
if (!isAvailable) {
return {
@@ -345,10 +345,17 @@ export function getStatus(): {
};
}
- const wasmAccelerated = isWASMAccelerated();
+ // HONESTY (audit docs/reviews/intelligence-system-audit-2026-05-29.md):
+ // ruvector's `isWasm()` does NOT mean "WASM-accelerated" β€” there is no WASM
+ // HNSW build in this stack. `isWasm()===true` means the do-nothing STUB is
+ // active (search() returns []), i.e. native NAPI failed to load. So
+ // wasmAccelerated===false is the HEALTHY state (native NAPI is the fastest
+ // backend available). We label the stub honestly so a regression into it is
+ // visible instead of being mistaken for a faster mode.
+ const stubActive = isWASMAccelerated();
return {
available: true,
- wasmAccelerated,
- backend: wasmAccelerated ? 'ruvector-wasm' : 'ruvector',
+ wasmAccelerated: stubActive,
+ backend: stubActive ? 'ruvector-stub-search-disabled' : 'ruvector-native',
};
}
diff --git a/v3/docs/adr/ADR-142-per-task-bandit-priors.md b/v3/docs/adr/ADR-142-per-task-bandit-priors.md
new file mode 100644
index 0000000000..88ac43d47d
--- /dev/null
+++ b/v3/docs/adr/ADR-142-per-task-bandit-priors.md
@@ -0,0 +1,61 @@
+# ADR-142 β€” Per-Task-Bucket Bandit Priors for Model Routing
+
+**Status**: Accepted β€” Implemented in v3.10.9 (2026-05-29)
+**Related**: ADR-026 (3-tier model routing), #1772 (Thompson-sampling bandit), docs/reviews/intelligence-system-audit-2026-05-29.md
+
+## Context
+
+The model-routing Thompson-sampling bandit (`v3/@claude-flow/cli/src/ruvector/model-router.ts`)
+kept Beta(Ξ±,Ξ²) priors **globally per model**: `priors: Record<ClaudeModel, BetaPrior>`.
+The intelligence audit found this is too coarse β€” e.g. 8 Haiku failures on one hard
+task suppress Haiku for **all** tasks, including trivial ones it handles well. The
+bandit could not learn "Haiku is fine for typos but bad for helpers."
+
+## Decision
+
+Key the priors by a **complexity bucket** derived from the existing
+`analyzeComplexity().score`, banded to mirror `MODEL_CAPABILITIES.maxComplexity`:
+
+- `low` β€” score < 0.4 (haiku territory)
+- `med` β€” 0.4 ≀ score < 0.7 (sonnet territory)
+- `high` β€” score β‰₯ 0.7 (opus territory)
+
+New shape: `priors: Record<ComplexityBucket, Record<ClaudeModel, BetaPrior>>`.
+
+- **Selection** (`selectModel`) samples from the bucket of the current task's
+ complexity score (already in scope).
+- **recordOutcome** re-derives the bucket from the `task` string via the SAME
+ `analyzeComplexity` path (the MCP `hooks_model-outcome` payload carries no
+ complexity, so record-time and select-time buckets match for the same task).
+- MCP tool signatures (`hooks_model-route`, `hooks_model-outcome`) are
+ **unchanged** β€” the bucket is derived internally.
+
+## Schema migration
+
+`model-router-state.json` gains `version: 2`. `migratePriors()` forward-migrates
+any prior layout without data loss or throwing:
+
+- **missing / garbage** β†’ fresh uniform buckets.
+- **flat per-model (v1)** β†’ seed ALL three buckets from the old global priors
+ (lossless: accumulated learning becomes a shared starting point that then
+ diverges per bucket).
+- **already bucketed** β†’ kept, backfilling any missing bucket.
+
+Readers MUST tolerate all three layouts. (`loadState` calls `migratePriors`.)
+
+## Consequences
+
+- **Fixes the cross-task interference defect** β€” failures in one bucket no longer
+ suppress a model in another (proven by the `per-bucket isolation` test).
+- Convergence is now per-bucket (β‰ˆ3Γ— the outcomes to fully converge all buckets) β€”
+ an acceptable cost for correct task-type-local learning.
+- `getBanditPriors(bucket = 'med')` now takes an optional bucket; added
+ `getBucketedPriors()` for dashboards/tests. The bandit test suite was updated
+ to be bucket-aware (query the task's bucket; aggregate across buckets for
+ convergence assertions) and gained isolation + migration tests.
+
+## Verification
+
+`__tests__/router-bandit.test.ts` β€” 8/8 pass, including:
+- per-bucket isolation (8 failures in `low` leave `high` at {1,1});
+- flat-v1 β†’ bucketed migration (seeds all buckets from the old global priors).