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 SQLite preparation errors in hive-mind spawn

rUvd9572f466be7
diff --git a/src/cli/simple-commands/hive-mind.js b/src/cli/simple-commands/hive-mind.js
index dc0a660681..284cca7d18 100644
--- a/src/cli/simple-commands/hive-mind.js
+++ b/src/cli/simple-commands/hive-mind.js
@@ -308,8 +308,10 @@ const hiveMindWizard = safeInteractive(
name: flags.name || `swarm-${Date.now()}`,
queenType: flags.queenType || flags['queen-type'] || 'strategic',
maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
- consensusAlgorithm: flags.consensus || 'majority',
+ consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
autoScale: flags.autoScale || flags['auto-scale'] || false,
+ namespace: flags.namespace || 'default',
+ verbose: flags.verbose || false,
encryption: flags.encryption || false,
};
@@ -405,11 +407,16 @@ async function spawnSwarmWizard() {
await spawnSwarm([answers.objective], {
name: answers.name,
queenType: answers.queenType,
+ 'queen-type': answers.queenType,
maxWorkers: answers.maxWorkers,
+ 'max-workers': answers.maxWorkers,
workerTypes: answers.workerTypes.join(','),
consensus: answers.consensusAlgorithm,
autoScale: answers.autoScale,
+ 'auto-scale': answers.autoScale,
monitor: answers.monitor,
+ namespace: answers.namespace || 'default',
+ verbose: answers.verbose || false,
});
}
@@ -425,6 +432,35 @@ async function spawnSwarm(args, flags) {
return;
}
+ // Validate parameters
+ if (flags.verbose) {
+ console.log(chalk.gray('🔍 Debug: Parsed flags:'));
+ console.log(chalk.gray(JSON.stringify(flags, null, 2)));
+ }
+
+ // Validate queen type
+ const validQueenTypes = ['strategic', 'tactical', 'adaptive'];
+ const queenType = flags.queenType || flags['queen-type'] || 'strategic';
+ if (!validQueenTypes.includes(queenType)) {
+ console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));
+ return;
+ }
+
+ // Validate max workers
+ const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');
+ if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {
+ console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));
+ return;
+ }
+
+ // Validate consensus algorithm
+ const validConsensusTypes = ['majority', 'weighted', 'byzantine'];
+ const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';
+ if (!validConsensusTypes.includes(consensusAlgorithm)) {
+ console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));
+ return;
+ }
+
const spinner = ora('Spawning Hive Mind swarm...').start();
try {
@@ -435,10 +471,11 @@ async function spawnSwarm(args, flags) {
hiveMind = new HiveMindCore({
objective,
name: flags.name || `hive-${Date.now()}`,
- queenType: flags.queenType || 'strategic',
- maxWorkers: flags.maxWorkers || 8,
- consensusAlgorithm: flags.consensus || 'majority',
- autoScale: flags.autoScale !== false,
+ queenType: flags.queenType || flags['queen-type'] || 'strategic',
+ maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),
+ consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',
+ autoScale: flags.autoScale !== undefined ? flags.autoScale : (flags['auto-scale'] !== undefined ? flags['auto-scale'] : true),
+ namespace: flags.namespace || 'default',
encryption: flags.encryption || false,
});
} catch (error) {
@@ -574,7 +611,7 @@ async function spawnSwarm(args, flags) {
// Create session for this swarm
spinner.text = 'Creating session tracking...';
const sessionManager = new HiveMindSessionManager();
- const sessionId = sessionManager.createSession(swarmId, hiveMind.config.name, objective, {
+ const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {
queenType: hiveMind.config.queenType,
maxWorkers: hiveMind.config.maxWorkers,
consensusAlgorithm: hiveMind.config.consensusAlgorithm,
@@ -584,14 +621,16 @@ async function spawnSwarm(args, flags) {
});
spinner.text = 'Session tracking established...';
- sessionManager.close();
- // Initialize auto-save middleware
- const autoSave = createAutoSaveMiddleware(sessionId, {
+ // Initialize auto-save middleware (use the same session manager)
+ const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {
saveInterval: 30000, // Save every 30 seconds
autoStart: true,
});
+ // Close session manager after auto-save is set up
+ // sessionManager.close(); // Don't close yet as auto-save needs it
+
// Track initial swarm creation
autoSave.trackChange('swarm_created', {
swarmId,
@@ -719,6 +758,59 @@ async function spawnSwarm(args, flags) {
console.log(chalk.blue('💡 To pause:') + ' Press Ctrl+C to safely pause and resume later');
console.log(chalk.blue('💡 To resume:') + ' claude-flow hive-mind resume ' + sessionId);
+ // Set up SIGINT handler for automatic session pausing
+ let isExiting = false;
+ const sigintHandler = async () => {
+ if (isExiting) return;
+ isExiting = true;
+
+ console.log('\n\n' + chalk.yellow('⏸️ Pausing session...'));
+
+ try {
+ // Save current checkpoint using the existing session manager
+ // const sessionManager = new HiveMindSessionManager(); // Use existing one
+
+ // Create checkpoint data
+ const checkpointData = {
+ timestamp: new Date().toISOString(),
+ swarmId,
+ objective,
+ workerCount: workers.length,
+ workerTypes,
+ status: 'paused_by_user',
+ reason: 'User pressed Ctrl+C',
+ };
+
+ // Save checkpoint
+ await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);
+
+ // Pause the session
+ await sessionManager.pauseSession(sessionId);
+
+ // Close session manager
+ sessionManager.close();
+
+ console.log(chalk.green('✓') + ' Session paused successfully');
+ console.log(chalk.cyan('\nTo resume this session, run:'));
+ console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));
+ console.log();
+
+ // Clean up auto-save if active
+ if (global.autoSaveInterval) {
+ clearInterval(global.autoSaveInterval);
+ }
+
+ process.exit(0);
+ } catch (error) {
+ console.error(chalk.red('Error pausing session:'), error.message);
+ process.exit(1);
+ }
+ };
+
+ // Register SIGINT handler
+ process.on('SIGINT', sigintHandler);
+ process.on('SIGTERM', sigintHandler);
+
// Offer to spawn Claude Code instances with coordination instructions
if (flags.claude || flags.spawn) {
await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);
@@ -1771,6 +1863,20 @@ async function exportMemoryBackup() {
}
}
+/**
+ * Get active session ID for a swarm
+ */
+async function getActiveSessionId(swarmId) {
+ const sessionManager = new HiveMindSessionManager();
+ try {
+ const sessions = sessionManager.getActiveSessions();
+ const activeSession = sessions.find(s => s.swarm_id === swarmId && s.status === 'active');
+ return activeSession ? activeSession.id : null;
+ } finally {
+ sessionManager.close();
+ }
+}
+
/**
* Spawn Claude Code with Hive Mind coordination instructions
*/
@@ -1850,6 +1956,59 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
shell: false,
});
+ // Track child process PID in session
+ const sessionManager = new HiveMindSessionManager();
+ const sessionId = await getActiveSessionId(swarmId);
+ if (sessionId && claudeProcess.pid) {
+ sessionManager.addChildPid(sessionId, claudeProcess.pid);
+ }
+
+ // Set up SIGINT handler for automatic session pausing
+ let isExiting = false;
+ const sigintHandler = async () => {
+ if (isExiting) return;
+ isExiting = true;
+
+ console.log('\n\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));
+
+ try {
+ // Terminate Claude Code process
+ if (claudeProcess && !claudeProcess.killed) {
+ claudeProcess.kill('SIGTERM');
+ }
+
+ // Save checkpoint and pause session
+ if (sessionId) {
+ const checkpointData = {
+ timestamp: new Date().toISOString(),
+ swarmId,
+ objective,
+ status: 'paused_by_user',
+ reason: 'User pressed Ctrl+C during Claude Code execution',
+ claudePid: claudeProcess.pid,
+ };
+
+ await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);
+ await sessionManager.pauseSession(sessionId);
+
+ console.log(chalk.green('✓') + ' Session paused successfully');
+ console.log(chalk.cyan('\nTo resume this session, run:'));
+ console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));
+ }
+
+ sessionManager.close();
+ process.exit(0);
+ } catch (error) {
+ console.error(chalk.red('Error pausing session:'), error.message);
+ sessionManager.close();
+ process.exit(1);
+ }
+ };
+
+ // Register SIGINT handler
+ process.on('SIGINT', sigintHandler);
+ process.on('SIGTERM', sigintHandler);
+
// Handle stdout
if (claudeProcess.stdout) {
claudeProcess.stdout.on('data', (data) => {
@@ -1866,9 +2025,15 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
// Handle process exit
claudeProcess.on('exit', (code) => {
+ // Remove child PID from session
+ if (sessionId && claudeProcess.pid) {
+ sessionManager.removeChildPid(sessionId, claudeProcess.pid);
+ sessionManager.close();
+ }
+
if (code === 0) {
console.log(chalk.green('\n✓ Claude Code completed successfully'));
- } else {
+ } else if (code !== null) {
console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
}
});
@@ -2574,6 +2739,18 @@ async function launchClaudeWithContext(prompt, flags) {
shell: false,
});
+ // Set up SIGINT handler for clean termination (no session pausing here since we're resuming)
+ const sigintHandler = () => {
+ console.log('\n\n' + chalk.yellow('⏹️ Terminating Claude Code...'));
+ if (claudeProcess && !claudeProcess.killed) {
+ claudeProcess.kill('SIGTERM');
+ }
+ process.exit(0);
+ };
+
+ process.on('SIGINT', sigintHandler);
+ process.on('SIGTERM', sigintHandler);
+
// Handle stdout
if (claudeProcess.stdout) {
claudeProcess.stdout.on('data', (data) => {
@@ -2592,9 +2769,13 @@ async function launchClaudeWithContext(prompt, flags) {
claudeProcess.on('exit', (code) => {
if (code === 0) {
console.log(chalk.green('\n✓ Claude Code completed successfully'));
- } else {
+ } else if (code !== null) {
console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
}
+
+ // Clean up signal handlers
+ process.removeListener('SIGINT', sigintHandler);
+ process.removeListener('SIGTERM', sigintHandler);
});
console.log(chalk.green('\n✓ Claude Code launched with restored session context'));
diff --git a/src/cli/simple-commands/hive-mind/auto-save-middleware.js b/src/cli/simple-commands/hive-mind/auto-save-middleware.js
index c24da89a76..e2ffc63324 100644
--- a/src/cli/simple-commands/hive-mind/auto-save-middleware.js
+++ b/src/cli/simple-commands/hive-mind/auto-save-middleware.js
@@ -6,10 +6,10 @@
import { HiveMindSessionManager } from './session-manager.js';
export class AutoSaveMiddleware {
- constructor(sessionId, saveInterval = 30000) {
+ constructor(sessionId, sessionManager, saveInterval = 30000) {
this.sessionId = sessionId;
this.saveInterval = saveInterval;
- this.sessionManager = new HiveMindSessionManager();
+ this.sessionManager = sessionManager; // Use provided session manager
this.saveTimer = null;
this.pendingChanges = [];
this.isActive = false;
@@ -178,7 +178,7 @@ export class AutoSaveMiddleware {
// Update session progress
if (completionPercentage > 0) {
- this.sessionManager.updateSessionProgress(this.sessionId, completionPercentage);
+ await this.sessionManager.updateSessionProgress(this.sessionId, completionPercentage);
}
// Log all changes as session events
@@ -278,7 +278,7 @@ export class AutoSaveMiddleware {
this.childProcesses.clear();
// Stop the session if it's still active
- const session = this.sessionManager.getSession(this.sessionId);
+ const session = await this.sessionManager.getSession(this.sessionId);
if (session && (session.status === 'active' || session.status === 'paused')) {
await this.sessionManager.stopSession(this.sessionId);
}
@@ -296,9 +296,9 @@ export class AutoSaveMiddleware {
/**
* Create auto-save middleware for a session
*/
-export function createAutoSaveMiddleware(sessionId, options = {}) {
+export function createAutoSaveMiddleware(sessionId, sessionManager, options = {}) {
const saveInterval = options.saveInterval || 30000; // Default 30 seconds
- const middleware = new AutoSaveMiddleware(sessionId, saveInterval);
+ const middleware = new AutoSaveMiddleware(sessionId, sessionManager, saveInterval);
if (options.autoStart !== false) {
middleware.start();
diff --git a/src/cli/simple-commands/hive-mind/session-manager.js b/src/cli/simple-commands/hive-mind/session-manager.js
index 4bab1c4463..888f283302 100644
--- a/src/cli/simple-commands/hive-mind/session-manager.js
+++ b/src/cli/simple-commands/hive-mind/session-manager.js
@@ -3,25 +3,77 @@
* Handles session persistence and resume functionality for swarms
*/
-import Database from 'better-sqlite3';
import path from 'path';
import { existsSync, mkdirSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import chalk from 'chalk';
import { cwd } from '../../node-compat.js';
+import { createDatabase, isSQLiteAvailable, isWindows } from '../../../memory/sqlite-wrapper.js';
export class HiveMindSessionManager {
constructor(hiveMindDir = null) {
this.hiveMindDir = hiveMindDir || path.join(cwd(), '.hive-mind');
this.sessionsDir = path.join(this.hiveMindDir, 'sessions');
this.dbPath = path.join(this.hiveMindDir, 'hive.db');
+ this.db = null;
+ this.isInMemory = false;
+ this.memoryStore = null;
// Ensure directories exist
this.ensureDirectories();
// Initialize database connection
- this.db = new Database(this.dbPath);
- this.initializeSchema();
+ this.initializeDatabase();
+ }
+
+ /**
+ * Initialize database with fallback support
+ */
+ async initializeDatabase() {
+ try {
+ const sqliteAvailable = await isSQLiteAvailable();
+
+ if (!sqliteAvailable) {
+ console.warn('SQLite not available, using in-memory session storage');
+ this.initializeInMemoryFallback();
+ return;
+ }
+
+ this.db = await createDatabase(this.dbPath);
+ this.initializeSchema();
+ } catch (error) {
+ console.error('Failed to create SQLite database:', error.message);
+ console.warn('Falling back to in-memory session storage');
+ this.initializeInMemoryFallback();
+ }
+ }
+
+ /**
+ * Ensure database is initialized before use
+ */
+ async ensureInitialized() {
+ if (this.db === null && !this.isInMemory) {
+ await this.initializeDatabase();
+ }
+ }
+
+ /**
+ * Initialize in-memory fallback for session storage
+ */
+ initializeInMemoryFallback() {
+ this.isInMemory = true;
+ this.memoryStore = {
+ sessions: new Map(),
+ checkpoints: new Map(),
+ logs: new Map()
+ };
+
+ if (isWindows()) {
+ console.info(`
+Note: Session data will not persist between runs on Windows without SQLite.
+To enable persistence, see: https://github.com/ruvnet/claude-code-flow/docs/windows-installation.md
+`);
+ }
}
/**
@@ -110,18 +162,38 @@ export class HiveMindSessionManager {
/**
* Create a new session for a swarm
*/
- createSession(swarmId, swarmName, objective, metadata = {}) {
+ async createSession(swarmId, swarmName, objective, metadata = {}) {
+ await this.ensureInitialized();
+
const sessionId = `session-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- const stmt = this.db.prepare(`
- INSERT INTO sessions (id, swarm_id, swarm_name, objective, metadata, parent_pid)
- VALUES (?, ?, ?, ?, ?, ?)
- `);
-
- stmt.run(sessionId, swarmId, swarmName, objective, JSON.stringify(metadata), process.pid);
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const sessionData = {
+ id: sessionId,
+ swarm_id: swarmId,
+ swarm_name: swarmName,
+ objective,
+ status: 'active',
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ metadata: JSON.stringify(metadata),
+ parent_pid: process.pid,
+ child_pids: '[]'
+ };
+ this.memoryStore.sessions.set(sessionId, sessionData);
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ INSERT INTO sessions (id, swarm_id, swarm_name, objective, metadata, parent_pid)
+ VALUES (?, ?, ?, ?, ?, ?)
+ `);
+
+ stmt.run(sessionId, swarmId, swarmName, objective, JSON.stringify(metadata), process.pid);
+ }
// Log session creation
- this.logSessionEvent(sessionId, 'info', 'Session created', null, {
+ await this.logSessionEvent(sessionId, 'info', 'Session created', null, {
swarmId,
swarmName,
objective,
@@ -135,24 +207,49 @@ export class HiveMindSessionManager {
* Save session checkpoint
*/
async saveCheckpoint(sessionId, checkpointName, checkpointData) {
+ await this.ensureInitialized();
+
const checkpointId = `checkpoint-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- // Save to database
- const stmt = this.db.prepare(`
- INSERT INTO session_checkpoints (id, session_id, checkpoint_name, checkpoint_data)
- VALUES (?, ?, ?, ?)
- `);
-
- stmt.run(checkpointId, sessionId, checkpointName, JSON.stringify(checkpointData));
-
- // Update session checkpoint data and timestamp
- const updateStmt = this.db.prepare(`
- UPDATE sessions
- SET checkpoint_data = ?, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?
- `);
-
- updateStmt.run(JSON.stringify(checkpointData), sessionId);
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const checkpointEntry = {
+ id: checkpointId,
+ session_id: sessionId,
+ checkpoint_name: checkpointName,
+ checkpoint_data: JSON.stringify(checkpointData),
+ created_at: new Date().toISOString()
+ };
+
+ if (!this.memoryStore.checkpoints.has(sessionId)) {
+ this.memoryStore.checkpoints.set(sessionId, []);
+ }
+ this.memoryStore.checkpoints.get(sessionId).push(checkpointEntry);
+
+ // Update session data
+ const session = this.memoryStore.sessions.get(sessionId);
+ if (session) {
+ session.checkpoint_data = JSON.stringify(checkpointData);
+ session.updated_at = new Date().toISOString();
+ }
+ } else {
+ // Save to database
+ const stmt = this.db.prepare(`
+ INSERT INTO session_checkpoints (id, session_id, checkpoint_name, checkpoint_data)
+ VALUES (?, ?, ?, ?)
+ `);
+
+ stmt.run(checkpointId, sessionId, checkpointName, JSON.stringify(checkpointData));
+
+ // Update session checkpoint data and timestamp
+ const updateStmt = this.db.prepare(`
+ UPDATE sessions
+ SET checkpoint_data = ?, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?
+ `);
+
+ updateStmt.run(JSON.stringify(checkpointData), sessionId);
+ }
// Save checkpoint file for backup
const checkpointFile = path.join(this.sessionsDir, `${sessionId}-${checkpointName}.json`);
@@ -171,7 +268,7 @@ export class HiveMindSessionManager {
),
);
- this.logSessionEvent(sessionId, 'info', `Checkpoint saved: ${checkpointName}`, null, {
+ await this.logSessionEvent(sessionId, 'info', `Checkpoint saved: ${checkpointName}`, null, {
checkpointId,
});
@@ -181,38 +278,91 @@ export class HiveMindSessionManager {
/**
* Get active sessions
*/
- getActiveSessions() {
- const stmt = this.db.prepare(`
- SELECT s.*,
- COUNT(DISTINCT a.id) as agent_count,
- COUNT(DISTINCT t.id) as task_count,
- SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks
- FROM sessions s
- LEFT JOIN agents a ON s.swarm_id = a.swarm_id
- LEFT JOIN tasks t ON s.swarm_id = t.swarm_id
- WHERE s.status = 'active' OR s.status = 'paused'
- GROUP BY s.id
- ORDER BY s.updated_at DESC
- `);
-
- const sessions = stmt.all();
-
- // Parse JSON fields
- return sessions.map((session) => ({
- ...session,
- metadata: session.metadata ? JSON.parse(session.metadata) : {},
- checkpoint_data: session.checkpoint_data ? JSON.parse(session.checkpoint_data) : null,
- completion_percentage:
- session.task_count > 0
- ? Math.round((session.completed_tasks / session.task_count) * 100)
- : 0,
- }));
+ async getActiveSessions() {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const sessions = [];
+ for (const [sessionId, session] of this.memoryStore.sessions) {
+ if (session.status === 'active' || session.status === 'paused') {
+ sessions.push({
+ ...session,
+ metadata: session.metadata ? JSON.parse(session.metadata) : {},
+ checkpoint_data: session.checkpoint_data ? JSON.parse(session.checkpoint_data) : null,
+ agent_count: 0, // Not tracked in memory mode
+ task_count: 0, // Not tracked in memory mode
+ completed_tasks: 0, // Not tracked in memory mode
+ completion_percentage: 0
+ });
+ }
+ }
+ return sessions.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ SELECT s.*,
+ COUNT(DISTINCT a.id) as agent_count,
+ COUNT(DISTINCT t.id) as task_count,
+ SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks
+ FROM sessions s
+ LEFT JOIN agents a ON s.swarm_id = a.swarm_id
+ LEFT JOIN tasks t ON s.swarm_id = t.swarm_id
+ WHERE s.status = 'active' OR s.status = 'paused'
+ GROUP BY s.id
+ ORDER BY s.updated_at DESC
+ `);
+
+ const sessions = stmt.all();
+
+ // Parse JSON fields
+ return sessions.map((session) => ({
+ ...session,
+ metadata: session.metadata ? JSON.parse(session.metadata) : {},
+ checkpoint_data: session.checkpoint_data ? JSON.parse(session.checkpoint_data) : null,
+ completion_percentage:
+ session.task_count > 0
+ ? Math.round((session.completed_tasks / session.task_count) * 100)
+ : 0,
+ }));
+ }
}
/**
* Get session by ID with full details
*/
- getSession(sessionId) {
+ async getSession(sessionId) {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const session = this.memoryStore.sessions.get(sessionId);
+ if (!session) {
+ return null;
+ }
+
+ // Return simplified session data for in-memory mode
+ return {
+ ...session,
+ metadata: session.metadata ? JSON.parse(session.metadata) : {},
+ checkpoint_data: session.checkpoint_data ? JSON.parse(session.checkpoint_data) : null,
+ swarm: null, // Not available in memory mode
+ agents: [], // Not available in memory mode
+ tasks: [], // Not available in memory mode
+ checkpoints: this.memoryStore.checkpoints.get(sessionId) || [],
+ recentLogs: this.memoryStore.logs.get(sessionId) || [],
+ statistics: {
+ totalAgents: 0,
+ activeAgents: 0,
+ totalTasks: 0,
+ completedTasks: 0,
+ pendingTasks: 0,
+ inProgressTasks: 0,
+ completionPercentage: session.completion_percentage || 0,
+ },
+ };
+ }
+
const session = this.db
.prepare(
`
@@ -307,28 +457,45 @@ export class HiveMindSessionManager {
/**
* Pause a session
*/
- pauseSession(sessionId) {
- const stmt = this.db.prepare(`
- UPDATE sessions
- SET status = 'paused', paused_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?
- `);
-
- const result = stmt.run(sessionId);
-
- if (result.changes > 0) {
- this.logSessionEvent(sessionId, 'info', 'Session paused');
-
- // Update swarm status
- const session = this.db.prepare('SELECT swarm_id FROM sessions WHERE id = ?').get(sessionId);
+ async pauseSession(sessionId) {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const session = this.memoryStore.sessions.get(sessionId);
if (session) {
- this.db
- .prepare('UPDATE swarms SET status = ? WHERE id = ?')
- .run('paused', session.swarm_id);
+ session.status = 'paused';
+ session.paused_at = new Date().toISOString();
+ session.updated_at = new Date().toISOString();
+
+ await this.logSessionEvent(sessionId, 'info', 'Session paused');
+ return true;
+ }
+ return false;
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ UPDATE sessions
+ SET status = 'paused', paused_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?
+ `);
+
+ const result = stmt.run(sessionId);
+
+ if (result.changes > 0) {
+ await this.logSessionEvent(sessionId, 'info', 'Session paused');
+
+ // Update swarm status
+ const session = this.db.prepare('SELECT swarm_id FROM sessions WHERE id = ?').get(sessionId);
+ if (session) {
+ this.db
+ .prepare('UPDATE swarms SET status = ? WHERE id = ?')
+ .run('paused', session.swarm_id);
+ }
}
- }
- return result.changes > 0;
+ return result.changes > 0;
+ }
}
/**
@@ -452,13 +619,35 @@ export class HiveMindSessionManager {
/**
* Log session event
*/
- logSessionEvent(sessionId, logLevel, message, agentId = null, data = null) {
- const stmt = this.db.prepare(`
- INSERT INTO session_logs (session_id, log_level, message, agent_id, data)
- VALUES (?, ?, ?, ?, ?)
- `);
-
- stmt.run(sessionId, logLevel, message, agentId, data ? JSON.stringify(data) : null);
+ async logSessionEvent(sessionId, logLevel, message, agentId = null, data = null) {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage for logs
+ const logId = `log-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
+ const logEntry = {
+ id: logId,
+ session_id: sessionId,
+ timestamp: new Date().toISOString(),
+ log_level: logLevel,
+ message,
+ agent_id: agentId,
+ data: data ? JSON.stringify(data) : null
+ };
+
+ if (!this.memoryStore.logs.has(sessionId)) {
+ this.memoryStore.logs.set(sessionId, []);
+ }
+ this.memoryStore.logs.get(sessionId).push(logEntry);
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ INSERT INTO session_logs (session_id, log_level, message, agent_id, data)
+ VALUES (?, ?, ?, ?, ?)
+ `);
+
+ stmt.run(sessionId, logLevel, message, agentId, data ? JSON.stringify(data) : null);
+ }
}
/**
@@ -483,14 +672,26 @@ export class HiveMindSessionManager {
/**
* Update session progress
*/
- updateSessionProgress(sessionId, completionPercentage) {
- const stmt = this.db.prepare(`
- UPDATE sessions
- SET completion_percentage = ?, updated_at = CURRENT_TIMESTAMP
- WHERE id = ?
- `);
-
- stmt.run(completionPercentage, sessionId);
+ async updateSessionProgress(sessionId, completionPercentage) {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const session = this.memoryStore.sessions.get(sessionId);
+ if (session) {
+ session.completion_percentage = completionPercentage;
+ session.updated_at = new Date().toISOString();
+ }
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ UPDATE sessions
+ SET completion_percentage = ?, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?
+ `);
+
+ stmt.run(completionPercentage, sessionId);
+ }
}
/**
@@ -652,33 +853,42 @@ export class HiveMindSessionManager {
/**
* Get all child PIDs for a session
*/
- getChildPids(sessionId) {
- const session = this.db.prepare('SELECT child_pids FROM sessions WHERE id = ?').get(sessionId);
- if (!session || !session.child_pids) return [];
-
- return JSON.parse(session.child_pids);
+ async getChildPids(sessionId) {
+ await this.ensureInitialized();
+
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const session = this.memoryStore.sessions.get(sessionId);
+ if (!session || !session.child_pids) return [];
+ return JSON.parse(session.child_pids);
+ } else {
+ // Use SQLite
+ const session = this.db.prepare('SELECT child_pids FROM sessions WHERE id = ?').get(sessionId);
+ if (!session || !session.child_pids) return [];
+ return JSON.parse(session.child_pids);
+ }
}
/**
* Stop a session and terminate all child processes
*/
async stopSession(sessionId) {
- const session = this.getSession(sessionId);
+ const session = await this.getSession(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not found`);
}
// Get child PIDs
- const childPids = this.getChildPids(sessionId);
+ const childPids = await this.getChildPids(sessionId);
// Terminate child processes
for (const pid of childPids) {
try {
process.kill(pid, 'SIGTERM');
- this.logSessionEvent(sessionId, 'info', 'Child process terminated', null, { pid });
+ await this.logSessionEvent(sessionId, 'info', 'Child process terminated', null, { pid });
} catch (err) {
// Process might already be dead
- this.logSessionEvent(sessionId, 'warning', 'Failed to terminate child process', null, {
+ await this.logSessionEvent(sessionId, 'warning', 'Failed to terminate child process', null, {
pid,
error: err.message,
});
@@ -686,18 +896,28 @@ export class HiveMindSessionManager {
}
// Update session status
- const stmt = this.db.prepare(`
- UPDATE sessions
- SET status = 'stopped', updated_at = CURRENT_TIMESTAMP
- WHERE id = ?
- `);
+ if (this.isInMemory) {
+ // Use in-memory storage
+ const sessionData = this.memoryStore.sessions.get(sessionId);
+ if (sessionData) {
+ sessionData.status = 'stopped';
+ sessionData.updated_at = new Date().toISOString();
+ }
+ } else {
+ // Use SQLite
+ const stmt = this.db.prepare(`
+ UPDATE sessions
+ SET status = 'stopped', updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?
+ `);
- stmt.run(sessionId);
+ stmt.run(sessionId);
- // Update swarm status
- this.db.prepare('UPDATE swarms SET status = ? WHERE id = ?').run('stopped', session.swarm_id);
+ // Update swarm status
+ this.db.prepare('UPDATE swarms SET status = ? WHERE id = ?').run('stopped', session.swarm_id);
+ }
- this.logSessionEvent(sessionId, 'info', 'Session stopped');
+ await this.logSessionEvent(sessionId, 'info', 'Session stopped');
return true;
}
@@ -766,7 +986,9 @@ export class HiveMindSessionManager {
* Clean up and close database connection
*/
close() {
- this.db.close();
+ if (this.db && !this.isInMemory) {
+ this.db.close();
+ }
}
}