From bbd057eb177f583d10d66f6e6dc2c6ed773c7dca Mon Sep 17 00:00:00 2001 From: rUv Date: Wed, 4 Nov 2026 01:57:56 -0600 Subject: [PATCH] fix(memory): find stored patterns when agentdb serves mock embeddings (#4643) (#4681) agentdb_pattern-store writes through ReasoningBank.storePattern(), but when agentdb's Transformers.js model fails to load (offline, failed sharp install, or a loaded CI runner) it serves hash-based mock embeddings. A passage and a query then embed to unrelated vectors, so searchPatterns() returned [] for a pattern that was just stored. This is the full-suite #2226 failure that has kept the CI ratchet red since the move to agentdb 3.2. - bridgeSearchPatterns: when the agentdb vector search returns nothing, scan the same reasoning_patterns table for the query text, matching what the LocalReasoningBank branch already does over getAll(). - rescueAgentdbEmbedder: agentdb 3.x's ReasoningBank calls embedQuery() / embedPassage(), which bypass embed(). Patch the role methods too and clear the cached mock vectors, so a host with ONNX actually gets real vectors. - Regression test forces AGENTDB_DISABLE_TRANSFORMERS=1 and requires the round-trip to hit; it fails without the fix. Co-authored-by: r --- .../__tests__/bug-cluster-2219-2226.test.ts | 32 +++++++++++ .../cli/src/memory/memory-bridge.ts | 57 +++++++++++++++---- 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts b/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts index 1ebeadb0df..2ce58db2b1 100644 --- a/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts +++ b/v3/@claude-flow/cli/__tests__/bug-cluster-2219-2226.test.ts @@ -180,6 +180,38 @@ describe('#2226 — pattern store and search share a backend', () => { rmSync(dir, { recursive: true, force: true }); } }, 60_000); + + // #4643: the full CI run failed this round-trip because agentdb served mock + // embeddings there (its Transformers.js model did not load). A passage and a + // query then hash to unrelated vectors, so the vector search alone misses a + // pattern storePattern just wrote. Force that state and require a hit. + it('finds a stored pattern when agentdb falls back to mock embeddings', async () => { + const marker = `mock-embedder-roundtrip-${process.pid}-${process.hrtime.bigint()}`; + const dir = mkdtempSync(path.join(tmpdir(), 'ruflo-4643-')); + const prevCwd = process.cwd(); + process.chdir(dir); + vi.stubEnv('CLAUDE_FLOW_MEMORY_PATH', path.join(dir, '.swarm')); + vi.stubEnv('AGENTDB_DISABLE_TRANSFORMERS', '1'); + vi.resetModules(); + try { + const { agentdbPatternStore, agentdbPatternSearch } = await import('../src/mcp-tools/agentdb-tools.js'); + const stored = await agentdbPatternStore.handler({ + pattern: `Use ${marker} for secure session renewal`, + type: 'auth-pattern', + confidence: 0.9, + }); + if (!stored || stored.success !== true) return; // backend unavailable in isolation — skip + + const found = await agentdbPatternSearch.handler({ query: marker, topK: 5, minConfidence: 0.1 }); + const hit = (found.results ?? []).find((r: any) => + String(r.content ?? r.pattern ?? '').includes(marker)); + expect(hit, `stored=${JSON.stringify(stored)} found=${JSON.stringify(found).slice(0, 800)}`).toBeDefined(); + } finally { + process.chdir(prevCwd); + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); }); describe('#3288 — pattern store/search surface degraded:true on every non-reasoningBank path', () => { diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts index 882354e5fb..d8de3886be 100644 --- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts +++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts @@ -975,9 +975,23 @@ export async function rescueAgentdbEmbedder(agentdb: { embedder?: { pipeline?: u ? out.embedding : new Float32Array((out.embedding as number[]) ?? []); }; - emb.embed = newEmbed; - emb.embedBatch = async (texts: string[]): Promise => + const newBatch = async (texts: string[]): Promise => Promise.all(texts.map(t => newEmbed(t))); + emb.embed = newEmbed; + emb.embedBatch = newBatch; + // #4643: agentdb 3.x's ReasoningBank calls embedQuery()/embedPassage(), + // which route through embedFor() → generateEmbedding() → mockEmbedding() + // and never touch embed(). Patch the role methods too, or the rescue never + // reaches pattern store/search. The model is symmetric, so both roles share + // one function; drop any mock vectors already cached under the old space. + const roles = emb as typeof emb & { + embedQuery?: unknown; embedPassage?: unknown; embedQueryBatch?: unknown; embedPassageBatch?: unknown; clearCache?: () => void; + }; + if (typeof roles.embedQuery === 'function') roles.embedQuery = newEmbed; + if (typeof roles.embedPassage === 'function') roles.embedPassage = newEmbed; + if (typeof roles.embedQueryBatch === 'function') roles.embedQueryBatch = newBatch; + if (typeof roles.embedPassageBatch === 'function') roles.embedPassageBatch = newBatch; + try { roles.clearCache?.(); } catch { /* best-effort */ } emb.__ruvectorRescued = true; } @@ -2683,6 +2697,25 @@ export async function bridgeStorePattern(options: { } } +/** + * Case-insensitive substring match over agentdb's reasoning_patterns table — + * the rows ReasoningBank.storePattern() writes. Used only when the vector + * search returns nothing. Returns [] when the table or handle is unavailable. + */ +function substringSearchReasoningPatterns(registry: any, query: string, k: number): Array<{ id: string; content: string; score: number }> { + try { + const db = registry?.getAgentDB?.()?.database; + if (!db || typeof db.prepare !== 'function') return []; + const like = `%${query.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`; + const rows = db.prepare( + "SELECT id, approach, success_rate FROM reasoning_patterns WHERE lower(approach) LIKE ? ESCAPE '\\' ORDER BY id DESC LIMIT ?", + ).all(like, k) as Array<{ id: number; approach: string; success_rate: number }>; + return rows.map((r) => ({ id: String(r.id), content: r.approach, score: r.success_rate ?? 0 })); + } catch { + return []; + } +} + /** * Search patterns via ReasoningBank controller. */ @@ -2713,14 +2746,18 @@ export async function bridgeSearchPatterns(options: { // 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: String(r.id ?? r.patternId ?? ''), - content: r.approach ?? r.content ?? r.pattern ?? '', - score: r.similarity ?? r.score ?? r.successRate ?? r.confidence ?? 0, - })) : [], - controller: 'reasoningBank', - }; + let mapped = Array.isArray(results) ? results.map((r: any) => ({ + id: String(r.id ?? r.patternId ?? ''), + content: r.approach ?? r.content ?? r.pattern ?? '', + score: r.similarity ?? r.score ?? r.successRate ?? r.confidence ?? 0, + })) : []; + // #4643 — with agentdb's mock embedder (Transformers.js failed to load: + // offline, or a failed `sharp` install) a passage and a query embed to + // unrelated hash vectors, so the vector search misses a pattern that + // storePattern just wrote. Scan the same reasoning_patterns table for the + // query text, as the LocalReasoningBank branch below does over getAll(). + if (mapped.length === 0) mapped = substringSearchReasoningPatterns(registry, options.query, options.topK || 5); + return { results: mapped, controller: 'reasoningBank' }; } // #2226 — the wired-in LocalReasoningBank implements store() + findSimilar()/getAll()