feat: implement hive-mind resume functionality (#245)

* fix: update hooks format for Claude Code 1.0.51+ compatibility

- Changed hooks from object format to array format (PreToolUse, PostToolUse, Stop)
- Added migration script for existing users
- Updated settings.json template in init command
- Removed unsupported fields (mcpServers, features, performance)
- Added @alpha tag to npx commands in hooks

Fixes #235

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: implement hive-mind resume functionality (alpha.50)

- Add HiveMindSessionManager for session persistence
- Implement auto-save middleware with 30-second intervals
- Add 'hive-mind resume <session-id>' command
- Add 'hive-mind sessions' command to list sessions
- Integrate session tracking into spawn workflow
- Add comprehensive test suite (80+ tests)
- Update documentation and fix README
- Bump version to 2.0.0-alpha.50

Fixes #232

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>

* chore: bump version to 2.0.0-alpha.51

- Update version strings in all CLI files
- Prepare for npm publication

🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
rUvandClaude authored and GitHub committed 2025-07-14 10:56:09 -04:00
1 parent db82963d74
commit af1c8a7c72
92 files changed
+7204 -428

No files matched your search

+1 -1
View File
@@ -3,7 +3,7 @@
* Provides clear, actionable command documentation
*/
export const VERSION = '2.0.0-alpha.49';
export const VERSION = '2.0.0-alpha.51';
export const MAIN_HELP = `
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
+1 -1
View File
@@ -18,7 +18,7 @@ import process from 'process';
import readline from 'readline';
import { getMainHelp, getCommandHelp } from './help-text.js';
const VERSION = '2.0.0-alpha.49';
const VERSION = '2.0.0-alpha.51';
function printHelp() {
console.log(getMainHelp());
+311
View File
@@ -24,6 +24,8 @@ import { HiveMindCore } from './hive-mind/core.js';
import { QueenCoordinator } from './hive-mind/queen.js';
import { CollectiveMemory } from './hive-mind/memory.js';
import { SwarmCommunication } from './hive-mind/communication.js';
import { HiveMindSessionManager } from './hive-mind/session-manager.js';
import { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';
function showHiveMindHelp() {
console.log(`
@@ -36,6 +38,8 @@ ${chalk.bold('SUBCOMMANDS:')}
${chalk.green('init')} Initialize hive mind system
${chalk.green('spawn')} Spawn hive mind swarm for a task
${chalk.green('status')} Show hive mind status
${chalk.green('resume')} Resume a paused hive mind session
${chalk.green('sessions')} List all hive mind sessions
${chalk.green('consensus')} View consensus decisions
${chalk.green('memory')} Manage collective memory
${chalk.green('metrics')} View performance metrics
@@ -63,6 +67,12 @@ ${chalk.bold('EXAMPLES:')}
${chalk.gray('# Auto-spawn coordinated Claude Code instances')}
claude-flow hive-mind spawn "Research AI trends" --auto-spawn --verbose
${chalk.gray('# List all sessions')}
claude-flow hive-mind sessions
${chalk.gray('# Resume a paused session')}
claude-flow hive-mind resume session-1234567890-abc123
${chalk.bold('KEY FEATURES:')}
${chalk.cyan('🐝')} Queen-led coordination with worker specialization
${chalk.cyan('🧠')} Collective memory and knowledge sharing
@@ -548,6 +558,35 @@ async function spawnSwarm(args, flags) {
throw new Error(`Failed to create swarm record: ${error.message}`);
}
// Create session for this swarm
spinner.text = 'Creating session tracking...';
const sessionManager = new HiveMindSessionManager();
const sessionId = sessionManager.createSession(swarmId, hiveMind.config.name, objective, {
queenType: hiveMind.config.queenType,
maxWorkers: hiveMind.config.maxWorkers,
consensusAlgorithm: hiveMind.config.consensusAlgorithm,
autoScale: hiveMind.config.autoScale,
encryption: hiveMind.config.encryption,
workerTypes: flags.workerTypes
});
spinner.text = 'Session tracking established...';
sessionManager.close();
// Initialize auto-save middleware
const autoSave = createAutoSaveMiddleware(sessionId, {
saveInterval: 30000, // Save every 30 seconds
autoStart: true
});
// Track initial swarm creation
autoSave.trackChange('swarm_created', {
swarmId,
swarmName: hiveMind.config.name,
objective,
workerCount: hiveMind.config.maxWorkers
});
spinner.text = 'Initializing Queen coordinator...';
// Initialize Queen
@@ -602,6 +641,12 @@ async function spawnSwarm(args, flags) {
INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)
VALUES (?, ?, ?, ?, ?, ?, ?)
`).run(...Object.values(worker));
// Track agent spawning for auto-save
autoSave.trackAgentActivity(workerId, 'spawned', {
type: workerType,
name: worker.name
});
}
spinner.text = 'Initializing collective memory...';
@@ -616,6 +661,7 @@ async function spawnSwarm(args, flags) {
memory.store('objective', objective, 'context');
memory.store('queen_type', hiveMind.config.queenType, 'config');
memory.store('worker_count', workers.length, 'metrics');
memory.store('session_id', sessionId, 'system');
spinner.text = 'Establishing communication channels...';
@@ -633,6 +679,7 @@ async function spawnSwarm(args, flags) {
console.log('\n' + chalk.bold('🐝 Swarm Summary:'));
console.log(chalk.gray('─'.repeat(50)));
console.log(chalk.cyan('Swarm ID:'), swarmId);
console.log(chalk.cyan('Session ID:'), sessionId);
console.log(chalk.cyan('Name:'), hiveMind.config.name);
console.log(chalk.cyan('Objective:'), objective);
console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);
@@ -651,6 +698,9 @@ async function spawnSwarm(args, flags) {
// Enhanced coordination instructions with MCP tools
console.log('\n' + chalk.green('✓') + ' Swarm is ready for coordination');
console.log(chalk.gray('Use "claude-flow hive-mind status" to view swarm activity'));
console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));
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);
// Offer to spawn Claude Code instances with coordination instructions
if (flags.claude || flags.spawn) {
@@ -1232,6 +1282,14 @@ export async function hiveMindCommand(args, flags) {
await showStatus(flags);
break;
case 'sessions':
await showSessions(flags);
break;
case 'resume':
await resumeSession(subArgs, flags);
break;
case 'consensus':
await showConsensus(flags);
break;
@@ -2013,6 +2071,259 @@ function getWorkerTypeInstructions(workerType) {
- Contribute to collective objectives`;
}
/**
* Show all hive mind sessions
*/
async function showSessions(flags) {
try {
const sessionManager = new HiveMindSessionManager();
const sessions = sessionManager.getActiveSessions();
if (sessions.length === 0) {
console.log(chalk.gray('No active or paused sessions found'));
sessionManager.close();
return;
}
console.log(chalk.bold('\n🗂️ Hive Mind Sessions\n'));
sessions.forEach((session, index) => {
const statusColor = session.status === 'active' ? 'green' :
session.status === 'paused' ? 'yellow' : 'gray';
const statusIcon = session.status === 'active' ? '🟢' :
session.status === 'paused' ? '🟡' : '⚫';
console.log(chalk.yellow('═'.repeat(60)));
console.log(`${statusIcon} ${chalk.bold(session.swarm_name)}`);
console.log(chalk.cyan('Session ID:'), session.id);
console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));
console.log(chalk.cyan('Objective:'), session.objective);
console.log(chalk.cyan('Progress:'), `${session.completion_percentage}%`);
console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());
console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());
if (session.paused_at) {
console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());
}
console.log('\n' + chalk.bold('Progress:'));
console.log(` Agents: ${session.agent_count || 0}`);
console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);
if (session.checkpoint_data) {
console.log('\n' + chalk.bold('Last Checkpoint:'));
console.log(chalk.gray(JSON.stringify(session.checkpoint_data, null, 2).substring(0, 200) + '...'));
}
});
console.log(chalk.yellow('═'.repeat(60)) + '\n');
console.log(chalk.blue('💡 Tips:'));
console.log(' • Resume a session: claude-flow hive-mind resume <session-id>');
console.log(' • View session details: claude-flow hive-mind status');
sessionManager.close();
} catch (error) {
console.error(chalk.red('Error:'), error.message);
exit(1);
}
}
/**
* Resume a paused hive mind session
*/
async function resumeSession(args, flags) {
const sessionId = args[0];
if (!sessionId) {
console.error(chalk.red('Error: Please provide a session ID'));
console.log('Usage: claude-flow hive-mind resume <session-id>');
console.log('Run "claude-flow hive-mind sessions" to see available sessions');
return;
}
const spinner = ora('Resuming Hive Mind session...').start();
try {
const sessionManager = new HiveMindSessionManager();
// Get session details
const session = sessionManager.getSession(sessionId);
if (!session) {
spinner.fail(`Session ${sessionId} not found`);
console.log('\nRun "claude-flow hive-mind sessions" to see available sessions');
sessionManager.close();
return;
}
if (session.status !== 'paused') {
spinner.fail(`Session is not paused (status: ${session.status})`);
sessionManager.close();
return;
}
// Resume the session
const resumedSession = await sessionManager.resumeSession(sessionId);
spinner.succeed('Session resumed successfully!');
// Display session summary
console.log('\n' + chalk.bold('📋 Resumed Session Summary:'));
console.log(chalk.gray('─'.repeat(50)));
console.log(chalk.cyan('Session ID:'), sessionId);
console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);
console.log(chalk.cyan('Objective:'), resumedSession.objective);
console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);
console.log(chalk.cyan('Active Agents:'), `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`);
console.log(chalk.cyan('Tasks:'), `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`);
console.log(chalk.gray('─'.repeat(50)));
// Show task breakdown
console.log('\n' + chalk.bold('📊 Task Status:'));
console.log(` ✅ Completed: ${resumedSession.statistics.completedTasks}`);
console.log(` 🔄 In Progress: ${resumedSession.statistics.inProgressTasks}`);
console.log(` ⏳ Pending: ${resumedSession.statistics.pendingTasks}`);
// Show recent activity
if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {
console.log('\n' + chalk.bold('📜 Recent Activity:'));
resumedSession.recentLogs.slice(0, 5).forEach(log => {
const timestamp = new Date(log.timestamp).toLocaleTimeString();
console.log(` [${timestamp}] ${log.message}`);
});
}
// Restore checkpoint if available
if (resumedSession.checkpoint_data) {
console.log('\n' + chalk.bold('♻️ Restoring from checkpoint...'));
console.log(chalk.gray('Checkpoint data available for restoration'));
}
sessionManager.close();
// Offer to spawn Claude Code with restored context
if (flags.claude || flags.spawn) {
console.log('\n' + chalk.yellow('🚀 Launching Claude Code with restored context...'));
// Generate prompt with session context
const restoredPrompt = generateRestoredSessionPrompt(resumedSession);
// Launch Claude Code with restored context
await launchClaudeWithContext(restoredPrompt, flags);
} else {
console.log('\n' + chalk.blue('💡 Pro Tip:') + ' Add --claude to spawn Claude Code with restored context');
console.log(chalk.gray(' claude-flow hive-mind resume ' + sessionId + ' --claude'));
}
} catch (error) {
spinner.fail('Failed to resume session');
console.error(chalk.red('Error:'), error.message);
exit(1);
}
}
/**
* Generate prompt for restored session
*/
function generateRestoredSessionPrompt(session) {
const activeAgents = session.agents.filter(a => a.status === 'active' || a.status === 'busy');
const pendingTasks = session.tasks.filter(t => t.status === 'pending' || t.status === 'in_progress');
return `🔄 RESUMING HIVE MIND SESSION
═══════════════════════════════════
You are resuming a paused Hive Mind session with the following context:
SESSION DETAILS:
📌 Session ID: ${session.id}
📌 Swarm Name: ${session.swarm_name}
🎯 Objective: ${session.objective}
📊 Progress: ${session.statistics.completionPercentage}% complete
⏸️ Paused: ${new Date(session.paused_at).toLocaleString()}
▶️ Resumed: ${new Date().toLocaleString()}
CURRENT STATUS:
• Total Agents: ${session.statistics.totalAgents}
• Active Agents: ${session.statistics.activeAgents}
• Completed Tasks: ${session.statistics.completedTasks}/${session.statistics.totalTasks}
• Pending Tasks: ${pendingTasks.length}
ACTIVE AGENTS:
${activeAgents.map(agent => `• ${agent.name} (${agent.type}) - ${agent.status}`).join('\n')}
PENDING TASKS:
${pendingTasks.slice(0, 10).map(task => `• [${task.priority}] ${task.description}`).join('\n')}
${pendingTasks.length > 10 ? `... and ${pendingTasks.length - 10} more tasks` : ''}
CHECKPOINT DATA:
${session.checkpoint_data ? JSON.stringify(session.checkpoint_data, null, 2) : 'No checkpoint data available'}
RECENT ACTIVITY:
${session.recentLogs.slice(0, 10).map(log => `[${new Date(log.timestamp).toLocaleTimeString()}] ${log.message}`).join('\n')}
🎯 RESUMPTION PROTOCOL:
1. **RESTORE CONTEXT**:
- Review the checkpoint data and recent activity
- Check collective memory for important decisions
- Verify agent status and reassign if needed
2. **CONTINUE EXECUTION**:
- Resume pending tasks based on priority
- Maintain coordination with existing agents
- Update progress tracking regularly
3. **COORDINATION**:
- Use mcp__claude-flow__memory_retrieve to access shared knowledge
- Continue using consensus mechanisms for decisions
- Maintain swarm communication protocols
Resume the hive mind operation and continue working towards the objective.`;
}
/**
* Launch Claude Code with context
*/
async function launchClaudeWithContext(prompt, flags) {
try {
const { spawn: childSpawn, execSync } = await import('child_process');
let claudeAvailable = false;
try {
execSync('which claude', { stdio: 'ignore' });
claudeAvailable = true;
} catch {
console.log(chalk.yellow('\n⚠️ Claude Code CLI not found'));
// Save prompt to file
const promptFile = `hive-mind-resume-${Date.now()}.txt`;
await writeFile(promptFile, prompt);
console.log(chalk.green(`\n✓ Session context saved to: ${promptFile}`));
console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));
return;
}
if (claudeAvailable && !flags.dryRun) {
const claudeArgs = [prompt];
if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
claudeArgs.push('--dangerously-skip-permissions');
}
const claudeProcess = childSpawn('claude', claudeArgs, {
stdio: 'inherit',
shell: false
});
console.log(chalk.green('\n✓ Claude Code launched with restored session context'));
}
} catch (error) {
console.error(chalk.red('Failed to launch Claude Code:'), error.message);
}
}
/**
* Get MCP wrapper instance
*/
@@ -0,0 +1,233 @@
/**
* Auto-save middleware for Hive Mind swarms
* Automatically saves session state during operations
*/
import { HiveMindSessionManager } from './session-manager.js';
export class AutoSaveMiddleware {
constructor(sessionId, saveInterval = 30000) {
this.sessionId = sessionId;
this.saveInterval = saveInterval;
this.sessionManager = new HiveMindSessionManager();
this.saveTimer = null;
this.pendingChanges = [];
this.isActive = false;
}
/**
* Start auto-save monitoring
*/
start() {
if (this.isActive) {
return;
}
this.isActive = true;
// Set up periodic saves
this.saveTimer = setInterval(() => {
if (this.pendingChanges.length > 0) {
this.performAutoSave();
}
}, this.saveInterval);
// Also save on process exit
process.on('beforeExit', () => {
this.performAutoSave();
});
process.on('SIGINT', () => {
this.performAutoSave();
process.exit();
});
process.on('SIGTERM', () => {
this.performAutoSave();
process.exit();
});
}
/**
* Stop auto-save monitoring
*/
stop() {
if (this.saveTimer) {
clearInterval(this.saveTimer);
this.saveTimer = null;
}
this.isActive = false;
// Final save
if (this.pendingChanges.length > 0) {
this.performAutoSave();
}
this.sessionManager.close();
}
/**
* Track a change for auto-save
*/
trackChange(changeType, data) {
this.pendingChanges.push({
type: changeType,
data: data,
timestamp: new Date().toISOString()
});
// Trigger immediate save for critical changes
if (changeType === 'task_completed' || changeType === 'agent_spawned' || changeType === 'consensus_reached') {
this.performAutoSave();
}
}
/**
* Track task progress
*/
trackTaskProgress(taskId, status, result = null) {
this.trackChange('task_progress', {
taskId,
status,
result
});
}
/**
* Track agent activity
*/
trackAgentActivity(agentId, activity, data = null) {
this.trackChange('agent_activity', {
agentId,
activity,
data
});
}
/**
* Track memory updates
*/
trackMemoryUpdate(key, value, type = 'general') {
this.trackChange('memory_update', {
key,
value,
type
});
}
/**
* Track consensus decisions
*/
trackConsensusDecision(topic, decision, votes) {
this.trackChange('consensus_reached', {
topic,
decision,
votes
});
}
/**
* Perform auto-save
*/
async performAutoSave() {
if (this.pendingChanges.length === 0) {
return;
}
try {
// Group changes by type
const changesByType = this.pendingChanges.reduce((acc, change) => {
if (!acc[change.type]) {
acc[change.type] = [];
}
acc[change.type].push(change);
return acc;
}, {});
// Calculate progress
const taskProgress = changesByType.task_progress || [];
const completedTasks = taskProgress.filter(t => t.data.status === 'completed').length;
const totalTasks = taskProgress.length;
const completionPercentage = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
// Create checkpoint data
const checkpointData = {
timestamp: new Date().toISOString(),
changeCount: this.pendingChanges.length,
changesByType,
statistics: {
tasksProcessed: taskProgress.length,
tasksCompleted: completedTasks,
memoryUpdates: (changesByType.memory_update || []).length,
agentActivities: (changesByType.agent_activity || []).length,
consensusDecisions: (changesByType.consensus_reached || []).length
}
};
// Save checkpoint
const checkpointName = `auto-save-${Date.now()}`;
await this.sessionManager.saveCheckpoint(this.sessionId, checkpointName, checkpointData);
// Update session progress
if (completionPercentage > 0) {
this.sessionManager.updateSessionProgress(this.sessionId, completionPercentage);
}
// Log all changes as session events
for (const change of this.pendingChanges) {
this.sessionManager.logSessionEvent(
this.sessionId,
'info',
`Auto-save: ${change.type}`,
change.data.agentId || null,
change.data
);
}
// Clear pending changes
this.pendingChanges = [];
} catch (error) {
console.error('Auto-save failed:', error);
// Keep changes for next attempt
}
}
/**
* Force immediate save
*/
async forceSave() {
await this.performAutoSave();
}
/**
* Get pending changes count
*/
getPendingChangesCount() {
return this.pendingChanges.length;
}
/**
* Check if auto-save is active
*/
isAutoSaveActive() {
return this.isActive;
}
}
/**
* Create auto-save middleware for a session
*/
export function createAutoSaveMiddleware(sessionId, options = {}) {
const saveInterval = options.saveInterval || 30000; // Default 30 seconds
const middleware = new AutoSaveMiddleware(sessionId, saveInterval);
if (options.autoStart !== false) {
middleware.start();
}
return middleware;
}
// Export for use in swarm operations
export default AutoSaveMiddleware;
@@ -0,0 +1,523 @@
/**
* Hive Mind Session Manager
* 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';
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');
// Ensure directories exist
this.ensureDirectories();
// Initialize database connection
this.db = new Database(this.dbPath);
this.initializeSchema();
}
/**
* Ensure required directories exist
*/
ensureDirectories() {
if (!existsSync(this.hiveMindDir)) {
mkdirSync(this.hiveMindDir, { recursive: true });
}
if (!existsSync(this.sessionsDir)) {
mkdirSync(this.sessionsDir, { recursive: true });
}
}
/**
* Initialize database schema for sessions
*/
initializeSchema() {
this.db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
swarm_id TEXT NOT NULL,
swarm_name TEXT NOT NULL,
objective TEXT,
status TEXT DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
paused_at DATETIME,
resumed_at DATETIME,
completion_percentage REAL DEFAULT 0,
checkpoint_data TEXT,
metadata TEXT,
FOREIGN KEY (swarm_id) REFERENCES swarms(id)
);
CREATE TABLE IF NOT EXISTS session_checkpoints (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
checkpoint_name TEXT NOT NULL,
checkpoint_data TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
CREATE TABLE IF NOT EXISTS session_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
log_level TEXT DEFAULT 'info',
message TEXT,
agent_id TEXT,
data TEXT,
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
`);
}
/**
* Create a new session for a swarm
*/
createSession(swarmId, swarmName, objective, metadata = {}) {
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)
VALUES (?, ?, ?, ?, ?)
`);
stmt.run(sessionId, swarmId, swarmName, objective, JSON.stringify(metadata));
// Log session creation
this.logSessionEvent(sessionId, 'info', 'Session created', null, {
swarmId,
swarmName,
objective
});
return sessionId;
}
/**
* Save session checkpoint
*/
async saveCheckpoint(sessionId, checkpointName, checkpointData) {
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);
// Save checkpoint file for backup
const checkpointFile = path.join(this.sessionsDir, `${sessionId}-${checkpointName}.json`);
await writeFile(checkpointFile, JSON.stringify({
sessionId,
checkpointId,
checkpointName,
timestamp: new Date().toISOString(),
data: checkpointData
}, null, 2));
this.logSessionEvent(sessionId, 'info', `Checkpoint saved: ${checkpointName}`, null, {
checkpointId
});
return checkpointId;
}
/**
* 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
}));
}
/**
* Get session by ID with full details
*/
getSession(sessionId) {
const session = this.db.prepare(`
SELECT * FROM sessions WHERE id = ?
`).get(sessionId);
if (!session) {
return null;
}
// Get associated swarm data
const swarm = this.db.prepare(`
SELECT * FROM swarms WHERE id = ?
`).get(session.swarm_id);
// Get agents
const agents = this.db.prepare(`
SELECT * FROM agents WHERE swarm_id = ?
`).all(session.swarm_id);
// Get tasks
const tasks = this.db.prepare(`
SELECT * FROM tasks WHERE swarm_id = ?
`).all(session.swarm_id);
// Get checkpoints
const checkpoints = this.db.prepare(`
SELECT * FROM session_checkpoints
WHERE session_id = ?
ORDER BY created_at DESC
`).all(sessionId);
// Get recent logs
const recentLogs = this.db.prepare(`
SELECT * FROM session_logs
WHERE session_id = ?
ORDER BY timestamp DESC
LIMIT 50
`).all(sessionId);
return {
...session,
metadata: session.metadata ? JSON.parse(session.metadata) : {},
checkpoint_data: session.checkpoint_data ? JSON.parse(session.checkpoint_data) : null,
swarm,
agents,
tasks,
checkpoints: checkpoints.map(cp => ({
...cp,
checkpoint_data: JSON.parse(cp.checkpoint_data)
})),
recentLogs,
statistics: {
totalAgents: agents.length,
activeAgents: agents.filter(a => a.status === 'active' || a.status === 'busy').length,
totalTasks: tasks.length,
completedTasks: tasks.filter(t => t.status === 'completed').length,
pendingTasks: tasks.filter(t => t.status === 'pending').length,
inProgressTasks: tasks.filter(t => t.status === 'in_progress').length,
completionPercentage: tasks.length > 0
? Math.round((tasks.filter(t => t.status === 'completed').length / tasks.length) * 100)
: 0
}
};
}
/**
* 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);
if (session) {
this.db.prepare('UPDATE swarms SET status = ? WHERE id = ?').run('paused', session.swarm_id);
}
}
return result.changes > 0;
}
/**
* Resume a paused session
*/
async resumeSession(sessionId) {
const session = this.getSession(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not found`);
}
if (session.status !== 'paused') {
throw new Error(`Session ${sessionId} is not paused (status: ${session.status})`);
}
// Update session status
const stmt = this.db.prepare(`
UPDATE sessions
SET status = 'active', resumed_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(sessionId);
// Update swarm status
this.db.prepare('UPDATE swarms SET status = ? WHERE id = ?').run('active', session.swarm_id);
// Update agent statuses
this.db.prepare(`
UPDATE agents
SET status = CASE
WHEN role = 'queen' THEN 'active'
ELSE 'idle'
END
WHERE swarm_id = ?
`).run(session.swarm_id);
this.logSessionEvent(sessionId, 'info', 'Session resumed', null, {
pausedDuration: session.paused_at
? new Date() - new Date(session.paused_at)
: null
});
return session;
}
/**
* Mark session as completed
*/
completeSession(sessionId) {
const stmt = this.db.prepare(`
UPDATE sessions
SET status = 'completed', updated_at = CURRENT_TIMESTAMP, completion_percentage = 100
WHERE id = ?
`);
const result = stmt.run(sessionId);
if (result.changes > 0) {
this.logSessionEvent(sessionId, 'info', 'Session completed');
// 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('completed', session.swarm_id);
}
}
return result.changes > 0;
}
/**
* Archive old sessions
*/
async archiveSessions(daysOld = 30) {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysOld);
const sessionsToArchive = this.db.prepare(`
SELECT * FROM sessions
WHERE status = 'completed' AND updated_at < ?
`).all(cutoffDate.toISOString());
const archiveDir = path.join(this.sessionsDir, 'archive');
if (!existsSync(archiveDir)) {
mkdirSync(archiveDir, { recursive: true });
}
for (const session of sessionsToArchive) {
const sessionData = this.getSession(session.id);
const archiveFile = path.join(archiveDir, `${session.id}-archive.json`);
await writeFile(archiveFile, JSON.stringify(sessionData, null, 2));
// Remove from database
this.db.prepare('DELETE FROM session_logs WHERE session_id = ?').run(session.id);
this.db.prepare('DELETE FROM session_checkpoints WHERE session_id = ?').run(session.id);
this.db.prepare('DELETE FROM sessions WHERE id = ?').run(session.id);
}
return sessionsToArchive.length;
}
/**
* 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);
}
/**
* Get session logs
*/
getSessionLogs(sessionId, limit = 100, offset = 0) {
const stmt = this.db.prepare(`
SELECT * FROM session_logs
WHERE session_id = ?
ORDER BY timestamp DESC
LIMIT ? OFFSET ?
`);
const logs = stmt.all(sessionId, limit, offset);
return logs.map(log => ({
...log,
data: log.data ? JSON.parse(log.data) : null
}));
}
/**
* 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);
}
/**
* Generate session summary
*/
generateSessionSummary(sessionId) {
const session = this.getSession(sessionId);
if (!session) {
return null;
}
const duration = session.paused_at && session.resumed_at
? new Date(session.updated_at) - new Date(session.created_at) - (new Date(session.resumed_at) - new Date(session.paused_at))
: new Date(session.updated_at) - new Date(session.created_at);
const tasksByType = session.agents.reduce((acc, agent) => {
const agentTasks = session.tasks.filter(t => t.agent_id === agent.id);
if (!acc[agent.type]) {
acc[agent.type] = {
total: 0,
completed: 0,
inProgress: 0,
pending: 0
};
}
acc[agent.type].total += agentTasks.length;
acc[agent.type].completed += agentTasks.filter(t => t.status === 'completed').length;
acc[agent.type].inProgress += agentTasks.filter(t => t.status === 'in_progress').length;
acc[agent.type].pending += agentTasks.filter(t => t.status === 'pending').length;
return acc;
}, {});
return {
sessionId: session.id,
swarmName: session.swarm_name,
objective: session.objective,
status: session.status,
duration: Math.round(duration / 1000 / 60), // minutes
statistics: session.statistics,
tasksByType,
checkpointCount: session.checkpoints.length,
lastCheckpoint: session.checkpoints[0] || null,
timeline: {
created: session.created_at,
lastUpdated: session.updated_at,
paused: session.paused_at,
resumed: session.resumed_at
}
};
}
/**
* Export session data
*/
async exportSession(sessionId, exportPath = null) {
const session = this.getSession(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not found`);
}
const exportFile = exportPath || path.join(this.sessionsDir, `${sessionId}-export.json`);
await writeFile(exportFile, JSON.stringify(session, null, 2));
return exportFile;
}
/**
* Import session data
*/
async importSession(importPath) {
const sessionData = JSON.parse(await readFile(importPath, 'utf8'));
// Create new session with imported data
const newSessionId = this.createSession(
sessionData.swarm_id,
sessionData.swarm_name,
sessionData.objective,
sessionData.metadata
);
// Import checkpoints
for (const checkpoint of sessionData.checkpoints || []) {
await this.saveCheckpoint(newSessionId, checkpoint.checkpoint_name, checkpoint.checkpoint_data);
}
// Import logs
for (const log of sessionData.recentLogs || []) {
this.logSessionEvent(
newSessionId,
log.log_level,
log.message,
log.agent_id,
log.data ? JSON.parse(log.data) : null
);
}
return newSessionId;
}
/**
* Clean up and close database connection
*/
close() {
this.db.close();
}
}
// Export for use in other modules
export default HiveMindSessionManager;
@@ -1260,36 +1260,56 @@ function createEnhancedSettingsJsonFallback() {
]
},
hooks: {
preEditHook: {
command: "npx",
args: ["claude-flow", "hook", "pre-edit", "--file", "${file}", "--auto-assign-agents", "true", "--load-context", "true"],
alwaysRun: false,
outputFormat: "json"
},
postEditHook: {
command: "npx",
args: ["claude-flow", "hook", "post-edit", "--file", "${file}", "--format", "true", "--update-memory", "true", "--train-neural", "true"],
alwaysRun: true,
outputFormat: "json"
},
preCommandHook: {
command: "npx",
args: ["claude-flow", "hook", "pre-command", "--command", "${command}", "--validate-safety", "true", "--prepare-resources", "true"],
alwaysRun: false,
outputFormat: "json"
},
postCommandHook: {
command: "npx",
args: ["claude-flow", "hook", "post-command", "--command", "${command}", "--track-metrics", "true", "--store-results", "true"],
alwaysRun: false,
outputFormat: "json"
},
sessionEndHook: {
command: "npx",
args: ["claude-flow", "hook", "session-end", "--generate-summary", "true", "--persist-state", "true", "--export-metrics", "true"],
alwaysRun: true,
outputFormat: "json"
}
PreToolUse: [
{
matcher: "Bash",
hooks: [
{
type: "command",
command: "npx claude-flow@alpha hooks pre-command --command \"${command}\" --validate-safety true --prepare-resources true"
}
]
},
{
matcher: "Write|Edit|MultiEdit",
hooks: [
{
type: "command",
command: "npx claude-flow@alpha hooks pre-edit --file \"${file}\" --auto-assign-agents true --load-context true"
}
]
}
],
PostToolUse: [
{
matcher: "Bash",
hooks: [
{
type: "command",
command: "npx claude-flow@alpha hooks post-command --command \"${command}\" --track-metrics true --store-results true"
}
]
},
{
matcher: "Write|Edit|MultiEdit",
hooks: [
{
type: "command",
command: "npx claude-flow@alpha hooks post-edit --file \"${file}\" --format true --update-memory true --train-neural true"
}
]
}
],
Stop: [
{
hooks: [
{
type: "command",
command: "npx claude-flow@alpha hooks session-end --generate-summary true --persist-state true --export-metrics true"
}
]
}
]
},
mcpServers: {
"claude-flow": {