🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
dream(intelligence, evaluated): wire CLAUDE_FLOW_PRIOR_DECAY env override for ModelRouter's dormant decay primitive (#3349) (#3350)
rUv4c2c62df2708
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex d61936475b..12ded52316 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-17):** verified via GitHub MCP tools (not inferred) before tonight's own row: **2026-09-13 and 2026-09-14 are genuine no-run gaps** — no `dream/2026-09-13-*`/`dream/2026-09-14-*` branch, no matching issue/PR, same class as the earlier 2026-08-20..23 gap. **2026-09-15 ran** (`performance`, #3329 — MoE gate load-balance loss computed but never applied to weights) and **2026-09-16 ran** (`security`, #3338 — hive-mind consensus bypass); neither transcribed as its own row here (out of scope for tonight's `intelligence` slot to backfill in full — flagging their existence is enough to keep STEP 1's gap-detection honest). Trailing-14 PR merge rate: **14/14 MERGED** — a bulk human-review sweep on 2026-09-14/15 cleared the entire backlog from #3086 through #3302 in one pass. This is the opposite extreme from the "0 of last 14" signal earlier nights tracked, so tonight did **not** bias toward an artificially small candidate on that basis — but the bulk-sweep nature (many PRs merged together) is a weaker scrutiny signal than a steady one-by-one trickle, noted for future nights' calibration.++| 2026-09-17 | intelligence | `ModelRouter`'s discounted-Thompson-sampling `priorDecay` primitive (built/tested/benchmarked in #3049, 2026-08-17) shipped permanently inert — `DEFAULT_CONFIG.priorDecay` hardcoded to `1` (disabled), no env/config override unlike sibling `maxUncertainty`; added `envPriorDecay()` mirroring the existing `envMaxUncertainty()` pattern exactly, acting on 09-12's own gist recommendation for a future `intelligence` night | #3349 | #3350 | yes | ACCEPT-scoped | stash-isolated: 1/3 new tests fail reverted, 16/16 pass restored; full `@claude-flow/cli` suite + `tsc --noEmit` byte-identical baseline vs candidate outside the 3 new tests (221 failures / 463 errors both ways); benchmark re-run byte-identical to 2026-08-17 receipt — real non-stationary recovery win in 'low' bucket (t=7.0), small but statistically real stationary-accuracy cost in 'med' bucket (t=-3.01, 0.08pp, inside the original ±1pp tolerance); independent adversarial critic CONFIRMED-WITH-CAVEATS, disclosed not oversold | 91d8edc3... | 08-24..09-11 backlog (10 PRs) + 09-12 (#3302) all MERGED 2026-09-14/15 in a bulk sweep; 09-13/09-14 no-run gap, 09-15/09-16 ran but not transcribed (see note above) || 2026-09-15 | performance | `MoERouter.route()` computed a Switch-Transformer-style load-balance auxiliary loss every call and returned it in `RoutingResult`, but `updateExpertWeights()` (the sole mutator of gate weights) never read that loss or its coefficient in its REINFORCE gradient math — the regularizer the module's own header claims had zero actual training effect; wired the analytic (softmax-Jacobian) gradient into the existing update path, using a per-`route()` fraction snapshot for consistency | #3329 | #3330 | yes | ACCEPT-scoped | 4 new discriminating tests, baseline-fails/candidate-passes via stash isolation (reproduced independently by critic); full `@claude-flow/neural` suite 132/132→136/136, 0 regressions; `tsc --noEmit` clean; independent adversarial critique CONFIRMED (scoping caveat: `updateExpertWeights()` has zero production callers today, though `route()` itself is live) | 5e719b96... | trailing 7 nights (#3086,#3139,#3152,#3160,#3232,#3243,#3266,#3291,#3302) all MERGED 2026-09-14 — full prior backlog cleared, reversing the earlier "0 of 14" signal |**Note (2026-09-21):** #3302 confirmed **MERGED** 2026-09-15 via `pull_request_read` (authoritative) — `search_pull_requests`'s `merged` field is stale/unreliable (it reported `merged:false` with a populated `merged_at` for this same PR; do not trust it for merge-state checks, use `pull_request_read`/`get`). **New no-run gap, confirmed via `git ls-remote --heads origin "dream/*"`**: 2026-09-13 and 2026-09-14 have no branch, issue, or PR — same verification standard as the documented 08-20..08-23 gap, root cause still undiagnosed. 2026-09-15 through 2026-09-20 all ran (real branches confirmed): #3329/#3330 (perf, MoE load-balance), #3338/#3339 (security, hive-mind capability-token round 2), #3349/#3350 (intelligence, ModelRouter prior-decay env override), #3351/#3352 (memory, AgentDBAdapter upsert-orphan fix), #3356/#3357 (swarm, topology mirror-edge fix), #3377/#3378 (performance, UnifiedSwarmCoordinator busy-poll→event-driven, ~487x measured) — not transcribed row-by-row here per the established "ledger rows only reach `main` via PR merge" convention; all currently open/draft, none stale (<14d old as of tonight).diff --git a/docs/dream-cycle/dream-gist-2026-09-17.md b/docs/dream-cycle/dream-gist-2026-09-17.mdnew file mode 100644index 0000000000..317bb8f9a3--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-09-17.md@@ -0,0 +1,82 @@+# Intelligence SOTA Report — 2026-09-17++**TL;DR**: Ruflo's discounted-Thompson-sampling model router (`priorDecay`, the primitive behind #3049) was built, unit-tested, and benchmarked back in 2026-08-17 — but shipped permanently inert: `DEFAULT_CONFIG.priorDecay` was hardcoded to `1` (disabled) with no env/config knob, unlike every sibling tunable in the same file. Last night's (2026-09-12) gist named this exact gap as tonight's recommended next step for a future `intelligence` night. Tonight wires `CLAUDE_FLOW_PRIOR_DECAY` in, mirroring the file's own existing `envMaxUncertainty()` pattern. Independent adversarial review returned **CONFIRMED-WITH-CAVEATS**: the fix itself is clean, but the underlying decay mechanism's benefit is real only in one of two benchmarked workload buckets — reported honestly below, not oversold.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| Discounted Thompson Sampling for non-stationary bandits (decay α/β geometrically before adding new reward) | arXiv:2305.10718 | A |+| ReasoningBank distills from both successes *and* failures as title/description/content triples; raw-trajectory storage underperforms | arXiv:2509.25140 (ICLR'26) | A |+| ST-MoE-style load-balance/z-loss regularization is required alongside any online reward-update to a MoE gate, or logits risk collapse/blowup | arXiv:2202.08906 (A), arXiv:2604.17228 (B, 2026, separates stability- vs policy-oriented aux losses) | A/B |+| Zep/Graphiti bi-temporal knowledge-graph memory (fact validity intervals, non-lossy invalidation) | arXiv:2501.13956 | A |+| MCP 2026-07-28 spec: capability/extension negotiation is checked per-request at the protocol boundary, not declared-once | modelcontextprotocol.io spec + blog | A |++## Ruflo Current Capability++The intelligence pipeline (RETRIEVE→JUDGE→DISTILL→CONSOLIDATE) spans `cli/src/memory/intelligence.ts`, `neural/src/{reasoning-bank,pattern-learner,moe-router}.ts`, and `cli/src/ruvector/{model-router,enhanced-model-router,q-learning-router}.ts`. Tonight's deep dive re-confirmed the RETRIEVE→JUDGE→DISTILL handoff in `intelligence.ts` is correctly wired (no new bug there — the Fisher-gate and confidence/similarity bugs from prior nights are the only history here). The gap tonight is narrower and specific: `ModelRouter`'s decay primitive has correct math, correct numerical-stability floor (`PRIOR_DECAY_FLOOR=0.05`), correct malformed-input fallback — and zero way to actually turn it on in a live deployment.++## Competitor Comparison++| Competitor | Capability | Ruflo status | Grade | Note |+|---|---|---|---|---|+| AutoGen/AG2 | Continual adaptation from task outcomes across runs | **Ahead** — measured cross-process persistence + confidence updates; AG2 in maintenance mode, no comparable roadmap | B | — |+| OpenAI Responses/Assistants API | Persistent cross-session behavioral memory | **Ahead, structurally** — Ruflo ships persistence in-repo; OpenAI's APIs are stateless server-side, offloaded to 3rd parties | B | — |+| Qdrant/Weaviate | Binary quantization compression | **Parity** — measured real 32× compression | B | — |+| Qdrant/Weaviate | Native BM25/SPLADE hybrid fusion | **Partial** — Ruflo's "sparse" arm is stopword-filtered keyword extraction, not term-weighted retrieval | C | Scoping decision, not solved elsewhere |+| Zep/Graphiti | Bi-temporal fact-validity memory | **None** | A | Genuine open gap, unbuilt — not deliberately avoided, just never scoped. Strongest future-night candidate. |++## Hypothesis++Given a long-running Ruflo deployment where `.swarm/model-router-state.json` accumulates Thompson-sampling history across many sessions, when `priorDecay` is exposed via a `CLAUDE_FLOW_PRIOR_DECAY` env override (mirroring `envMaxUncertainty()`, default unchanged at `1`/disabled), then the router should recover faster from a real model-quality shift when an operator opts in, subject to: no change in default runtime behavior when unset (trivially true by construction — disclosed, not hidden), no numeric-stability regression (existing floor untouched), and no material stationary-workload accuracy loss (pre-declared ±1pp tolerance from the original #3049 benchmark, not invented tonight).++## Benchmarks++`benchmarks/results/scripts/prior-decay-benchmark.mjs` — 2 complexity buckets (low/med), paired-seed deterministic RNG, 30 trials each, stationary + non-stationary (mid-run model-quality shift) scenarios. Re-run tonight, independently re-run a second time by the adversarial critic: **byte-identical to the 2026-08-17 original receipt** both times.++## Evaluation++- **Code-level (stash-isolated)**: reverted only the source fix, kept the 3 new tests → 1/3 failed exactly as predicted (env var silently ignored). Restored fix → 16/16 pass (13 pre-existing + 3 new).+- **Full `@claude-flow/cli` suite, byte-identical both ways**: 221 pre-existing failures (unbuilt-dist/network-dependent integration tests, unrelated), 2497→2500 passed (+3, exactly our new tests), 105 skipped both ways.+- **`tsc --noEmit`**: 463 pre-existing errors, byte-identical error-line sets baseline vs candidate (diff clean).+- **Benchmark receipt** (both buckets, 30 trials, t-stats):+ - **low** bucket (haiku→sonnet shift): recovery 26.5→21.9 rounds (t=7.0, real win); post-shift accuracy +1.3pp (t=5.9); stationary Δ=+0.02pp (t=0.7, noise).+ - **med** bucket (sonnet→opus shift): recovery flat (t=−0.74); post-shift accuracy flat (t=−0.33); stationary Δ=**−0.08pp (t=−3.01)** — a small but statistically real regression, accepted only because it sits inside the pre-declared ±1pp tolerance band from the original 2026-08-17 receipt.+- **Independent adversarial critic** re-ran everything itself (not trusting the description): **CONFIRMED-WITH-CAVEATS**. No test/benchmark weakening, no gold-answer tampering, no evaluator exploitation, no cost-path touched, no injection surface, reward-hack checklist entirely clear. Explicit caveat: describe this as "safely exposes an existing opt-in knob, net-positive in the tested low-complexity bucket, negligible-but-real cost in med-complexity" — **not** an unqualified win.++## Darwin Results++`@metaharness/[email protected]` is available (confirmed via `ruvector harness status --json`) but was **not invoked**. The decay value (0.995) was already the subject of last month's own benchmark/selection; tonight's diff is a pure config-exposure wiring change with no new free parameter for Darwin to search — running it would add cost with no marginal evidence for this specific patch. Also probed `@metaharness/[email protected]`'s `gate <evidence>`: its frozen conjunctive rule expects `{candidate,baseline}.{primary,noopRate,costPerWin}` — an executor-commit-rate shape that doesn't map onto this candidate's bandit-recovery evidence without fabricating a `noopRate` that doesn't exist here. Declined to force it rather than invent a metric.++## SOTA Proof & Witness++| Field | Value |+|---|---|+| Session commit | `6f0ed7112873eedc7cfe17281a2585188190b790` |+| Gist SHA-256 (pre-witness content) | `e97f610c7699f729fbb4c738486f0201e21230b185006dca2da6116da8d5938a` |+| Witness stamp | `91d8edc3bf54252f847c593d1e2bd7a7f4e50afae5a18bdf558d9329ebf57715` |+| Evaluation receipt | `v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.json` (regenerated 2026-09-17, byte-identical to 2026-08-17 original) |+| Flywheel evidence | N/A — schema mismatch disclosed above (gate rule expects executor commit/no-op-rate shape), declined to fabricate a metric |+| Darwin lineage | N/A — not invoked, rationale disclosed above |++Verifier procedure: fetch this gist, strip the witness table's filled values back to `PENDING`, SHA-256 the result, concatenate with the session commit above, SHA-256 again — result must equal the witness stamp.++## Scan Findings: capabilities++`plugins install` (`v3/@claude-flow/cli/src/commands/plugins.ts` → `plugins/manager.ts`) fetches a registry `PluginEntry` only to print its name/version, then unconditionally `npm install`s it — never checking the entry's declared `permissions`/`trustLevel`/`securityAudit` against `PluginStoreConfig.allowedPermissions`/`minTrustLevel`/`requireVerification`, despite all of that being fully modeled in `store/types.ts` and named in `SECURITY.md` as the privilege-escalation mitigation. Bonus: `plugins.ts`'s `--verify` flag (checksum verification, "default: true") is parsed into a local var and never read again. Not selected (SCAN surface); real gap for a future `capabilities`/security night.++## Scan Findings: memory++`hnsw-index.ts`'s `binaryQuantize()`/`scalarQuantize()` produce bit-packed/min-range-polluted arrays, but `distance()` only special-cases quantization for `'product'` (the already-fixed #3093/#3094 bug) — `'binary'` and `'scalar'` fall through to generic cosine/euclidean/dot computed directly on the packed representation, numerically meaningless. No `binaryQuantizeDistance()`/`scalarQuantizeDistance()` exists. Also: CLAUDE.md's "RaBitQ Quantization — Measured" claim has zero matching implementation under `grep -ri rabitq` in `memory/src`. Not selected (SCAN surface); strong candidate for a future `memory` DEEP night.++## Competitors Reviewed++AutoGen/AG2, OpenAI Responses/Assistants API, CrewAI/LangGraph (context), Qdrant, Weaviate, Milvus, LanceDB, Zep/Graphiti, MCP 2026-07-28 spec (capabilities scan), OpenAI Agents SDK function-calling strict mode (capabilities scan).++## Recommended Next Steps++1. **Ship `SONAAdapter.forceLearningCycle()` wiring** (`v3/@claude-flow/integration/src/sona-adapter.ts:664`) — the periodic consolidation timer calls `consolidatePatterns()` directly instead of `forceLearningCycle()`, so `learningCycleCount`/`stats.learningCycles` stay permanently 0 and periodic pruning never runs automatically. One-line fix, existing test file, smallest/safest candidate surfaced tonight — good for tomorrow.+2. **MoE gate online learning, as a themed 2-part sequence**: `moe-router.ts`'s `updateExpertWeights()` (full REINFORCE update, exported, tested in isolation) has **zero production callers** — the live `mode==='moe'` path only ever calls the forward pass — despite CLAUDE.md asserting "MoE Gate converges — confidence 0.13→0.88" as **Measured** with no in-repo source for that number. Wiring the reward callback is real value, but ST-MoE literature (arXiv:2202.08906) warns an unregularized reward update risks gate collapse — so pair it with also wiring the already-computed-but-discarded `computeLoadBalanceLoss()`/`loadBalanceCoef` into the same gradient step, in the same night, not sequentially.+3. **HNSW binary/scalar quantization distance dispatch** (`v3/@claude-flow/memory/src/hnsw-index.ts`) — same bug class as the already-fixed product-quantization dispatch bug (#3093/#3094), left unfixed for the other two `QuantizationConfig.type` values: `binaryQuantize()`/`scalarQuantize()` pack bit-masks/min-range-polluted arrays that then get cosine/euclidean/dot distance computed directly on the packed representation — numerically meaningless, silently, for any caller using `type: 'binary'` or `'scalar'`.++Also flagged, lower priority: `plugins install` never enforces its own declared `permissions`/`trustLevel`/`--verify` checksum gate against `allowedPermissions` config (capabilities scan); CLAUDE.md's "RaBitQ Quantization — Measured" claim has zero matching implementation under `grep -ri rabitq` in `memory/src` (memory scan, needs follow-up); Zep-style bi-temporal fact memory is a well-specified, A-grade-sourced, structurally new capability worth a dedicated future night.diff --git a/scripts/audit-env-var-precedence.mjs b/scripts/audit-env-var-precedence.mjsindex c5755cac6b..5b065bedbc 100644--- a/scripts/audit-env-var-precedence.mjs+++ b/scripts/audit-env-var-precedence.mjs@@ -165,6 +165,14 @@ const KNOWN_ESCAPE_HATCHES = new Set([// single CLI invocation owns the router's lifetime.'CLAUDE_FLOW_MAX_UNCERTAINTY',+ // Added 2026-09-17 (Dream Cycle #3349/#3350): same operator-knob shape as+ // CLAUDE_FLOW_MAX_UNCERTAINTY directly above — model-router's discounted-+ // Thompson-sampling decay factor, tuned by ops across the router's whole+ // persisted lifetime (.swarm/model-router-state.json), not selected per+ // CLI invocation. envPriorDecay() in model-router.ts mirrors+ // envMaxUncertainty() exactly, including this escape-hatch registration.+ 'CLAUDE_FLOW_PRIOR_DECAY',+// ── MCP-tool-shaped tunables (param wins over env; env is documented fallback) ─// Added 2026-06-02 (ADR-089 #2246): memory_search_unified resolves namespaces// in this priority: `namespace` param → `namespaces[]` param → env var →diff --git a/v3/@claude-flow/cli/__tests__/router-bandit.test.ts b/v3/@claude-flow/cli/__tests__/router-bandit.test.tsindex 68a33f15e9..37efb6c6df 100644--- a/v3/@claude-flow/cli/__tests__/router-bandit.test.ts+++ b/v3/@claude-flow/cli/__tests__/router-bandit.test.ts@@ -14,7 +14,7 @@* escalated` strings, which is exactly what hooks_model-outcome delivers.*/-import { describe, expect, it, beforeEach, afterEach } from 'vitest';+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';import { rmSync, mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -303,3 +303,61 @@ describe('ModelRouter — priorDecay (discounted Thompson sampling, arXiv 2305.1expect(candidate).toBeGreaterThanOrEqual(baseline - 0.05); // no material regression}, 30_000);});++describe('ModelRouter — CLAUDE_FLOW_PRIOR_DECAY env override (Dream Cycle 2026-09-17, mirrors #2250 envMaxUncertainty)', () => {+ const ENV_KEY = 'CLAUDE_FLOW_PRIOR_DECAY';+ let originalEnv: string | undefined;++ beforeEach(() => {+ setupTempCwd();+ originalEnv = process.env[ENV_KEY];+ });++ afterEach(() => {+ cleanupTempCwd();+ if (originalEnv === undefined) delete process.env[ENV_KEY];+ else process.env[ENV_KEY] = originalEnv;+ vi.resetModules();+ });++ it('wires the env var into the default priorDecay for a router built with no explicit config', async () => {+ process.env[ENV_KEY] = '0.5';+ vi.resetModules();+ const { ModelRouter: FreshModelRouter } = await import('../src/ruvector/model-router.js');+ const router = new FreshModelRouter();+ const task = 'simple task';+ const bucket = bucketOf(router, task);+ router.recordOutcome(task, 'haiku', 'success');+ const p = router.getBanditPriors(bucket);+ // Same math as the explicit `new ModelRouter({ priorDecay: 0.5 })` case above:+ // decay Beta(1,1)->Beta(0.5,0.5) (no-op at the uniform prior) then +1.0 success.+ expect(p.haiku.alpha).toBeCloseTo(1.5, 5);+ expect(p.haiku.beta).toBeCloseTo(0.5, 5);+ });++ it('falls back to disabled (1) for an out-of-range env value, matching the constructor guard', async () => {+ process.env[ENV_KEY] = '1.5';+ vi.resetModules();+ const { ModelRouter: FreshModelRouter } = await import('../src/ruvector/model-router.js');+ const router = new FreshModelRouter();+ const task = 'simple task';+ const bucket = bucketOf(router, task);+ router.recordOutcome(task, 'haiku', 'success');+ const p = router.getBanditPriors(bucket);+ expect(p.haiku.alpha).toBeCloseTo(2.0, 5); // no decay: 1 + 1*1.0+ expect(p.haiku.beta).toBeCloseTo(1.0, 5);+ });++ it('defaults to disabled (1) when unset — zero behavior change for existing deployments', async () => {+ delete process.env[ENV_KEY];+ vi.resetModules();+ const { ModelRouter: FreshModelRouter } = await import('../src/ruvector/model-router.js');+ const router = new FreshModelRouter();+ const task = 'simple task';+ const bucket = bucketOf(router, task);+ router.recordOutcome(task, 'haiku', 'success');+ const p = router.getBanditPriors(bucket);+ expect(p.haiku.alpha).toBeCloseTo(2.0, 5);+ expect(p.haiku.beta).toBeCloseTo(1.0, 5);+ });+});diff --git a/v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.json b/v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.jsonindex 4f8a03c7a8..58cc43c3af 100644--- a/v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.json+++ b/v3/@claude-flow/cli/benchmarks/results/prior-decay-receipt.json@@ -55,5 +55,6 @@}}],- "generatedAt": "2026-08-17T06:29:03.189Z"+ "generatedAt": "2026-09-17T06:11:51.261Z",+ "note": "Regenerated 2026-09-17 (Dream Cycle intelligence night) to confirm reproducibility ahead of wiring CLAUDE_FLOW_PRIOR_DECAY env override (#pending). Numbers identical to 2026-08-17 original (deterministic paired-seed RNG) — this benchmark exercises the decay math directly via constructor config, independent of tonight's env-var wiring change."}\ No newline at end of filediff --git a/v3/@claude-flow/cli/src/ruvector/model-router.ts b/v3/@claude-flow/cli/src/ruvector/model-router.tsindex 1a1ec9b5c6..e75ccff72d 100644--- a/v3/@claude-flow/cli/src/ruvector/model-router.ts+++ b/v3/@claude-flow/cli/src/ruvector/model-router.ts@@ -512,6 +512,23 @@ function envMaxUncertainty(): number | undefined {return n;}+// Dream Cycle 2026-09-17 — env override for priorDecay, mirroring+// envMaxUncertainty() above. The discounted-Thompson-sampling primitive+// (see priorDecay's doc comment) was built, tested, and benchmarked in+// #3049 but shipped with no way to actually turn it on — DEFAULT_CONFIG+// hardcoded 1 (disabled) with no env/config knob, unlike every sibling+// tunable in this file. Parsed once at module load; invalid/out-of-range+// values fall through to the constructor's own priorDecay<=0||>1 guard,+// which already normalizes to 1 (disabled) — so an unset or malformed env+// var is fully backward compatible with existing deployments.+function envPriorDecay(): number | undefined {+ const raw = process.env.CLAUDE_FLOW_PRIOR_DECAY;+ if (!raw) return undefined;+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0 || n > 1) return undefined;+ return n;+}+const DEFAULT_CONFIG: ModelRouterConfig = {confidenceThreshold: 0.85,maxUncertainty: envMaxUncertainty() ?? 0.15,@@ -521,7 +538,7 @@ const DEFAULT_CONFIG: ModelRouterConfig = {autoSaveInterval: 1, // Save after every decision for CLI persistenceenableCostOptimization: true,preferSpeed: true,- priorDecay: 1,+ priorDecay: envPriorDecay() ?? 1,};// Beta shape parameters must stay well clear of 0 for sampleGamma/sampleBeta