π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(memory): preserve retrieval relevance in smart search results
takagibit1879529c6cf6bd
diff --git a/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts b/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.tsindex 170e4ba268..0a016c29e3 100644--- a/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts+++ b/v3/@claude-flow/cli-core/src/mcp-tools/memory-defs.ts@@ -65,7 +65,7 @@ export const memoryToolDefs: MCPToolDef[] = [{name: 'memory_search',description:- 'Find stored memories by meaning (vector similarity), not by literal text β finds "JWT auth pattern" when you query "token-based login flow". Use when native Grep is wrong because Grep matches characters and you need to find conceptually-related entries across past sessions. Backed by HNSW index over ONNX embeddings (heavy backend) or substring fallback (lite cli-core JSON backend); returns top-k with similarity scores.',+ 'Find stored memories by meaning (vector similarity), not by literal text β finds "JWT auth pattern" when you query "token-based login flow". Use when native Grep is wrong because Grep matches characters and you need to find conceptually-related entries across past sessions. Heavy retrieval or lite substring fallback returns similarity as raw retrieval relevance, not guaranteed cosine similarity. With smart=true on the heavy backend, similarity is the highest raw score across query variants and rankingScore is composite ranking relevance, not cosine similarity, probability, or confidence. Diversity can change result order.',category: 'memory',inputSchema: {type: 'object',@@ -73,8 +73,8 @@ export const memoryToolDefs: MCPToolDef[] = [query: { type: 'string', description: 'Search query (semantic similarity)' },namespace: { type: 'string', description: 'Namespace to search (default: "default")' },limit: { type: 'number', description: 'Maximum results (default: 10)' },- threshold: { type: 'number', description: 'Minimum similarity threshold 0-1 (default: 0.3)' },- smart: { type: 'boolean', description: 'Enable SmartRetrieval pipeline β query expansion, RRF fusion, recency boost, MMR diversity (default: false). No-op in cli-core lite backend.' },+ 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)' },+ smart: { type: 'boolean', description: 'Enable SmartRetrieval β query expansion, RRF fusion, recency boost, MMR diversity; preserves raw similarity and adds rankingScore (default: false). No-op in cli-core lite backend.' },provenance_filter: {type: 'array',items: { type: 'string', enum: ['user_claim', 'agent_output', 'system_observation', 'tool_result', 'unknown'] },diff --git a/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.tsnew file mode 100644index 0000000000..cefc6ee3a3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-search-scores-3327.test.ts@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { RawSearchRequest } from '../../memory/src/smart-retrieval.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: 'test',+ provenanceType: 'tool_result', embedding: [1, 0, 0],+});+interface SearchResponse {+ results: Array<{ key: string; namespace: string; value: unknown; similarity: number; rankingScore?: number }>;+ total: number;+ backend: string;+ smartFallback?: string;+ stats?: { variantCount: number; rawCandidateCount: number };+}+async function search(input: Record<string, unknown>): Promise<SearchResponse> {+ const { memoryTools } = await import('../src/mcp-tools/memory-tools.js');+ return memoryTools.find(t => t.name === 'memory_search')!.handler(input) as Promise<SearchResponse>;+}++beforeEach(() => {+ vi.resetModules();+ searchEntries.mockReset();+ // Run the actual pipeline from this checkout. Only the store/initialization+ // are faked; this exercises the real MCP handler and its response whitelist.+ // The CLI's externalize-optional-deps plugin rewrites this dynamic import+ // to /@id/...; mock that resolved ID so Vitest 4 intercepts the import.+ vi.doMock('/@id/@claude-flow/memory', async () => import('../../memory/src/smart-retrieval.js'));+});+afterEach(() => vi.restoreAllMocks());++describe('memory_search score contract (#3327 Finding B)', () => {+ it('returns raw relevance as similarity, never the RRF ranking score', async () => {+ searchEntries.mockImplementation(async ({ query }: RawSearchRequest) => ({+ success: true, results: query === 'alpha'+ ? [entry('a', 0.8)] : [entry('b', 0.9), entry('a', 0.65)],+ }));+ const result = await search({ query: 'alpha', smart: true });+ expect(result.backend).toBe('SmartRetrieval (RRF + MMR + Recency)');+ expect(result.results.map(r => r.key)).toEqual(['a', 'b']);+ // Baseline fails here: similarity is 0.03252247488101534, not 0.8.+ expect(result.results[0].similarity).toBe(0.8);+ expect(result.results[0].rankingScore).toBe(1 / 61 + 1 / 62);+ expect(result.results[0]).toEqual({+ key: 'a', namespace: 'test', value: { note: 'a' }, similarity: 0.8,+ rankingScore: 1 / 61 + 1 / 62, provenanceType: 'tool_result',+ }); // embedding, rawScore, and other internal fields must not leak+ expect(result.total).toBe(2);+ });++ it('uses the highest retrieval relevance across all expanded queries', async () => {+ const scores: Record<string, number> = {+ 'What is alpha?': 0.41, alpha: 0.73, 'tell me about what is alpha': 0.52,+ };+ searchEntries.mockImplementation(async ({ query }: RawSearchRequest) => ({+ success: true, results: [entry('a', scores[query])],+ }));+ const result = await search({ query: 'What is alpha?', smart: true });+ expect(searchEntries).toHaveBeenCalledTimes(3);+ expect(result.results[0].similarity).toBe(0.73);+ expect(result.results[0].rankingScore).toBe(3 / 61);+ });++ it('retains admitted results even when final ranking is below threshold', async () => {+ searchEntries.mockImplementation(async ({ threshold }: RawSearchRequest) => ({+ success: true, results: [entry('a', 0.7), entry('b', 0.2)]+ .filter(r => r.score >= (threshold ?? 0)),+ }));+ const result = await search({+ query: 'alpha', smart: true, threshold: 0.3, namespace: 'test',+ provenance_filter: ['tool_result'],+ });+ expect(result.results.map(r => r.key)).toEqual(['a']);+ expect(result.results[0].similarity).toBe(0.7);+ expect(result.results[0].rankingScore).toBe(2 / 61);+ for (const [request] of searchEntries.mock.calls) {+ expect(request).toMatchObject({ threshold: 0.3, namespace: 'test', provenanceFilter: ['tool_result'] });+ }+ expect(result.stats).toMatchObject({ rawCandidateCount: 2, variantCount: 2 });+ });++ it('preserves zero similarity instead of falling back to a positive ranking score', async () => {+ searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0)] });+ const result = await search({ query: 'alpha', smart: true, threshold: 0 });+ expect(result.results[0].similarity).toBe(0);+ expect(result.results[0].rankingScore).toBe(2 / 61);+ });++ it('keeps standard search output compatible without rankingScore', async () => {+ searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0.49)] });+ const result = await search({ query: 'alpha', smart: false });+ expect(result.results).toEqual([{+ key: 'a', namespace: 'test', value: { note: 'a' }, similarity: 0.49, provenanceType: 'tool_result',+ }]);+ expect(searchEntries).toHaveBeenCalledTimes(1);+ });++ it.each(['missing export', 'import failure'])('preserves standard fallback on %s', async (reason) => {+ vi.doMock('/@id/@claude-flow/memory', () => {+ if (reason === 'import failure') throw new Error('unavailable package');+ return { smartSearch: undefined };+ });+ searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0.49)] });+ const result = await search({ query: 'alpha', smart: true });+ expect(result.results).toEqual([{+ key: 'a', namespace: 'test', value: { note: 'a' }, similarity: 0.49, provenanceType: 'tool_result',+ }]);+ expect(result.smartFallback).toContain(reason === 'import failure' ? 'failed to load' : 'not exported');+ expect(result.backend).toBe('HNSW + sql.js');+ expect(searchEntries).toHaveBeenCalledTimes(1);+ });++ it('supplies rawScore to older SmartRetrieval implementations that preserve candidate fields', async () => {+ vi.doMock('/@id/@claude-flow/memory', () => ({+ // The existing return projection is {...candidate, score}. This fake+ // deliberately does not create rawScore: the MCP adapter must supply it.+ smartSearch: async (rawSearch: (request: RawSearchRequest) => Promise<{ results: object[] }>) => {+ const raw = await rawSearch({ query: 'alpha' });+ return { results: raw.results.map(r => ({ ...r, score: 0.05 })), stats: {} };+ },+ }));+ searchEntries.mockResolvedValue({ success: true, results: [entry('a', 0)] });+ const result = await search({ query: 'alpha', smart: true, threshold: 0 });+ expect(result.results[0].similarity).toBe(0);+ expect(result.results[0].rankingScore).toBe(0.05);+ });+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.tsindex 5b2ac16e85..8836fc0fbc 100644--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts@@ -559,7 +559,7 @@ export const memoryTools: MCPTool[] = [},{name: 'memory_search',- description: 'Find stored memories by meaning (vector similarity), not by literal text β finds "JWT auth pattern" when you query "token-based login flow". Use when native Grep is wrong because Grep matches characters and you need to find conceptually-related entries across past sessions. Backed by HNSW index over ONNX embeddings; returns top-k with similarity scores. Pair with smart=true for query expansion + MMR diversity.',+ description: 'Find stored memories by meaning (vector similarity), not by literal text β finds "JWT auth pattern" when you query "token-based login flow". Use when native Grep is wrong because Grep matches characters and you need to find conceptually-related entries across past sessions. Returns top-k with similarity: raw retrieval relevance, which may include lexical scoring and is not guaranteed to be cosine similarity. With smart=true, similarity is the highest raw score across query variants; rankingScore is the composite relevance score used by the ranking pipeline, not cosine similarity, probability, or confidence. Diversity can change result order.',category: 'memory',inputSchema: {type: 'object',@@ -567,8 +567,8 @@ 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 similarity threshold 0-1 (default: 0.3)' },- smart: { type: 'boolean', description: 'Enable SmartRetrieval pipeline β query expansion, RRF fusion, recency boost, MMR diversity (default: false)' },+ 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)' },+ 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',items: { type: 'string', enum: ['user_claim', 'agent_output', 'system_observation', 'tool_result', 'unknown'] },@@ -635,6 +635,7 @@ export const memoryTools: MCPTool[] = [key: e.key,content: e.content,score: e.score,+ rawScore: e.score,namespace: e.namespace,provenanceType: e.provenanceType,// Dream Cycle 2026-09-03: thread the already-computed@@ -654,14 +655,15 @@ export const memoryTools: MCPTool[] = [const duration = performance.now() - startTime;- const results = smartResult.results.map((r: { content: string; key: string; namespace: string; score: number; provenanceType?: string }) => {+ const results = smartResult.results.map((r: { content: string; key: string; namespace: string; score: number; rawScore?: number; provenanceType?: string }) => {let value: unknown = r.content;try { value = JSON.parse(r.content); } catch { /* keep as string */ }return {key: r.key,namespace: r.namespace,value,- similarity: r.score,+ similarity: r.rawScore,+ rankingScore: r.score,provenanceType: r.provenanceType,};});diff --git a/v3/@claude-flow/memory/src/smart-retrieval-scores.test.ts b/v3/@claude-flow/memory/src/smart-retrieval-scores.test.tsnew file mode 100644index 0000000000..7c62e70d66--- /dev/null+++ b/v3/@claude-flow/memory/src/smart-retrieval-scores.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from 'vitest';+import { smartSearch, type SearchCandidate, type SearchFn } from './smart-retrieval.js';++const candidate = (id: string, score: number): SearchCandidate => ({+ id, key: id, content: id, namespace: 'test', score,+});+const isolated = {+ query: 'original', recencyBoost: false, diversityMMR: false, sessionDiversity: false,+};++describe('smartSearch raw retrieval score (#3327 Finding B)', () => {+ it('retains raw relevance separately from multi-query RRF ranking', async () => {+ const search: SearchFn = async ({ query }) => ({ results: query === 'original'+ ? [candidate('a', 0.8)]+ : [candidate('b', 0.9), candidate('a', 0.65)],+ });+ const result = await smartSearch(search, {+ ...isolated, queryExpansions: () => ['original', 'expanded'],+ });+ expect(result.results.map(r => r.id)).toEqual(['a', 'b']);+ expect(result.results[0].score).toBe(1 / 61 + 1 / 62);+ expect(result.results[0]).toMatchObject({ rawScore: 0.8 });+ });++ it('retains the highest raw score across query variants', async () => {+ const scores: Record<string, number> = { a: 0.41, b: 0.73, c: 0.52 };+ const result = await smartSearch(async ({ query }) => ({+ results: [candidate('same-document', scores[query])],+ }), { ...isolated, queryExpansions: () => ['a', 'b', 'c'] });+ expect(result.results[0].score).toBe(3 / 61);+ expect(result.results[0]).toMatchObject({ rawScore: 0.73 });+ });++ it('preserves single-query scores and order, including zero', async () => {+ const inputs = [candidate('a', 0.8), candidate('b', 0)];+ const result = await smartSearch(async () => ({ results: inputs }), {+ ...isolated, multiQuery: false, threshold: 0,+ });+ expect(result.results).toEqual(inputs.map(r => ({ ...r, rawScore: r.score })));+ expect(inputs[0]).not.toHaveProperty('rawScore'); // no mutation of SearchFn results+ });++ it('keeps raw zero while recency changes the final ranking score', async () => {+ const result = await smartSearch(async () => ({ results: [{+ ...candidate('a', 0), updatedAt: 1000,+ }] }), {+ ...isolated, queryExpansions: () => ['a', 'b'], threshold: 0,+ recencyBoost: true, now: 1000,+ });+ expect(result.results[0].score).toBe((2 / 61) * 1.2);+ expect(result.results[0]).toMatchObject({ rawScore: 0 });+ });++ it('preserves an explicitly supplied rawScore of zero', async () => {+ const result = await smartSearch(async () => ({ results: [{+ ...candidate('a', 0.4), rawScore: 0,+ }] }), { ...isolated, multiQuery: false });+ expect(result.results[0]).toMatchObject({ score: 0.4, rawScore: 0 });+ });++ it('applies threshold only through raw candidate admission', async () => {+ const admitted: string[][] = [];+ const thresholds: Array<number | undefined> = [];+ const search: SearchFn = async ({ threshold }) => {+ thresholds.push(threshold);+ const results = [candidate('a', 0.7), candidate('b', 0.2)]+ .filter(r => r.score >= (threshold ?? 0));+ admitted.push(results.map(r => r.id));+ return { results };+ };+ const result = await smartSearch(search, {+ ...isolated, threshold: 0.3, queryExpansions: () => ['a', 'b'],+ });+ expect(thresholds).toEqual([0.3, 0.3]);+ expect(admitted).toEqual([['a'], ['a']]);+ expect(result.results.map(r => r.id)).toEqual(['a']);+ expect(result.results[0].score).toBe(2 / 61);+ expect(result.results[0].score).toBeLessThan(0.3);+ expect(result.results[0]).toMatchObject({ rawScore: 0.7 });+ });+});diff --git a/v3/@claude-flow/memory/src/smart-retrieval.ts b/v3/@claude-flow/memory/src/smart-retrieval.tsindex 276db20013..f78fcf2d83 100644--- a/v3/@claude-flow/memory/src/smart-retrieval.ts+++ b/v3/@claude-flow/memory/src/smart-retrieval.ts@@ -22,7 +22,14 @@ export interface SearchCandidate {id: string;key: string;content: string;+ /** Raw retrieval score on input; pipeline ranking score on smartSearch output. */score: number;+ /**+ * Underlying retrieval relevance before SmartRetrieval ranking, not necessarily+ * cosine similarity. Defaults to the selected candidate's input score; RRF+ * selects the candidate with the highest input score across query variants.+ */+ rawScore?: number;namespace: string;/** Optional metadata pulled through from the underlying store. */metadata?: Record<string, unknown>;@@ -60,7 +67,7 @@ export interface SmartSearchOptions {namespace?: string;/** Final number of results to return (default 10). */limit?: number;- /** Similarity floor applied to the raw store (default 0.3). */+ /** Retrieval relevance floor applied to the raw store, not final ranking (default 0.3). */threshold?: number;// ββ Phase toggles ββ@@ -533,6 +540,7 @@ export async function smartSearch(return {results: final.slice(0, limit).map(({ candidate, score }) => ({...candidate,+ rawScore: candidate.rawScore ?? candidate.score,score,})),stats: {