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): restore keyword+semantic recall in `memory search` (#2558) (#2567)

rUv51085bf68d7a
diff --git a/v3/@claude-flow/cli/__tests__/memory-search-recall-2558.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-recall-2558.test.ts
new file mode 100644
index 0000000000..629e7d4eed
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-search-recall-2558.test.ts
@@ -0,0 +1,135 @@
+// #2558 regression: `memory search` recall was broken in v3.19.0/3.20.0 —
+// confirmed-stored entries were not recalled by keyword OR semantic search,
+// while store/list/retrieve/delete worked, and the HNSW index reported 0
+// vectors. Root cause was in the AgentDB bridge search path
+// (`bridgeSearchEntries`): it fused
+// 0.7 * cosine + 0.3 * (BM25 / 10)
+// and BM25's IDF collapses toward zero when a term appears in most/all
+// documents (routine on small memory corpora), so an exact-keyword hit scored
+// well below the default 0.3 threshold and was dropped. Separately,
+// better-sqlite3's WAL was never checkpointed and `vector_indexes.total_vectors`
+// was never updated, so WAL-blind readers reported "HNSW index: 0 vectors".
+//
+// This is an end-to-end guard: it drives the built CLI in a throwaway cwd
+// exactly like the bug report (store → list → search), because the AgentDB
+// bridge (better-sqlite3 + embedder) is the path that regressed and it only
+// activates in a real CLI process, not under the vitest transform.
+//
+// The test is skipped when the CLI has not been built (`bin/cli.js` absent).
+// The documented flow is `npm run build && npm test`, so the guard is active
+// in the standard dev/release pipeline.
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const CLI = path.resolve(HERE, '..', 'bin', 'cli.js');
+const CLI_BUILT = fs.existsSync(CLI);
+
+const NS = 'recall2558';
+const ENTRIES = [
+ { key: 'note/alpha', value: 'ruflo memory connectivity health probe alpha', unique: 'probe' },
+ { key: 'note/beta', value: 'ruflo memory connectivity latency check beta', unique: 'latency' },
+ { key: 'note/gamma', value: 'ruflo memory connectivity throughput report gamma', unique: 'throughput' },
+];
+
+let cwd = '';
+
+function cli(args: string[]): string {
+ return execFileSync('node', [CLI, ...args], {
+ cwd,
+ encoding: 'utf8',
+ timeout: 90_000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+}
+
+// The CLI prints a human `[INFO] …` line before the JSON body; slice from the
+// first `{` so we parse only the JSON document.
+function searchJson(query: string): { results: Array<{ key: string; score: number }> } {
+ const out = cli(['memory', 'search', '--query', query, '-n', NS, '--format', 'json']);
+ const start = out.indexOf('{');
+ expect(start).toBeGreaterThanOrEqual(0);
+ return JSON.parse(out.slice(start));
+}
+
+describe.skipIf(!CLI_BUILT)('memory search recall (#2558, end-to-end)', () => {
+ beforeAll(() => {
+ cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'cf-2558-'));
+ cli(['memory', 'init']);
+ for (const e of ENTRIES) {
+ cli(['memory', 'store', '-k', e.key, '-n', NS, '--value', e.value]);
+ }
+ }, 180_000);
+
+ afterAll(() => {
+ if (cwd) {
+ try { fs.rmSync(cwd, { recursive: true, force: true }); } catch { /* ignore */ }
+ }
+ });
+
+ it('list shows all stored entries (CRUD path is unaffected)', () => {
+ const out = cli(['memory', 'list', '-n', NS]);
+ for (const e of ENTRIES) expect(out).toContain(e.key);
+ });
+
+ it('recalls EVERY stored entry by a shared keyword (the core regression)', () => {
+ // Pre-fix this returned zero results at the default 0.3 threshold.
+ const r = searchJson('connectivity');
+ const keys = r.results.map((x) => x.key);
+ for (const e of ENTRIES) expect(keys).toContain(e.key);
+ });
+
+ it('discriminates by a unique keyword (recall is targeted, not a blanket dump)', () => {
+ const r = searchJson('throughput');
+ const keys = r.results.map((x) => x.key);
+ expect(keys).toContain('note/gamma');
+ // Entries that never mention "throughput" must NOT be pulled in — otherwise
+ // "recall" would be meaningless.
+ expect(keys).not.toContain('note/alpha');
+ expect(keys).not.toContain('note/beta');
+ });
+
+ it('reports N vectors, not 0, and is visible to WAL-blind readers', async () => {
+ // The bridge writes via better-sqlite3 in WAL mode. sql.js does NOT apply
+ // the -wal file, so reading the main DB file only sees rows that were
+ // checkpointed into it — exactly the "0 vectors" failure mode. The
+ // store-side WAL checkpoint (#2558) makes committed rows visible here.
+ const dbPath = path.join(cwd, '.swarm', 'memory.db');
+ expect(fs.existsSync(dbPath)).toBe(true);
+
+ const initSqlJs = (await import('sql.js')).default;
+ const SQL = await initSqlJs();
+ const db = new SQL.Database(fs.readFileSync(dbPath));
+
+ const rowCount = Number(
+ db.exec(`SELECT COUNT(*) FROM memory_entries WHERE namespace = '${NS}'`)[0]
+ ?.values?.[0]?.[0] ?? 0,
+ );
+ expect(rowCount).toBe(ENTRIES.length);
+
+ const embedded = Number(
+ db.exec(
+ `SELECT COUNT(*) FROM memory_entries WHERE namespace = '${NS}' AND embedding IS NOT NULL`,
+ )[0]?.values?.[0]?.[0] ?? 0,
+ );
+
+ // When the embedder produced vectors (the default), the surfaced vector
+ // count must reflect them rather than staying pinned at 0.
+ if (embedded > 0) {
+ expect(embedded).toBe(ENTRIES.length);
+ const totalVectors = db.exec(
+ `SELECT total_vectors FROM vector_indexes WHERE name = '${NS}'`,
+ )[0]?.values?.[0]?.[0];
+ if (totalVectors !== undefined) {
+ expect(Number(totalVectors)).toBe(ENTRIES.length);
+ }
+ }
+
+ db.close();
+ }, 30_000);
+});
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index d0f49d902c..6f0c8605d8 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -725,6 +725,33 @@ export async function bridgeStoreEntry(options: {
ttl ? now + (ttl * 1000) : null
);
+ // #2558: keep `vector_indexes.total_vectors` accurate so status/tooling
+ // stop reporting "HNSW index: 0 vectors" while embedded entries exist.
+ try {
+ ctx.db
+ .prepare(
+ `UPDATE vector_indexes SET
+ total_vectors = (SELECT COUNT(*) FROM memory_entries
+ WHERE namespace = ? AND embedding IS NOT NULL),
+ updated_at = ?
+ WHERE name = ?`,
+ )
+ .run(namespace, now, namespace);
+ } catch { /* vector_indexes may not exist on legacy DBs — non-fatal */ }
+
+ // #2558: better-sqlite3 opens the DB in WAL mode and, for the small write
+ // volumes typical of CLI usage, may never reach the auto-checkpoint
+ // threshold — leaving committed rows only in the -wal file. WAL-blind
+ // readers (the sql.js fallback search path; the statusline's read-only
+ // `sqlite3` vector count) then see a stale/empty main DB file and report
+ // "0 vectors" / empty search. A PASSIVE checkpoint flushes committed pages
+ // into the main file without blocking writers. Best-effort, never fatal.
+ try {
+ if (typeof ctx.db.pragma === 'function') {
+ ctx.db.pragma('wal_checkpoint(PASSIVE)');
+ }
+ } catch { /* non-WAL, busy, or unsupported — non-fatal */ }
+
// Phase 2: Write-through to TieredCache
const safeNs = String(namespace).replace(/:/g, '_');
const safeKey = String(key).replace(/:/g, '_');
@@ -842,18 +869,35 @@ export async function bridgeSearchEntries(options: {
bm25ScoreVal = Math.min(bm25ScoreVal / 10, 1.0);
}
- // Reciprocal rank fusion: combine semantic and BM25
- // Weight: 0.7 semantic + 0.3 BM25 when both embeddings present
- // Fall back to BM25-only when either query or row lacks an embedding
- const score = semanticScore > 0
- ? (0.7 * semanticScore + 0.3 * bm25ScoreVal)
- : bm25ScoreVal;
+ // #2558: keyword-coverage floor for the lexical signal.
+ // BM25's IDF collapses toward zero when a term appears in most/all
+ // documents (routine on small memory corpora), and the /10 normalization
+ // crushed exact-keyword hits well below the default 0.3 threshold — so
+ // `memory search` recalled NOTHING even when the content literally
+ // contained the query term (issue #2558: "keyword recall random"). The
+ // pre-BM25 fallback guaranteed keyword recall via matchCount/words*0.5;
+ // this restores that guarantee. `coverage` is the fraction of query
+ // terms present in the document — a full-coverage hit must always be
+ // recallable regardless of IDF.
+ const contentLower = String(row.content || '').toLowerCase();
+ const matchedTerms = queryTerms.filter(t => contentLower.includes(t)).length;
+ const coverage = queryTerms.length > 0 ? matchedTerms / queryTerms.length : 0;
+ const lexicalScore = Math.max(bm25ScoreVal, coverage);
+
+ // Recall-friendly fusion: a strong semantic OR lexical signal alone must
+ // clear the threshold. `blended` (0.6 semantic + 0.4 lexical) drives
+ // ranking; taking max() with the raw semantic score means (a) a genuinely
+ // similar entry is never dropped just because it lacks the query's exact
+ // words, and (b) a full-coverage keyword hit (lexical=1 → blended≥0.4) is
+ // never dropped just because its embedding cosine is low or negative.
+ const blended = 0.6 * Math.max(0, semanticScore) + 0.4 * lexicalScore;
+ const score = Math.max(blended, semanticScore);
if (score >= threshold) {
// Phase 4: ExplainableRecall provenance
const provenance = queryEmbedding
- ? `semantic:${semanticScore.toFixed(3)}+bm25:${bm25ScoreVal.toFixed(3)}`
- : `bm25:${bm25ScoreVal.toFixed(3)}`;
+ ? `semantic:${semanticScore.toFixed(3)}+lexical:${lexicalScore.toFixed(3)}`
+ : `lexical:${lexicalScore.toFixed(3)}`;
results.push({
id: String(row.id).substring(0, 12),