🌊 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(session): import round-trips and save actually includes memory (#3573, #3575)
ruv18d6a7b70c44
diff --git a/v3/@claude-flow/cli/__tests__/session-export-memory-exclusion.test.ts b/v3/@claude-flow/cli/__tests__/session-export-memory-exclusion.test.tsindex 5cded6a3c4..296e70ed0a 100644--- a/v3/@claude-flow/cli/__tests__/session-export-memory-exclusion.test.ts+++ b/v3/@claude-flow/cli/__tests__/session-export-memory-exclusion.test.ts@@ -5,15 +5,21 @@ import { join } from 'node:path';const state = vi.hoisted(() => ({ cwd: '' }));vi.mock('../src/mcp-tools/types.js', () => ({ getProjectCwd: () => state.cwd }));import { sessionTools } from '../src/mcp-tools/session-tools.js';+import { _resetMemoryRootCache } from '../src/memory/memory-initializer.js';const call = (name: string, input: any):Promise<any> => sessionTools.find(t=>t.name===name)!.handler(input) as Promise<any>;beforeEach(() => {state.cwd=mkdtempSync(join(tmpdir(),'ruflo-export-'));+ // #3573: session_save now also captures the live memory DB; point it at an+ // empty root so only the legacy store.json below is in scope.+ vi.stubEnv('CLAUDE_FLOW_MEMORY_PATH', join(state.cwd, '.swarm'));+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', '');+ _resetMemoryRootCache();for(const kind of ['tasks','agents','memory']) {mkdirSync(join(state.cwd,'.claude-flow',kind),{recursive:true});writeFileSync(join(state.cwd,'.claude-flow',kind,'store.json'),JSON.stringify({[kind==='memory'?'entries':kind]: { saved: {value:kind==='memory'?'private-memory':'kept'} }}));}});-afterEach(()=>rmSync(state.cwd,{recursive:true,force:true}));+afterEach(()=>{vi.unstubAllEnvs();_resetMemoryRootCache();rmSync(state.cwd,{recursive:true,force:true});});it('excludes memory from returned and written exports while preserving the saved session',async()=>{const saved=await call('session_save',{name:'checkpoint',includeMemory:true,includeTasks:true,includeAgents:true});const outputPath=join(state.cwd,'export.json');diff --git a/v3/@claude-flow/cli/__tests__/session-import-and-memory-3573-3575.test.ts b/v3/@claude-flow/cli/__tests__/session-import-and-memory-3573-3575.test.tsnew file mode 100644index 0000000000..2d0de63048--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/session-import-and-memory-3573-3575.test.ts@@ -0,0 +1,187 @@+/**+ * #3575: `session import` could never succeed — the CLI passed a parsed `data`+ * object to session_import, which required `inputPath`, then printed+ * "Session imported" and crashed reading the error result.+ *+ * #3573: `session save --include-memory` defaulted to true but captured nothing,+ * because it read only the pre-SQLite `.claude-flow/memory/store.json`.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const state = vi.hoisted(() => ({ cwd: '' }));+vi.mock('../src/mcp-tools/types.js', () => ({ getProjectCwd: () => state.cwd }));+// Route CLI calls straight to the real session tool handlers (no policy layer).+vi.mock('../src/mcp-client.js', async () => {+ const { sessionTools } = await import('../src/mcp-tools/session-tools.js');+ class MCPClientError extends Error {}+ return {+ MCPClientError,+ callMCPTool: async (name: string, input: Record<string, unknown>) =>+ sessionTools.find(t => t.name === name)!.handler(input),+ };+});++import { output } from '../src/output.js';+import { sessionCommand } from '../src/commands/session.js';+import { sessionTools } from '../src/mcp-tools/session-tools.js';+import {+ _resetMemoryRootCache, initializeMemoryDatabase, storeEntry, listEntries, purgeNamespace,+} from '../src/memory/memory-initializer.js';++const tool = (name: string, input: Record<string, unknown>): Promise<any> =>+ sessionTools.find(t => t.name === name)!.handler(input) as Promise<any>;+const sub = (name: string) => sessionCommand.subcommands!.find(c => c.name === name)!;+const run = (name: string, args: string[], flags: Record<string, unknown> = {}) =>+ sub(name).action!({ args, flags, cwd: state.cwd, interactive: false } as never) as Promise<any>;++let spinner: { succeed: ReturnType<typeof vi.fn>; fail: ReturnType<typeof vi.fn> };+let printed: { success: string[]; error: string[]; tables: any[] };++beforeEach(() => {+ state.cwd = mkdtempSync(join(tmpdir(), 'ruflo-session-3575-'));+ const memDir = join(state.cwd, '.swarm');+ mkdirSync(memDir, { recursive: true });+ vi.stubEnv('CLAUDE_FLOW_MEMORY_PATH', memDir);+ vi.stubEnv('CLAUDE_FLOW_DB_PATH', '');+ vi.stubEnv('CLAUDE_FLOW_DISABLE_BRIDGE', '1');+ vi.stubEnv('CLAUDE_FLOW_ENCRYPT_AT_REST', '0');+ _resetMemoryRootCache();+ mkdirSync(join(state.cwd, '.claude-flow', 'agents'), { recursive: true });+ writeFileSync(join(state.cwd, '.claude-flow', 'agents', 'store.json'),+ JSON.stringify({ agents: { a1: { agentId: 'a1' }, a2: { agentId: 'a2' } } }));++ spinner = { succeed: vi.fn(), fail: vi.fn() };+ printed = { success: [], error: [], tables: [] };+ vi.spyOn(output, 'createSpinner').mockReturnValue({ start: vi.fn(), stop: vi.fn(), ...spinner } as never);+ vi.spyOn(output, 'printSuccess').mockImplementation((m: string) => { printed.success.push(m); });+ vi.spyOn(output, 'printError').mockImplementation((m: string) => { printed.error.push(m); });+ vi.spyOn(output, 'printTable').mockImplementation((t: any) => { printed.tables.push(t); });+ for (const quiet of ['writeln', 'printInfo', 'printWarning', 'printJson'] as const) {+ vi.spyOn(output, quiet).mockImplementation(() => undefined as never);+ }+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ _resetMemoryRootCache();+ rmSync(state.cwd, { recursive: true, force: true });+});++describe('#3575 session import', () => {+ it('round-trips export -> import and the imported session is listed', async () => {+ const saved = await tool('session_save', { name: 'checkpoint', includeAgents: true });+ const file = join(state.cwd, 'backup.json');++ const exported = await run('export', [saved.sessionId], { output: file, format: 'json' });+ expect(exported.success).toBe(true);+ expect(existsSync(file)).toBe(true);++ const imported = await run('import', [file], { name: 'restored-copy' });+ expect(imported.success).toBe(true);+ expect(imported.data.stats.agentsImported).toBe(2);+ expect(spinner.succeed).toHaveBeenCalledWith('Session imported');++ const listed = await tool('session_list', { limit: 50 });+ expect(listed.sessions.map((s: any) => s.name)).toContain('restored-copy');+ });++ it('fails cleanly on a missing file: non-zero exit, no success line', async () => {+ const result = await run('import', [join(state.cwd, 'nope.json')]);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(printed.success).toEqual([]);+ });++ it('fails cleanly on a file that is not a session: no "Session imported", no TypeError', async () => {+ const file = join(state.cwd, 'not-a-session.json');+ writeFileSync(file, JSON.stringify(['not', 'a', 'session']));+ const result = await run('import', [file]);+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ expect(spinner.succeed).not.toHaveBeenCalled();+ expect(printed.success).toEqual([]);+ expect(printed.error.join('\n')).not.toMatch(/TypeError/);+ expect(printed.error.join('\n')).toMatch(/Not a session record/);+ });++ it('session_import accepts the record inline as data, not only as a path', async () => {+ const saved = await tool('session_save', { name: 'inline-src', includeAgents: true });+ const record = (await tool('session_export', { sessionId: saved.sessionId })).data;+ const result = await tool('session_import', { data: record, name: 'inline-copy' });+ expect(result.error).toBeUndefined();+ expect(result.stats.agentsImported).toBe(2);+ });++ it('export with no session id refuses (like delete) unless --latest is given', async () => {+ await tool('session_save', { name: 'only-one', includeAgents: true });+ const refused = await run('export', [], { output: join(state.cwd, 'x.json'), format: 'json' });+ expect(refused).toMatchObject({ success: false, exitCode: 1 });+ expect(existsSync(join(state.cwd, 'x.json'))).toBe(false);++ const latest = await run('export', [], { latest: true, output: join(state.cwd, 'y.json'), format: 'json' });+ expect(latest.success).toBe(true);+ expect(existsSync(join(state.cwd, 'y.json'))).toBe(true);+ });+});++describe('#3573 session save includes memory', () => {+ const primary = () => join(state.cwd, '.swarm', 'memory.db');+ const mirror = () => join(state.cwd, '.swarm', 'agentdb-memory.db');+ const all = async (dbPath: string) =>+ (await listEntries({ dbPath, limit: 100, includeContent: true })).entries+ .map(e => `${e.namespace}/${e.key}=${e.content}`).sort();++ beforeEach(async () => {+ expect((await initializeMemoryDatabase({ dbPath: primary(), force: true, migrate: false })).success).toBe(true);+ for (let i = 1; i <= 6; i++) {+ const r = await storeEntry({+ dbPath: primary(), namespace: i <= 3 ? 'alpha' : 'beta', key: `k${i}`, value: `value-${i}`,+ generateEmbeddingFlag: false,+ });+ expect(r.success).toBe(true);+ }+ });++ it('6 entries -> save -> file holds 6 -> wipe -> restore --memory-only -> 6 are back', async () => {+ const before = await all(primary());+ expect(before).toHaveLength(6);++ const saved = await tool('session_save', { name: 'with-memory', includeMemory: true, includeAgents: true });+ expect(saved.stats.memoryEntries).toBe(6);+ expect(saved.memoryCapture).toMatchObject({ requested: true, status: 'captured', entries: 6 });++ const onDisk = JSON.parse(readFileSync(saved.path, 'utf-8'));+ expect(Object.keys(onDisk.data.memory.entries)).toHaveLength(6);+ expect(onDisk.stats.memoryEntries).toBe(6);++ for (const ns of ['alpha', 'beta']) await purgeNamespace({ dbPath: primary(), namespace: ns });+ expect(await all(primary())).toHaveLength(0);++ // `session restore --memory-only`, through the CLI.+ const restored = await run('restore', [saved.sessionId], { 'memory-only': true, force: true });+ expect(restored.success).toBe(true);+ expect(restored.data.memoryRestore).toMatchObject({ restored: 6, failed: 0 });+ expect(await all(primary())).toEqual(before);+ });++ it('captures rows that exist only in the sibling AgentDB store, without duplicating mirrored ones', async () => {+ expect((await initializeMemoryDatabase({ dbPath: mirror(), force: true, migrate: false })).success).toBe(true);+ // One row mirrored in both stores, one written only by the MCP/AgentDB path.+ await storeEntry({ dbPath: mirror(), namespace: 'alpha', key: 'k1', value: 'value-1', generateEmbeddingFlag: false });+ await storeEntry({ dbPath: mirror(), namespace: 'mcp', key: 'agent-note', value: 'from-mcp', generateEmbeddingFlag: false });++ const saved = await tool('session_save', { name: 'both-stores', includeMemory: true });+ expect(saved.memoryCapture).toMatchObject({ entries: 7, sources: { memoryDb: 6, agentdb: 1 } });+ const entries = JSON.parse(readFileSync(saved.path, 'utf-8')).data.memory.entries;+ expect(entries['mcp::agent-note']).toMatchObject({ value: 'from-mcp', source: 'agentdb' });+ });++ it('the save table says "not included" instead of an invented 0 when memory is excluded', async () => {+ const result = await run('save', [], { name: 'no-mem', 'include-memory': false });+ expect(result.success).toBe(true);+ const row = printed.tables[0].data.find((r: any) => r.property === 'Memory Entries');+ expect(row.value).toBe('not included');+ });+});diff --git a/v3/@claude-flow/cli/src/commands/session.ts b/v3/@claude-flow/cli/src/commands/session.tsindex e88b70a42a..e54d291975 100644--- a/v3/@claude-flow/cli/src/commands/session.ts+++ b/v3/@claude-flow/cli/src/commands/session.ts@@ -33,6 +33,35 @@ function formatDate(dateStr: string): string {return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();}+/**+ * #3575: the session MCP tools report failure as `{ error }` (or+ * `success: false`) rather than throwing, so every call site must check before+ * printing a success line or reading result fields.+ */+function toolError(result: unknown): string | null {+ if (!result || typeof result !== 'object') return 'the tool returned no result';+ const r = result as { error?: unknown; success?: unknown };+ if (typeof r.error === 'string' && r.error.length > 0) return r.error;+ if (r.success === false) return 'the operation failed';+ return null;+}++interface MemoryCaptureSummary {+ requested: boolean;+ status: 'not-requested' | 'captured' | 'no-store' | 'error';+ entries: number;+ error?: string;+}++/** #3573: say what happened to memory instead of printing an invented 0. */+function memoryCaptureLabel(capture: MemoryCaptureSummary | undefined, fallback: number | undefined): string | number {+ if (!capture) return fallback ?? 'unknown';+ if (!capture.requested) return 'not included';+ if (capture.status === 'error') return `not captured (${capture.error || 'error'})`;+ if (capture.status === 'no-store') return '0 (no memory store found)';+ return capture.entries;+}+// Format session statusfunction formatStatus(status: string): string {switch (status) {@@ -229,6 +258,7 @@ const saveCommand: Command = {memoryEntries?: number;totalSize?: number;};+ memoryCapture?: MemoryCaptureSummary;}>('session_save', {name: sessionName,description,@@ -237,6 +267,13 @@ const saveCommand: Command = {includeTasks: ctx.flags['include-tasks'] !== false});+ const failure = toolError(result);+ if (failure) {+ spinner.fail('Failed to save session');+ output.printError(failure);+ return { success: false, exitCode: 1 };+ }+spinner.succeed('Session saved');output.writeln();@@ -253,11 +290,15 @@ const saveCommand: Command = {{ property: 'Saved At', value: new Date(result.savedAt).toLocaleString() },{ property: 'Agents', value: stats.agentCount ?? stats.agents ?? 0 },{ property: 'Tasks', value: stats.taskCount ?? stats.tasks ?? 0 },- { property: 'Memory Entries', value: stats.memoryEntries ?? 0 },+ { property: 'Memory Entries', value: memoryCaptureLabel(result.memoryCapture, stats.memoryEntries) },{ property: 'Total Size', value: formatSize(stats.totalSize ?? 0) }]});+ if (result.memoryCapture?.status === 'error') {+ output.printWarning(`Memory was requested but could not be captured: ${result.memoryCapture.error}`);+ }+output.writeln();output.printSuccess(`Session saved: ${result.sessionId}`);output.printInfo(`Restore with: claude-flow session restore ${result.sessionId}`);@@ -384,7 +425,9 @@ const restoreCommand: Command = {agents: number;tasks: number;memoryEntries: number;+ memoryEntriesRestored?: number;};+ memoryRestore?: { restored: number; failed: number; errors: string[] };}>('session_restore', {sessionId,restoreMemory,@@ -392,9 +435,27 @@ const restoreCommand: Command = {restoreTasks});- spinner.succeed('Session restored');+ const failure = toolError(result) ?? (result.restored === false ? 'Session not found' : null);+ if (failure) {+ spinner.fail('Failed to restore session');+ output.printError(failure);+ return { success: false, exitCode: 1 };+ }++ const memoryRestore = result.memoryRestore;+ const memoryPartial = !!memoryRestore && memoryRestore.failed > 0;+ if (memoryPartial) {+ spinner.fail('Session restored with memory errors');+ } else {+ spinner.succeed('Session restored');+ }output.writeln();+ // #3573: distinguish "not requested" from "the session holds no memory".+ const memoryStatus = result.restoredComponents.memory+ ? (memoryPartial ? output.error('Partial') : output.success('Restored'))+ : restoreMemory ? output.dim('Not in session') : output.dim('Skipped');+output.printTable({columns: [{ key: 'component', header: 'Component', width: 20 },@@ -404,8 +465,10 @@ const restoreCommand: Command = {data: [{component: 'Memory',- status: result.restoredComponents.memory ? output.success('Restored') : output.dim('Skipped'),- count: result.restoredComponents.memory ? result.stats.memoryEntries : 0+ status: memoryStatus,+ count: result.restoredComponents.memory+ ? (result.stats.memoryEntriesRestored ?? result.stats.memoryEntries)+ : 0},{component: 'Agents',@@ -421,13 +484,22 @@ const restoreCommand: Command = {});output.writeln();- output.printSuccess(`Session ${sessionId} restored successfully`);+ if (memoryPartial) {+ output.printWarning(+ `${memoryRestore!.failed} memory entries could not be restored` ++ (memoryRestore!.errors.length ? `: ${memoryRestore!.errors.join('; ')}` : ''),+ );+ } else {+ output.printSuccess(`Session ${sessionId} restored successfully`);+ }if (ctx.flags.format === 'json') {output.printJson(result);}- return { success: true, data: result };+ return memoryPartial+ ? { success: false, exitCode: 1, data: result }+ : { success: true, data: result };} catch (error) {spinner.fail('Failed to restore session');if (error instanceof MCPClientError) {@@ -482,6 +554,12 @@ const deleteCommand: Command = {deletedAt: string;}>('session_delete', { sessionId });+ const failure = toolError(result) ?? (result.deleted === false ? 'Session not found' : null);+ if (failure) {+ output.printError(`Failed to delete session: ${failure}`);+ return { success: false, exitCode: 1 };+ }+output.writeln();output.printSuccess(`Session ${sessionId} deleted`);@@ -504,7 +582,7 @@ const deleteCommand: Command = {// Export subcommandconst exportCommand: Command = {name: 'export',- description: 'Export session to file',+ description: 'Export a saved session to a file. Usage: session export <session-id> [-o file] (or --latest)',options: [{name: 'output',@@ -512,6 +590,12 @@ const exportCommand: Command = {description: 'Output file path',type: 'string'},+ {+ name: 'latest',+ description: 'Export the most recently saved session when no session id is given',+ type: 'boolean',+ default: false+ },{name: 'format',short: 'f',@@ -539,13 +623,22 @@ const exportCommand: Command = {const exportFormat = ctx.flags.format as string;const compress = ctx.flags.compress as boolean;- // Get current session if no ID provided+ // #3575: like `session delete`, refuse to guess which session to act on.+ // Exporting the most recent one is available, but only when asked for.if (!sessionId) {+ if (!ctx.flags.latest) {+ output.printError('Session ID is required. Pass a session id, or --latest to export the most recently saved session.');+ return { success: false, exitCode: 1 };+ }try {- const current = await callMCPTool<{ sessionId: string }>('session_current', {});+ const current = await callMCPTool<{ sessionId: string; error?: string }>('session_current', {});+ if (toolError(current) || !current.sessionId) {+ output.printError('No saved sessions to export.');+ return { success: false, exitCode: 1 };+ }sessionId = current.sessionId;} catch {- output.printError('No active session. Provide a session ID to export.');+ output.printError('No saved sessions to export.');return { success: false, exitCode: 1 };}}@@ -575,6 +668,13 @@ const exportCommand: Command = {includeMemory: ctx.flags['include-memory'] !== false});+ const failure = toolError(result);+ if (failure || result.data === undefined) {+ spinner.fail('Failed to export session');+ output.printError(failure || 'The export returned no session data');+ return { success: false, exitCode: 1 };+ }+// Format outputlet content: string;if (exportFormat === 'yaml') {@@ -593,7 +693,8 @@ const exportCommand: Command = {spinner.succeed('Session exported');output.writeln();- const exportStats = result.stats || {};+ // session_export returns the whole record under `data`; its stats live there.+ const exportStats = result.stats || (result.data as { stats?: typeof result.stats })?.stats || {};output.printTable({columns: [{ key: 'property', header: 'Property', width: 18 },@@ -632,7 +733,7 @@ const exportCommand: Command = {// Import subcommandconst importCommand: Command = {name: 'import',- description: 'Import session from file',+ description: 'Import a session from a file written by session export. Usage: session import <file> [--name n] [--activate]',options: [{name: 'name',@@ -670,17 +771,21 @@ const importCommand: Command = {spinner.start();try {- const content = fs.readFileSync(absolutePath, 'utf-8');- let data: unknown;-- // Parse based on extension+ // The YAML written by `session export --format yaml` is display-only;+ // there is no YAML parser here, so say so instead of failing obscurely.if (absolutePath.endsWith('.yaml') || absolutePath.endsWith('.yml')) {- // Simple YAML parsing (basic implementation)- data = JSON.parse(content); // Would need proper YAML parser- } else {- data = JSON.parse(content);+ try {+ JSON.parse(fs.readFileSync(absolutePath, 'utf-8'));+ } catch {+ spinner.fail('Failed to import session');+ output.printError('YAML session import is not supported. Export with --format json and import that file.');+ return { success: false, exitCode: 1 };+ }}+ // #3575: session_import reads the file itself from `inputPath`. Passing a+ // parsed `data` object used to hit its required-argument check, and the+ // CLI then printed "Session imported" before crashing on the error result.const result = await callMCPTool<{sessionId: string;name: string;@@ -691,12 +796,20 @@ const importCommand: Command = {memoryEntriesImported: number;};activated: boolean;+ error?: string;}>('session_import', {- data,+ inputPath: absolutePath,name: sessionName,activate});+ const failure = toolError(result);+ if (failure) {+ spinner.fail('Failed to import session');+ output.printError(failure);+ return { success: false, exitCode: 1 };+ }+spinner.succeed('Session imported');output.writeln();@@ -763,6 +876,12 @@ const currentCommand: Command = {};}>('session_current', { includeStats: true });+ if (toolError(result)) {+ output.printWarning('No active session');+ output.printInfo('Save one with "claude-flow session save"');+ return { success: true, data: { active: false } };+ }+if (ctx.flags.format === 'json') {output.printJson(result);return { success: true, data: result };@@ -875,7 +994,8 @@ export const sessionCommand: Command = {{ command: 'claude-flow session save -n "checkpoint-1"', description: 'Save current session' },{ command: 'claude-flow session restore session-123', description: 'Restore a session' },{ command: 'claude-flow session delete session-123', description: 'Delete a session' },- { command: 'claude-flow session export -o backup.json', description: 'Export session to file' },+ { command: 'claude-flow session export session-123 -o backup.json', description: 'Export a session to file' },+ { command: 'claude-flow session export --latest -o backup.json', description: 'Export the most recently saved session' },{ command: 'claude-flow session import backup.json', description: 'Import session from file' },{ command: 'claude-flow session current', description: 'Show current session' }],diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.tsindex 3da5bda412..190019b8fa 100644--- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts@@ -104,17 +104,149 @@ function listSessions(): SessionRecord[] {return sessions;}+/** Snapshot format written by session_save since #3573. */+const MEMORY_SNAPSHOT_FORMAT = 'ruflo-session-memory/2';+const MEMORY_PAGE_SIZE = 500;++interface MemorySnapshotEntry {+ key: string;+ value: string;+ namespace: string;+ provenanceType?: string;+ source: 'memory-db' | 'agentdb' | 'legacy-json';+}++/**+ * #3573: what session_save learned about memory, so callers can say+ * "not included" or "no store" instead of printing an invented 0.+ */+export interface MemoryCaptureReport {+ requested: boolean;+ status: 'not-requested' | 'captured' | 'no-store' | 'error';+ entries: number;+ sources: { memoryDb: number; agentdb: number; legacyJson: number };+ error?: string;+}++async function readLiveEntries(+ listEntries: typeof import('../memory/memory-initializer.js').listEntries,+ dbPath: string,+ encryptWrites?: boolean,+): Promise<Array<{ key: string; namespace: string; content?: string; provenanceType?: string }>> {+ const rows: Array<{ key: string; namespace: string; content?: string; provenanceType?: string }> = [];+ // Bounded: stop on a short page, once `total` rows are in hand, or after a+ // hard cap, so a backend that ignores `offset` cannot loop forever.+ for (let page = 0, offset = 0; page < 10_000; page++, offset += MEMORY_PAGE_SIZE) {+ const result = await listEntries({+ dbPath, includeContent: true, limit: MEMORY_PAGE_SIZE, offset,+ ...(encryptWrites === undefined ? {} : { encryptWrites }),+ });+ if (!result.success) throw new Error(result.error || `could not list ${dbPath}`);+ rows.push(...result.entries);+ if (result.entries.length < MEMORY_PAGE_SIZE || rows.length >= result.total) break;+ }+ return rows;+}++/**+ * #3573: capture the memory the user actually has.+ *+ * Before this, session_save read only the pre-SQLite `.claude-flow/memory/store.json`,+ * which a current install never writes, so `--include-memory` saved nothing and+ * reported "Memory Entries: 0". The snapshot now covers the same store `memory+ * list` reads (resolveDbPath), plus rows that exist only in the sibling AgentDB+ * store written by the MCP path, de-duplicated by namespace+key (default CLI+ * writes are mirrored into AgentDB, so most rows are in both). A legacy+ * store.json is still captured for backward compatibility.+ */+async function captureMemorySnapshot(): Promise<{ memory?: Record<string, unknown>; report: MemoryCaptureReport }> {+ const report: MemoryCaptureReport = {+ requested: true, status: 'captured', entries: 0,+ sources: { memoryDb: 0, agentdb: 0, legacyJson: 0 },+ };+ const entries: Record<string, MemorySnapshotEntry | Record<string, unknown>> = {};+ let legacy: unknown;++ const legacyPath = join(getProjectCwd(), STORAGE_DIR, 'memory', 'store.json');+ if (existsSync(legacyPath)) {+ try {+ legacy = JSON.parse(readFileSync(legacyPath, 'utf-8'));+ const legacyEntries = (legacy as { entries?: Record<string, Record<string, unknown>> }).entries || {};+ for (const [id, entry] of Object.entries(legacyEntries)) {+ entries[id] = entry;+ report.sources.legacyJson++;+ }+ } catch { /* unreadable legacy file is not memory we can restore */ }+ }++ let sawStore = legacy !== undefined;+ try {+ const { listEntries, resolveDbPath } = await import('../memory/memory-initializer.js');+ const primary = resolveDbPath();+ const seen = new Set<string>();+ if (existsSync(primary)) {+ sawStore = true;+ for (const row of await readLiveEntries(listEntries, primary)) {+ const id = `${row.namespace}::${row.key}`;+ seen.add(id);+ entries[id] = {+ key: row.key, value: row.content ?? '', namespace: row.namespace,+ provenanceType: row.provenanceType, source: 'memory-db',+ };+ report.sources.memoryDb++;+ }+ }+ let sibling: string | null = null;+ try {+ const { siblingAgentDbPath } = await import('../memory/memory-bridge.js');+ sibling = siblingAgentDbPath(primary);+ } catch { /* no bridge, no sibling store */ }+ if (sibling && existsSync(sibling)) {+ sawStore = true;+ // The AgentDB store is read by native SQLite and must stay plaintext.+ for (const row of await readLiveEntries(listEntries, sibling, false)) {+ const id = `${row.namespace}::${row.key}`;+ if (seen.has(id)) continue;+ seen.add(id);+ entries[id] = {+ key: row.key, value: row.content ?? '', namespace: row.namespace,+ provenanceType: row.provenanceType, source: 'agentdb',+ };+ report.sources.agentdb++;+ }+ }+ } catch (e) {+ report.status = 'error';+ report.error = (e as Error).message;+ }++ report.entries = Object.keys(entries).length;+ if (report.status !== 'error' && !sawStore) report.status = 'no-store';+ if (report.entries === 0 && legacy === undefined) {+ return { report };+ }+ return {+ memory: {+ format: MEMORY_SNAPSHOT_FORMAT,+ entries,+ ...(legacy !== undefined ? { legacy } : {}),+ },+ report,+ };+}+// Load related stores for session data-function loadRelatedStores(options: { includeMemory?: boolean; includeTasks?: boolean; includeAgents?: boolean }) {+async function loadRelatedStores(options: { includeMemory?: boolean; includeTasks?: boolean; includeAgents?: boolean }) {const data: SessionRecord['data'] = {};+ let memoryCapture: MemoryCaptureReport = {+ requested: false, status: 'not-requested', entries: 0,+ sources: { memoryDb: 0, agentdb: 0, legacyJson: 0 },+ };if (options.includeMemory) {- try {- const memoryPath = join(getProjectCwd(), STORAGE_DIR, 'memory', 'store.json');- if (existsSync(memoryPath)) {- data.memory = JSON.parse(readFileSync(memoryPath, 'utf-8'));- }- } catch { /* ignore */ }+ const captured = await captureMemorySnapshot();+ memoryCapture = captured.report;+ if (captured.memory) data.memory = captured.memory;}if (options.includeTasks) {@@ -135,7 +267,86 @@ function loadRelatedStores(options: { includeMemory?: boolean; includeTasks?: bo} catch { /* ignore */ }}- return data;+ return { data, memoryCapture };+}++/** Count entries in a memory snapshot of either format. */+function countMemoryEntries(memory: unknown): number {+ if (!memory || typeof memory !== 'object') return 0;+ return Object.keys((memory as { entries?: object }).entries || {}).length;+}++/**+ * Restore a memory snapshot into the live store and report what was actually+ * written. #3573: the previous restore swallowed every write failure and then+ * echoed the count recorded at save time.+ */+async function restoreMemorySnapshot(memory: Record<string, unknown>): Promise<{+ restored: number; failed: number; errors: string[];+}> {+ const outcome = { restored: 0, failed: 0, errors: [] as string[] };+ const isV2 = memory.format === MEMORY_SNAPSHOT_FORMAT;+ // Legacy snapshots are the old store.json itself; v2 snapshots carry it+ // under `legacy` only when one existed at save time.+ const legacyJson = isV2 ? memory.legacy : memory;+ if (legacyJson !== undefined) {+ const memoryDir = join(getProjectCwd(), STORAGE_DIR, 'memory');+ if (!existsSync(memoryDir)) mkdirRestricted(memoryDir);+ writeFileRestricted(join(memoryDir, 'store.json'), JSON.stringify(legacyJson, null, 2));+ }++ const entries = (memory as {+ entries?: Record<string, { key?: string; id?: string; value?: string; content?: string; namespace?: string; provenanceType?: string }>;+ }).entries;+ if (!entries) return outcome;++ let storeEntry: typeof import('../memory/memory-initializer.js').storeEntry;+ let isValidProvenanceType: (value: unknown) => boolean = () => false;+ try {+ const mod = await import('../memory/memory-initializer.js');+ storeEntry = mod.storeEntry;+ try { if (typeof mod.isValidProvenanceType === 'function') isValidProvenanceType = mod.isValidProvenanceType; }+ catch { /* optional: without it, provenance is simply not carried over */ }+ } catch (e) {+ outcome.failed = Object.keys(entries).length;+ outcome.errors.push(`memory store unavailable: ${(e as Error).message}`);+ return outcome;+ }+ for (const entry of Object.values(entries)) {+ const key = entry.key || entry.id || '';+ const value = entry.value || entry.content || '';+ if (!key || !value) { outcome.failed++; continue; }+ try {+ // A snapshot from another version may carry a provenance value this one+ // rejects; drop it rather than fail an otherwise-good row.+ const provenance = entry.provenanceType && entry.provenanceType !== 'unknown'+ && isValidProvenanceType(entry.provenanceType) ? entry.provenanceType : undefined;+ const result = await storeEntry({+ key,+ value,+ namespace: entry.namespace || 'restored',+ upsert: true,+ ...(provenance ? { provenanceType: provenance } : {}),+ });+ if (result && result.success === false) {+ outcome.failed++;+ if (result.error && outcome.errors.length < 5) outcome.errors.push(`${key}: ${result.error}`);+ } else {+ outcome.restored++;+ }+ } catch (e) {+ outcome.failed++;+ if (outcome.errors.length < 5) outcome.errors.push(`${key}: ${(e as Error).message}`);+ }+ }+ return outcome;+}++/** A session record is an object that carries at least one of its defining fields. */+function isSessionRecordLike(value: unknown): value is Partial<SessionRecord> {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const v = value as Record<string, unknown>;+ return 'data' in v || 'stats' in v || 'sessionId' in v || 'savedAt' in v;}export const sessionTools: MCPTool[] = [@@ -166,7 +377,7 @@ export const sessionTools: MCPTool[] = [const sessionId = `session-${Date.now()}-${randomUUID().slice(0, 8)}`;// Load related data based on options- const data = loadRelatedStores({+ const { data, memoryCapture } = await loadRelatedStores({includeMemory: input.includeMemory as boolean,includeTasks: input.includeTasks as boolean,includeAgents: input.includeAgents as boolean,@@ -176,7 +387,7 @@ export const sessionTools: MCPTool[] = [const stats = {tasks: data.tasks ? Object.keys((data.tasks as { tasks?: object }).tasks || {}).length : 0,agents: data.agents ? Object.keys((data.agents as { agents?: object }).agents || {}).length : 0,- memoryEntries: data.memory ? Object.keys((data.memory as { entries?: object }).entries || {}).length : 0,+ memoryEntries: countMemoryEntries(data.memory),totalSize: 0,};@@ -200,6 +411,7 @@ export const sessionTools: MCPTool[] = [name: session.name,savedAt: session.savedAt,stats: session.stats,+ memoryCapture,path: getSessionPath(sessionId),};},@@ -252,34 +464,11 @@ export const sessionTools: MCPTool[] = [}if (session) {- // Restore data to respective stores (legacy JSON for backward compat).- // audit_1776853149979: tighten perms on the restored stores too.+ // Restore data to respective stores. audit_1776853149979: tighten+ // perms on the restored stores too.+ let memoryRestore: { restored: number; failed: number; errors: string[] } | undefined;if (input.restoreMemory !== false && session.data?.memory) {- const memoryDir = join(getProjectCwd(), STORAGE_DIR, 'memory');- if (!existsSync(memoryDir)) mkdirRestricted(memoryDir);- writeFileRestricted(join(memoryDir, 'store.json'), JSON.stringify(session.data.memory, null, 2));-- // Also populate active sql.js SQLite database so memory-tools can find entries- try {- const { storeEntry } = await import('../memory/memory-initializer.js');- const memoryData = session.data.memory as { entries?: Record<string, { key?: string; id?: string; value?: string; content?: string; namespace?: string }> };- if (memoryData.entries) {- for (const entry of Object.values(memoryData.entries)) {- const key = entry.key || entry.id || '';- const value = entry.value || entry.content || '';- if (key && value) {- await storeEntry({- key,- value,- namespace: entry.namespace || 'restored',- upsert: true,- });- }- }- }- } catch {- // Legacy JSON restore is the fallback -- sql.js import may not be available- }+ memoryRestore = await restoreMemorySnapshot(session.data.memory as Record<string, unknown>);}if (input.restoreTasks !== false && session.data?.tasks) {const taskDir = join(getProjectCwd(), STORAGE_DIR, 'tasks');@@ -303,6 +492,11 @@ export const sessionTools: MCPTool[] = [},restoredAt: new Date().toISOString(),stats: session.stats,+ // #3573: counts actually written, not the count recorded at save time.+ ...(memoryRestore ? {+ memoryRestore,+ stats: { ...session.stats, memoryEntriesRestored: memoryRestore.restored },+ } : {}),};}@@ -532,25 +726,33 @@ export const sessionTools: MCPTool[] = [// #1916: `ruflo session import <file>` referenced an unregistered// `session_import` tool. Reads a session JSON and re-saves it locally.name: 'session_import',- description: 'Import a session JSON file (produced by session_export) into the local session store and optionally activate it. Use when native Read is wrong because the file is a structured session record that must be re-registered (new id, stats recomputed) rather than just read. For reading the file, native Read is fine. Pair with session_export on the source.',+ description: 'Import a session (produced by session_export) into the local session store and optionally activate it. Pass either inputPath (a session JSON file) or data (the session record itself). Use when native Read is wrong because the file is a structured session record that must be re-registered (new id, stats recomputed) rather than just read. For reading the file, native Read is fine. Pair with session_export on the source.',category: 'session',inputSchema: {type: 'object',properties: {- inputPath: { type: 'string', description: 'Path to the session JSON file to import' },+ inputPath: { type: 'string', description: 'Path to the session JSON file to import (or pass data)' },+ data: { type: 'object', description: 'The session record itself, as written by session_export (or pass inputPath)' },name: { type: 'string', description: 'Override the imported session name' },activate: { type: 'boolean', description: 'Restore the imported session into the active stores' },},- required: ['inputPath'],},handler: async (input) => {- const inputPath = String(input.inputPath ?? '');- if (!inputPath || !existsSync(inputPath)) return { error: `File not found: ${inputPath || '(empty)'}` };- let parsed: SessionRecord;- try { parsed = JSON.parse(readFileSync(inputPath, 'utf-8')); }- catch (e) { return { error: `Invalid session JSON: ${(e as Error).message}` }; }+ let parsed: unknown;+ if (input.data !== undefined && input.data !== null) {+ parsed = input.data;+ } else {+ const inputPath = String(input.inputPath ?? '');+ if (!inputPath) return { error: 'Provide inputPath (a session JSON file) or data (a session record)' };+ if (!existsSync(inputPath)) return { error: `File not found: ${inputPath}` };+ try { parsed = JSON.parse(readFileSync(inputPath, 'utf-8')); }+ catch (e) { return { error: `Invalid session JSON: ${(e as Error).message}` }; }+ }+ if (!isSessionRecordLike(parsed)) {+ return { error: 'Not a session record: expected an object produced by session export' };+ }const newId = `session-${Date.now()}-${randomUUID().slice(0, 8)}`;- const stats = parsed.stats || { tasks: 0, agents: 0, memoryEntries: 0, totalSize: 0 };+ const stats = { tasks: 0, agents: 0, memoryEntries: 0, totalSize: 0, ...(parsed.stats || {}) };const session: SessionRecord = {sessionId: newId,name: input.name ? String(input.name) : (parsed.name || 'imported-session'),