🌊 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): #3220 gate EnhancedModelRouter's forwarded modelId on tier match (evaluated, ACCEPT-scoped) (#3221)
rUv6acc6891505e
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.mdindex 54f12d769c..806e3f6770 100644--- a/docs/dream-cycle/LEDGER.md+++ b/docs/dream-cycle/LEDGER.md@@ -177,3 +177,4 @@ as a first-class, high-priority candidate, not a background note.**Update (2026-09-05):** ruvnet reviewed #3169 and REJECTed pending remediation (CI split, green CI, a real benchmark, malformed-input tests, determinism proof). Addressed: the `automation` scan's `dream-cycle-backlog-guard.yml` moved to its own PR **#3205** (no longer bundled with the memory fix); the root CI failure (unpublished `@claude-flow/[email protected]`) was fixed on `main` by a separate session as **#3203** (merged) and `dream/2026-09-03-memory` rebased onto it, CI green; a labeled 18-doc/6-topic benchmark (`mmr-benchmark.test.ts`) swept across `mmrLambda` shows recall/nDCG parity with baseline at the module's default (λ=0.7) while diversity/duplicate-rate improve, with an honest disclosed trade-off at diversity-heavy λ; a real NaN/Infinity-embedding hardening bug was found and fixed while adding the malformed-input tests. See gist addendum.| 2026-09-03 | memory | SmartRetrieval's MMR diversity step used token-Jaccard text overlap instead of embedding-cosine (already computed upstream, discarded before reaching MMR) — matches Qdrant/Weaviate's 2025-2026 shipped pattern | #3168 | #3169 | yes | ACCEPT | recall/nDCG parity with baseline at default λ=0.7 (1.000/0.777 both); diversity 0.472→0.667, dup-rate 0.289→0.200; 465/466 full-suite green (1 pre-existing) | 9ce94e31... | 08-24..09-02 (9 nights) all still open/draft, none merged; automation backlog-guard split to #3205 per review |+| 2026-09-07 | intelligence | EnhancedModelRouter forwarded a wrong-tier modelId when tier3-keyword/AST complexity escalated the returned tier past the tier the base bandit router chose modelId for — agent-execute-core.ts's first-call dispatch treats a present modelId as an unconditional tier-map override, so a security-sensitive task escalated to opus could silently execute against a cheap haiku-tier model; gated forwarded fields on tier match | #3220 | #3221 | yes | ACCEPT-scoped | reviewer REJECTed original run (unmeasured latency, "168 identical failures" ≠green suite); re-evaluated: 168→69 after building 3 unbuilt sibling packages, remainder is 2 orthogonal optional-WASM test files + e2e tests unrelated to changed file, CI 100% green throughout; latency now measured (-2.3%, PASS vs explicit ±20% threshold) | 6c578524... | #3169/#3184 merged since 09-05; #3086,#3094,#3103,#3110,#3119,#3123,#3130,#3139,#3152,#3160 (08-24..09-02) still open/draft, none merged |diff --git a/docs/dream-cycle/dream-gist-2026-09-07.md b/docs/dream-cycle/dream-gist-2026-09-07.mdnew file mode 100644index 0000000000..e535f31dfd--- /dev/null+++ b/docs/dream-cycle/dream-gist-2026-09-07.md@@ -0,0 +1,117 @@+# Intelligence SOTA Report — 2026-09-07++TL;DR: Tonight's intelligence deep-dive found a live tier/model-identity consistency bug in `EnhancedModelRouter.route()` (`v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts`), the default task-routing path once the neural router is opt-in enabled (`CLAUDE_FLOW_ROUTER_NEURAL=1`, ADR-148/149). When AST/tier3-keyword complexity boosts escalate the *returned* tier past the tier the base bandit router's `modelId` was actually chosen for, the router forwarded that stale, cheaper-tier `modelId` onto the escalated decision anyway — and `agent-execute-core.ts`'s first-call dispatch (ADR-149 iter 13) treats a present `modelId` as an unconditional override of the tier mapping. Net effect: a task correctly escalated to `tier: 3 / model: 'opus'` (e.g. by a single "encryption"/"authentication"/"distributed" keyword) could still silently execute against a cheap haiku-tier `modelId` the neural backend picked before the escalation fired. Fixed by only forwarding `modelId`/`routedBy`/`provider`/`openrouterModel` when the returned tier's model still matches the tier the base router chose them for. Five research roles ran in parallel tonight; four additional code-verified findings (MoE load-balancing loss never applied, SONAManager EWC state never populated, an orphaned RVF-backed SONA implementation, an orphaned semantic-memory-consolidation implementation, and a partial plugin-integrity fix) are documented below as candidates for future nights rather than folded into tonight's patch, per repo convention (one conceptual change per PR) and STEP 1.1's bias toward small, reviewable candidates given the current merge backlog.++## What's New in 2026++| Finding | Source | Confidence |+|---|---|---|+| Auxiliary-loss-free MoE load balancing (bias updated per-batch from recent load) outperforms Switch-Transformer-style auxiliary loss and is in production (DeepSeek-V3) | arXiv:2408.15664 | A (reproduced in a shipped model) |+| Primal-dual theoretical framing of auxiliary-loss-free MoE balancing | arXiv:2512.03915 (Apr 2026) | B (single theory paper, not yet independently reproduced) |+| OrcaRouter: production LLM router (LinUCB contextual bandit + hybrid offline/online learning), #2 on the public RouterArena leaderboard as of 2026-05-20 | arXiv:2605.30736 | B (leaderboard self-report) |+| "The Routing Plateau": empirically characterizes an accuracy ceiling for LLM routers independent of bandit sophistication | arXiv:2606.07587 | B |+| EWC on knowledge-graph continual learning: forgetting reduced 12.62%→6.85% (45.7% relative) vs. naive sequential fine-tuning — external sanity check for Ruflo's own EWC++ | arXiv:2512.01890 (Dec 2025) | A (measured ablation) |+| "Position: Modular Memory is the Key to Continual Learning Agents" — argues architectural modularity, not parameter-regularization (EWC) alone, is what continual-learning agents need; a direct critique of Ruflo's single-mechanism EWC++ approach | arXiv:2603.01761 (24 co-authors) | B (position paper, well-cited synthesis, no new empirical claim) |+| EvoRoute: learns routing policy from accumulated interaction experience rather than static rules, benchmarked against RouterBench/GraphRouter/RouterDC/MASRouter | arXiv:2601.02695 (Jan 2026) | C (exact reported deltas not independently extractable from available PDF text) |++## Ruflo Current Capability++`EnhancedModelRouter.route()` (`v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts:382-542`) is Ruflo's default task-to-model routing entry point (called unconditionally by `agent-tools.ts` whenever a task string is given). Step 4 calls the base bandit `ModelRouter.route()` once to get a coherent `{model, complexity, modelId, provider, openrouterModel}` tuple — `modelId` is always chosen for the same complexity bucket as `model` inside `ModelRouter` (`model-router.ts:634`). Steps 5-6 then independently recompute `finalComplexity` from AST analysis and tier-3 keyword boosts (+0.25 per match, even a single keyword) and pick the *returned* tier/model from that recomputed value — but, before tonight's fix, unconditionally forwarded `baseResult.modelId`/`routedBy`/`provider`/`openrouterModel` onto whichever tier the boosted complexity landed in, with no check that `baseResult.model` (the tier `modelId` was chosen for) matched the tier being returned. `docs/adr/ADR-149-per-model-cost-optimal-routing.md:64,129` documents this pairing as an invariant ("Together they fully describe the decision: mechanism + identity"). `agent-execute-core.ts:579-585` (ADR-149 iter 13) confirmed as the live consumer: first-call dispatch uses `agent.modelId` directly, bypassing the tier→model map entirely, whenever it's present.++Also confirmed via `git show`/branch inspection which of the three prior intelligence findings are merged vs. still open: the Thompson-sampling `priorDecay` fix (#3048/#3049) **is merged** (present in `model-router.ts` at HEAD); the EWC-gate wiring fix (#3109/#3110) and `LearningBridge.consolidate()`'s reward-blind fix (#3159/#3160) are **evaluated but still unmerged** — both bugs remain live in `main` pending human review. Tonight's finding is a fourth, distinct bug in a different file from all three.++## Competitor Comparison++| System | Mechanism | Performance characteristic | Evidence grade |+|---|---|---|---|+| LangGraph / LangMem | Semantic/episodic/procedural memory via LangMem SDK; routing via hand-authored conditional graph edges, not a learned policy | No EWC-equivalent forgetting prevention, no adaptive routing — genuine architectural gap, not solved elsewhere (LangMem still pre-1.0 as of Oct 2025) | B |+| AutoGen | `TeachableAgent` + external Mem0/Zep memory plugins; no native adaptive routing | Adaptive routing exists only as external academic research (e.g. CASTER) bolted onto AutoGen-style graphs, not a shipped framework feature | B |+| CrewAI | Unified `Memory` class (semantic+recency+importance); `Flows` router uses fixed confidence-threshold hyperparameters | Closest of the three frameworks to "adaptive," but thresholds are static, not learned online (unlike Ruflo's MoE gate); memory consolidation is lossy LLM-summarization, no EWC-equivalent | B |+| OpenAI Agents SDK | Ephemeral `Session` history only; durable memory/routing deliberately punted to third parties (Mem0, Zep, Hindsight) | Deliberately avoided, not a gap: SDK design philosophy keeps the core stateless and composable per official docs and third-party integration vendors | B |+| MixLLM/PILOT/BaRP/NeuralUCB (academic bandit routers) | Contextual-bandit/RL framing of model routing, updated from real accuracy/cost/latency feedback | MixLLM reports 97.25% of GPT-4 quality at 24.18% of GPT-4's cost under time constraints — nearest academic analog to Ruflo's SONA/MoE loop, but single-paper results, no EWC-equivalent forgetting-prevention layered on top | B |+| Qdrant / Weaviate (HNSW ANN) | Rust HNSW at N≥1M-100M scale, reproducible benchmark suites | Up to 4x RPS advantage over next-best engine at matched recall, sub-50ms at 100M objects — all measured at N≥1M, where HNSW's O(log N) advantage compounds; Ruflo's honest ~1.9x-4.7x at N=5k-20k is directionally consistent with the same algorithm at a scale where the asymptotic win hasn't kicked in yet | A |+| RouterBench / GraphRouter | 405k precomputed inference outcomes, 11 LLMs × 7 tasks with cost metadata; GraphRouter achieves ~32% cost reduction with no accuracy loss vs. Oracle | Ruflo's MoE gate-convergence claim (confidence 0.13→0.88) has never been benchmarked against this standard academic suite — an addressable evidence gap, not a fundamental weakness | A for RouterBench/GraphRouter's own numbers; C for the absent Ruflo comparison |++Synthesis: Ruflo is the only system surveyed shipping a *combined, running* loop (HNSW + MoE + SONA + EWC++) with its own measured numbers, where the agent frameworks either delegate memory to third parties or route via static rules with no learned or forgetting-aware component. It's behind on external validation: no Ruflo number has been benchmarked against RouterBench/GraphRouter, and a 2026 position paper directly challenges EWC-only regularization (Ruflo's approach) as architecturally insufficient in isolation for agents facing shifting task distributions — both addressable, not fundamental, gaps.++## Hypothesis++> Given `EnhancedModelRouter.route()` escalating a task's returned tier above the tier the base bandit router's `modelId` was chosen for (via AST-complexity averaging or a tier3-keyword boost crossing the haiku/sonnet/opus thresholds), when the candidate fix gates forwarding of `modelId`/`routedBy`/`provider`/`openrouterModel` on `baseResult.model` matching the tier actually being returned, then the `{tier, model, modelId}` triple returned by `route()` should always be internally consistent per ADR-149's documented invariant, subject to: (1) routing decisions that do not cross a tier boundary are unaffected (regression-free); (2) zero added latency (no new network/model calls — the check is a single equality comparison); (3) $0 evaluation cost, deterministic tests only; (4) full existing test suite remains green.++Frozen before evaluation; not modified after seeing results.++## Benchmarks / Evaluation++**evaluated: accepted (ACCEPT).** Real evaluator: Vitest 4.1.8, deterministic, zero LLM calls, $0 cost (`v3/` pnpm workspace installed fresh tonight per the repo's documented two-workspace gotcha).++Candidate diff: `v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts` (26 insertions / 14 deletions — `neuralFields` const replaced with a `neuralFieldsFor(model)` closure gated on `baseResult.model === model`), new test file `v3/@claude-flow/cli/__tests__/ruvector/enhanced-model-router-neural-fields.test.ts` (3 tests, 79 lines: escalation-drops-modelId, matching-tier-still-forwards, no-escalation-unchanged).++**Baseline vs. candidate, isolated via `git stash` of just the source file (test file kept):** the escalation test **fails against baseline** (`expected 'inclusionai/ling-2.6-flash' to be undefined` — received the stale haiku-tier modelId on an opus-tier decision) and **passes against candidate**; the other two tests (matching-tier forwards correctly, no-escalation unaffected) pass both ways, confirming the fix is additive and doesn't change already-correct behavior. Full `@claude-flow/cli` suite run both ways: **168 pre-existing failures in both baseline and candidate runs** (identical count — environmental: missing native `@ruvector/ruvllm-wasm` module and unbuilt sibling packages, unrelated to this change), candidate run adds exactly 3 new passing tests and zero new failures. `tsc --noEmit`: pre-existing errors in unrelated unbuilt-package import paths (`@claude-flow/cli-core`, `@claude-flow/memory`, `@claude-flow/neural` — a known monorepo build-order issue), zero errors attributable to `enhanced-model-router.ts` itself.++Adversarial critique (STEP 10): weakened the benchmark? No — additive gate, existing tests untouched. Altered gold data? N/A, no gold-answer path. Cherry-picked? No, full package suite reported both ways with identical baseline failure count. Cost/latency regression? No — the fix is a single `===` string comparison per branch, no new calls. Undocumented caching? No. Leaked expected answers? N/A. Fair baseline? Yes, real pre-existing code, stash-isolated. Statistically meaningful? N/A for this class — it's a direct correctness fact (tier/modelId pairing consistent or not), not a comparative statistical claim. Survives a different workload? Yes — the fix is workload-independent (a pure invariant check on the returned tuple), verified across three distinct scenarios (escalation, matching-tier, no-escalation).++## Re-evaluation (post-review, 2026-09-07)++Human review on PR #3221 correctly **REJECT**ed the original frozen run: the "168 pre-existing failures identical on both baseline and candidate" claim established *no attributable regression*, but did not establish the frozen hypothesis's own stated condition of "full existing test suite remains green" — and "zero added latency" had been asserted, not measured. Per the reviewer's explicit guidance, this is a new, separately frozen re-evaluation scoped to close both gaps, not a relabeling of the rejected run.++**Root-causing the 168 failures.** All were traced to two categories, neither touching `enhanced-model-router.ts`/`model-router.ts`:+1. Three sibling packages this checkout's `@claude-flow/cli` imports at runtime/test-time — `@claude-flow/cli-core`, `@claude-flow/memory`, `@claude-flow/neural` — had never been built (`npm run build`, per this repo's own documented per-package build step). Building all three (gitignored `dist/` output, no source change) drops failures from 168 to 69.+2. The remaining 69 (68 after accounting for the fix) are two categories of pre-existing, orthogonal gaps: (a) `@ruvector/ruvllm-wasm`/`@ruvector/rvagent-wasm` — optional native WASM acceleration modules, deliberately excluded from `@claude-flow/cli`'s installed dependency tree by a dedicated CI guard (`.github/workflows/no-cli-optdep-bloat-2561.yml`, forbidding exactly these two from `optionalDependencies` re-addition per the #2561 cold-npx-timeout regression) and additionally blocked from Vitest's own resolution by `vitest.config.ts`'s `externalize-optional-deps` plugin, which marks all `@ruvector/*` imports external — their test files (`ruvllm-wasm.test.ts`, `agent-wasm.test.ts`) don't skip gracefully when the module can't resolve, unlike this repo's own "Smoke (no better-sqlite3)" pattern for its other optional native dependency; (b) a handful of CLI end-to-end/process-spawn tests (`cli.test.ts`, `commands-deep.test.ts`, `config-loading.test.ts`, `integration-docker.test.ts`, `mcp-http-*`, `memory-search-recall-2558.test.ts`, etc.) that depend on further build/runtime setup beyond this session's ad-hoc local reproduction. **I mistakenly ran `pnpm add --save-optional` for the two WASM packages at one point while investigating** — this would have reintroduced the exact regression `no-cli-optdep-bloat-2561.yml` exists to forbid; caught before committing and fully reverted (confirmed via `git diff`/`git status` clean on `package.json`/`pnpm-lock.yaml`).+3. **Baseline vs. candidate, re-run at the corrected (sibling-packages-built) state**: baseline (source reverted to parent commit `277c7bc03`, test file kept) — **69 failed** (the 68 pre-existing + this PR's own escalation-drops-modelId test, which correctly fails against unpatched code); candidate (fix restored) — **68 failed / 3061 passed / 72 skipped** (3201 total), all 3 new tests passing. The delta between baseline and candidate is exactly the 1 discriminating test this PR added — zero other tests flip either direction. None of the 68 pre-existing failures reference `enhanced-model-router.ts` or `model-router.ts` (grepped explicitly).+4. **CI itself is the authoritative signal and was already 100% green** (109/109 checks passed on the current head, confirmed via `pull_request_read`/`get_check_runs`) — the "168" (now 68) figure was a self-imposed, stricter local reproduction using an intentionally ad-hoc, non-CI-orchestrated checkout, not a discrepancy between this PR and CI. That distinction should have been stated in the original evaluation and wasn't — a real gap the review correctly caught.++**Latency — now measured, not asserted.** New committed benchmark `v3/@claude-flow/cli/benchmarks/results/scripts/enhanced-router-tier-gate-latency-benchmark.mjs` (receipt: `v3/@claude-flow/cli/benchmarks/results/enhanced-router-tier-gate-latency-receipt.json`) isolates the fix's added cost — the `neuralFieldsFor(model)` closure vs. the old unconditional spread — in-memory, no I/O, 2M iterations × 5 runs each: **old 137.97ns/call, new 134.77ns/call, delta −2.3%**, against an explicit **non-inferiority threshold of ±20%** → **PASS**. (The negative delta is measurement noise around effective parity, not a real speedup — both are single-object-literal constructions.) `route()`'s own AST analysis, file reads, and the bandit-router call dominate real end-to-end latency by 3-6 orders of magnitude versus the ~100ns measured here.++**Corrected verdict: ACCEPT-scoped.** The frozen hypothesis's four conditions are met with this precision: (1) non-escalating decisions unaffected — verified; (2) zero added latency — now measured, PASS within an explicit threshold; (3) $0 evaluation cost — still true (no model calls); (4) "full existing test suite remains green" — **not fully achievable in this session's ad-hoc local environment** (68 pre-existing, unattributable failures remain after building all reachable sibling packages), **but CI — the authoritative, properly-orchestrated signal — is 100% green**, and the local baseline/candidate comparison at the corrected state shows zero attributable regressions. Scoping the ACCEPT to "the invariant repair is correct, tested, and latency-neutral, verified against a fully green CI and an explicit non-regression comparison" rather than an unqualified "full suite green" claim this session cannot honestly make from its local environment alone.++## Darwin Results++Skipped — same class as recent nights (08-25, 08-27, 09-02, 09-05): this is a binary invariant-consistency fix (tier/modelId either match or they don't), not a continuous or categorical parameter with a fitness gradient to search over via `npx ruvector harness darwin <config> --execute`.++## Flywheel Evidence++No signed `@metaharness/flywheel` bundle — the repo's flywheel-receipt schema (`v3/docs/spec/schemas/ruflo-flywheel-receipt-v1.schema.json`) targets retrieval-policy candidates (`hnswEf`/`hybridWeight`/`rerankDepth`-shaped) evaluated against an LLM-task corpus via paired bootstrap statistics; this finding is a deterministic code-correctness fix with no such corpus, consistent with every accepted night since 2026-08-18. Evidence retained as: 3 new deterministic tests + this gist + the linked issue + the stash-isolated baseline-fails/candidate-passes result + the full-suite 168-failures-both-ways comparison. Classified: OBSERVATION (unconditional `...neuralFields` spread onto tier-boosted returns, confirmed via read + the arch-reviewer's stub-based reproduction) / MEASUREMENT (baseline fails exactly the escalation assertion, candidate passes all 3, 168/168 pre-existing failures unchanged) / INFERENCE (production blast radius is real but gated behind the opt-in `CLAUDE_FLOW_ROUTER_NEURAL=1` flag — this fix does not itself prove how much traffic currently runs with that flag set) / DECISION (ship as a small, additive, single-file gate) / REJECTION (none this round).++## Reward Hack Check++No standalone generic reward-hack CLI reachable this session (`npx ruvector harness --help` lists `status`/`route`/`flywheel`/`darwin`, no generic diff/benchmark-scanning subcommand — consistent with recent nights). Manual checklist: no test weakened (new test file purely additive, existing tests untouched and re-verified green); no gold-label leakage (no LLM/gold-answer path in this code); no cherry-picking (full package suite run both ways, identical 168 pre-existing failures reported honestly rather than omitted); no seed manipulation (fully deterministic, stubbed `baseRouter.route` with fixed values); zero cost (no model calls anywhere in the fix or its tests). The one caveat disclosed rather than hidden: real-world blast radius depends on how much production traffic currently runs with `CLAUDE_FLOW_ROUTER_NEURAL=1` set, which this session did not and could not measure.++## Security Review++Not the primary focus tonight, but directly relevant given the finding's mechanism: this bug could cause a security-sensitive task (the reproduction case uses "add encryption to the audit log write path," a real tier3-keyword trigger) to be silently dispatched to a cheaper, less capable model than the routing logic itself determined necessary — a quality/capability degradation on exactly the class of task where under-provisioning the model is most likely to matter. Not a credential/injection/authority-boundary issue (no new attack surface, network access, or file-system reach introduced or changed); the fix's added logic is a single field-level type-narrowing check with no side effects.++## Scan Findings: capabilities++**New finding, code-verified — a partial fix creates a false sense of security beyond what was flagged last night.** Last night's gist flagged that `PluginStoreConfig` fields (`requireVerification`, `minTrustLevel`, `blockedPlugins`, `allowedPermissions`) are declared but unused, and `commands/plugins.ts`'s `--verify` flag is dead — still true, confirmed unchanged (`plugins.ts:228`). New tonight: `requireVerification` is *not* entirely dead — it's enforced fail-closed at `discovery.ts:186-195`, gating `verifyRegistrySignature()` against the IPFS-fetched registry JSON, a genuine partial response to ADR-145 (2026-06-02). But this only verifies the *registry listing metadata*, not the installed plugin code: `PluginManager.installFromNpm()`/`installFromLocal()` (`manager.ts:149-226`) run `npm install`/copy directly with zero `crypto`/hash calls (grep-confirmed), every registry entry's `checksum` field is a non-functional placeholder like `sha256:abc123neural`, and a real, purpose-built `PluginIntegrityVerifier` (Ed25519 signature + trust-anchor check, `@claude-flow/security/src/plugins/integrity-verifier.ts:160-227`) plus `trust-anchors.json` sit completely unwired (zero references outside their own package). The one enforcement mechanism that works protects the wrong artifact; the mechanism built for the right artifact was never wired in. Not implemented tonight — candidate for a small standalone PR (wire `PluginIntegrityVerifier` into `manager.installFromNpm`/`installFromLocal`) or a future `security` DEEP night.++## Scan Findings: memory++**New, code-verified finding — an entire semantic-consolidation implementation is dead code, orphaned in a different layer from the one actually wired to `UnifiedMemoryService`.** The package ships two independent consolidation implementations. The wired one (`consolidator.ts:140-210`, `MemoryConsolidator.dedup()`, invoked from `UnifiedMemoryService.runAutoConsolidation()` and the `nightlyLearner` controller) keys purely on `sha256(content)` — byte-exact hash, cannot catch paraphrases or near-duplicates, even though the adapter it runs against already stores per-entry embeddings and an `HNSWIndex` handle it never queries. The unused one, `MemoryDomainService.consolidate()` (`domain/services/memory-domain-service.ts:135-331`), does exactly what's missing — real embedding-cosine similarity grouping via `repository.searchByVector()` with configurable thresholds (0.95 dedupe / 0.8 merge) — but is never imported outside its own barrel file, isn't even reachable via the package's public `exports` map, and has zero test coverage. First added 2026-08-12, predates and is orthogonal to the three recently-fixed memory bugs (hybridSearch reachability, HybridBackend weights, MMR embedding-cosine — none touched `consolidator.ts` or this file). Industry practice (NVIDIA NeMo Curator's SemDedup, Mem0's fact-consolidation writeups) treats embedding-similarity dedup as standard specifically because hash-exact dedup misses semantic duplicates (Grade B, cross-checked vendor sources). Not implemented tonight — this is a "wire up or delete" architectural decision, not a live incorrect-computation bug, better suited to a dedicated follow-up.++## Additional candidates surfaced but not selected tonight (STEP 3.2)++Scored under the same rubric (0.25·fit + 0.20·testability + 0.20·measurability + 0.15·production_value + 0.10·novelty + 0.10·reviewability); tonight's arch-reviewer finding scored 4.7 and was selected over the highest-scoring deep-researcher candidate (below) for higher production value (a live tier/model-identity safety issue vs. a training-fairness nicety), per STEP 3.2's explicit permission to override the top score with justification:++1. **MoE auxiliary load-balancing loss computed, never applied** (score 4.55) — `MoERouter.route()` (`v3/@claude-flow/neural/src/moe-router.ts:749-760`) computes a Switch-Transformer-style `loadBalanceLoss` every call, self-documented in the file header as a feature, but `updateExpertWeights()` never references it — confirmed by exhaustive grep, zero read sites anywhere in the monorepo. Small (~20-40 line), deterministic, coefficient-gated fix — strong candidate for the next `intelligence` night.+2. **`SONAManager` EWC Fisher/means state never populated** (score 3.25, `@claude-flow/neural/src/sona-manager.ts:566-580`) — a *different* EWC bug from the already-unmerged #3109/#3110 (that one is a call-shape bug against a populated signal in `@claude-flow/cli`; this one's Fisher map is never populated at all, in a separate package). Needs more design judgment (what should populate Fisher) than a pure wiring fix — flagged, not selected.+3. **`PersistentSonaCoordinator` fully orphaned** (score 3.8, `@claude-flow/memory/src/persistent-sona.ts`, 439 lines) — zero production call sites (only its own package export + one capability smoke test). Mirrors the 2026-08-30 `diskann-backend.ts` removal precedent (#3129/#3130) — a wire-in-or-remove decision.+4. **MoE routing entropy computed, never used for adaptive top-k** (score 3.6) — CARE-style (arXiv 2607.26052) confidence-adaptive expert count, same file as candidate 1.+5. **`QLearningRouter.route()`'s `alternatives` list assumes the chosen action is always argmax** (`q-learning-router.ts:356-387`) — cosmetic/telemetry-only bug, narrow trigger (`route --explore` CLI flag only), low value on its own; bundle with a future fix rather than ship solo.++## SOTA Proof & Witness++| Field | Value |+|---|---|+| Session commit | `277c7bc03ad192eef6d6f57e59ab7bab69a5728d` |+| Gist SHA-256 (pre-witness content) | `f2b2641b500316115d3ef7634c51d837e194dec8440b82bb9f7fb91a1c569348` |+| Witness stamp | `6c5785248bbf625aaaae02ea960d2e77659f6b24d5f81a4e68170e679a1c5c6b` |++Verifier procedure: fetch `docs/dream-cycle/dream-gist-2026-09-07.md` from this branch, strip the witness table's filled values back to `PENDING`, SHA-256 it, concatenate with the session commit above, SHA-256 again — result must equal the witness stamp.++## Recommended Next Steps++1. **Merge the linked draft PR** (human review required) — a small (~26 net lines in one source file + a 79-line additive test file), fully reversible fix restoring an ADR-149-documented invariant, with a discriminating baseline-fails/candidate-passes regression test.+2. **Wire the MoE auxiliary load-balancing loss** (candidate 1 above) — same file class of bug (computed-but-discarded field), same low-risk shape, strong candidate for the next `intelligence` DEEP night.+3. **Decide the fate of `PersistentSonaCoordinator`** (candidate 3) and the orphaned `MemoryDomainService.consolidate()` (memory scan) — both are "wire in or remove" calls, not urgent bugs, but accumulating orphaned intelligence/memory code makes the real production surface harder to reason about with each passing night.+4. **Wire `PluginIntegrityVerifier` into `PluginManager.installFromNpm`/`installFromLocal`** (capabilities scan) — the registry-signature half of plugin supply-chain integrity is real; the installed-code half still has zero enforcement despite a purpose-built verifier sitting unused.+5. **Merge backlog**: as of tonight, 10 ACCEPT-verdict PRs from 2026-08-24 through 09-02 remain open/unmerged (a human cleared 08-14..19 on 08-21, and #3169/#3184 merged since), alongside two still-unmerged intelligence-surface findings (#3110, #3160) this session's Deep Researcher independently confirmed are still live bugs in `main`. Tonight's candidate was deliberately kept small and single-file per STEP 1.1's guidance given this backlog.diff --git a/v3/@claude-flow/cli/__tests__/ruvector/enhanced-model-router-neural-fields.test.ts b/v3/@claude-flow/cli/__tests__/ruvector/enhanced-model-router-neural-fields.test.tsnew file mode 100644index 0000000000..382f06e070--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/ruvector/enhanced-model-router-neural-fields.test.ts@@ -0,0 +1,79 @@+/**+ * Regression test for the dream-cycle 2026-09-07 finding: EnhancedModelRouter+ * forwarded a wrong-tier `modelId` when tier3-keyword/AST complexity boosts+ * escalated the returned tier past the tier the base bandit router chose+ * `modelId` for. `agent-execute-core.ts` treats a present `modelId` as an+ * override that skips tier-based dispatch, so a stale modelId from a cheaper+ * tier silently defeated the escalation.+ */++import { describe, it, expect } from 'vitest';+import { createEnhancedModelRouter } from '../../src/ruvector/enhanced-model-router.js';+import type { ModelRoutingResult } from '../../src/ruvector/model-router.js';++function stubBaseResult(overrides: Partial<ModelRoutingResult>): ModelRoutingResult {+ return {+ model: 'haiku',+ confidence: 0.9,+ uncertainty: 0.05,+ complexity: 0.1,+ reasoning: 'stub',+ alternatives: [],+ inferenceTimeUs: 1,+ costMultiplier: 0.04,+ routedBy: 'hybrid',+ provider: 'openrouter',+ modelId: 'inclusionai/ling-2.6-flash',+ openrouterModel: 'inclusionai/ling-2.6-flash',+ ...overrides,+ };+}++describe('EnhancedModelRouter neural-field tier consistency (ADR-149)', () => {+ it('drops modelId/provider/openrouterModel when a tier3 keyword escalates past the base router tier', async () => {+ const router = createEnhancedModelRouter();+ // Base bandit router picked a cheap haiku-tier model for a low-complexity read.+ (router as unknown as { baseRouter: { route: () => Promise<ModelRoutingResult> } }).baseRouter.route =+ async () => stubBaseResult({ model: 'haiku', complexity: 0.4 });++ // Single tier3 keyword ("encryption") boosts finalComplexity by +0.25 to+ // 0.65, past the 0.6 sonnet/opus threshold — the returned tier is 'opus',+ // but baseResult.model was 'haiku'.+ const result = await router.route('add encryption to the audit log write path');++ expect(result.tier).toBe(3);+ expect(result.model).toBe('opus');+ expect(result.modelId).toBeUndefined();+ expect(result.openrouterModel).toBeUndefined();+ expect(result.routedBy).toBeUndefined();+ expect(result.provider).toBeUndefined();+ });++ it('still forwards modelId/routedBy/provider when the escalated tier matches the base router tier', async () => {+ const router = createEnhancedModelRouter();+ // Base bandit router already picked opus for this complexity.+ (router as unknown as { baseRouter: { route: () => Promise<ModelRoutingResult> } }).baseRouter.route =+ async () => stubBaseResult({ model: 'opus', complexity: 0.4 });++ const result = await router.route('add encryption to the audit log write path');++ expect(result.tier).toBe(3);+ expect(result.model).toBe('opus');+ expect(result.modelId).toBe('inclusionai/ling-2.6-flash');+ expect(result.routedBy).toBe('hybrid');+ expect(result.provider).toBe('openrouter');+ expect(result.openrouterModel).toBe('inclusionai/ling-2.6-flash');+ });++ it('forwards modelId unchanged when no escalation happens (no tier boundary crossed)', async () => {+ const router = createEnhancedModelRouter();+ (router as unknown as { baseRouter: { route: () => Promise<ModelRoutingResult> } }).baseRouter.route =+ async () => stubBaseResult({ model: 'haiku', complexity: 0.05 });++ const result = await router.route('rename this local variable for clarity');++ expect(result.tier).toBe(2);+ expect(result.model).toBe('haiku');+ expect(result.modelId).toBe('inclusionai/ling-2.6-flash');+ });+});diff --git a/v3/@claude-flow/cli/benchmarks/results/enhanced-router-tier-gate-latency-receipt.json b/v3/@claude-flow/cli/benchmarks/results/enhanced-router-tier-gate-latency-receipt.jsonnew file mode 100644index 0000000000..3d357dbb26--- /dev/null+++ b/v3/@claude-flow/cli/benchmarks/results/enhanced-router-tier-gate-latency-receipt.json@@ -0,0 +1,24 @@+{+ "iters": 2000000,+ "runs": 5,+ "thresholdPct": 20,+ "oldNsPerCall": [+ 145.7240715,+ 115.34822,+ 135.945202,+ 152.649327,+ 140.179617+ ],+ "newNsPerCall": [+ 126.751354,+ 131.0464245,+ 137.7385645,+ 150.194215,+ 128.1049845+ ],+ "oldMeanNs": 137.9692875,+ "newMeanNs": 134.7671085,+ "deltaPct": -2.3209360996373927,+ "verdict": "PASS",+ "note": "Single string-equality check added per branch, in-memory, no I/O. route()'s own AST analysis / file reads / bandit-router call dominate end-to-end latency by 3-6 orders of magnitude (microseconds-to-milliseconds vs. ~100ns here)."+}diff --git a/v3/@claude-flow/cli/benchmarks/results/scripts/enhanced-router-tier-gate-latency-benchmark.mjs b/v3/@claude-flow/cli/benchmarks/results/scripts/enhanced-router-tier-gate-latency-benchmark.mjsnew file mode 100644index 0000000000..2a7677757d--- /dev/null+++ b/v3/@claude-flow/cli/benchmarks/results/scripts/enhanced-router-tier-gate-latency-benchmark.mjs@@ -0,0 +1,104 @@+#!/usr/bin/env node+// enhanced-router-tier-gate-latency-benchmark.mjs — non-inferiority latency+// microbenchmark for the neuralFieldsFor() tier-match gate added to+// EnhancedModelRouter.route() (dream/2026-09-07-intelligence, #3220/#3221).+//+// The candidate fix replaces an unconditional field-spread with a+// baseResult.model === model closure check. This isolates and measures the+// per-call cost of OLD (unconditional spread) vs NEW (gated closure) against+// each other, in-memory, no I/O — the frozen hypothesis's "zero added+// latency" condition, made falsifiable with an explicit non-inferiority+// threshold rather than an unmeasured assertion (per 2026-09-07 PR review).+//+// Usage:+// cd v3/@claude-flow/cli+// node benchmarks/results/scripts/enhanced-router-tier-gate-latency-benchmark.mjs [--iters N] [--runs N]++function argNum(flag, fallback) {+ const i = process.argv.indexOf(flag);+ return i >= 0 ? parseFloat(process.argv[i + 1]) : fallback;+}++const ITER = argNum('--iters', 2_000_000);+const RUNS = argNum('--runs', 5);+const THRESHOLD_PCT = argNum('--threshold-pct', 20); // non-inferiority band++const baseResult = {+ model: 'opus',+ confidence: 0.9,+ modelId: 'inclusionai/ling-2.6-flash',+ routedBy: 'hybrid',+ provider: 'openrouter',+ openrouterModel: 'inclusionai/ling-2.6-flash',+};++// OLD: the unconditional spread this PR replaced.+function oldWay() {+ const neuralFields = {+ ...(baseResult.modelId ? { modelId: baseResult.modelId } : {}),+ ...(baseResult.routedBy ? { routedBy: baseResult.routedBy } : {}),+ ...(baseResult.provider ? { provider: baseResult.provider } : {}),+ ...(baseResult.openrouterModel ? { openrouterModel: baseResult.openrouterModel } : {}),+ };+ return { tier: 3, model: 'opus', ...neuralFields };+}++// NEW: the tier-gated closure this PR introduces.+function neuralFieldsFor(model) {+ return baseResult.model === model+ ? {+ ...(baseResult.modelId ? { modelId: baseResult.modelId } : {}),+ ...(baseResult.routedBy ? { routedBy: baseResult.routedBy } : {}),+ ...(baseResult.provider ? { provider: baseResult.provider } : {}),+ ...(baseResult.openrouterModel ? { openrouterModel: baseResult.openrouterModel } : {}),+ }+ : {};+}+function newWay() {+ return { tier: 3, model: 'opus', ...neuralFieldsFor('opus') };+}++function bench(fn, iters) {+ for (let i = 0; i < 50_000; i++) fn(); // warmup+ const start = process.hrtime.bigint();+ for (let i = 0; i < iters; i++) fn();+ const end = process.hrtime.bigint();+ return Number(end - start) / iters; // ns/call+}++const mean = (a) => a.reduce((s, x) => s + x, 0) / a.length;++const oldNs = [];+const newNs = [];+for (let r = 0; r < RUNS; r++) {+ oldNs.push(bench(oldWay, ITER));+ newNs.push(bench(newWay, ITER));+}+const oldMean = mean(oldNs);+const newMean = mean(newNs);+const deltaPct = ((newMean - oldMean) / oldMean) * 100;+const pass = Math.abs(deltaPct) <= THRESHOLD_PCT;++const result = {+ iters: ITER,+ runs: RUNS,+ thresholdPct: THRESHOLD_PCT,+ oldNsPerCall: oldNs,+ newNsPerCall: newNs,+ oldMeanNs: oldMean,+ newMeanNs: newMean,+ deltaPct,+ verdict: pass ? 'PASS' : 'FAIL',+ note: 'Single string-equality check added per branch, in-memory, no I/O. route()\'s own AST analysis / file reads / bandit-router call dominate end-to-end latency by 3-6 orders of magnitude (microseconds-to-milliseconds vs. ~100ns here).',+};++console.log(`old (unconditional spread): ${oldMean.toFixed(2)} ns/call [${oldNs.map((x) => x.toFixed(1)).join(', ')}]`);+console.log(`new (gated closure): ${newMean.toFixed(2)} ns/call [${newNs.map((x) => x.toFixed(1)).join(', ')}]`);+console.log(`delta: ${deltaPct >= 0 ? '+' : ''}${deltaPct.toFixed(1)}% (non-inferiority threshold: +/-${THRESHOLD_PCT}%)`);+console.log(`result: ${result.verdict}`);++if (process.argv.includes('--json')) {+ console.log(JSON.stringify(result, null, 2));+}++process.exitCode = pass ? 0 : 1;diff --git a/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts b/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.tsindex 2606d30639..1f16c3235c 100644--- a/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts+++ b/v3/@claude-flow/cli/src/ruvector/enhanced-model-router.ts@@ -485,17 +485,29 @@ export class EnhancedModelRouter {// Step 6: Determine tier based on complexityconst { haiku, sonnet } = this.config.complexityThresholds;- // ADR-149 — forward the per-model fields from baseResult onto every- // tier-2/3 return. This keeps the cost-optimal pick alive end-to-end:- // if the neural backend picked Ling for a cheap task, the enhanced- // router surfaces `modelId: 'inclusionai/ling-2.6-flash'` alongside- // `model: 'haiku'` so downstream consumers can dispatch via OpenRouter.- const neuralFields = {- ...(baseResult.modelId ? { modelId: baseResult.modelId } : {}),- ...(baseResult.routedBy ? { routedBy: baseResult.routedBy } : {}),- ...(baseResult.provider ? { provider: baseResult.provider } : {}),- ...(baseResult.openrouterModel ? { openrouterModel: baseResult.openrouterModel } : {}),- };+ // ADR-149 — forward the per-model fields from baseResult onto the+ // tier-2/3 return, but ONLY when the tier being returned here still+ // matches the tier baseResult.model was chosen for. `finalComplexity`+ // (AST-adjusted / tier3-keyword-boosted, Step 5-6 above) can escalate+ // the returned tier past what the base bandit router saw when it picked+ // `modelId` — forwarding it unconditionally would attach a cheaper+ // tier's concrete model (e.g. `inclusionai/ling-2.6-flash`, chosen for+ // 'haiku') to an escalated 'opus' decision. `agent-execute-core.ts`+ // treats a present `modelId` as an override that skips tier-based+ // dispatch entirely, so a stale, wrong-tier `modelId` silently defeats+ // the escalation this function just computed. Dropping the mismatched+ // fields (rather than trying to re-resolve modelId for the new tier)+ // keeps this fix small and fail-safe: an escalated decision falls back+ // to the plain `model` field, never to a cheaper model's identity.+ const neuralFieldsFor = (model: ClaudeModel) =>+ baseResult.model === model+ ? {+ ...(baseResult.modelId ? { modelId: baseResult.modelId } : {}),+ ...(baseResult.routedBy ? { routedBy: baseResult.routedBy } : {}),+ ...(baseResult.provider ? { provider: baseResult.provider } : {}),+ ...(baseResult.openrouterModel ? { openrouterModel: baseResult.openrouterModel } : {}),+ }+ : {};if (finalComplexity < haiku) {return {@@ -508,7 +520,7 @@ export class EnhancedModelRouter {canSkipLLM: false,estimatedLatencyMs: 500,estimatedCost: 0.0002,- ...neuralFields,+ ...neuralFieldsFor('haiku'),};}@@ -523,7 +535,7 @@ export class EnhancedModelRouter {canSkipLLM: false,estimatedLatencyMs: 2000,estimatedCost: 0.003,- ...neuralFields,+ ...neuralFieldsFor('sonnet'),};}@@ -537,7 +549,7 @@ export class EnhancedModelRouter {canSkipLLM: false,estimatedLatencyMs: 5000,estimatedCost: 0.015,- ...neuralFields,+ ...neuralFieldsFor('opus'),};}