🌊 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): let export target an explicit store (#4341)
ordinary being22d0f16db1ea
diff --git a/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.tsnew file mode 100644index 0000000000..daeda676da--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts@@ -0,0 +1,98 @@+/**+ * #3196 (export half): `memory export` had no `--path` and+ * `memory_export` had no `dbPath` input. An explicit snapshot could not be+ * exported, and the handler always opened the default store(s), so exporting+ * a sibling/backup DB was impossible from the CLI.+ *+ * The handler test uses a sql.js fixture (no native module) and an explicit+ * dbPath; it must not initialize or touch the default store.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { memoryTools } from '../src/mcp-tools/memory-tools.js';+import { MEMORY_SCHEMA_V3 } from '../src/memory/memory-initializer.js';+import { memoryCommand } from '../src/commands/memory.js';++const exportTool = memoryTools.find(t => t.name === 'memory_export')!;+const exportCommand = memoryCommand.subcommands!.find(c => c.name === 'export')!;++let Database: any;++async function seed(dbPath: string, keys: string[]): Promise<void> {+ const initSqlJs = (await import('sql.js')).default;+ const SQL = await initSqlJs();+ const db = new SQL.Database();+ try {+ db.run(MEMORY_SCHEMA_V3);+ const now = Date.now();+ for (const [i, key] of keys.entries()) {+ db.run(+ `INSERT INTO memory_entries+ (id, key, namespace, content, access_count, created_at, updated_at, status)+ VALUES (?, ?, 'snapshot', ?, 0, ?, ?, 'active')`,+ [`id-${i}`, key, `value for ${key}`, now, now],+ );+ }+ db.run('PRAGMA wal_checkpoint');+ const bytes = db.export();+ const { writeFileSync } = await import('node:fs');+ writeFileSync(dbPath, Buffer.from(bytes));+ } finally {+ db.close();+ }+}++describe('memory export explicit dbPath (#3196)', () => {+ let dir: string;+ let prevMemoryPath: string | undefined;+ let prevBridge: string | undefined;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'memory-export-path-'));+ prevMemoryPath = process.env.CLAUDE_FLOW_MEMORY_PATH;+ prevBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE;+ process.env.CLAUDE_FLOW_MEMORY_PATH = join(dir, 'default-memory-root');+ process.env.CLAUDE_FLOW_DISABLE_BRIDGE = '1';+ vi.resetModules();+ });++ afterEach(() => {+ if (prevMemoryPath === undefined) delete process.env.CLAUDE_FLOW_MEMORY_PATH;+ else process.env.CLAUDE_FLOW_MEMORY_PATH = prevMemoryPath;+ if (prevBridge === undefined) delete process.env.CLAUDE_FLOW_DISABLE_BRIDGE;+ else process.env.CLAUDE_FLOW_DISABLE_BRIDGE = prevBridge;+ rmSync(dir, { recursive: true, force: true });+ });++ it('advertises --path on the CLI and dbPath on the MCP tool', () => {+ expect(exportCommand.options?.some(o => o.name === 'path')).toBe(true);+ expect(exportTool.inputSchema.properties).toHaveProperty('dbPath');+ });++ it('exports exactly the explicit file and does not initialize the default store', async () => {+ const dbPath = join(dir, 'snapshot.db');+ const outputPath = join(dir, 'export.json');+ await seed(dbPath, ['alpha', 'beta']);++ const result = await exportTool.handler({ outputPath, dbPath, format: 'json' }) as Record<string, any>;++ expect(result.error).toBeUndefined();+ expect(result.exported.entries).toBe(2);+ expect(result.stores).toEqual([{ store: dbPath, entries: 2 }]);+ const payload = JSON.parse(readFileSync(outputPath, 'utf8'));+ expect(payload.schema).toBe('ruflo-memory-export/v1.1');+ expect(payload.entries.map((e: { key: string }) => e.key).sort()).toEqual(['alpha', 'beta']);+ expect(existsSync(join(dir, 'default-memory-root', 'memory.db'))).toBe(false);+ });++ it('returns a clear error when the explicit file is missing', async () => {+ const result = await exportTool.handler({+ outputPath: join(dir, 'missing.json'),+ dbPath: join(dir, 'does-not-exist.db'),+ }) as Record<string, any>;+ expect(result.error).toMatch(/Database not found|not found/i);+ });+});diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.tsindex 1e02c488a9..de02eb7c4f 100644--- a/v3/@claude-flow/cli/src/commands/memory.ts+++ b/v3/@claude-flow/cli/src/commands/memory.ts@@ -1790,10 +1790,12 @@ const exportCommand: Command = {description: 'Include vector embeddings',type: 'boolean',default: true- }+ },+ DB_PATH_OPTION],examples: [{ command: 'claude-flow memory export -o ./backup.json', description: 'Export all to JSON' },+ { command: 'claude-flow memory export -o ./agentdb.json --path .swarm/agentdb-memory.db', description: 'Export one specific store' },{ command: 'claude-flow memory export -o ./data.csv -f csv', description: 'Export to CSV' }],action: async (ctx: CommandContext): Promise<CommandResult> => {@@ -1822,6 +1824,7 @@ const exportCommand: Command = {format,namespace: ctx.flags.namespace,includeVectors: ctx.flags.includeVectors ?? true,+ dbPath: resolveDbPath(ctx.flags.path as string | undefined),});// memory_export reports failure as { error } rather than throwing; withoutdiff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.tsindex a599bb3c56..ff5307b1d9 100644--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts@@ -1657,13 +1657,19 @@ export const memoryTools: MCPTool[] = [properties: {outputPath: { type: 'string', description: 'File path to write the JSON export to' },format: { type: 'string', enum: ['json', 'csv'], description: 'Export format (csv falls back to json today)' },+ dbPath: { type: 'string', description: 'Explicit memory DB to export (default: the AgentDB store plus the CLI sibling)' },namespace: { type: 'string', description: 'Limit export to one namespace' },includeVectors: { type: 'boolean', description: 'Include embedding vectors (advisory — not exported yet)' },},required: ['outputPath'],},handler: async (input) => {- await ensureInitialized();+ const requestedDbPath = typeof input.dbPath === 'string' && input.dbPath.trim()+ ? resolve(input.dbPath)+ : undefined;+ // An explicit file selection is a single-store read. Do not initialize or+ // migrate the unrelated default store just to export a snapshot.+ if (!requestedDbPath) await ensureInitialized();const { listEntries } = await getMemoryFunctions();const outputPath = String(input.outputPath ?? '');if (!outputPath) return { error: 'outputPath is required' };@@ -1690,14 +1696,16 @@ export const memoryTools: MCPTool[] = [} while (out.length < total);return { entries: out };};- const primary = await readStore();+ const primary = await readStore(requestedDbPath);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 stores: Array<{ store: string; entries: number }> = [+ { store: requestedDbPath ?? 'default', entries: primary.entries.length },+ ];const merged = new Map<string, ExportEntry>();const keep = (e: ExportEntry): void => {const id = `${e.namespace}\u0000${e.key}`;@@ -1705,14 +1713,18 @@ export const memoryTools: MCPTool[] = [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);+ // The implicit default export still merges the sibling CLI store; an+ // explicit dbPath must cover exactly that file.+ if (!requestedDbPath) {+ 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);+ }}}const all = { entries: [...merged.values()] };