diff --git a/v3/@claude-flow/cli/__tests__/intelligence-flush-failure-4880.test.ts b/v3/@claude-flow/cli/__tests__/intelligence-flush-failure-4880.test.ts new file mode 100644 index 0000000000..0dcf621aa2 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/intelligence-flush-failure-4880.test.ts @@ -0,0 +1,149 @@ +/** + * #4880: LocalReasoningBank.flushToDisk() caught write errors (e.g. ENOSPC), + * logged them and left the bank dirty, but returned void — so callers such as + * recordTrajectory() reported success for patterns that never reached disk. + * flushToDisk() now returns false on failure, records the error, and exposes + * it through getPersistenceStatus(); recordTrajectory() surfaces the failure. + */ +import { afterAll, beforeAll, beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +// Switchable fault: when on, writes of the patterns temp file fail with ENOSPC. +// Every other fs call (lock dir, stats file, reads) uses the real module. +const fault = vi.hoisted(() => ({ enospc: false })); +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + const writeFileSync = ((file: unknown, ...rest: unknown[]) => { + if (fault.enospc && typeof file === 'string' && /patterns\.json\..*\.tmp$/.test(file)) { + throw Object.assign(new Error('ENOSPC: no space left on device, write'), { code: 'ENOSPC' }); + } + return (actual.writeFileSync as (...a: unknown[]) => void)(file, ...rest); + }) as typeof actual.writeFileSync; + return { ...actual, default: { ...actual, writeFileSync }, writeFileSync }; +}); + +// Keep any embedding the module generates deterministic (no model cache needed). +vi.mock('../src/memory/memory-bridge.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, bridgeGenerateEmbedding: vi.fn(async () => null) }; +}); +vi.mock('../src/memory/memory-initializer.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + generateEmbedding: vi.fn(async () => ({ + embedding: [1, 0, 0], dimensions: 3, model: 'mock-deterministic', backend: 'mock' as const, + })), + }; +}); + +const SCRATCH = mkdtempSync(join(tmpdir(), 'intel-flush-4880-')); +const patternsPath = join(SCRATCH, '.claude-flow', 'neural', 'patterns.json'); +let originalCwd: string; + +function pattern(id: string, content: string) { + return { id, type: 'test', embedding: [0.1, 0.2, 0.3], content, confidence: 0.8 }; +} + +beforeAll(() => { + originalCwd = process.cwd(); + process.chdir(SCRATCH); + mkdirSync(join(SCRATCH, '.claude-flow'), { recursive: true }); +}); + +afterAll(() => { + try { process.chdir(originalCwd); } catch { /* best-effort */ } + rmSync(SCRATCH, { recursive: true, force: true }); +}); + +beforeEach(async () => { + fault.enospc = false; + vi.spyOn(console, 'error').mockImplementation(() => {}); + const intel = await import('../src/memory/intelligence.js'); + intel.clearIntelligence(); + rmSync(join(SCRATCH, '.claude-flow', 'neural'), { recursive: true, force: true }); + await intel.initializeIntelligence(); +}); + +afterEach(() => { + fault.enospc = false; + vi.restoreAllMocks(); +}); + +describe('LocalReasoningBank flush failure reporting (#4880)', () => { + it('returns false, stays dirty and records the error when the write fails', async () => { + const intel = await import('../src/memory/intelligence.js'); + const bank = intel.getReasoningBank()!; + + bank.store(pattern('p-1', 'pattern one')); + fault.enospc = true; + + expect(bank.flushToDisk()).toBe(false); + + const state = bank.getFlushState(); + expect(state.dirty).toBe(true); + expect(state.lastFlushError).toMatch(/ENOSPC/); + expect(typeof state.lastFlushAt).toBe('number'); + + const status = intel.getPersistenceStatus(); + expect(status.dirty).toBe(true); + expect(status.lastFlushError).toMatch(/ENOSPC/); + expect(status.lastFlushAt).toBe(state.lastFlushAt); + + // Nothing reached disk, and the failure did not throw out of the timer path. + expect(() => readFileSync(patternsPath, 'utf-8')).toThrow(); + }); + + it('recordTrajectory surfaces the failed flush instead of reporting success', async () => { + const intel = await import('../src/memory/intelligence.js'); + fault.enospc = true; + + const recorded = await intel.recordTrajectory( + [{ type: 'action', content: 'write a regression test', embedding: [1, 0, 0], timestamp: Date.now() }], + 'success', + ); + + expect(recorded).toBe(false); + expect(intel.getPersistenceStatus().lastFlushError).toMatch(/ENOSPC/); + expect(intel.flushPatterns()).toBe(false); + }); + + it('a later successful flush persists the patterns and clears the error', async () => { + const intel = await import('../src/memory/intelligence.js'); + const bank = intel.getReasoningBank()!; + + bank.store(pattern('p-1', 'pattern one')); + fault.enospc = true; + expect(bank.flushToDisk()).toBe(false); + + fault.enospc = false; + expect(bank.flushToDisk()).toBe(true); + + const status = intel.getPersistenceStatus(); + expect(status.dirty).toBe(false); + expect(status.lastFlushError).toBeNull(); + expect(typeof status.lastFlushAt).toBe('number'); + + const ids = JSON.parse(readFileSync(patternsPath, 'utf-8')).map((p: { id: string }) => p.id); + expect(ids).toContain('p-1'); + }); + + it('reports success on the happy path, and when there is nothing to write', async () => { + const intel = await import('../src/memory/intelligence.js'); + const bank = intel.getReasoningBank()!; + + expect(bank.flushToDisk()).toBe(true); // clean bank: nothing to write + + const recorded = await intel.recordTrajectory( + [{ type: 'action', content: 'happy path step', embedding: [1, 0, 0], timestamp: Date.now() }], + 'success', + ); + expect(recorded).toBe(true); + + const status = intel.getPersistenceStatus(); + expect(status.dirty).toBe(false); + expect(status.lastFlushError).toBeNull(); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/memory-search-unified-namespace-errors-4876.test.ts b/v3/@claude-flow/cli/__tests__/memory-search-unified-namespace-errors-4876.test.ts new file mode 100644 index 0000000000..3ae4f8e157 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/memory-search-unified-namespace-errors-4876.test.ts @@ -0,0 +1,134 @@ +// #4876: memory_search_unified (a) reported a timestamp as `searchTime`, +// (b) swallowed per-namespace errors so success:true did not prove coverage, +// and (c) searched namespaces one after another. It now reports elapsed ms, +// returns namespaceErrors with counts, and searches up to 4 namespaces at a +// time while keeping the merged ranking identical to the sequential order. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('fs', () => ({ + existsSync: vi.fn(() => false), mkdirSync: vi.fn(), readdirSync: vi.fn(() => []), + readFileSync: vi.fn(() => '{}'), statSync: 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 })), +})); + +import { memoryTools } from '../src/mcp-tools/memory-tools.js'; + +const tool = memoryTools.find((t) => t.name === 'memory_search_unified')!; + +interface UnifiedResult { + success: boolean; + results: Array<{ key: string; namespace: string; score: number }>; + total: number; + searchTime: string; + namespacesSearched: number; + namespacesFailed: number; + namespaceErrors: Array<{ namespace: string; error: string }>; +} + +type Hit = { key: string; content: string; score: number }; + +// Fixed fixture with ties across namespaces, so ordering depends on the merge +// order and not only on the scores. +const FIXTURE: Record = { + ns1: [{ key: 'a', content: 'a', score: 0.9 }, { key: 'tie', content: 't1', score: 0.5 }], + ns2: [{ key: 'b', content: 'b', score: 0.7 }, { key: 'tie', content: 't2', score: 0.5 }], + ns3: [{ key: 'c', content: 'c', score: 0.9 }], + ns4: [{ key: 'tie', content: 't4', score: 0.5 }, { key: 'd', content: 'd', score: 0.1 }], + ns5: [{ key: 'e', content: 'e', score: 0.7 }], + ns6: [{ key: 'tie', content: 't6', score: 0.5 }], +}; +const NAMESPACES = Object.keys(FIXTURE); + +/** The pre-#4876 sequential algorithm, kept as the ordering baseline. */ +function sequentialBaseline(namespaces: string[], limit: number) { + const all: Array<{ key: string; namespace: string; score: number }> = []; + for (const ns of namespaces) { + for (const e of FIXTURE[ns] ?? []) all.push({ key: e.key, namespace: ns, score: e.score }); + } + all.sort((x, y) => y.score - x.score); + return all.slice(0, limit); +} + +const tick = () => new Promise((r) => setTimeout(r, 0)); + +describe('memory_search_unified namespace fan-out (#4876)', () => { + let inFlight = 0; + let maxInFlight = 0; + + beforeEach(() => { + inFlight = 0; + maxInFlight = 0; + searchEntries.mockReset(); + // Later namespaces finish first, so completion order differs from + // namespace order; the result must still match the sequential baseline. + searchEntries.mockImplementation(async ({ namespace }: { namespace: string }) => { + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + const delay = NAMESPACES.length - NAMESPACES.indexOf(namespace); + for (let i = 0; i < delay; i++) await tick(); + inFlight--; + if (namespace === 'ns3') throw new Error('namespace backend exploded'); + if (namespace === 'ns5') return { success: false, results: [], searchTime: 0, error: 'Database not found' }; + return { + success: true, + results: (FIXTURE[namespace] ?? []).map((e) => ({ ...e, id: e.key, namespace })), + searchTime: 0, + }; + }); + }); + + it('reports failed namespaces and still returns results from the others', async () => { + const r = await tool.handler({ query: 'q', namespaces: NAMESPACES, limit: 20 }) as UnifiedResult; + + expect(r.success).toBe(true); + expect(r.namespacesSearched).toBe(6); + expect(r.namespacesFailed).toBe(2); + expect(r.namespaceErrors).toEqual([ + { namespace: 'ns3', error: 'namespace backend exploded' }, + { namespace: 'ns5', error: 'Database not found' }, + ]); + const namespacesWithResults = new Set(r.results.map((e) => e.namespace)); + expect(namespacesWithResults).toEqual(new Set(['ns1', 'ns2', 'ns4', 'ns6'])); + }); + + it('reports elapsed time in ms, not a timestamp', async () => { + const r = await tool.handler({ query: 'q', namespaces: NAMESPACES }) as UnifiedResult; + expect(r.searchTime).toMatch(/^\d+\.\d{2}ms$/); + expect(parseFloat(r.searchTime)).toBeLessThan(60_000); + }); + + it('keeps the sequential ranking and ordering on a fixed fixture', async () => { + const r = await tool.handler({ query: 'q', namespaces: NAMESPACES, limit: 20 }) as UnifiedResult; + const ok = NAMESPACES.filter((ns) => ns !== 'ns3' && ns !== 'ns5'); + expect(r.results.map((e) => [e.namespace, e.key, e.score])) + .toEqual(sequentialBaseline(ok, 20).map((e) => [e.namespace, e.key, e.score])); + + const top3 = await tool.handler({ query: 'q', namespaces: NAMESPACES, limit: 3 }) as UnifiedResult; + expect(top3.results.map((e) => [e.namespace, e.key])) + .toEqual(sequentialBaseline(ok, 3).map((e) => [e.namespace, e.key])); + }); + + it('runs namespaces concurrently, at most 4 at a time', async () => { + await tool.handler({ query: 'q', namespaces: NAMESPACES }); + expect(searchEntries).toHaveBeenCalledTimes(6); + expect(maxInFlight).toBeGreaterThan(1); + expect(maxInFlight).toBeLessThanOrEqual(4); + }); + + it('fails only when every namespace failed', async () => { + searchEntries.mockImplementation(async () => { throw new Error('store offline'); }); + const r = await tool.handler({ query: 'q', namespaces: ['x', 'y'] }) as UnifiedResult; + expect(r.success).toBe(false); + expect(r.namespacesFailed).toBe(2); + expect(r.namespaceErrors.map((e) => e.namespace)).toEqual(['x', 'y']); + expect(r.results).toEqual([]); + }); +}); 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 af4319035a..6ed7fdd334 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -1506,6 +1506,7 @@ export const memoryTools: MCPTool[] = [ return { success: false, query: input.query, results: [], total: 0, ...missingQuery }; } + const startTime = performance.now(); await ensureInitialized(); const { searchEntries, listEntries } = await getMemoryFunctions(); validateMemoryInput(undefined, undefined, input.query as string); @@ -1552,24 +1553,57 @@ export const memoryTools: MCPTool[] = [ } } - const allResults: Array<{ key: string; content: string; score: number; namespace: string; source: string }> = []; + type UnifiedHit = { key: string; content: string; score: number; namespace: string; source: string }; - for (const searchNs of namespaces) { + // #4876: namespaces are searched concurrently (bounded) instead of one + // after another. Each search is a read of the same store and keeps no + // shared mutable state, so they are independent. Results land in a slot + // per namespace and are flattened in namespace order, so the merge below + // sees exactly the sequence the sequential loop produced. Failures are + // collected instead of swallowed, so success:true no longer hides + // namespaces that were never searched. + const NAMESPACE_CONCURRENCY = 4; + const perNamespace: UnifiedHit[][] = namespaces.map(() => []); + const namespaceErrors: Array<{ namespace: string; error: string }> = []; + const failedAt: Array = namespaces.map(() => undefined); + + const searchOne = async (index: number): Promise => { + const searchNs = namespaces[index]; try { const r = await searchEntries({ query, namespace: searchNs, limit: limit * 2 }); - if (r?.results) { - for (const entry of r.results) { - allResults.push({ - key: entry.key || entry.id || '', - content: (entry.content || (entry as any).value || '').toString().slice(0, 200), - score: entry.score || 0, - namespace: searchNs, - source: searchNs === 'claude-memories' ? 'claude-code' : searchNs === 'auto-memory' ? 'auto-memory' : 'agentdb', - }); - } + if (r && r.success === false && r.error) { + failedAt[index] = String(r.error); + return; } - } catch { /* namespace may not exist */ } - } + for (const entry of r?.results ?? []) { + perNamespace[index].push({ + key: entry.key || entry.id || '', + content: (entry.content || (entry as any).value || '').toString().slice(0, 200), + score: entry.score || 0, + namespace: searchNs, + source: searchNs === 'claude-memories' ? 'claude-code' : searchNs === 'auto-memory' ? 'auto-memory' : 'agentdb', + }); + } + } catch (error) { + failedAt[index] = error instanceof Error ? error.message : String(error); + } + }; + + let nextIndex = 0; + const worker = async (): Promise => { + while (nextIndex < namespaces.length) { + const index = nextIndex++; + await searchOne(index); + } + }; + await Promise.all( + Array.from({ length: Math.min(NAMESPACE_CONCURRENCY, namespaces.length) }, () => worker()), + ); + + failedAt.forEach((error, index) => { + if (error !== undefined) namespaceErrors.push({ namespace: namespaces[index], error }); + }); + const allResults: UnifiedHit[] = perNamespace.flat(); // Sort by score, deduplicate by (namespace, key), take top N. An entry is // identified by both (see #2271), so the same key in another namespace is @@ -1583,14 +1617,23 @@ export const memoryTools: MCPTool[] = [ return true; }).slice(0, limit); + const duration = performance.now() - startTime; + const namespacesFailed = namespaceErrors.length; + return { - success: true, + // Partial coverage still succeeds; only a search where every + // namespace failed is a failure (#4876). + success: namespaces.length === 0 || namespacesFailed < namespaces.length, query, results: deduplicated, total: deduplicated.length, searchedNamespaces: namespaces, namespaceSource, // #2246 — surface how the namespace list was resolved - searchTime: Date.now(), + namespacesSearched: namespaces.length, + namespacesFailed, + namespaceErrors, + // #4876: elapsed time, not a timestamp. + searchTime: `${duration.toFixed(2)}ms`, }; }, }, diff --git a/v3/@claude-flow/cli/src/memory/intelligence.ts b/v3/@claude-flow/cli/src/memory/intelligence.ts index b30d4da8b9..f525bc2b4b 100644 --- a/v3/@claude-flow/cli/src/memory/intelligence.ts +++ b/v3/@claude-flow/cli/src/memory/intelligence.ts @@ -462,6 +462,10 @@ class LocalReasoningBank { private deletedIds: Set = new Set(); /** A local clear() must remove disk entries too. */ private clearRequested: boolean = false; + /** Message of the most recent failed flush; null after a successful one (#4880). */ + private lastFlushError: string | null = null; + /** Time (ms epoch) of the most recent flush attempt that had something to write. */ + private lastFlushAt: number | null = null; constructor(options: { maxSize: number; persistence?: boolean }) { this.maxSize = options.maxSize; @@ -567,9 +571,17 @@ class LocalReasoningBank { * patterns this process changed, so a long-lived daemon cannot erase patterns * written by another hook/process (#4735). Deletions and clear() are carried * as tombstones; the write itself is temp-file + rename. + * + * Returns true when the patterns are on disk (or there was nothing to + * write) and false when the write failed. A failed flush leaves the bank + * dirty so the next flush retries, and records the error for + * getPersistenceStatus() (#4880). Never throws: the debounce timer and exit + * paths rely on that. */ - flushToDisk(): void { - if (!this.persistenceEnabled || !this.dirty) return; + flushToDisk(): boolean { + if (!this.persistenceEnabled || !this.dirty) return true; + + this.lastFlushAt = Date.now(); try { ensureDataDir(); @@ -618,8 +630,20 @@ class LocalReasoningBank { }); } catch (error) { // Log but don't throw - persistence failures shouldn't break training. + this.lastFlushError = error instanceof Error ? error.message : String(error); console.error('Failed to persist patterns:', error); } + // `dirty` is cleared only after the rename succeeded, so any path that did + // not complete the write reads as a failure here. + if (!this.dirty) this.lastFlushError = null; + return !this.dirty; + } + + /** + * Read-only view of the persistence state (#4880). + */ + getFlushState(): { dirty: boolean; lastFlushError: string | null; lastFlushAt: number | null } { + return { dirty: this.dirty, lastFlushError: this.lastFlushError, lastFlushAt: this.lastFlushAt }; } /** @@ -1390,10 +1414,12 @@ export async function recordTrajectory( // #4283: the bank's own save is debounced, and the one-shot bins exit as // soon as the command resolves, so write the patterns now. Otherwise // stats.json counts patterns that never reach patterns.json. - reasoningBank?.flushToDisk(); + // #4880: a failed write (e.g. ENOSPC) returns false instead of claiming + // success for patterns that exist only in memory. + const persisted = reasoningBank ? reasoningBank.flushToDisk() : true; savePersistedStats(); - return true; + return persisted; } catch { return false; } @@ -1702,12 +1728,13 @@ export async function getPatternsByType(type: string): Promise { /** * Flush patterns to disk immediately * Call this at the end of training to ensure all patterns are saved + * + * @returns false when the patterns could not be written (#4880) */ -export function flushPatterns(): void { - if (reasoningBank) { - reasoningBank.flushToDisk(); - } +export function flushPatterns(): boolean { + const persisted = reasoningBank ? reasoningBank.flushToDisk() : true; savePersistedStats(); + return persisted; } /** @@ -1831,10 +1858,19 @@ export function getPersistenceStatus(): { statsFile: string; patternsExist: boolean; statsExist: boolean; + /** Patterns changed in memory that are not on disk yet (#4880). */ + dirty: boolean; + /** Error from the most recent failed pattern flush; null after a success. */ + lastFlushError: string | null; + /** Time (ms epoch) of the most recent pattern flush attempt. */ + lastFlushAt: number | null; } { const dataDir = getDataDir(); const patternsFile = getPatternsPath(); const statsFile = getStatsPath(); + const flush = reasoningBank + ? reasoningBank.getFlushState() + : { dirty: false, lastFlushError: null, lastFlushAt: null }; return { enabled: true, @@ -1842,6 +1878,7 @@ export function getPersistenceStatus(): { patternsFile, statsFile, patternsExist: existsSync(patternsFile), - statsExist: existsSync(statsFile) + statsExist: existsSync(statsFile), + ...flush, }; }