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): memory_export reads the CLI store as well as the AgentDB store (#4148)

rb3d1ec2df471
diff --git a/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts
new file mode 100644
index 0000000000..563af5ab46
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const state = vi.hoisted(() => ({ cliStore: '', stores: {} as Record<string, unknown[] | 'error'> }));
+const entry = (key: string, namespace: string, updatedAt: string, content = key) => ({
+ id: `${namespace}/${key}`, key, namespace, size: content.length, accessCount: 0,
+ createdAt: updatedAt, updatedAt, hasEmbedding: false, content,
+});
+vi.mock('../src/memory/memory-initializer.js', () => ({
+ storeEntry: vi.fn(), searchEntries: vi.fn(), getEntry: vi.fn(), deleteEntry: vi.fn(), initializeMemoryDatabase: vi.fn(),
+ checkMemoryInitialization: vi.fn(async () => ({ initialized: true })),
+ resolveDbPath: () => state.cliStore,
+ listEntries: async (o: { dbPath?: string; namespace?: string; offset?: number }) => {
+ const rows = state.stores[o.dbPath ?? 'default'];
+ if (rows === 'error') return { success: false, entries: [], total: 0, error: 'RFE1 key missing' };
+ const filtered = (rows ?? []).filter((r) => !o.namespace || (r as { namespace: string }).namespace === o.namespace);
+ return { success: true, entries: (o.offset ?? 0) > 0 ? [] : filtered, total: filtered.length };
+ },
+}));
+
+let dir: string;
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ruflo-export-4148-'));
+ state.cliStore = join(dir, 'memory.db');
+ writeFileSync(state.cliStore, 'x'); // the CLI store exists on disk
+ state.stores = {};
+});
+afterEach(() => rmSync(dir, { recursive: true, force: true }));
+
+async function exportTo(input: Record<string, unknown>) {
+ const { memoryTools } = await import('../src/mcp-tools/memory-tools.js');
+ const outputPath = join(dir, 'out.json');
+ const result = await memoryTools.find(t => t.name === 'memory_export')!.handler({ outputPath, ...input }) as Record<string, any>;
+ return { result, rows: result.error ? [] : JSON.parse(readFileSync(outputPath, 'utf8')).entries as Array<{ key: string; namespace: string; value: string }> };
+}
+
+describe('memory_export covers every store the CLI reads (#4148)', () => {
+ it('exports the 591 claude-memories rows that only the CLI store holds (the default reader had 0)', async () => {
+ state.stores.default = [entry('agentdb-only', 'patterns', '2026-10-01')];
+ state.stores[state.cliStore] = Array.from({ length: 591 }, (_, i) => entry(`m${i}`, 'claude-memories', '2026-10-02'));
+ const { result, rows } = await exportTo({ namespace: 'claude-memories' });
+ expect(result.exported.entries).toBe(591);
+ expect(rows).toHaveLength(591);
+ expect(result.stores).toEqual([{ store: 'default', entries: 0 }, { store: state.cliStore, entries: 591 }]);
+ });
+
+ it('merges both stores and keeps the newest copy of a duplicated (namespace, key)', async () => {
+ state.stores.default = [entry('shared', 'notes', '2026-10-01', 'old'), entry('only-a', 'notes', '2026-10-01')];
+ state.stores[state.cliStore] = [entry('shared', 'notes', '2026-10-05', 'new'), entry('only-b', 'notes', '2026-10-01')];
+ const { rows, result } = await exportTo({});
+ expect(rows.map(r => r.key).sort()).toEqual(['only-a', 'only-b', 'shared']);
+ expect(rows.find(r => r.key === 'shared')!.value).toBe('new');
+ expect(result.exported.entries).toBe(3);
+ });
+
+ it('an unreadable CLI store is a warning, not a silent partial success', async () => {
+ state.stores.default = [entry('a', 'notes', '2026-10-01')];
+ state.stores[state.cliStore] = 'error';
+ const { result } = await exportTo({});
+ expect(result.exported.entries).toBe(1);
+ expect(result.warnings?.[0]).toMatch(/Could not read the CLI store .*RFE1 key missing/);
+ });
+
+ it('works unchanged when there is no separate CLI store file', async () => {
+ rmSync(state.cliStore);
+ state.stores.default = [entry('a', 'notes', '2026-10-01')];
+ const { result } = await exportTo({});
+ expect(result.exported.entries).toBe(1);
+ expect(result.stores).toEqual([{ store: 'default', entries: 1 }]);
+ expect(result.warnings).toBeUndefined();
+ });
+});
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..6fef82780a 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -277,6 +277,19 @@ async function getMemoryFunctions() {
};
}
+/**
+ * Path of the CLI's own store (.swarm/memory.db or CLAUDE_FLOW_DB_PATH), or
+ * undefined when the memory module cannot say (#4148). Never throws.
+ */
+async function resolveCliStorePath(): Promise<string | undefined> {
+ try {
+ const mod = await import('../memory/memory-initializer.js');
+ return typeof mod.resolveDbPath === 'function' ? mod.resolveDbPath() : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/**
* #2922: every `backend:` field in this file's tool responses used to be the
* hardcoded literal `'sql.js + HNSW'` regardless of which search path was
@@ -1567,18 +1580,47 @@ export const memoryTools: MCPTool[] = [
// they need it).
// A successful export must cover the whole reported store. Read all
// pages before touching an existing snapshot, including on read failure.
- const entries: Awaited<ReturnType<typeof listEntries>>['entries'] = [];
- let total: number | undefined;
- do {
- const page = await listEntries({ limit: 10000, offset: entries.length, namespace, includeContent: true });
- if (!page.success) return { error: page.error || 'Could not read memory for export' };
- total ??= page.total;
- if (page.entries.length === 0 && entries.length < total) {
- return { error: `Incomplete memory export: read ${entries.length} of ${total} entries` };
+ type ExportEntry = Awaited<ReturnType<typeof listEntries>>['entries'][number];
+ const readStore = async (dbPath?: string): Promise<{ entries: ExportEntry[] } | { error: string }> => {
+ const out: ExportEntry[] = [];
+ let total: number | undefined;
+ do {
+ const page = await listEntries({ limit: 10000, offset: out.length, namespace, includeContent: true, ...(dbPath ? { dbPath } : {}) });
+ if (!page.success) return { error: page.error || 'Could not read memory for export' };
+ total ??= page.total;
+ if (page.entries.length === 0 && out.length < total) {
+ return { error: `Incomplete memory export: read ${out.length} of ${total} entries` };
+ }
+ out.push(...page.entries);
+ } while (out.length < total);
+ return { entries: out };
+ };
+ const primary = await readStore();
+ if ('error' in primary) return { error: primary.error };
+ // #4148: the default reader is the AgentDB bridge, but the CLI's own store
+ // (.swarm/memory.db, possibly encrypted) can hold rows the bridge never
+ // sees, so an export silently covered one store and reported success. Read
+ // the CLI store too and merge, newest copy of a (namespace, key) winning.
+ const warnings: string[] = [];
+ const stores: Array<{ store: string; entries: number }> = [{ store: 'default', entries: primary.entries.length }];
+ const merged = new Map<string, ExportEntry>();
+ const keep = (e: ExportEntry): void => {
+ const id = `${e.namespace}\u0000${e.key}`;
+ const have = merged.get(id);
+ if (!have || String(e.updatedAt) > String(have.updatedAt)) merged.set(id, e);
+ };
+ primary.entries.forEach(keep);
+ const cliStore = await resolveCliStorePath();
+ if (cliStore && existsSync(cliStore)) {
+ const secondary = await readStore(cliStore);
+ if ('error' in secondary) {
+ warnings.push(`Could not read the CLI store ${cliStore} (${secondary.error}); the export covers the AgentDB store only.`);
+ } else {
+ stores.push({ store: cliStore, entries: secondary.entries.length });
+ secondary.entries.forEach(keep);
}
- entries.push(...page.entries);
- } while (entries.length < total);
- const all = { entries };
+ }
+ const all = { entries: [...merged.values()] };
const payload = {
schema: 'ruflo-memory-export/v1',
exportedAt: new Date().toISOString(),
@@ -1601,6 +1643,8 @@ export const memoryTools: MCPTool[] = [
outputPath,
format: (input.format as string) || 'json',
exported: { entries: all.entries.length, vectors: vectorsWithEmb, patterns: 0 },
+ stores,
+ ...(warnings.length ? { warnings } : {}),
fileSize: `${Buffer.byteLength(JSON.stringify(payload))}B`,
note: input.format === 'csv' ? 'CSV not implemented yet — wrote JSON' : undefined,
};