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(session): round-trip compressed JSON backups

Rudy Celeklibc6d654d223e
diff --git a/docs/USERGUIDE.md b/docs/USERGUIDE.md
index 9765ae088a..10d52ef3f3 100644
--- a/docs/USERGUIDE.md
+++ b/docs/USERGUIDE.md
@@ -3629,7 +3629,11 @@ npx ruflo@latest memory export --include-embeddings --output ./full-export.json
npx ruflo@latest config export --scope project --output ./agent-configs.json
# Export session state
-npx ruflo@latest session export --session-id "my-session" --output ./session.json
+npx ruflo@latest session export "my-session" --format json --output ./session.json
+
+# Compress a JSON backup and import it later (gzip is detected from the file bytes)
+npx ruflo@latest session export "my-session" --format json --compress --output ./session.json.gz
+npx ruflo@latest session import ./session.json.gz
```
### Import Commands
diff --git a/v3/@claude-flow/cli/__tests__/session-compressed-backup.test.ts b/v3/@claude-flow/cli/__tests__/session-compressed-backup.test.ts
new file mode 100644
index 0000000000..4cbfb616d6
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/session-compressed-backup.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { gzipSync, gunzipSync } from 'node:zlib';
+import { sessionCommand } from '../src/commands/session.js';
+import { callMCPTool } from '../src/mcp-client.js';
+
+interface SavedSession { sessionId: string }
+interface SessionSnapshot { data: { name: string; description?: string } }
+
+const action = (name: string) => {
+ const handler = sessionCommand.subcommands?.find(command => command.name === name)?.action;
+ if (!handler) throw new Error(`session ${name} action is unavailable`);
+ return handler;
+};
+
+const save = () => callMCPTool<SavedSession>('session_save', {
+ name: 'checkpoint', description: 'Unicode résumé 🐢',
+ includeMemory: false, includeTasks: false, includeAgents: false,
+});
+
+describe('compressed session backups through the public command and tools', () => {
+ let root: string;
+ let previous: string;
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'ruflo-session-gzip-'));
+ previous = process.cwd();
+ process.chdir(root);
+ });
+ afterEach(() => { process.chdir(previous); rmSync(root, { recursive: true, force: true }); });
+
+ it.each([undefined, 'named-backup.bin'])('writes real gzip bytes with output %s', async (file) => {
+ const saved = await save();
+ const snapshot = await callMCPTool<SessionSnapshot>('session_export', { sessionId: saved.sessionId });
+ const result = await action('export')({
+ args: [saved.sessionId], flags: { _: [], format: 'json', compress: true, ...(file ? { output: file } : {}) },
+ cwd: root, interactive: false,
+ });
+ expect(result?.success).toBe(true);
+ const bytes = readFileSync(join(root, file ?? `session-${saved.sessionId}.json.gz`));
+ expect(bytes.subarray(0, 2).toString('hex')).toBe('1f8b');
+ expect(JSON.parse(gunzipSync(bytes).toString('utf8'))).toEqual(snapshot.data);
+ expect(result?.data).toMatchObject({ size: bytes.length });
+ });
+
+ it('round-trips a compressed JSON export through session import', async () => {
+ const saved = await save();
+ const snapshot = await callMCPTool<SessionSnapshot>('session_export', { sessionId: saved.sessionId });
+ await action('export')({ args: [saved.sessionId], flags: { _: [], format: 'json', output: 'backup.json.gz', compress: true }, cwd: root, interactive: false });
+ const imported = await action('import')({ args: ['backup.json.gz'], flags: { _: [] }, cwd: root, interactive: false });
+ expect(imported?.success).toBe(true);
+ const id = (imported?.data as SavedSession).sessionId;
+ expect(id).not.toBe(saved.sessionId);
+ const restored = await callMCPTool<SessionSnapshot>('session_export', { sessionId: id });
+ expect(restored.data.name).toBe(snapshot.data.name);
+ expect(restored.data.description).toBe(snapshot.data.description);
+ });
+
+ it('imports gzip JSON by magic bytes regardless of the filename', async () => {
+ const saved = await save();
+ const snapshot = await callMCPTool<SessionSnapshot>('session_export', { sessionId: saved.sessionId });
+ writeFileSync('external-backup.bin', gzipSync(JSON.stringify(snapshot.data)));
+ const imported = await callMCPTool<SavedSession & { error?: string }>('session_import', { inputPath: join(root, 'external-backup.bin') });
+ expect(imported.error).toBeUndefined();
+ const restored = await callMCPTool<SessionSnapshot>('session_export', { sessionId: imported.sessionId });
+ expect(restored.data.name).toBe('checkpoint');
+ });
+
+ it('retains plain JSON and reports its actual UTF-8 byte count', async () => {
+ const saved = await save();
+ const result = await action('export')({ args: [saved.sessionId], flags: { _: [], format: 'json', output: 'plain.json', compress: false }, cwd: root, interactive: false });
+ const bytes = readFileSync('plain.json');
+ expect(JSON.parse(bytes.toString('utf8')).name).toBe('checkpoint');
+ expect(result?.data).toMatchObject({ size: bytes.length });
+ const imported = await action('import')({ args: ['plain.json'], flags: { _: [] }, cwd: root, interactive: false });
+ expect(imported?.success).toBe(true);
+ });
+
+ it('continues to reject display-only YAML backups', async () => {
+ writeFileSync('backup.yaml.gz', gzipSync('name: checkpoint\nsessionId: example\n'));
+ const result = await action('import')({ args: ['backup.yaml.gz'], flags: { _: [] }, cwd: root, interactive: false });
+ expect(result).toMatchObject({ success: false, exitCode: 1 });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/session.ts b/v3/@claude-flow/cli/src/commands/session.ts
index e54d291975..73ce6fe653 100644
--- a/v3/@claude-flow/cli/src/commands/session.ts
+++ b/v3/@claude-flow/cli/src/commands/session.ts
@@ -9,6 +9,7 @@ import { confirm, input, select } from '../prompt.js';
import { callMCPTool, MCPClientError } from '../mcp-client.js';
import * as fs from 'fs';
import * as path from 'path';
+import { gzipSync, gunzipSync } from 'node:zlib';
// Format date for display
function formatDate(dateStr: string): string {
@@ -688,7 +689,8 @@ const exportCommand: Command = {
? outputPath
: path.join(ctx.cwd, outputPath);
- fs.writeFileSync(absolutePath, content, 'utf-8');
+ const bytes = compress ? gzipSync(content) : Buffer.from(content, 'utf-8');
+ fs.writeFileSync(absolutePath, bytes);
spinner.succeed('Session exported');
output.writeln();
@@ -707,7 +709,7 @@ const exportCommand: Command = {
{ property: 'Agents', value: exportStats.agentCount ?? exportStats.agents ?? 0 },
{ property: 'Tasks', value: exportStats.taskCount ?? exportStats.tasks ?? 0 },
{ property: 'Memory Entries', value: exportStats.memoryEntries ?? 0 },
- { property: 'File Size', value: formatSize(content.length) }
+ { property: 'File Size', value: formatSize(bytes.length) }
]
});
@@ -716,7 +718,7 @@ const exportCommand: Command = {
return {
success: true,
- data: { sessionId, outputPath, format: exportFormat, size: content.length }
+ data: { sessionId, outputPath, format: exportFormat, size: bytes.length }
};
} catch (error) {
spinner.fail('Failed to export session');
@@ -773,9 +775,11 @@ const importCommand: Command = {
try {
// 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')) {
+ if (/\.ya?ml(?:\.gz)?$/i.test(absolutePath)) {
try {
- JSON.parse(fs.readFileSync(absolutePath, 'utf-8'));
+ const bytes = fs.readFileSync(absolutePath);
+ const content = bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes;
+ JSON.parse(content.toString('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.');
diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts
index 190019b8fa..51c6ea4526 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts
@@ -6,6 +6,7 @@
import { existsSync, readFileSync, readdirSync, unlinkSync, statSync, writeFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
+import { gunzipSync } from 'node:zlib';
import { join } from 'node:path';
import { type MCPTool, getProjectCwd } from './types.js';
import {
@@ -745,7 +746,11 @@ export const sessionTools: MCPTool[] = [
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')); }
+ try {
+ const bytes = readFileSync(inputPath);
+ const content = bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes;
+ parsed = JSON.parse(content.toString('utf-8'));
+ }
catch (e) { return { error: `Invalid session JSON: ${(e as Error).message}` }; }
}
if (!isSessionRecordLike(parsed)) {