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): import into the CLI-selected database

Rudy Celeklid4c94e344fce
diff --git a/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts
new file mode 100644
index 0000000000..80e1465ff9
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts
@@ -0,0 +1,100 @@
+/** Regression for #3196: CLI import must write to the same resolved store as CLI store. */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const mocks = vi.hoisted(() => ({
+ callMCPTool: vi.fn(),
+ checkMemoryInitialization: vi.fn(),
+ initializeMemoryDatabase: vi.fn(),
+ storeEntry: vi.fn(),
+}));
+
+vi.mock('../src/mcp-client.js', () => ({
+ callMCPTool: mocks.callMCPTool,
+ MCPClientError: class MCPClientError extends Error {},
+}));
+
+vi.mock('../src/memory/memory-initializer.js', () => ({
+ resolveDbPath: (path?: string) => path || '/project/.swarm/memory.db',
+ checkMemoryInitialization: mocks.checkMemoryInitialization,
+ initializeMemoryDatabase: mocks.initializeMemoryDatabase,
+ storeEntry: mocks.storeEntry,
+ searchEntries: vi.fn(),
+ listEntries: vi.fn(),
+ getEntry: vi.fn(),
+ deleteEntry: vi.fn(),
+}));
+
+import { memoryCommand } from '../src/commands/memory.js';
+import { memoryTools } from '../src/mcp-tools/memory-tools.js';
+
+const importCommand = memoryCommand.subcommands!.find(command => command.name === 'import')!;
+const importTool = memoryTools.find(tool => tool.name === 'memory_import')!;
+const tempDir = mkdtempSync(join(tmpdir(), 'ruflo-import-3196-'));
+const importPath = join(tempDir, 'export.json');
+writeFileSync(importPath, JSON.stringify({
+ entries: [{ key: 'remember-me', namespace: 'project', value: 'persisted' }],
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.callMCPTool.mockResolvedValue({
+ inputPath: importPath,
+ imported: { entries: 1, vectors: 0, patterns: 0 },
+ skipped: 0,
+ duration: 1,
+ });
+ mocks.checkMemoryInitialization.mockResolvedValue({ initialized: false });
+ mocks.initializeMemoryDatabase.mockResolvedValue({ success: true });
+ mocks.storeEntry.mockResolvedValue({ success: true, id: 'row-1' });
+});
+
+describe('memory import database selection', () => {
+ afterAll(() => rmSync(tempDir, { recursive: true, force: true }));
+
+ it('exposes --path and sends the resolved path to the MCP import tool', async () => {
+ expect(importCommand.options?.some(option => option.name === 'path')).toBe(true);
+ await importCommand.action!({
+ args: [],
+ flags: { input: importPath, path: '/project/custom.db' },
+ } as any);
+ expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({
+ dbPath: '/project/custom.db',
+ }));
+ });
+
+ it('uses the same default database as CLI store when --path is omitted', async () => {
+ await importCommand.action!({
+ args: [],
+ flags: { input: importPath },
+ } as any);
+ expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({
+ dbPath: '/project/.swarm/memory.db',
+ }));
+ });
+
+ it('initializes and writes the selected file rather than the bridge fallback', async () => {
+ const result = await importTool.handler({
+ inputPath: importPath,
+ dbPath: '/project/custom.db',
+ }) as { imported: { entries: number }; skipped: number };
+ expect(mocks.checkMemoryInitialization).toHaveBeenCalledWith('/project/custom.db');
+ expect(mocks.initializeMemoryDatabase).toHaveBeenCalledWith(expect.objectContaining({ dbPath: '/project/custom.db' }));
+ expect(mocks.storeEntry).toHaveBeenCalledWith(expect.objectContaining({
+ key: 'remember-me', dbPath: '/project/custom.db',
+ }));
+ expect(result.imported.entries).toBe(1);
+ });
+
+ it('does not claim failed bridge writes were imported', async () => {
+ mocks.storeEntry.mockResolvedValue({ success: false, error: 'database unavailable' });
+ const result = await importTool.handler({
+ inputPath: importPath,
+ dbPath: '/project/custom.db',
+ }) as { imported: { entries: number }; skipped: number };
+ expect(result.imported.entries).toBe(0);
+ expect(result.skipped).toBe(1);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts
index ca06bcaeae..1958387606 100644
--- a/v3/@claude-flow/cli/src/commands/memory.ts
+++ b/v3/@claude-flow/cli/src/commands/memory.ts
@@ -1699,7 +1699,8 @@ const importCommand: Command = {
short: 'n',
description: 'Import into specific namespace',
type: 'string'
- }
+ },
+ DB_PATH_OPTION
],
examples: [
{ command: 'claude-flow memory import -i ./backup.json', description: 'Import from file' },
@@ -1729,6 +1730,7 @@ const importCommand: Command = {
inputPath,
merge: ctx.flags.merge ?? true,
namespace: ctx.flags.namespace,
+ dbPath: resolveDbPath(ctx.flags.path as string | undefined),
});
output.printSuccess(`Imported from ${result.inputPath}`);
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 9930cd5305..29ed87214b 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts
@@ -385,40 +385,46 @@ async function readMemoryStatusLabels(): Promise<{
* #1606: Wrapped in try/catch to prevent process-level crashes that kill
* the stdio MCP transport on Windows/Codex.
*/
-async function ensureInitialized(): Promise<void> {
+async function ensureInitialized(dbPath?: string): Promise<void> {
try {
const { initializeMemoryDatabase, checkMemoryInitialization, storeEntry } = await getMemoryFunctions();
// Check if already initialized
- const status = await checkMemoryInitialization();
+ const status = await checkMemoryInitialization(dbPath);
if (!status.initialized) {
- await initializeMemoryDatabase({ force: false, verbose: false });
+ await initializeMemoryDatabase({ force: false, verbose: false, dbPath });
}
// Migrate legacy JSON data if exists (from old .claude-flow/memory/ location)
+ // A custom import target must not consume the one-time migration marker
+ // for the project's normal memory store.
if (hasLegacyStore()) {
- const legacyStore = loadLegacyStore();
- if (legacyStore && Object.keys(legacyStore.entries).length > 0) {
- console.error('[MCP Memory] Migrating legacy JSON store to sql.js...');
- let migrated = 0;
-
- for (const [key, entry] of Object.entries(legacyStore.entries)) {
- try {
- const value = typeof entry.value === 'string' ? entry.value : JSON.stringify(entry.value);
- await storeEntry({
- key,
- value,
- namespace: 'default',
- generateEmbeddingFlag: true,
- });
- migrated++;
- } catch (e) {
- console.error(`[MCP Memory] Failed to migrate key "${key}":`, e);
+ const { resolveDbPath } = await import('../memory/memory-initializer.js');
+ if (!dbPath || dbPath === resolveDbPath()) {
+ const legacyStore = loadLegacyStore();
+ if (legacyStore && Object.keys(legacyStore.entries).length > 0) {
+ console.error('[MCP Memory] Migrating legacy JSON store to sql.js...');
+ let migrated = 0;
+
+ for (const [key, entry] of Object.entries(legacyStore.entries)) {
+ try {
+ const value = typeof entry.value === 'string' ? entry.value : JSON.stringify(entry.value);
+ await storeEntry({
+ key,
+ value,
+ namespace: 'default',
+ generateEmbeddingFlag: true,
+ dbPath,
+ });
+ migrated++;
+ } catch (e) {
+ console.error(`[MCP Memory] Failed to migrate key "${key}":`, e);
+ }
}
- }
- console.error(`[MCP Memory] Migrated ${migrated}/${Object.keys(legacyStore.entries).length} entries`);
- markMigrationComplete();
+ console.error(`[MCP Memory] Migrated ${migrated}/${Object.keys(legacyStore.entries).length} entries`);
+ markMigrationComplete();
+ }
}
}
} catch (error) {
@@ -1547,11 +1553,15 @@ export const memoryTools: MCPTool[] = [
inputPath: { type: 'string', description: 'Path to the JSON export file' },
merge: { type: 'boolean', description: 'Merge into existing entries (upsert) vs. fail on conflict (default true)' },
namespace: { type: 'string', description: 'Override the namespace for all imported entries' },
+ dbPath: { type: 'string', description: 'Database file to import into (defaults to the MCP memory store)' },
},
required: ['inputPath'],
},
handler: async (input) => {
- await ensureInitialized();
+ const dbPath = typeof input.dbPath === 'string' && input.dbPath.trim()
+ ? resolve(input.dbPath)
+ : undefined;
+ await ensureInitialized(dbPath);
const { storeEntry } = await getMemoryFunctions();
const t0 = Date.now();
const inputPath = String(input.inputPath ?? '');
@@ -1567,8 +1577,9 @@ export const memoryTools: MCPTool[] = [
if (!e || typeof e.key !== 'string') { skipped++; continue; }
const value = typeof e.value === 'string' ? e.value : JSON.stringify(e.value ?? null);
try {
- await storeEntry({ key: e.key, value, namespace: nsOverride ?? e.namespace ?? 'default', upsert: input.merge !== false });
- imported++;
+ const result = await storeEntry({ key: e.key, value, namespace: nsOverride ?? e.namespace ?? 'default', upsert: input.merge !== false, dbPath });
+ if (result.success) imported++;
+ else skipped++;
} catch { skipped++; }
}
return {