From fb026a7bb2502cd38e73d0e1892a2265b1da83c3 Mon Sep 17 00:00:00 2001 From: ruvnet Date: Sat, 18 Jul 2026 17:51:27 -0400 Subject: [PATCH] fix(memory): memory_search omitted namespace no longer collapses to empty 'default' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #2646 (3rd occurrence of the #1123/#1131 bug shape). Root cause: the memory_search MCP tool handler coerced an omitted `namespace` parameter to the literal string 'default': const namespace = (input.namespace as string) || 'default'; But both underlying search implementations already resolve an omitted/undefined namespace to the 'all' sentinel (fan out across every namespace): const effectiveNamespace = namespace || 'all'; // memory-initializer.ts const effectiveNamespace = namespace || 'all'; // memory-bridge.ts 'default' is truthy, so passing it explicitly defeated that fallback and silently scoped the search to a namespace that is usually empty — exactly matching memory_stats showing entries across other namespaces while memory_search with no namespace returned 0 results. The CLI's `memory search` command already got this right (defaults to 'all', not 'default'), which is what tipped this off as a tool-handler-only bug. Fix: leave `namespace` undefined when the caller omits it, so the search layer's own `|| 'all'` fallback actually fires. Also corrected the inputSchema description, which previously (and misleadingly) documented the empty-default behavior as intended. Added __tests__/memory-search-namespace-default-2646.test.ts, which mocks the search layer to assert the tool forwards `namespace: undefined` (not 'default') and reproduces the issue's exact repro shape end-to-end. Verified it fails against the pre-fix handler and passes against the fix. Co-Authored-By: RuFlo --- ...mory-search-namespace-default-2646.test.ts | 141 ++++++++++++++++++ .../cli/src/mcp-tools/memory-tools.ts | 14 +- 2 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/memory-search-namespace-default-2646.test.ts diff --git a/v3/@claude-flow/cli/__tests__/memory-search-namespace-default-2646.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-namespace-default-2646.test.ts new file mode 100644 index 0000000000..9b1083ebdf --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/memory-search-namespace-default-2646.test.ts @@ -0,0 +1,141 @@ +/** + * Regression guard for issue #2646 — the MCP `memory_search` tool returned + * 0 results when the optional `namespace` parameter was omitted, even though + * `memory_stats` confirmed entries existed across multiple namespaces with + * 100% embedding coverage. Passing any concrete `namespace` returned the + * expected hits immediately. + * + * This is the THIRD occurrence of this exact bug shape (#1123, #1131 — both + * closed Feb/Mar). Root cause each time: the `memory_search` tool handler in + * `mcp-tools/memory-tools.ts` coerces an omitted `namespace` to the literal + * string `'default'`: + * + * const namespace = (input.namespace as string) || 'default'; + * + * But BOTH underlying search implementations — `searchEntries()` in + * `memory/memory-initializer.ts` and `bridgeSearchEntries()` in + * `memory/memory-bridge.ts` — already resolve an omitted/undefined namespace + * to the `'all'` sentinel (fan out across every namespace): + * + * const effectiveNamespace = namespace || 'all'; + * + * `'default'` is truthy, so passing it explicitly defeats that fallback and + * silently scopes the search to a namespace that is usually empty (the CLI + * `memory search` command already gets this right — see + * `commands/memory.ts`, which defaults to `'all'`, not `'default'`). + * + * Why prior fixes didn't catch the regression: #1123/#1131 fixed the + * *search-layer* default (`searchEntries`/`bridgeSearchEntries`) but nothing + * asserted what the `memory_search` MCP *tool handler* actually forwards to + * that layer, so a later refactor of `memory-tools.ts` could silently + * reintroduce `|| 'default'` at the tool boundary without breaking anything. + * This guard asserts the forwarded argument directly, at the tool boundary. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Mock fs so `ensureInitialized()`'s legacy-migration check (`hasLegacyStore`) +// is a deterministic no-op regardless of the real cwd. +vi.mock('fs', () => ({ + existsSync: vi.fn(() => false), + mkdirSync: vi.fn(), + readdirSync: vi.fn(() => []), + readFileSync: vi.fn(() => '{}'), + unlinkSync: vi.fn(), + writeFileSync: vi.fn(), +})); + +// Spy on the search layer so we can assert exactly what `memory_search` +// forwards to it, and simulate the real-world repro: a populated +// "projetos" namespace alongside an empty "default" one. +// `vi.hoisted()` is required here: `vi.mock()` factories are hoisted above +// all other module-level code (including `const` declarations), so a plain +// `const searchEntries = vi.fn(...)` referenced inside the factory below +// would throw a temporal-dead-zone error at mock-evaluation time. +const { searchEntries } = vi.hoisted(() => { + const fn = vi.fn(async (opts: { namespace?: string }) => { + // Faithful to the real implementations' `namespace || 'all'` semantics — + // an omitted/undefined namespace (or the explicit 'all' sentinel) must + // search across every namespace; anything else scopes to that namespace. + const effectiveNamespace = opts.namespace || 'all'; + + const allEntries = [ + { id: 'a1', key: 'note/alpha', content: 'ruflo memory probe', score: 0.9, namespace: 'projetos' }, + { id: 'a2', key: 'note/beta', content: 'ruflo memory probe', score: 0.8, namespace: 'patterns' }, + ]; + + if (effectiveNamespace === 'all') { + return { success: true, results: allEntries, searchTime: 1 }; + } + // The 'default' namespace (and any other namespace with no data) is empty + // — exactly the failure mode from the issue's memory_stats repro. + const scoped = allEntries.filter((e) => e.namespace === effectiveNamespace); + return { success: true, results: scoped, searchTime: 1 }; + }); + return { searchEntries: fn }; +}); + +vi.mock('../src/memory/memory-initializer.js', () => ({ + generateEmbedding: vi.fn(async () => ({ embedding: new Array(384).fill(0.1), dimensions: 384, model: 'mock' })), + storeEntry: vi.fn(async () => ({ success: true, id: 'mock-id' })), + searchEntries, + listEntries: vi.fn(async () => ({ success: true, entries: [], total: 0 })), + getEntry: vi.fn(async () => null), + deleteEntry: vi.fn(async () => ({ success: true })), + getStats: vi.fn(async () => ({ totalEntries: 0 })), + initializeDatabase: vi.fn(async () => ({ success: true })), + initializeMemoryDatabase: vi.fn(async () => ({ success: true })), + checkMemoryInitialization: vi.fn(async () => ({ initialized: true, version: '3.0.0' })), + migrateFromLegacy: vi.fn(async () => ({ success: true, migrated: 0 })), +})); + +import { memoryTools } from '../src/mcp-tools/memory-tools.js'; + +const tool = memoryTools.find((t) => t.name === 'memory_search'); + +describe('memory_search namespace default (#2646, 3rd occurrence of #1123/#1131)', () => { + beforeEach(() => { + searchEntries.mockClear(); + }); + + it('exists', () => { + expect(tool).toBeDefined(); + }); + + it('schema no longer documents a literal "default" namespace default (the misleading doc from the issue)', () => { + const props = (tool!.inputSchema as { properties: Record }).properties; + const desc = props.namespace?.description ?? ''; + expect(desc).not.toContain('default: "default"'); + }); + + it('omitting namespace forwards namespace=undefined to the search layer, not the literal string "default"', async () => { + await tool!.handler({ query: 'test query' }); + expect(searchEntries).toHaveBeenCalled(); + const callArgs = searchEntries.mock.calls[0][0] as { namespace?: string }; + // This is the exact assertion that would have failed against the + // regressed code (`namespace = input.namespace || 'default'`). + expect(callArgs.namespace).not.toBe('default'); + expect(callArgs.namespace).toBeUndefined(); + }); + + it('reproduces the issue #2646 repro end-to-end: omitting namespace returns hits from ALL namespaces', async () => { + const r = await tool!.handler({ query: 'ruflo memory probe' }) as { results: unknown[]; total: number }; + // Pre-fix this was `{ results: [], total: 0 }` even though entries existed + // in "projetos"/"patterns" — exactly the memory_stats-vs-memory_search + // mismatch reported in the issue. + expect(r.total).toBe(2); + expect(r.results.map((e) => (e as { key: string }).key)).toEqual( + expect.arrayContaining(['note/alpha', 'note/beta']), + ); + }); + + it('an explicit namespace is still forwarded unchanged (back-compat with the issue\'s working case)', async () => { + await tool!.handler({ query: 'test', namespace: 'projetos' }); + const callArgs = searchEntries.mock.calls[0][0] as { namespace?: string }; + expect(callArgs.namespace).toBe('projetos'); + + const r = await tool!.handler({ query: 'test', namespace: 'projetos' }) as { results: unknown[]; total: number }; + expect(r.total).toBe(1); + expect((r.results[0] as { key: string }).key).toBe('note/alpha'); + }); +}); 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 45c714e35a..2fe20f96d6 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -443,7 +443,7 @@ export const memoryTools: MCPTool[] = [ type: 'object', properties: { query: { type: 'string', description: 'Search query (semantic similarity)' }, - namespace: { type: 'string', description: 'Namespace to search (default: "default")' }, + 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)' }, @@ -455,11 +455,19 @@ export const memoryTools: MCPTool[] = [ const { searchEntries } = await getMemoryFunctions(); const query = input.query as string; - const namespace = (input.namespace as string) || 'default'; + // #2646 (3rd occurrence of #1123/#1131 shape): do NOT coerce an omitted + // namespace to the literal string 'default' here. Both searchEntries() + // and bridgeSearchEntries() already resolve an omitted/undefined + // namespace to 'all' (fan out across every namespace) — but 'default' + // is truthy, so passing it defeats that fallback and silently scopes + // the search to a namespace that is usually empty. Leave namespace + // undefined when not provided so the underlying `|| 'all'` fallback + // 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; - validateMemoryInput(undefined, undefined, query); + validateMemoryInput(undefined, undefined, query, namespace); const startTime = performance.now();