Merge branch 'main' into fix/federation-handoff-dual-floor

This commit is contained in:
rUv authored and GitHub committed 2026-11-04 01:58:09 -06:00
commit 504c2bd080
5 files changed
+226 -16

No files matched your search

@@ -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', () => {
@@ -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();
});
});
@@ -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<string, any> {
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: <x>Attention.computeRaw is not a function' }.
expect(r[fn].error, fn).toBeUndefined();
expect(r[fn], fn).toHaveLength(8);
}, 150_000);
}
});
+71 -11
View File
@@ -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<Float32Array[]> =>
const newBatch = async (texts: string[]): Promise<Float32Array[]> =>
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()
@@ -3643,6 +3680,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 +3701,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 +3735,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;
}
@@ -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 };
}