From 55260ca55a68e6fd27c83b2fe077374b241a4b00 Mon Sep 17 00:00:00 2001 From: Aaditya <107977627+555aaditya@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:31:04 +0530 Subject: [PATCH 1/3] fix(neural): call the @ruvector/attention API that exists (#4613) * fix(neural): call the @ruvector/attention API that exists ruvector-training called methods the binding does not have, in 0.1.31 and in the latest 2.2.2: - computeContrastiveLoss called InfoNceLoss.compute(anchor, positives[], negatives), which throws "Get TypedArray info failed" because the binding takes a single positive, and then InfoNceLoss.backward(), which does not exist. `neural train`'s contrastive leg (with --backend wasm, or auto without the native ruvllm trainer) swallowed the error every epoch and reported "LoRA Adaptations 0". - computeFlashAttention, computeMoEAttention and computeHyperbolicAttention called computeRaw(); the classes expose compute(query, keys, values). computeContrastiveLoss now uses computeWithGradients(anchor, positive, negatives) and averages over the positives, so the list signature keeps its meaning; it rejects an empty list. The attention helpers call compute(). With the fix, `neural train --backend wasm --epochs 5` reports 3 LoRA adaptations instead of 0. Fixes #4610 * test(neural): skip the #4610 cases unless initializeTraining brought the feature up Resolving @ruvector/attention is not enough. In CI the package resolves but the binding does not initialize, so the cases failed with "Flash attention not initialized". The test now runs initializeTraining once in a child and gates each case on the feature it reports: InfoNCE Loss for the contrastive case, and FlashAttention, MoE and HyperbolicAttention for their helpers. Refs #4610 --- ...vector-training-attention-api-4610.test.ts | 81 +++++++++++++++++++ .../cli/src/services/ruvector-training.ts | 22 +++-- 2 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/ruvector-training-attention-api-4610.test.ts diff --git a/v3/@claude-flow/cli/__tests__/ruvector-training-attention-api-4610.test.ts b/v3/@claude-flow/cli/__tests__/ruvector-training-attention-api-4610.test.ts new file mode 100644 index 0000000000..6c995940e7 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/ruvector-training-attention-api-4610.test.ts @@ -0,0 +1,81 @@ +/** + * #4610: ruvector-training called @ruvector/attention methods that don't exist: + * InfoNceLoss.backward() (and compute() with an array of positives), and + * computeRaw() on FlashAttention / MoEAttention / HyperbolicAttention. The + * contrastive leg of `neural train` swallowed the error every epoch. + * + * Runs against the real binding, since a mock would hide exactly this kind of + * API mismatch. vitest externalizes `@ruvector/*`, so the source runs in a child + * process under tsx (as agentic-flow-root-import.test.ts does). Each case runs + * only if initializeTraining actually brought the feature up: resolving the + * package is not enough, since the native binding can still fail to load (CI). + */ +import { describe, expect, it } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const CLI = resolve(__dirname, '..'); +const SRC = JSON.stringify(pathToFileURL(join(CLI, 'src', 'services', 'ruvector-training.ts')).href); +const hasBinding = (() => { try { createRequire(import.meta.url).resolve('@ruvector/attention'); return true; } catch { return false; } })(); + +/** Run `body` after initializeTraining in a child; it must print one RESULT= JSON line. */ +function probe(body: string): Record { + const script = ` + const rt = await import(${SRC}); + const binding = (await import('node:module')).createRequire(import.meta.url)('@ruvector/attention'); + const init = await rt.initializeTraining({ dim: 8, useFlashAttention: true, useMoE: true, useHyperbolic: true }); + const vec = s => Float32Array.from({ length: 8 }, (_, i) => Math.sin(s + i) * 0.5); + const out = {}; + const attempt = (name, f) => { try { out[name] = f(); } catch (e) { out[name] = { error: e.constructor.name + ': ' + e.message }; } }; + ${body} + console.log('RESULT=' + JSON.stringify(out, (_, v) => v instanceof Float32Array ? Array.from(v) : v)); + process.exit(0);`; + const child = spawnSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], { cwd: CLI, encoding: 'utf8', timeout: 120_000 }); + const line = child.stdout.split('\n').find((l) => l.startsWith('RESULT=')); + if (!line) throw new Error(`probe produced no result: ${child.stderr.slice(-500)}`); + return JSON.parse(line.slice('RESULT='.length)); +} + +/** Features initializeTraining reported in a child, or [] when it could not run. */ +const features: string[] = (() => { + if (!hasBinding) return []; + try { return probe('out.features = init.features ?? [];').features ?? []; } catch { return []; } +})(); +const has = (name: string) => features.some((f) => f.startsWith(name)); +const HELPERS = [ + ['computeFlashAttention', 'FlashAttention'], + ['computeMoEAttention', 'MoE'], + ['computeHyperbolicAttention', 'HyperbolicAttention'], +] as const; + +describe('ruvector-training against the real @ruvector/attention API (#4610)', () => { + it.skipIf(!has('InfoNCE Loss'))('computeContrastiveLoss returns the binding loss and gradients, averaging positives', () => { + const r = probe(` + const anchor = vec(1), negatives = [vec(7), vec(9)]; + attempt('one', () => rt.computeContrastiveLoss(anchor, [vec(2)], negatives)); + attempt('expected', () => new binding.InfoNceLoss(0.07).computeWithGradients(anchor, vec(2), negatives)); + attempt('a', () => rt.computeContrastiveLoss(anchor, [vec(2)], [vec(7)])); + attempt('b', () => rt.computeContrastiveLoss(anchor, [vec(3)], [vec(7)])); + attempt('both', () => rt.computeContrastiveLoss(anchor, [vec(2), vec(3)], [vec(7)])); + attempt('none', () => rt.computeContrastiveLoss(anchor, [], negatives));`); + // Baseline: { error: 'Error: Get TypedArray info failed' } (and backward() does not exist). + expect(r.one.error).toBeUndefined(); + expect(r.one.loss).toBeCloseTo(r.expected.loss, 6); + expect(r.one.gradient).toHaveLength(8); + r.one.gradient.forEach((g: number, i: number) => expect(g).toBeCloseTo(r.expected.gradients[i], 6)); + expect(r.both.loss).toBeCloseTo((r.a.loss + r.b.loss) / 2, 6); + expect(r.both.gradient[0]).toBeCloseTo((r.a.gradient[0] + r.b.gradient[0]) / 2, 6); + expect(r.none.error).toMatch(/at least one positive/); + }, 150_000); + + for (const [fn, feature] of HELPERS) { + it.skipIf(!has(feature))(`${fn} returns an attended vector`, () => { + const r = probe(`attempt('${fn}', () => rt.${fn}(vec(1), [vec(2), vec(3)], [vec(4), vec(5)]));`); + // Baseline: { error: 'TypeError: Attention.computeRaw is not a function' }. + expect(r[fn].error, fn).toBeUndefined(); + expect(r[fn], fn).toHaveLength(8); + }, 150_000); + } +}); diff --git a/v3/@claude-flow/cli/src/services/ruvector-training.ts b/v3/@claude-flow/cli/src/services/ruvector-training.ts index a963403e8c..a4f23a93cd 100644 --- a/v3/@claude-flow/cli/src/services/ruvector-training.ts +++ b/v3/@claude-flow/cli/src/services/ruvector-training.ts @@ -591,7 +591,8 @@ export function computeFlashAttention( throw new Error('Flash attention not initialized'); } - return flashAttention.computeRaw(query, keys, values); + // #4610: the @ruvector/attention classes expose compute(), not computeRaw(). + return flashAttention.compute(query, keys, values); } /** @@ -606,7 +607,7 @@ export function computeMoEAttention( throw new Error('MoE attention not initialized'); } - return moeAttention.computeRaw(query, keys, values); + return moeAttention.compute(query, keys, values); } /** @@ -621,7 +622,7 @@ export function computeHyperbolicAttention( throw new Error('Hyperbolic attention not initialized'); } - return hyperbolicAttention.computeRaw(query, keys, values); + return hyperbolicAttention.compute(query, keys, values); } /** @@ -636,8 +637,19 @@ export function computeContrastiveLoss( throw new Error('Contrastive loss not initialized'); } - const loss = contrastiveLoss.compute(anchor, positives, negatives); - const gradient = contrastiveLoss.backward(anchor, positives, negatives); + // #4610: InfoNceLoss has no backward(); computeWithGradients(anchor, positive, + // negatives) takes one positive and returns { loss, gradients }. Average over + // the positives so the list signature keeps its meaning. + if (positives.length === 0) { + throw new Error('Contrastive loss needs at least one positive'); + } + let loss = 0; + const gradient = new Float32Array(anchor.length); + for (const positive of positives) { + const result = contrastiveLoss.computeWithGradients(anchor, positive, negatives); + loss += result.loss / positives.length; + for (let i = 0; i < gradient.length; i++) gradient[i] += result.gradients[i] / positives.length; + } return { loss, gradient }; } From 762fbf74c2b7315a94bfa0d036880688120aaabe Mon Sep 17 00:00:00 2001 From: ordinary being Date: Wed, 4 Nov 2026 15:01:20 +0800 Subject: [PATCH 2/3] fix(memory): expose AgentDB init failures in health (#4667) agentdb_health could return available:true with controllers while AgentDB itself had failed to open (for example because the daemon or another MCP server owned the RuVector store). The only trace was the separate isBridgeAvailable() check; the health payload had no init error or lock hint (#4654).\n\nbridgeHealthCheck now reads the registry's getAgentDBInitError(), reports available:false, includes agentdbInitError and the recorded bridgeFailureReason, and adds an actionable hint when the cause is an already-open/locked native store. Older registries without the record are unchanged.\n\nRegression extends the #4622 fake registry with listControllers and covers failed and healthy health payloads. Baseline returns available:true and no error for the failure case; candidate 5/5 with the Windows bridge opt-in, existing 3 tests unchanged. --- ...ory-bridge-agentdb-init-error-4622.test.ts | 25 +++++++++++++++++++ .../cli/src/memory/memory-bridge.ts | 25 ++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/v3/@claude-flow/cli/__tests__/memory-bridge-agentdb-init-error-4622.test.ts b/v3/@claude-flow/cli/__tests__/memory-bridge-agentdb-init-error-4622.test.ts index 2a95a23eae..d3877adacb 100644 --- a/v3/@claude-flow/cli/__tests__/memory-bridge-agentdb-init-error-4622.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-bridge-agentdb-init-error-4622.test.ts @@ -12,6 +12,7 @@ import * as path from 'node:path'; import { __setMemoryBridgeRegistryFactoryForTests, _resetRegistryCacheForTest, + bridgeHealthCheck, getBridgeFailureReason, isBridgeAvailable, } from '../src/memory/memory-bridge.js'; @@ -24,6 +25,7 @@ function fakeRegistry(initError: string | null, hasRecord = true) { getAgentDB: () => (initError ? null : {}), get: (name: string) => controllers.get(name), set: (name: string, value: unknown) => { controllers.set(name, value); }, + listControllers: () => [], }; if (hasRecord) reg.getAgentDBInitError = () => initError; return reg; @@ -66,4 +68,27 @@ describe('memory bridge: AgentDB init failure (#4622)', () => { expect(await isBridgeAvailable(db)).toBe(true); expect(getBridgeFailureReason(db)).toBeNull(); }); + + it('surfaces the AgentDB init cause and a lock hint in health', async () => { + const lock = 'Database already open. Cannot acquire lock'; + __setMemoryBridgeRegistryFactoryForTests(() => fakeRegistry(lock)); + const db = dbFile(); + + const health = await bridgeHealthCheck(db); + expect(health).not.toBeNull(); + expect(health?.available).toBe(false); + expect(health?.agentdbInitError).toContain(lock); + expect(health?.bridgeFailureReason).toContain(lock); + expect(health?.hint).toMatch(/another process/i); + }); + + it('keeps health available when AgentDB opened', async () => { + __setMemoryBridgeRegistryFactoryForTests(() => fakeRegistry(null)); + const db = dbFile(); + + const health = await bridgeHealthCheck(db); + expect(health?.available).toBe(true); + expect(health?.agentdbInitError).toBeNull(); + expect(health?.hint).toBeUndefined(); + }); }); diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts index e6739b6847..882354e5fb 100644 --- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts +++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts @@ -3643,6 +3643,12 @@ export async function bridgeHealthCheck( controllers: Array<{ name: string; enabled: boolean; level: number }>; attestationCount?: number; cacheStats?: { size: number; hits: number; misses: number }; + /** Why AgentDB failed to open, or null when it opened (#4654). */ + agentdbInitError?: string | null; + /** Last bridge-level failure, including the AgentDB lock cause (#4622/#4654). */ + bridgeFailureReason?: string | null; + /** Actionable next step when a second process owns the native store. */ + hint?: string; hierarchicalMemory?: { controller: string; durable: boolean; @@ -3658,6 +3664,12 @@ export async function bridgeHealthCheck( try { const controllers = registry.listControllers(); + const resolvedPath = canonicalDbPath(dbPath); + const agentdbInitError = agentdbInitFailure(registry, resolvedPath); + const bridgeFailureReason = getBridgeFailureReason(dbPath); + const lockHint = agentdbInitError && /already open|cannot acquire lock|locked/i.test(agentdbInitError) + ? 'Another process (often the ruflo daemon or a second MCP server) owns the native vector store. Stop one owner and reconnect; reads currently use the volatile fallback.' + : undefined; // Phase 4: AttestationLog stats let attestationCount = 0; @@ -3686,7 +3698,18 @@ export async function bridgeHealthCheck( }; } - return { available: true, controllers, attestationCount, cacheStats, hierarchicalMemory }; + return { + // A registry with a failed AgentDB still serves its other controllers, + // but it is not a working persistent bridge (#4622/#4654). + available: agentdbInitError === null, + controllers, + attestationCount, + cacheStats, + agentdbInitError, + bridgeFailureReason, + ...(lockHint ? { hint: lockHint } : {}), + hierarchicalMemory, + }; } catch { return null; } From bbd057eb177f583d10d66f6e6dc2c6ed773c7dca Mon Sep 17 00:00:00 2001 From: rUv Date: Wed, 4 Nov 2026 01:57:56 -0600 Subject: [PATCH 3/3] 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()