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

fix(memory): activate reasoningBank β€” wire the real embedder + correct the bridge contract (#3327 Finding A) (#3390)

rUv11ce88327b31
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index e247c93900..37f5033c6b 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -2094,16 +2094,33 @@ export async function bridgeStorePattern(options: {
const reasoningBank = registry.get('reasoningBank');
const patternId = generateId('pattern');
- if (reasoningBank && typeof reasoningBank.store === 'function') {
- await reasoningBank.store({
- id: patternId,
- content: options.pattern,
- type: options.type,
- confidence: options.confidence,
+ // #3327 Finding A β€” the real method is `storePattern`, and it takes a
+ // ReasoningPattern, NOT the {id, content, type, confidence} shape used
+ // here before. `reasoningBank.store` has never existed on agentdb's
+ // ReasoningBank, so `typeof ... === 'function'` was always false and this
+ // branch was dead code β€” every write fell through to bridge-fallback while
+ // `agentdb_controllers` cheerfully reported `reasoningBank: enabled=true`.
+ //
+ // Contract (agentdb ReasoningBank.d.ts):
+ // storePattern({ taskType, approach, successRate, uses?, avgReward?,
+ // tags?, metadata? }) => Promise<number> // sqlite rowid
+ // The embedded text is `${taskType}: ${approach}`, so the caller's pattern
+ // text must land in `approach` for search to match on it.
+ if (reasoningBank && typeof reasoningBank.storePattern === 'function') {
+ const rowId = await reasoningBank.storePattern({
+ taskType: options.type,
+ approach: options.pattern,
+ successRate: options.confidence,
+ tags: [options.type, 'reasoning-pattern'],
metadata: options.metadata,
- timestamp: Date.now(),
});
- return { success: true, patternId, controller: 'reasoningBank' };
+ // storePattern returns a numeric rowid; surface it as the caller-facing
+ // id so a later getPattern/deletePattern by this id resolves.
+ return {
+ success: true,
+ patternId: rowId != null ? String(rowId) : patternId,
+ controller: 'reasoningBank',
+ };
}
// Fallback: store via bridge SQL
@@ -2138,7 +2155,13 @@ export async function bridgeStorePattern(options: {
// so returning result.id here handed the caller a handle that can never
// be read back β€” return `patternId` (the real key) instead.
return { success: true, patternId, controller: 'bridge-fallback' };
- } catch {
+ } catch (err) {
+ // #3327 Finding A β€” this catch is what hid the defect for months. When
+ // ReasoningBank threw `embedPassage is not a function`, the error was
+ // discarded and the caller saw an ordinary fallback, indistinguishable
+ // from "no controller registered". Record it so `agentdb_health` and the
+ // degraded `reason` can name the real cause instead of guessing.
+ bridgeFailureReason = err instanceof Error ? err.message : String(err);
return null;
}
}
@@ -2166,11 +2189,17 @@ export async function bridgeSearchPatterns(options: {
} else {
results = await reasoningBank.search(options.query, { topK: options.topK || 5, minScore: options.minConfidence || 0.3 });
}
+ // #3327 Finding A β€” agentdb returns ReasoningPattern[]: the text lives in
+ // `approach` and the cosine score in `similarity`. Neither `content`/
+ // `pattern` nor `score`/`confidence` exists on that shape, so the old
+ // mapping produced `content: ''` and `score: 0` for every hit even when
+ // the search itself succeeded. Read the real fields first, keeping the
+ // legacy names as fallbacks for the pre-agentdb shape.
return {
results: Array.isArray(results) ? results.map((r: any) => ({
- id: r.id || r.patternId || '',
- content: r.content || r.pattern || '',
- score: r.score ?? r.confidence ?? 0,
+ id: String(r.id ?? r.patternId ?? ''),
+ content: r.approach ?? r.content ?? r.pattern ?? '',
+ score: r.similarity ?? r.score ?? r.successRate ?? r.confidence ?? 0,
})) : [],
controller: 'reasoningBank',
};
@@ -2228,7 +2257,12 @@ export async function bridgeSearchPatterns(options: {
results: result.results.map(r => ({ id: r.id, content: r.content, score: r.score })),
controller: 'bridge-fallback',
} : null;
- } catch {
+ } catch (err) {
+ // #3327 Finding A β€” see bridgeStorePattern's catch. `embedQuery is not a
+ // function` died here silently, which is why search reported
+ // `reasoningBank-unavailable:registry-null` (a null return) even though
+ // the registry was present and the controller was reported enabled.
+ bridgeFailureReason = err instanceof Error ? err.message : String(err);
return null;
}
}
diff --git a/v3/@claude-flow/memory/src/controller-registry.test.ts b/v3/@claude-flow/memory/src/controller-registry.test.ts
index 412d375721..7fe4b737c1 100644
--- a/v3/@claude-flow/memory/src/controller-registry.test.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.test.ts
@@ -850,3 +850,132 @@ describe('HybridBackend proxy methods', () => {
await backend.shutdown();
});
});
+
+// ===== #3327 Finding A β€” ReasoningBank embedder contract =====
+//
+// agentdb's ReasoningBank calls `embedder.embedPassage()` on store and
+// `embedder.embedQuery()` on search. For months the registry handed it an
+// object exposing only {embed, embedBatch, initialize}, so BOTH paths threw
+// `TypeError: ... is not a function`. The bridge's catch swallowed the throw
+// and reported an ordinary fallback, so `agentdb_controllers` showed
+// `reasoningBank: enabled=true` while every read and write silently routed to
+// substring matching.
+//
+// Second, independent defect: the no-generator branch returned ZERO vectors,
+// so even with the method names shimmed every pattern embeds identically and
+// ranks on noise.
+
+describe('#3327 β€” embedder handed to agentdb controllers satisfies the asymmetric contract', () => {
+ // NOTE: the constructor takes no arguments β€” `config` is assigned by
+ // initialize(). Set it directly so these stay pure unit tests that do not
+ // need AgentDB, a database file, or a downloaded embedding model.
+ const makeRegistry = (config: Partial<RuntimeConfig> = {}) => {
+ const reg = new ControllerRegistry() as any;
+ reg.config = { dimension: 384, ...config } as RuntimeConfig;
+ return reg;
+ };
+
+ it('exposes embedQuery/embedPassage on the user-generator branch', async () => {
+ const reg = makeRegistry({ embeddingGenerator: async () => new Float32Array(384).fill(0.5) });
+ const svc = reg.createEmbeddingService();
+
+ for (const fn of ['embed', 'embedQuery', 'embedPassage', 'embedBatch']) {
+ expect(typeof svc[fn], `${fn} must exist β€” ReasoningBank calls it`).toBe('function');
+ }
+ // The aliases must return the generator's real vector, not a placeholder.
+ const q = await svc.embedQuery('hello');
+ expect(Array.from(q).some((x) => x !== 0)).toBe(true);
+ });
+
+ it('exposes embedQuery/embedPassage on the fallback stub branch too', () => {
+ const svc = makeRegistry().createEmbeddingService();
+ for (const fn of ['embed', 'embedQuery', 'embedPassage', 'embedBatch']) {
+ expect(typeof svc[fn], `${fn} missing => ReasoningBank throws at call time`).toBe('function');
+ }
+ });
+
+ it('marks the zero-vector stub so callers can refuse to rank on noise', async () => {
+ const svc = makeRegistry().createEmbeddingService();
+ expect(svc.isStubEmbedder).toBe(true);
+ const v = await svc.embedQuery('anything');
+ expect(Array.from(v).every((x) => x === 0)).toBe(true);
+ });
+
+ it('a real embeddingGenerator is NOT flagged as a stub', () => {
+ const reg = makeRegistry({ embeddingGenerator: async () => new Float32Array(384).fill(0.1) });
+ expect(reg.createEmbeddingService().isStubEmbedder).toBeUndefined();
+ });
+
+ it("prefers AgentDB's own embedder over the local service for reasoningBank", async () => {
+ const reg = makeRegistry();
+ const realEmbedder = {
+ embed: async () => new Float32Array(384).fill(0.25),
+ embedQuery: async () => new Float32Array(384).fill(0.25),
+ embedPassage: async () => new Float32Array(384).fill(0.25),
+ };
+ let handed: any = null;
+ reg.agentdb = { database: {}, embedder: realEmbedder };
+
+ // Stand in for agentdb's ReasoningBank so the assertion is about WHICH
+ // embedder the registry passes, not about agentdb being installed.
+ vi.doMock('agentdb', () => ({
+ ReasoningBank: class {
+ constructor(_db: unknown, embedder: unknown) { handed = embedder; }
+ },
+ }));
+
+ const inst = await reg.createController('reasoningBank').catch(() => null);
+ if (inst === null && handed === null) return; // agentdb not resolvable here β€” skip
+
+ expect(handed, 'registry must hand ReasoningBank a usable embedder').toBeTruthy();
+ expect(handed.isStubEmbedder, 'must NOT be the zero-vector stub').toBeUndefined();
+ expect(typeof handed.embedPassage).toBe('function');
+ expect(typeof handed.embedQuery).toBe('function');
+ });
+});
+
+describe('#3327 β€” adaptEmbedderForAgentdb covers the degraded-embedder path', () => {
+ const reg = () => new ControllerRegistry() as any;
+
+ it("aliases embed onto embedQuery/embedPassage for agentdb's mock embedder", async () => {
+ // When Transformers.js cannot load (offline, or a failed `sharp` optional
+ // install) agentdb substitutes a mock embedder exposing only `embed`.
+ // Passing that through untouched reintroduces the original crash β€” this
+ // case is why `?? createEmbeddingService()` alone was not sufficient.
+ const mock = { embed: async (t: string) => new Float32Array(384).fill(t.length || 1) };
+ const out = reg().adaptEmbedderForAgentdb(mock);
+
+ expect(typeof out.embedQuery).toBe('function');
+ expect(typeof out.embedPassage).toBe('function');
+ expect(typeof out.embedBatch).toBe('function');
+ expect(Array.from(await out.embedPassage('abc'))[0]).toBe(3);
+ expect(Array.from(await out.embedQuery('abcd'))[0]).toBe(4);
+ });
+
+ it('passes a already-complete embedder through untouched', () => {
+ const real = {
+ embed: async () => new Float32Array(1),
+ embedQuery: async () => new Float32Array(1),
+ embedPassage: async () => new Float32Array(1),
+ };
+ expect(reg().adaptEmbedderForAgentdb(real)).toBe(real);
+ });
+
+ it('returns null when there is nothing usable to adapt', () => {
+ const r = reg();
+ expect(r.adaptEmbedderForAgentdb(null)).toBeNull();
+ expect(r.adaptEmbedderForAgentdb(undefined)).toBeNull();
+ expect(r.adaptEmbedderForAgentdb({})).toBeNull();
+ expect(r.adaptEmbedderForAgentdb({ embed: 'not-a-function' })).toBeNull();
+ });
+
+ it('preserves a native embedBatch rather than serialising one call at a time', async () => {
+ let usedNative = false;
+ const withBatch = {
+ embed: async () => new Float32Array(1),
+ embedBatch: async (ts: string[]) => { usedNative = true; return ts.map(() => new Float32Array(1)); },
+ };
+ await reg().adaptEmbedderForAgentdb(withBatch).embedBatch(['a', 'b']);
+ expect(usedNative).toBe(true);
+ });
+});
diff --git a/v3/@claude-flow/memory/src/controller-registry.ts b/v3/@claude-flow/memory/src/controller-registry.ts
index 1d452b382b..e22c99118f 100644
--- a/v3/@claude-flow/memory/src/controller-registry.ts
+++ b/v3/@claude-flow/memory/src/controller-registry.ts
@@ -961,7 +961,31 @@ export class ControllerRegistry extends EventEmitter {
const agentdbModule: any = await import('agentdb');
const RB = agentdbModule.ReasoningBank;
if (!RB) return null;
- const embedder = this.createEmbeddingService();
+ // #3327 Finding A β€” ReasoningBank MUST get AgentDB's own embedder,
+ // not createEmbeddingService(). Two independent reasons, both fatal:
+ //
+ // 1. agentdb's ReasoningBank calls `embedder.embedPassage()` on
+ // store and `embedder.embedQuery()` on search (asymmetric
+ // query/passage embedding). createEmbeddingService() returns
+ // only {embed, embedBatch, initialize}, so BOTH paths threw
+ // `TypeError: this.embedder.embedPassage is not a function`.
+ // The throw was swallowed by the bridge's catch, which is why
+ // the controller reported `enabled: true` while every write and
+ // read silently routed to bridge-fallback/substring instead.
+ // 2. Even with the names shimmed, the no-generator branch of
+ // createEmbeddingService() returns ZERO vectors, so every
+ // pattern would embed identically and rank meaninglessly.
+ //
+ // `this.agentdb.embedder` is normally the real Transformers.js
+ // service, which already implements the full contract. But when the
+ // model cannot load (offline, or agentdb's `sharp`/transformers
+ // optional dep fails to install) agentdb silently swaps in a MOCK
+ // embedder that exposes only `embed` β€” so taking it as-is
+ // reintroduces the exact crash this fixes. Adapt whatever we get,
+ // and fall back to the local service only when there is no embedder
+ // at all.
+ const embedder = this.adaptEmbedderForAgentdb(this.agentdb.embedder)
+ ?? this.createEmbeddingService();
return new RB(this.agentdb.database, embedder);
} catch { return null; }
}
@@ -1150,18 +1174,68 @@ export class ControllerRegistry extends EventEmitter {
* Create an EmbeddingService for controllers that need it.
* Uses the config's embedding generator or creates a minimal local service.
*/
+ /**
+ * Adapt an arbitrary embedder to the contract agentdb's controllers call
+ * (#3327).
+ *
+ * ReasoningBank uses asymmetric query/passage embedding β€” `embedQuery()` on
+ * search, `embedPassage()` on store. Several embedders reaching here expose
+ * only `embed()`:
+ * β€’ agentdb's mock embedder, substituted whenever the Transformers.js
+ * model fails to load (offline, or a failed `sharp` optional install);
+ * β€’ any host-supplied `embeddingGenerator` wrapper.
+ *
+ * Passing one of those through unchanged throws `... is not a function`
+ * deep inside the controller, where the bridge's catch converts it into a
+ * silent fallback β€” the failure this whole fix is about. Aliasing is
+ * semantically safe: a symmetric model returns the same vector for both
+ * roles, which is precisely what a single `embed()` implies.
+ *
+ * Returns null when there is nothing usable to adapt.
+ */
+ private adaptEmbedderForAgentdb(embedder: any): any {
+ if (!embedder || typeof embedder.embed !== 'function') return null;
+ if (typeof embedder.embedQuery === 'function' && typeof embedder.embedPassage === 'function') {
+ return embedder; // already satisfies the contract β€” pass through untouched
+ }
+ const embed = embedder.embed.bind(embedder);
+ return Object.assign(Object.create(embedder), {
+ embed,
+ embedQuery: typeof embedder.embedQuery === 'function' ? embedder.embedQuery.bind(embedder) : embed,
+ embedPassage: typeof embedder.embedPassage === 'function' ? embedder.embedPassage.bind(embedder) : embed,
+ embedBatch: typeof embedder.embedBatch === 'function'
+ ? embedder.embedBatch.bind(embedder)
+ : async (texts: string[]) => Promise.all(texts.map((t) => embed(t))),
+ });
+ }
+
private createEmbeddingService(): any {
- // If user provided an embedding generator, wrap it
+ // #3327 β€” agentdb controllers call the asymmetric query/passage methods
+ // (`embedQuery` / `embedPassage`), not just `embed`. Anything handed this
+ // object must satisfy that wider contract or it throws at call time, deep
+ // inside a controller, where the bridge's catch turns it into a silent
+ // fallback. Alias them onto both branches.
if (this.config.embeddingGenerator) {
+ const embed = async (text: string) => this.config.embeddingGenerator!(text);
return {
- embed: async (text: string) => this.config.embeddingGenerator!(text),
+ embed,
+ embedQuery: embed,
+ embedPassage: embed,
embedBatch: async (texts: string[]) => Promise.all(texts.map(t => this.config.embeddingGenerator!(t))),
initialize: async () => {},
};
}
- // Return a minimal stub β€” HierarchicalMemory falls back to manualSearch without embeddings
+ // Zero-vector stub β€” HierarchicalMemory falls back to manualSearch without
+ // embeddings. NOTE: these vectors are all-zero and carry NO semantic
+ // signal; every pair scores identically. `isStubEmbedder` is exposed so a
+ // caller that needs real similarity can detect this and refuse, rather
+ // than ranking on noise (#3327).
+ const zero = async () => new Float32Array(this.config.dimension || 384);
return {
- embed: async () => new Float32Array(this.config.dimension || 384),
+ isStubEmbedder: true,
+ embed: zero,
+ embedQuery: zero,
+ embedPassage: zero,
embedBatch: async (texts: string[]) => texts.map(() => new Float32Array(this.config.dimension || 384)),
initialize: async () => {},
};