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): calibrated default search threshold (0.2) and near-miss hints when a default search is empty (#4129)

r6c5992a03061
diff --git a/v3/@claude-flow/cli/__tests__/memory-search-default-threshold-4129.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-default-threshold-4129.test.ts
new file mode 100644
index 0000000000..f67fb11535
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-search-default-threshold-4129.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_SEARCH_THRESHOLD, nearMisses } from '../src/memory/search-defaults.js';
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn(() => false), mkdirSync: vi.fn(), readdirSync: vi.fn(() => []),
+ readFileSync: vi.fn(() => '{}'), unlinkSync: vi.fn(), writeFileSync: vi.fn(),
+}));
+const { searchEntries } = vi.hoisted(() => ({ searchEntries: vi.fn() }));
+vi.mock('../src/memory/memory-initializer.js', () => ({
+ searchEntries,
+ storeEntry: vi.fn(), listEntries: vi.fn(), getEntry: vi.fn(), deleteEntry: vi.fn(),
+ initializeMemoryDatabase: vi.fn(),
+ checkMemoryInitialization: vi.fn(async () => ({ initialized: true })),
+}));
+
+const entry = (key: string, score: number) => ({
+ id: key, key, content: JSON.stringify({ note: key }), score, namespace: 'rules', provenanceType: 'tool_result',
+});
+interface Resp { results: Array<{ key: string; similarity: number }>; total: number; nearMisses?: Array<{ key: string; similarity: number }>; hint?: string }
+async function search(input: Record<string, unknown>): Promise<Resp> {
+ const { memoryTools } = await import('../src/mcp-tools/memory-tools.js');
+ return memoryTools.find(t => t.name === 'memory_search')!.handler(input) as Promise<Resp>;
+}
+/** A store that honours the threshold like the real one. */
+const store = (rows: Array<ReturnType<typeof entry>>) =>
+ searchEntries.mockImplementation(async ({ threshold, limit }: { threshold?: number; limit?: number }) => ({
+ success: true, results: rows.filter(r => r.score >= (threshold ?? 0)).slice(0, limit ?? 10),
+ }));
+
+beforeEach(() => { vi.resetModules(); searchEntries.mockReset(); });
+afterEach(() => vi.restoreAllMocks());
+
+describe('memory_search default threshold (#4129)', () => {
+ it('the default floor is below the 0.28 a correct paraphrase scores and above the 0.4 recall-fusion limit (#2558)', () => {
+ expect(DEFAULT_SEARCH_THRESHOLD).toBeLessThan(0.28);
+ expect(DEFAULT_SEARCH_THRESHOLD).toBeLessThanOrEqual(0.4);
+ expect(DEFAULT_SEARCH_THRESHOLD).toBeGreaterThan(0.15); // unrelated text sits at 0.0-0.15
+ });
+
+ it('returns a 0.28 paraphrase match with the threshold omitted', async () => {
+ store([entry('rls-policies', 0.28), entry('concrete-cure', 0.07)]);
+ const r = await search({ query: "stop one customer from seeing another customer's records in the database" });
+ expect(r.results.map(x => x.key)).toEqual(['rls-policies']);
+ expect(r.nearMisses).toBeUndefined();
+ expect(searchEntries.mock.calls[0][0].threshold).toBe(DEFAULT_SEARCH_THRESHOLD);
+ });
+
+ it('still drops unrelated text at the default and says what was closest', async () => {
+ store([entry('concrete-cure', 0.09), entry('oauth-pkce', 0.05)]);
+ const r = await search({ query: 'completely different topic' });
+ expect(r.total).toBe(0);
+ expect(r.nearMisses?.map(n => n.key)).toEqual(['concrete-cure', 'oauth-pkce']);
+ expect(r.nearMisses?.[0].similarity).toBe(0.09);
+ expect(r.hint).toMatch(/threshold: 0/);
+ const second = searchEntries.mock.calls[1][0];
+ expect(second.threshold).toBe(0);
+ expect(second.limit).toBe(3);
+ });
+
+ it('an explicit threshold is honoured, including 0, and adds no near-miss query', async () => {
+ store([entry('a', 0.05)]);
+ const strict = await search({ query: 'q', threshold: 0.9 });
+ expect(strict.total).toBe(0);
+ expect(strict.nearMisses).toBeUndefined();
+ expect(searchEntries).toHaveBeenCalledTimes(1);
+ searchEntries.mockClear();
+ const zero = await search({ query: 'q', threshold: 0 });
+ expect(zero.results.map(x => x.key)).toEqual(['a']);
+ expect(searchEntries).toHaveBeenCalledTimes(1);
+ });
+
+ it('nearMisses never throws and is absent when the store has nothing at all', async () => {
+ expect(await nearMisses(async () => { throw new Error('db gone'); }, { query: 'x' })).toBeUndefined();
+ expect(await nearMisses(async () => ({ success: true, results: [] }), { query: 'x' })).toBeUndefined();
+ expect(await nearMisses(async () => ({ success: false }), { query: 'x' })).toBeUndefined();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index d19ad464d3..9b92d8c269 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -3,6 +3,7 @@
* Memory operations for AgentDB integration
*/
import { validateAppendConditions } from '../memory/append-conditions.js';
+import { DEFAULT_SEARCH_THRESHOLD, nearMisses } from '../memory/search-defaults.js';
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
@@ -463,7 +464,7 @@ const searchCommand: Command = {
// default to 0.7, which silently re-broke #2558: `memory search` matched
// content word-for-word and still returned nothing. Regression guard:
// __tests__/memory-search-recall-2558.test.ts.
- default: 0.3
+ default: 0.2
},
{
name: 'type',
@@ -532,7 +533,9 @@ const searchCommand: Command = {
// coalescing preserves an explicit zero. Fallback aligned with the
// option's declared `default: 0.7` (was `0.3` — the two disagreed
// and --help advertised a default the code did not honor).
- const threshold = ctx.flags.threshold as number ?? 0.3;
+ const threshold = ctx.flags.threshold as number ?? DEFAULT_SEARCH_THRESHOLD;
+ // The parser fills the option's declared default, so an untouched flag arrives as the default value.
+ const thresholdWasDefault = ctx.flags.threshold === undefined || ctx.flags.threshold === DEFAULT_SEARCH_THRESHOLD;
const searchType = ctx.flags.type as string || 'semantic';
const buildHnsw = (ctx.flags['build-hnsw'] || ctx.flags.buildHnsw) as boolean;
const requestedIntent = (ctx.flags.intent as string) || 'mixed';
@@ -785,6 +788,15 @@ const searchCommand: Command = {
if (results.length === 0) {
output.printWarning('No results found');
+ if (thresholdWasDefault) {
+ const near = await nearMisses(searchEntries, { query, namespace, provenanceFilter, dbPath: dbPathSearch });
+ if (near) {
+ output.writeln(output.dim(` ${near.hint.replace(' in nearMisses', ' below').replace('Pass threshold: 0', 'Pass --threshold 0')}`));
+ for (const n of near.nearMisses) {
+ output.writeln(output.dim(` ${n.similarity.toFixed(2)} ${n.namespace}/${n.key}`));
+ }
+ }
+ }
await warnIfSiblingHasRows(ctx.flags.path);
output.writeln(output.dim('Try: claude-flow memory store -k "key" --value "data"'));
return { success: true, data: [] };
diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
index 8793d48352..81871d62bb 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -16,6 +16,7 @@ import { join, resolve } from 'path';
import { createHash } from 'crypto';
import type { MCPTool } from './types.js';
import { validateIdentifier } from './validate-input.js';
+import { DEFAULT_SEARCH_THRESHOLD, nearMisses } from '../memory/search-defaults.js';
// Legacy JSON store interface (for migration)
interface LegacyMemoryEntry {
@@ -623,7 +624,7 @@ export const memoryTools: MCPTool[] = [
query: { type: 'string', description: 'Search query (semantic similarity)' },
namespace: { type: 'string', description: 'Namespace to search (default: all namespaces — omit to search across every namespace)' },
limit: { type: 'number', description: 'Maximum results (default: 10)' },
- threshold: { type: 'number', description: 'Minimum raw retrieval relevance 0-1 for candidate admission, applied per query before SmartRetrieval ranking; not a floor on rankingScore (default: 0.3)' },
+ threshold: { type: 'number', description: 'Minimum raw retrieval relevance 0-1 for candidate admission, applied per query before SmartRetrieval ranking; not a floor on rankingScore (default: 0.2; calibrated for the bundled embedding model, pass 0 to see every match)' },
smart: { type: 'boolean', description: 'Enable SmartRetrieval — query expansion, RRF fusion, recency boost, MMR diversity; preserves raw similarity and adds rankingScore (default: false)' },
provenance_filter: {
type: 'array',
@@ -654,7 +655,8 @@ export const memoryTools: MCPTool[] = [
// in the search layer actually fires.
const namespace = input.namespace as string | undefined;
const limit = (input.limit as number) ?? 10;
- const threshold = (input.threshold as number) ?? 0.3;
+ const threshold = (input.threshold as number) ?? DEFAULT_SEARCH_THRESHOLD;
+ const thresholdWasDefault = input.threshold === undefined || input.threshold === null;
validateMemoryInput(undefined, undefined, query, namespace);
@@ -729,10 +731,15 @@ export const memoryTools: MCPTool[] = [
};
});
+ const smartNearMisses = results.length === 0 && thresholdWasDefault
+ ? await nearMisses(searchEntries, { query, namespace, provenanceFilter })
+ : undefined;
+
return {
query,
results,
total: results.length,
+ ...(smartNearMisses ?? {}),
searchTime: `${duration.toFixed(2)}ms`,
backend: 'SmartRetrieval (RRF + MMR + Recency)',
stats: smartResult.stats,
@@ -782,10 +789,15 @@ export const memoryTools: MCPTool[] = [
};
});
+ const nearMissInfo = results.length === 0 && thresholdWasDefault
+ ? await nearMisses(searchEntries, { query, namespace, provenanceFilter })
+ : undefined;
+
return {
query,
results,
total: results.length,
+ ...(nearMissInfo ?? {}),
searchTime: `${duration.toFixed(2)}ms`,
backend: 'HNSW + sql.js',
...(smartFallbackReason ? { smartFallback: smartFallbackReason } : {}),
diff --git a/v3/@claude-flow/cli/src/memory/memory-bridge.ts b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
index 3921ad2476..3c1f0de45b 100644
--- a/v3/@claude-flow/cli/src/memory/memory-bridge.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-bridge.ts
@@ -20,6 +20,7 @@ import { AppendConditionFailed, assertAppendConditions, validateAppendConditions
import { liveMemoryRowSql } from './live-memory-row.js';
import { resolveAgentdbBetterSqlite3 } from './shared-sqlite.js';
+import { DEFAULT_SEARCH_THRESHOLD } from './search-defaults.js';
import { encodeEmbeddingQ8, MAX_LIST_EMBEDDINGS } from './embedding-q8.js';
import * as path from 'path';
import * as crypto from 'crypto';
@@ -1398,7 +1399,7 @@ export async function bridgeSearchEntries(options: {
if (!ctx) return null;
try {
- const { query: queryStr, namespace, limit = 10, threshold = 0.3, provenanceFilter } = options;
+ const { query: queryStr, namespace, limit = 10, threshold = DEFAULT_SEARCH_THRESHOLD, provenanceFilter } = options;
const effectiveNamespace = namespace || 'all';
const startTime = Date.now();
@@ -2095,7 +2096,7 @@ export async function bridgeSearchBruteForceCosine(
try {
const k = options?.k ?? 10;
- const threshold = options?.threshold ?? 0.3;
+ const threshold = options?.threshold ?? DEFAULT_SEARCH_THRESHOLD;
const nsFilter = options?.namespace && options.namespace !== 'all'
? `AND namespace = ?`
: '';
diff --git a/v3/@claude-flow/cli/src/memory/memory-initializer.ts b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
index d1f0a1bd12..3d788d8e38 100644
--- a/v3/@claude-flow/cli/src/memory/memory-initializer.ts
+++ b/v3/@claude-flow/cli/src/memory/memory-initializer.ts
@@ -12,6 +12,7 @@ import type { AppendCondition } from './append-conditions.js';
import { loadBetterSqlite3 } from './shared-sqlite.js';
import { resolveMemoryRoot } from './memory-root.js';
+import { DEFAULT_SEARCH_THRESHOLD } from './search-defaults.js';
import { liveMemoryRowSql } from './live-memory-row.js';
import { encodeEmbeddingQ8, MAX_LIST_EMBEDDINGS, type EmbeddingQ8 } from './embedding-q8.js';
import * as fs from 'fs';
@@ -3186,7 +3187,7 @@ export async function searchEntries(options: {
query,
namespace,
limit = 10,
- threshold = 0.3,
+ threshold = DEFAULT_SEARCH_THRESHOLD,
dbPath: customPath,
provenanceFilter
} = options;
diff --git a/v3/@claude-flow/cli/src/memory/search-defaults.ts b/v3/@claude-flow/cli/src/memory/search-defaults.ts
new file mode 100644
index 0000000000..907b352890
--- /dev/null
+++ b/v3/@claude-flow/cli/src/memory/search-defaults.ts
@@ -0,0 +1,44 @@
+/**
+ * Default relevance floor for memory search (#4129).
+ *
+ * The bundled 384-dim embedding model scores a correct paraphrase match at
+ * roughly 0.25-0.5 and unrelated text at 0.0-0.15, so the old 0.3 floor sent
+ * back an empty list for natural-language queries whose right answer was
+ * clearly the best match (0.28 in the report). 0.2 sits between the two
+ * populations. An explicit `threshold` always wins, including 0.
+ *
+ * #2558 constraint stays: the fused recall score of a full-coverage exact
+ * keyword hit with semantic cosine <= 0 tops out at 0.40, so this must stay
+ * well below 0.4.
+ */
+export const DEFAULT_SEARCH_THRESHOLD = 0.2;
+
+/** How many below-threshold matches an empty default search reports as hints. */
+export const NEAR_MISS_LIMIT = 3;
+
+interface NearMissSearch {
+ (req: { query: string; namespace?: string; limit?: number; threshold?: number; provenanceFilter?: string[]; dbPath?: string }):
+ Promise<{ success: boolean; results?: Array<{ key: string; namespace: string; score: number }> }>;
+}
+
+/**
+ * When a search that used the DEFAULT threshold returns nothing, say what was
+ * close instead of leaving the caller to assume the store has no answer
+ * (#4129). One extra, cheap query at threshold 0; never throws; absent when
+ * nothing at all matched.
+ */
+export async function nearMisses(
+ search: NearMissSearch,
+ req: { query: string; namespace?: string; provenanceFilter?: string[]; dbPath?: string },
+): Promise<{ nearMisses: Array<{ key: string; namespace: string; similarity: number }>; hint: string } | undefined> {
+ try {
+ const r = await search({ ...req, limit: NEAR_MISS_LIMIT, threshold: 0 });
+ if (!r?.success || !r.results?.length) return undefined;
+ return {
+ nearMisses: r.results.map(e => ({ key: e.key, namespace: e.namespace, similarity: e.score })),
+ hint: `No result reached the default threshold (${DEFAULT_SEARCH_THRESHOLD}); the closest matches are in nearMisses. Pass threshold: 0 to include them in results.`,
+ };
+ } catch {
+ return undefined;
+ }
+}