Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

dream(memory): #4549 wire ControllerRegistry.set() β€” MutationGuard/AttestationLog activation was permanently dead (evaluated, ACCEPT-scoped) (#4550)

rUv738729556888
diff --git a/docs/dream-cycle/LEDGER.md b/docs/dream-cycle/LEDGER.md
index fe9e34ec8b..535f2db51f 100644
--- a/docs/dream-cycle/LEDGER.md
+++ b/docs/dream-cycle/LEDGER.md
@@ -247,3 +247,4 @@ as a first-class, high-priority candidate, not a background note.
| 2026-10-20 | security (SCAN override of performance DEEP, see note above) | `hooks_codemod` MCP tool's `resolveTargets()` path-containment check used an unanchored `abs.startsWith(cwd)` string-prefix comparison β€” since `path.resolve(cwd, p)` returns an already-absolute `p` unchanged, a sibling directory merely starting with the project directory's name (e.g. `cwd`-staging) passed containment, letting this live, CLAUDE.md-recommended Tier-1 tool read **and write** (dryRun defaults false) outside the project root (CWE-22); anchored both call sites (`file`/`files[]` and `glob` branches) at a path-separator boundary, matching the already-correct `isWithinPrefix()` pattern used elsewhere in this exact codebase (`@claude-flow/security`, `@claude-flow/hooks/workers`, `@claude-flow/plugins/security`) | #4312 | #4313 | yes | ACCEPT | 4 new tests (2 discriminating, real temp-dir fs I/O; 2 non-discriminating controls); stash-isolated baseline fails both escape tests exactly as predicted (file genuinely overwritten outside root, not simulated), candidate 4/4 pass β€” independently reproduced twice (session + a separate adversarial-critic subagent from scratch, which also built its own symlink-escape repro); related suites (`mcp-tools-deep`, `validate-input-*`, `codemod-*`) 229/229 both ways (twice-reproduced); `tsc --noEmit` byte-identical 9 pre-existing errors; full `@claude-flow/cli` suite ~480/503 both ways, same ~21-22 pre-existing-failure set by name untouched by this change (second full-suite run disclosed as contaminated mid-run by this session's own revert/restore cycle, not relied on); independent adversarial critique CONFIRMED-WITH-CAVEATS β€” 1 non-blocking caveat (symlink-based containment bypass, CWE-59, distinct/broader gap) disclosed in-source as a KNOWN LIMITATION comment rather than fixed, deferred to a future realpath-hardening night | d501ab48... | 10-09/10-10/10-11/10-15/10-16/10-18/10-19 MERGED (7/7 of trailing window with a decision); 10-17 #4250 open/draft, not stale |
| 2026-10-26 | security | `http_fetch`'s `isPrivateOrLoopback()` SSRF guard (`v3/@claude-flow/cli/src/mcp-tools/http-fetch-tools.ts`) never stripped the `[...]` brackets Node's URL parser keeps on IPv6 literals β€” silently dead-coding the existing `fc00::/7`/`fe80::/10` checks AND leaving IPv4-mapped-IPv6 literals (`::ffff:127.0.0.1`, `::ffff:169.254.169.254`) completely unchecked, a live reproduced SSRF bypass reaching loopback/cloud-metadata; fixed by stripping brackets once and decoding IPv4-mapped forms into the existing IPv4 rules (one root-cause fix, not two). SCAN: intelligence (EWC++ Fisher map in `SONAManager` never populated β€” `consolidateEWC()` has zero callers, "prevents forgetting" is a silent no-op; new finding, deferred), swarm (10-25's deferred `TopologyManager` role-bug finding confirmed already fixed by an external PR #4483 citing our own #4481). Architecture review also found `.harness/mcp-policy.json` falsely claims zero shell/network tool surface β€” `terminal_execute`/`http_fetch` both contradict it (score 4.55, deferred as a design question, not a unilateral patch) | #4503 | #4504 | yes | ACCEPT | 13 new tests (8 discriminating, 5 controls), stash-isolated baseline 8/8 fail exactly as predicted β†’ candidate 37/37 pass, independently reproduced by a fresh-context adversarial critic; scoped-but-wider related-suite run (109 tests) 12 pre-existing failures confirmed byte-identical on the true pre-fix commit (unbuilt `@claude-flow/mcp` sibling, unrelated); full-suite run timed out at 300s (environmental); `tsc --noEmit` 0 errors touching changed files either way (raw aggregate count noisy, 80↔510, same unbuilt-sibling cause, disclosed); independent adversarial critique CONFIRMED-WITH-CAVEATS β€” 2 non-blocking pre-existing gaps (IPv6 `::`/multicast/NAT64 unblocked) disclosed in-source as KNOWN LIMITATION | 9294b5d7... | 10-19/10-20 MERGED; 10-21/10-22/10-23/10-24/10-25 open/draft, none stale (<14d); merge rate 2/7 trailing window, not zero |
| 2026-10-27 | intelligence | `SONAManager`'s EWC++ Fisher map (`v3/@claude-flow/neural/src/sona-manager.ts`) was permanently empty β€” nothing ever wrote to `ewcState.fisher`/`.means`, `consolidateEWC()` had zero callers, every `computeEWCPenalty`/`computeEWCLoss` call across all 5 modes returned exactly 0, forever, in the production-reachable path (`NeuralLearningSystem` β†’ `@claude-flow/memory`'s `learning-bridge.ts`); directly acting on 10-26's own carried-forward recommendation #3. Wired `BalancedMode`'s (default-mode-only) existing `gradientAccumulator` into a real delta-based Fisher/means snapshot via a new `getConsolidationSnapshot()`, folded into `ewcState` by `consolidateEWC()`'s existing decay step + additive accumulation (online EWC), mirroring a proven-but-unwired reference pattern in `v3/plugins/cognitive-kernel/src/bridges/sona-bridge.ts`. Also removed 18 stale, never-`.gitignore`d, circularly-broken build artifacts (`.js`/`.d.ts`/maps/`tmp.json`) under `src/modes/` that were blocking any vitest test of this subsystem from running at all. SCAN: capabilities (`.harness/mcp-policy.json`'s false shell/network-surface claim still unenforced even after the interim `policy-enforcer.ts` fix, score 4.45, deferred), memory (`CacheManager.clear()` reports `previousSize:0` always β€” reads `.size` after `.clear()`, score 4.45, deferred) | #4531 | #4532 | yes | ACCEPT-scoped (post-critique) | 4 new tests, stash-isolated 3/4 fail baseline β†’ 4/4 pass candidate (1 non-discriminating control); full `@claude-flow/neural` suite 139/139β†’143/143, 0 regressions, `tsc --noEmit` 0 errors both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS β€” found a real round-1 divergence bug (squaring the raw lifetime-cumulative accumulator instead of a delta, proved to diverge: 25 cycles 0.00012β†’0.68), fixed forward same session to a delta-based snapshot; tracing further surfaced a second, deeper, separate, pre-existing cause of residual growth (`triggerLearning()` reprocesses the full historical trajectory backlog every call, no "already learned from" tracking) β€” disclosed, not fixed, named as the priority follow-up ahead of ever wiring the penalty into a real gradient update; 2 minor nits (an overclaimed single-cycle test identity, an incomplete stale-artifact cleanup) also fixed forward | 7b524483... | 10-20/10-26 MERGED; 10-21/10-22/10-23/10-24/10-25 open/draft, none stale; merge rate 2/7 trailing window, not zero |
+| 2026-10-28 | memory | `memory-bridge.ts`'s post-init controller-activation wiring (reasoningBank/learningSystem/skills/semanticRouter/gnnService/rvfOptimizer/mutationGuard/attestationLog/guardedVectorBackend, 9 controllers via 7 call sites) gated registration on `typeof reg.set === 'function'`, falling back to an unread `reg._controllers` property; `ControllerRegistry` never implemented a public `set()` method, so every activation silently took the dead fallback since this wiring was added β€” `guardValidate()`/`logAttestation()` always found `get('mutationGuard')`/`get('attestationLog')` null, permanently disabling write-mutation validation (fail-open) and audit logging (silent no-op) on real store/delete/purge paths. Same bug shape as the already-fixed #3327 Finding A. SCAN: plugins (identical dead-config anti-pattern reproduced in `@claude-flow/plugin-agent-federation`'s `SecurityPolicy.minTrustLevelForSpawn`/etc., gating cross-node agent spawning; new finding, deferred), automation (`hooks_worker-detect` auto-dispatch fabricates completed workers with zero disclosure, unlike its hardened sibling `hooks_worker-dispatch`; `worker-daemon.ts`'s default-on critical-priority `audit` worker fabricates `noHardcodedSecrets:true`/`riskLevel:'low'` with no scan performed, every 10 min by default; both new findings, deferred) | #4549 | #4550 | yes | ACCEPT-scoped (post-critique) | 6 new discriminating tests (5 round-1 + 1 post-critique), stash-isolated baseline fails 5/5 round-1 (`registry.set is not a function`, independently confirmed via `tsc` TS2339 too) β†’ candidate 82/82 β†’ 83/83; full `@claude-flow/memory` suite 651/652 both ways (1 pre-existing environmental chmod/root-bypass failure, byte-identical, independently re-confirmed by the critic); `tsc --noEmit` 0 errors both ways; independent adversarial critique CONFIRMED-WITH-CAVEATS (fresh worktree, fetched and checked out the real pushed commit after an initial attempt correctly rejected reviewing an empty worktree) β€” found a real issue (set() silently orphaned a pre-existing resource-holding instance on overwrite, same leak class as #2432, not currently triggerable through shipped call sites but unprotected at the API level), fixed forward same session via the existing `closePriorIfAny()`; a second gap (`causalRecall` absent from every `INIT_LEVELS` entry, so `shutdown()` would never find a controller registered under that name) disclosed as a KNOWN LIMITATION, not fixed (needs a human call on init-level ordering) | 5f0e5fdd... | 10-15/10-16/10-18/10-19/10-20/10-26/10-27 MERGED (7/7 of trailing window with a decision); 10-21/10-22/10-23/10-24/10-25 open/draft, none stale. Prior gist (10-27, intelligence) scored 10/10 (2+2+2+2+1(1494 words)+1) |
diff --git a/docs/dream-cycle/dream-gist-2026-10-28.md b/docs/dream-cycle/dream-gist-2026-10-28.md
new file mode 100644
index 0000000000..0256a48f2c
--- /dev/null
+++ b/docs/dream-cycle/dream-gist-2026-10-28.md
@@ -0,0 +1,71 @@
+# Memory SOTA Report β€” 2026-10-28
+
+**TL;DR**: In 2026, every major agent-memory framework (LangMem, AutoGen/MS Agent Framework, CrewAI, OpenAI Agents SDK) still keeps "remembering" entirely in the context/retrieval layer, deliberately avoiding weight-level consolidation β€” a tradeoff a fresh academic critique (arXiv 2604.27707) names explicitly as "lookup, not memory." Ruflo is unusual in having real EWC++-style importance-protection machinery for its own learning subsystem, but tonight's deep code review found that machinery's *write-path enforcement* has been silently dead since it was added: `ControllerRegistry` never implemented the `set()` method `memory-bridge.ts`'s controller-activation wiring has called on every startup, so `MutationGuard` (write validation) and `AttestationLog` (audit trail) permanently fell through to a no-op fallback. Fixed tonight with a 20-line, fully tested, zero-regression patch.
+
+## What's New in 2026
+
+| Finding | Source | Confidence |
+|---|---|---|
+| MemCon frames memory ops (retrieve/consolidate/forget) as an MDP solved by a contextual bandit; +15.2pt task success, 5-20% lower tokens across 6 benchmarks | arXiv 2607.13591 (Jul 2026) | B |
+| "Contextual Agentic Memory is a Memo, Not True Memory" β€” names the shared architectural gap across LangMem/AutoGen/CrewAI/OpenAI Agents SDK: exemplar lookup, zero weight-space consolidation | arXiv 2604.27707 (Apr 2026), CUHK+Zhejiang Univ. | A/B |
+| TMEM β€” first concrete counter-proposal: writes real per-episode LoRA weight deltas online to escape the "lookup ceiling" | arXiv 2606.04536 (Jun 2026) | B |
+| Microsoft folded AutoGen + Semantic Kernel into Agent Framework 1.0 GA (Apr 2026); AutoGen's "Task-Centric Memory" (learn from own trial-and-error) left in undocumented limbo | Microsoft release notes + secondary sources | B/C |
+| Qdrant-style `exp_decay`/`gauss_decay` time-decay rescoring is now the standard hybrid-search recipe industry-wide | Qdrant docs + arXiv 2609.00548 | B |
+
+## Ruflo Current Capability
+
+Ruflo's memory stack (`v3/@claude-flow/memory`, `v3/@claude-flow/hooks/src/reasoningbank`) has real, shipped mechanisms most competitors lack: native BM25+cosine hybrid search, embedding-based dedup, half-life recency decay (`smart-retrieval.ts`), and an EWC++ Fisher-penalty for pattern-confidence forgetting-prevention (fixed two nights ago, 2026-10-27). Tonight's architecture review found this is not one coherent service: at least four parallel memory implementations coexist (`ControllerRegistry`'s AgentDB wrapper, a separate in-process `AgentDBAdapter`, a third hand-rolled `ReasoningBank` in `hooks/`, and an orphaned DDD application-service stack) β€” the "unify 6+ memory systems" ADR-006/ADR-009 unification CLAUDE.md describes is incomplete, and ADR-053's "Implemented" status has drifted from current code (6-8 of its flagship controllers are hardcoded dead per issue #2977, undisclosed in the ADR text).
+
+## Competitor Comparison
+
+| Competitor | Mechanism | Touches weights? | Grade |
+|---|---|---|---|
+| LangGraph / LangMem | `BaseStore` + semantic/episodic/procedural (prompt-rewrite) memory types | No | B |
+| AutoGen β†’ MS Agent Framework | `TeachableAgent` memos β†’ Task-Centric trial-and-error learning (status post-merge unclear) | No | B/C |
+| CrewAI | RAG-based short/long-term/entity memory, unified `Memory` class (2026); `crew.train()` is prompt/few-shot, not memory | No | B |
+| OpenAI Agents SDK | `Session` = short-term conversation history only, explicitly "not general-purpose memory"; long-term pushed to Mem0/Hindsight; RFT is a disconnected weight-training product | No (Sessions) / Yes (separate RFT) | B |
+| Academic: TMEM (arXiv 2606.04536) | Online per-episode LoRA weight writes β€” closest real counter-example to the industry consensus | Yes | B |
+
+**Why every production row reads "no weight touch"**: not an oversight β€” arXiv 2604.27707 argues it's a deliberate, stated-cost tradeoff (training-loop cost, forgetting risk, multi-tenant incompatibility). Ruflo's own EWC++ protects SONA's small adaptation parameters, not an LLM's weights, so it's the same category as its competitors, not a counterexample β€” only TMEM (academic, unshipped) proposes otherwise.
+
+## Hypothesis
+
+> Given `memory-bridge.ts`'s post-init controller-activation wiring, which externally constructs `MutationGuard`/`AttestationLog`/`SemanticRouter`/etc. and gates registration on `typeof reg.set === 'function'`, when a public `ControllerRegistry.set<T>(name, instance)` method is added (mirroring the shape `initController()` already produces internally: `{name, instance, level, initTimeMs, enabled}`), then `registry.get('mutationGuard')`/`get('attestationLog')` should return the externally-constructed instance instead of permanently null, and `guardValidate()`/`logAttestation()` in `memory-bridge.ts` should route through their real-guard/real-log branches instead of the permanent degraded-mode fallback β€” subject to: zero change to `initController()`'s internal path, zero regression to the existing `controller-registry.test.ts` suite (82 tests pre-fix), deterministic $0 Vitest evaluation. Frozen before evaluation; not modified after.
+
+## Benchmarks
+
+No agent-task benchmark corpus applies β€” this is a unit-level wiring/correctness fix to an internal controller-registration mechanism, evaluated via discriminating Vitest tests (stash-isolated baseline-fails/candidate-passes), consistent with this repo's convention for non-routing/non-topology fixes. `.harness/bench.json` does not exist in this checkout.
+
+## Evaluation
+
+**evaluated: accepted β€” ACCEPT-scoped (post-critique).** Real evaluator: Vitest 4.1.8, package `@claude-flow/memory`.
+
+Round 1: 5 new discriminating tests added to `controller-registry.test.ts`, reproducing memory-bridge.ts's exact `typeof reg.set === 'function'` activation pattern. Stash-isolated baseline (`controller-registry.ts` only reverted): 5/5 fail exactly as predicted (`registry.set is not a function`; `tsc --noEmit` independently confirms with 5 `TS2339` errors), 77/82 pass. Candidate: 82/82 pass.
+
+An independent adversarial critic (fresh context, no authoring context, own isolated git worktree checked out at the real pushed commit) reproduced all of the above from scratch β€” **CONFIRMED-WITH-CAVEATS**. Two real findings: (1) `set()` silently dropped a reference to any pre-existing resource-holding instance on overwrite, reintroducing the exact leak class issue #2432 fixed for `initController()`'s own replacement path β€” not currently triggerable through the shipped wiring (every real call site guards with `if (!reg.get(name))` first), but the API itself offered no protection. **Fixed forward same session**: `set()` now dispatches the existing `closePriorIfAny(name)` before overwriting, same as `initController()`. (2) `causalRecall` is the one `ControllerName` absent from every `INIT_LEVELS` entry, so `shutdown()`'s by-static-list lookup would never find/close a controller registered under that name via `set()` β€” unexercised today (no call site uses it); **disclosed, not fixed tonight** (would need a human call on correct init-level ordering for a controller never previously activated anywhere). No reward-hacking found: diff is purely additive, no existing test/threshold touched.
+
+Final: 1 more discriminating test added (6 total), full `@claude-flow/memory` suite **651/652 both ways**, 0 regressions (the 1 failure, a chmod-based permission test, reproduces byte-identically on baseline β€” confirmed environmental, container runs as root). `tsc --noEmit`: 0 errors both ways.
+
+**Security note**: this activates a previously-fully-dormant validation path (MutationGuard can now actually reject a write; AttestationLog now actually records). That is the intended behavior, not a new risk surface, but it is a real behavior change on live `store`/`delete`/`purge` code paths that has never run against production traffic β€” flagged for human reviewer attention, not a blocker.
+
+## Darwin Results
+
+Skipped β€” binary wiring/correctness fix (a method either exists and is called, or doesn't), not a continuous/categorical parameter Darwin's bounded-evolution interface can search over. Same skip class as nearly every ACCEPT in this repo's history that wasn't a routing/topology weight.
+
+## SOTA Proof & Witness
+
+Session commit: bd19b6f984fb0b4465e333c5e24cc5333784f410
+Candidate commit: 1b973fbc47c9dc25ab440055e8fd5dcc5faff9b2
+Gist SHA-256 (pre-witness, this block held to the literal text `PENDING`): 6bfed140ea589b31648dc52cf9c4ede513c7529925a1c0054ed54d08a1941247
+Witness stamp: 5f0e5fddb734fc8b6ce83e6cfe203ab4b3682c4ca9b7e0a1fddc83bb431fd293
+
+Verifier: fetch this file, replace this block's four filled-in values with the literal text `PENDING` (as it was before this computation), SHA-256 the result, concatenate with the Session commit above, SHA-256 again β€” must equal the Witness stamp.
+
+Evaluation receipt identity: 6 new tests in `controller-registry.test.ts` (5 round-1 + 1 post-critique), stash-isolated 5/5-fail-baseline β†’ 83/83-pass-candidate (round 1), full suite 651/652 both ways (round 2) β€” independently reproduced in an isolated worktree by a fresh-context adversarial critic at commit afe2cdd, who found and this session fixed forward one real issue (see Evaluation). Flywheel evidence identity: none (`.claude-flow/flywheel/` doesn't exist in this repo). Darwin lineage identity: none (skipped β€” binary wiring fix, not a tunable parameter).
+
+## Recommended Next Steps
+
+1. **Wire `GuardedVectorBackend` end-to-end and add an integration test on `memory-bridge.ts` itself** (not just the registry unit) proving a real `store()`/`delete()` call now actually gets rejected by a MutationGuard that denies β€” tonight's fix makes activation possible but the bridge-level integration test is a natural fast-follow, not done tonight to keep blast radius minimal.
+2. **Reconcile ADR-053's "Implemented" status** against issue #2977's hardcoded-dead controller list β€” a documentation/governance fix, not a patch, flagged by tonight's architecture review.
+3. **`@claude-flow/plugin-agent-federation`'s `SecurityPolicy.minTrustLevelForSpawn`/etc. are declared, defaulted, and never read** β€” the identical dead-config anti-pattern as tonight's fix, in a sibling package, gating cross-node agent spawning (a meaningfully dangerous capability). Strong candidate for a future night.
+4. **`worker-daemon.ts`'s default-on, critical-priority `audit` worker fabricates `noHardcodedSecrets: true` every 10 minutes** with no real scan performed (confirmed live, reachable, SCAN:automation finding) β€” a believable false-negative security claim, textbook undisclosed-fallback pattern. Carried forward as a strong SCAN candidate for a future automation night.
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 297c9e0ac6..8e03f0575e 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -127,12 +127,12 @@
"ws": "^8.21.0",
"yaml": "^2.8.0",
"zod": "^3.22.0",
- "@claude-flow/memory": "3.0.9"
+ "@claude-flow/memory": "3.1.0"
},
"optionalDependencies": {
"@agntcy/slim-bindings": "2.1.1",
"@claude-flow/aidefence": "3.0.2",
- "@claude-flow/memory": "3.0.9",
+ "@claude-flow/memory": "3.1.0",
"@metaharness/darwin": "~0.12.0",
"@metaharness/flywheel": "~0.1.10",
"@metaharness/radio": "~0.1.0",
diff --git a/v3/@claude-flow/memory/package.json b/v3/@claude-flow/memory/package.json
index 45ed50a41e..5dcd0072a3 100644
--- a/v3/@claude-flow/memory/package.json
+++ b/v3/@claude-flow/memory/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/memory",
- "version": "3.0.9",
+ "version": "3.1.0",
"type": "module",
"description": "Memory module - AgentDB unification, HNSW indexing, vector search, hybrid SQLite+AgentDB backend (ADR-009)",
"main": "dist/index.js",
diff --git a/v3/@claude-flow/memory/src/controller-registry.test.ts b/v3/@claude-flow/memory/src/controller-registry.test.ts
index 7fe4b737c1..541df47383 100644
--- a/v3/@claude-flow/memory/src/controller-registry.test.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.test.ts
@@ -465,6 +465,115 @@ describe('ControllerRegistry', () => {
});
});
+ // ----- External controller registration (set) -----
+ //
+ // Dream Cycle 2026-10-28: `memory-bridge.ts`'s post-init wiring
+ // constructs several AgentDB-bundled controllers itself (mutationGuard,
+ // attestationLog, semanticRouter, skills, reasoningBank, learningSystem,
+ // gnnService, rvfOptimizer, guardedVectorBackend) and has always gated
+ // registration on `typeof reg.set === 'function'`, falling back to an
+ // unread `reg._controllers` property otherwise. `ControllerRegistry` had
+ // no public `set()` until this fix, so every one of those activations
+ // silently wrote to the dead fallback β€” `get('mutationGuard')` and
+ // `get('attestationLog')` always returned null, permanently disabling
+ // write-mutation validation (fail-open) and audit logging (silent no-op).
+ describe('external controller registration (set)', () => {
+ it('makes an externally-constructed instance immediately visible via get()/isEnabled()', async () => {
+ await registry.initialize({ backend: mockBackend });
+
+ const fakeGuard = { validate: () => ({ allowed: true }) };
+ expect(registry.get('mutationGuard')).toBeNull();
+ expect(registry.isEnabled('mutationGuard')).toBe(false);
+
+ registry.set('mutationGuard', fakeGuard);
+
+ expect(registry.get('mutationGuard')).toBe(fakeGuard);
+ expect(registry.isEnabled('mutationGuard')).toBe(true);
+ });
+
+ it('reproduces the exact memory-bridge.ts activation pattern end-to-end', async () => {
+ // Mirrors memory-bridge.ts's real activation guard verbatim:
+ // if (typeof reg.set === 'function') reg.set(name, inst);
+ // else reg._controllers = { ...(reg._controllers || {}), [name]: inst };
+ await registry.initialize({ backend: mockBackend });
+
+ const reg = registry as unknown as Record<string, unknown>;
+ const fakeAttestation = { record: vi.fn() };
+
+ if (typeof reg.set === 'function') {
+ (reg.set as (n: ControllerName, i: unknown) => void)('attestationLog', fakeAttestation);
+ } else {
+ (reg as any)._controllers = { ...((reg as any)._controllers || {}), attestationLog: fakeAttestation };
+ }
+
+ // Before the fix this fell through to the dead `_controllers` branch
+ // and get() stayed null forever β€” the exact production symptom.
+ expect(registry.get('attestationLog')).toBe(fakeAttestation);
+ });
+
+ it('lists an externally-set controller via listControllers() and getActiveCount()', async () => {
+ await registry.initialize({ backend: mockBackend });
+ expect(registry.isEnabled('guardedVectorBackend')).toBe(false);
+ const activeBefore = registry.getActiveCount();
+
+ registry.set('guardedVectorBackend', { lookup: () => [] });
+
+ expect(registry.getActiveCount()).toBe(activeBefore + 1);
+ const entry = registry.listControllers().find((c) => c.name === 'guardedVectorBackend');
+ expect(entry).toBeDefined();
+ expect(entry?.enabled).toBe(true);
+ });
+
+ it('shuts down an externally-set controller cleanly on registry.shutdown()', async () => {
+ await registry.initialize({ backend: mockBackend });
+ const destroy = vi.fn();
+ registry.set('mutationGuard', { destroy });
+
+ await registry.shutdown();
+
+ expect(destroy).toHaveBeenCalledOnce();
+ expect(registry.getActiveCount()).toBe(0);
+ });
+
+ it('overwrites a prior entry cleanly on re-registration (non-discriminating control)', async () => {
+ await registry.initialize({ backend: mockBackend });
+ const first = { id: 'first' };
+ const second = { id: 'second' };
+
+ registry.set('semanticRouter', first);
+ registry.set('semanticRouter', second);
+
+ expect(registry.get('semanticRouter')).toBe(second);
+ });
+
+ // Adversarial-critique follow-up (same Dream Cycle session): set() must
+ // not orphan a resource-holding prior instance the way #2432 originally
+ // fixed for initController()'s own replacement path. The new instance
+ // must still be visible via get() synchronously, with the old one's
+ // close() dispatched in the background.
+ it('closes a replaced instance\'s resources without delaying visibility of the new one (#2432 class)', async () => {
+ await registry.initialize({ backend: mockBackend });
+ let closeResolve!: () => void;
+ const closed = new Promise<void>((resolve) => { closeResolve = resolve; });
+ const oldInstance = { close: vi.fn(() => closed) };
+ const newInstance = { id: 'new' };
+
+ registry.set('semanticRouter', oldInstance);
+ registry.set('semanticRouter', newInstance);
+
+ // New instance is visible immediately, even though oldInstance.close()
+ // is still an unresolved promise in the background.
+ expect(registry.get('semanticRouter')).toBe(newInstance);
+ expect(oldInstance.close).toHaveBeenCalledOnce();
+
+ closeResolve();
+ await closed;
+ // Replacing again after close resolves must not have reverted or
+ // dropped the second registration.
+ expect(registry.get('semanticRouter')).toBe(newInstance);
+ });
+ });
+
// ----- Health Check -----
describe('health check', () => {
diff --git a/v3/@claude-flow/memory/src/controller-registry.ts b/v3/@claude-flow/memory/src/controller-registry.ts
index 9abd60c7af..0e01735939 100644
--- a/v3/@claude-flow/memory/src/controller-registry.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.ts
@@ -431,6 +431,43 @@ export class ControllerRegistry extends EventEmitter {
return false;
}
+ /**
+ * Register an already-constructed controller instance directly, outside
+ * the level-based `initialize()` path.
+ *
+ * Dream Cycle 2026-10-28: this method did not exist until now, even though
+ * `memory-bridge.ts`'s post-init wiring (reasoningBank/learningSystem/
+ * skills/semanticRouter/gnnService/rvfOptimizer/mutationGuard/
+ * attestationLog/guardedVectorBackend) has called `typeof reg.set ===
+ * 'function'` and fallen through to a dead `reg._controllers` property β€”
+ * never read anywhere β€” on every call since that wiring was added. As a
+ * result `get('mutationGuard')`/`get('attestationLog')` always returned
+ * null, so `guardValidate()` always took its "no guard installed = allow"
+ * branch and `logAttestation()` was a permanent no-op. Same shape as the
+ * already-fixed #3327 Finding A (`reasoningBank.store` never existed, so
+ * its own `typeof ... === 'function'` guard was dead too).
+ *
+ * Dispatches #2432's `closePriorIfAny(name)` for whatever entry `name`
+ * currently holds *before* overwriting the map, same as `initController()`
+ * does, so a `set()` that replaces a resource-holding instance (one
+ * constructed via the normal `initialize()` path, or a prior `set()`
+ * call) doesn't silently orphan it. Intentionally not awaited β€” like
+ * every other post-init activation call site, `set()` stays synchronous
+ * so `get(name)` reflects the new instance immediately; the old
+ * instance's `close()`/`dispose()` (best-effort, errors swallowed) runs
+ * in the background.
+ */
+ set<T>(name: ControllerName, instance: T): void {
+ void this.closePriorIfAny(name);
+ this.controllers.set(name, {
+ name,
+ instance,
+ level: -1, // externally registered β€” not part of level-based init
+ initTimeMs: 0,
+ enabled: true,
+ });
+ }
+
/**
* Aggregate health check across all controllers.
*/
diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml
index d1e81dce54..eb240589f1 100644
--- a/v3/pnpm-lock.yaml
+++ b/v3/pnpm-lock.yaml
@@ -218,7 +218,7 @@ importers:
specifier: 3.0.2
version: link:../aidefence
'@claude-flow/memory':
- specifier: 3.0.9
+ specifier: 3.1.0
version: link:../memory
'@metaharness/darwin':
specifier: ~0.12.0
@@ -13755,3 +13755,4 @@ packages:
resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==}
+ dev: false