diff --git a/v3/@claude-flow/cli/__tests__/intelligence-patterns-merge-4735.test.ts b/v3/@claude-flow/cli/__tests__/intelligence-patterns-merge-4735.test.ts new file mode 100644 index 0000000000..96399298c1 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/intelligence-patterns-merge-4735.test.ts @@ -0,0 +1,109 @@ +/** + * #4735: LocalReasoningBank.flushToDisk() wrote its whole in-memory list, + * erasing patterns added by another process. A corrupt patterns.json was also + * ignored and then overwritten. Flushes now merge under the cooperating-writer + * lock, carry tombstones, and quarantine corrupt files. + */ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; + +const scratch = mkdtempSync(join(tmpdir(), 'patterns-merge-4735-')); +const patternsPath = join(scratch, '.claude-flow', 'neural', 'patterns.json'); +let originalCwd: string; + +function pattern(id: string, content: string) { + const now = Date.now(); + return { + id, + type: 'test', + embedding: [0.1, 0.2, 0.3], + content, + confidence: 0.8, + usageCount: 0, + createdAt: now, + lastUsedAt: now, + }; +} + +beforeAll(() => { + originalCwd = process.cwd(); + process.chdir(scratch); + mkdirSync(join(scratch, '.claude-flow'), { recursive: true }); +}); + +afterAll(() => { + process.chdir(originalCwd); + rmSync(scratch, { recursive: true, force: true }); +}); + +beforeEach(async () => { + const intel = await import('../src/memory/intelligence.js'); + intel.clearIntelligence(); + rmSync(patternsPath, { force: true }); + rmSync(dirname(patternsPath), { recursive: true, force: true }); + await intel.initializeIntelligence(); +}); + +describe('LocalReasoningBank cross-process pattern persistence (#4735)', () => { + it('keeps a pattern written by another process during flush', async () => { + const intel = await import('../src/memory/intelligence.js'); + const bank = intel.getReasoningBank()!; + + bank.store({ ...pattern('local-a', 'local pattern A') }); + mkdirSync(dirname(patternsPath), { recursive: true }); + writeFileSync(patternsPath, JSON.stringify([pattern('external-b', 'external pattern B')])); + + bank.flushToDisk(); + + const ids = JSON.parse(readFileSync(patternsPath, 'utf-8')).map((p: { id: string }) => p.id); + expect(ids).toContain('local-a'); + expect(ids).toContain('external-b'); + }); + + it('does not resurrect a locally deleted pattern from disk', async () => { + const intel = await import('../src/memory/intelligence.js'); + const bank = intel.getReasoningBank()!; + + bank.store({ ...pattern('local-a', 'local pattern A') }); + bank.flushToDisk(); + + mkdirSync(dirname(patternsPath), { recursive: true }); + writeFileSync(patternsPath, JSON.stringify([ + pattern('local-a', 'local pattern A'), + pattern('external-b', 'external pattern B'), + ])); + + bank.delete('local-a'); + bank.flushToDisk(); + + const ids = JSON.parse(readFileSync(patternsPath, 'utf-8')).map((p: { id: string }) => p.id); + expect(ids).toEqual(['external-b']); + }); + + it('preserves a corrupt patterns file instead of overwriting it', async () => { + const intel = await import('../src/memory/intelligence.js'); + mkdirSync(dirname(patternsPath), { recursive: true }); + writeFileSync(patternsPath, '{broken'); + + intel.clearIntelligence(); + await intel.initializeIntelligence(); + const freshBank = intel.getReasoningBank()!; + freshBank.store({ ...pattern('after-corrupt', 'new pattern') }); + freshBank.flushToDisk(); + + const corruptFiles = readdirSync(dirname(patternsPath)).filter(name => name.includes('.corrupt-')); + expect(corruptFiles.length).toBeGreaterThan(0); + expect(readFileSync(join(dirname(patternsPath), corruptFiles[0]), 'utf-8')).toBe('{broken'); + expect(JSON.parse(readFileSync(patternsPath, 'utf-8')).map((p: { id: string }) => p.id)) + .toContain('after-corrupt'); + }); +}); diff --git a/v3/@claude-flow/cli/src/memory/intelligence.ts b/v3/@claude-flow/cli/src/memory/intelligence.ts index 28f99d88f1..b30d4da8b9 100644 --- a/v3/@claude-flow/cli/src/memory/intelligence.ts +++ b/v3/@claude-flow/cli/src/memory/intelligence.ts @@ -456,6 +456,12 @@ class LocalReasoningBank { private persistenceEnabled: boolean; private dirty: boolean = false; private saveTimeout: ReturnType | null = null; + /** IDs changed locally since the last successful flush. */ + private dirtyIds: Set = new Set(); + /** IDs deleted locally; a disk copy must not be resurrected. */ + private deletedIds: Set = new Set(); + /** A local clear() must remove disk entries too. */ + private clearRequested: boolean = false; constructor(options: { maxSize: number; persistence?: boolean }) { this.maxSize = options.maxSize; @@ -482,6 +488,7 @@ class LocalReasoningBank { // Group by content to deduplicate const byContent = new Map(); + const removedIds: string[] = []; for (const pattern of data) { const key = pattern.content; const existing = byContent.get(key); @@ -496,9 +503,11 @@ class LocalReasoningBank { ) { // Merge: adopt the higher usageCount sum pattern.usageCount = (pattern.usageCount ?? 0) + (existing.usageCount ?? 0); + removedIds.push(existing.id); byContent.set(key, pattern); } else { existing.usageCount = (existing.usageCount ?? 0) + (pattern.usageCount ?? 0); + removedIds.push(pattern.id); } } } @@ -512,14 +521,24 @@ class LocalReasoningBank { const removed = totalLoaded - byContent.size; if (removed > 0) { console.log(`Deduplicated ${removed} patterns (${byContent.size} unique)`); - // Persist the compacted set immediately so the file shrinks on disk + // Persist the compacted set immediately so the file shrinks on disk. + // Mark every kept row dirty so this compaction wins over the disk + // copies, and tombstone the discarded duplicates. + for (const pattern of byContent.values()) this.dirtyIds.add(pattern.id); + for (const id of removedIds) this.deletedIds.add(id); this.dirty = true; this.flushToDisk(); } } } - } catch { - // Ignore load errors, start fresh + } catch (error) { + // A corrupt patterns file must be preserved, not silently replaced by + // an empty bank on the next flush (#4735). + try { + const corruptPath = `${getPatternsPath()}.corrupt-${Date.now()}`; + renameSync(getPatternsPath(), corruptPath); + console.warn(`[intelligence] Corrupt patterns file moved to ${corruptPath}`); + } catch { /* already absent or rename failed — never overwrite it below */ } } } @@ -543,6 +562,11 @@ class LocalReasoningBank { /** * Immediately flush patterns to disk + * + * Re-reads the file under the cooperating-writer lock and merges only the + * 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. */ flushToDisk(): void { if (!this.persistenceEnabled || !this.dirty) return; @@ -550,10 +574,50 @@ class LocalReasoningBank { try { ensureDataDir(); const path = getPatternsPath(); - writeFileSync(path, JSON.stringify(this.patternList, null, 2), 'utf-8'); - this.dirty = false; + withStatsFileLock(path, (canonicalPath) => { + let diskPatterns: StoredPattern[] = []; + if (existsSync(canonicalPath)) { + try { + const parsed = JSON.parse(readFileSync(canonicalPath, 'utf-8')); + if (!Array.isArray(parsed)) throw new Error('patterns.json is not an array'); + diskPatterns = parsed as StoredPattern[]; + } catch { + // Preserve the corrupt original instead of overwriting it with an + // empty bank; the new file is written only after this rename. + try { + const corruptPath = `${canonicalPath}.corrupt-${Date.now()}`; + renameSync(canonicalPath, corruptPath); + console.warn(`[intelligence] Corrupt patterns file moved to ${corruptPath}`); + } catch { /* leave the original in place */ } + } + } + + const merged = new Map(); + if (!this.clearRequested) { + for (const pattern of diskPatterns) { + if (!this.deletedIds.has(pattern.id)) merged.set(pattern.id, pattern); + } + } + for (const pattern of this.patternList) { + if (this.clearRequested || this.dirtyIds.has(pattern.id)) { + merged.set(pattern.id, pattern); + } + } + + const list = [...merged.values()]; + const tmp = `${canonicalPath}.${process.pid}.${Date.now()}.tmp`; + writeFileSync(tmp, JSON.stringify(list, null, 2), 'utf-8'); + renameSync(tmp, canonicalPath); + + this.patterns = new Map(list.map((pattern) => [pattern.id, pattern])); + this.patternList = list; + this.dirty = false; + this.dirtyIds.clear(); + this.deletedIds.clear(); + this.clearRequested = false; + }); } catch (error) { - // Log but don't throw - persistence failures shouldn't break training + // Log but don't throw - persistence failures shouldn't break training. console.error('Failed to persist patterns:', error); } } @@ -589,6 +653,7 @@ class LocalReasoningBank { this.patternList[idx] = stored; } this.patterns.set(pattern.id, stored); + this.dirtyIds.add(pattern.id); this.saveToDisk(); return false; } else { @@ -603,6 +668,7 @@ class LocalReasoningBank { } // Keep the Map in sync with the mutated object this.patterns.set(contentDupe.id, contentDupe); + this.dirtyIds.add(contentDupe.id); this.saveToDisk(); return false; } @@ -612,12 +678,15 @@ class LocalReasoningBank { const oldest = this.patternList.shift(); if (oldest) { this.patterns.delete(oldest.id); + this.deletedIds.add(oldest.id); + this.dirtyIds.delete(oldest.id); } } this.patternList.push(stored); } this.patterns.set(pattern.id, stored); + this.dirtyIds.add(stored.id); // Trigger persistence (debounced) this.saveToDisk(); @@ -730,6 +799,8 @@ class LocalReasoningBank { if (idx >= 0) { this.patternList.splice(idx, 1); } + this.dirtyIds.delete(id); + this.deletedIds.add(id); this.saveToDisk(); return true; @@ -741,6 +812,9 @@ class LocalReasoningBank { clear(): void { this.patterns.clear(); this.patternList = []; + this.dirtyIds.clear(); + this.deletedIds.clear(); + this.clearRequested = true; this.saveToDisk(); } }