mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 14:43:05 +09:00
feat: complete SQLite memory system implementation for v2.0.4
This commit brings v2.0.4 changes to main without problematic SQLite database files: ### 🗄️ SQLite Memory System - Enhanced SQLite Schema with 12 specialized tables - Persistent storage in .swarm/memory.db with WAL mode - Cross-session persistence for Claude Code sessions - Namespace support for organized memory management ### 🔧 MCP Server Integration - EnhancedMemory class extending SqliteMemoryStore - 14 Hook types for comprehensive operation tracking - Memory synchronization between CLI and MCP tools - Robust error handling and database integrity ### 📁 Project Organization - Archive legacy systems to archive/legacy-memory-system - Clean root structure for better maintainability - Updated documentation reflecting SQLite architecture ### 🔗 NPM Package Updates - Include memory JS/SQL files in distribution - MCP server files included in npm package - Version updated to 2.0.0-alpha.42 ### ⚙️ Configuration Updates - .gitignore excludes SQLite database files - .npmignore includes necessary memory components - CLI version consistency at 2.0.0-alpha.42 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
024dce2d6e
commit
5aada0b189
77 files changed
+25806
-29
No files matched your search
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* Examples of using enhanced memory features
|
||||
*/
|
||||
|
||||
import { enhancedMemory } from './enhanced-memory.js';
|
||||
|
||||
// Initialize enhanced memory
|
||||
await enhancedMemory.initialize();
|
||||
|
||||
// === 1. Session Management Example ===
|
||||
async function exampleSessionManagement() {
|
||||
console.log('\n=== Session Management ===');
|
||||
|
||||
// Save current session state
|
||||
const sessionId = `session-${Date.now()}`;
|
||||
await enhancedMemory.saveSessionState(sessionId, {
|
||||
state: 'active',
|
||||
context: {
|
||||
currentTask: 'Implementing authentication',
|
||||
openFiles: ['src/auth.js', 'src/middleware/auth.js'],
|
||||
cursorPositions: { 'src/auth.js': { line: 45, column: 12 } },
|
||||
activeAgents: ['AuthExpert', 'SecurityReviewer'],
|
||||
completedSteps: ['Design API', 'Create models'],
|
||||
nextSteps: ['Implement JWT', 'Add tests']
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Session saved:', sessionId);
|
||||
|
||||
// Later, resume the session
|
||||
const resumed = await enhancedMemory.resumeSession(sessionId);
|
||||
console.log('Resumed context:', resumed.context);
|
||||
}
|
||||
|
||||
// === 2. MCP Tool Usage Tracking ===
|
||||
async function exampleToolTracking() {
|
||||
console.log('\n=== Tool Usage Tracking ===');
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
// Track a successful tool usage
|
||||
await enhancedMemory.trackToolUsage(
|
||||
'memory_usage',
|
||||
{ action: 'store', key: 'test', value: 'data' },
|
||||
{ success: true, stored: true },
|
||||
Date.now() - startTime,
|
||||
true
|
||||
);
|
||||
|
||||
// Track a failed tool usage
|
||||
await enhancedMemory.trackToolUsage(
|
||||
'swarm_init',
|
||||
{ topology: 'invalid' },
|
||||
null,
|
||||
150,
|
||||
false,
|
||||
'Invalid topology specified'
|
||||
);
|
||||
|
||||
// Get tool statistics
|
||||
const stats = await enhancedMemory.getToolStats();
|
||||
console.log('Tool effectiveness:', stats);
|
||||
}
|
||||
|
||||
// === 3. Training Data Collection ===
|
||||
async function exampleTrainingData() {
|
||||
console.log('\n=== Training Data ===');
|
||||
|
||||
// Record a successful code fix
|
||||
await enhancedMemory.recordTrainingExample(
|
||||
'error_fix',
|
||||
{
|
||||
error: 'TypeError: Cannot read property of undefined',
|
||||
code: 'const result = user.profile.name;',
|
||||
context: 'User object might be null'
|
||||
},
|
||||
{
|
||||
fix: 'const result = user?.profile?.name || "Anonymous";',
|
||||
explanation: 'Added optional chaining and default value'
|
||||
},
|
||||
{
|
||||
errorResolved: true,
|
||||
testsPass: true
|
||||
},
|
||||
0.95,
|
||||
'Good defensive programming practice'
|
||||
);
|
||||
|
||||
// Get training examples
|
||||
const examples = await enhancedMemory.getTrainingData('error_fix', 5);
|
||||
console.log('Training examples:', examples.length);
|
||||
}
|
||||
|
||||
// === 4. Code Pattern Recognition ===
|
||||
async function exampleCodePatterns() {
|
||||
console.log('\n=== Code Patterns ===');
|
||||
|
||||
// Record a frequently used pattern
|
||||
await enhancedMemory.recordCodePattern(
|
||||
'src/utils/api.js',
|
||||
'error_handler',
|
||||
`
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(\`HTTP \${response.status}\`);
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('API Error:', error);
|
||||
throw new ApiError(error.message, error.status);
|
||||
}
|
||||
`,
|
||||
'javascript'
|
||||
);
|
||||
|
||||
// Find similar patterns
|
||||
const patterns = await enhancedMemory.findSimilarPatterns('javascript', 5);
|
||||
console.log('Found patterns:', patterns.map(p => p.pattern_name));
|
||||
}
|
||||
|
||||
// === 5. Agent Collaboration ===
|
||||
async function exampleAgentCollaboration() {
|
||||
console.log('\n=== Agent Collaboration ===');
|
||||
|
||||
const taskId = 'task-auth-001';
|
||||
|
||||
// Record agent interactions
|
||||
await enhancedMemory.recordAgentInteraction(
|
||||
'Coordinator',
|
||||
'AuthExpert',
|
||||
'request',
|
||||
{ action: 'design', component: 'JWT middleware' },
|
||||
taskId
|
||||
);
|
||||
|
||||
await enhancedMemory.recordAgentInteraction(
|
||||
'AuthExpert',
|
||||
'Coordinator',
|
||||
'response',
|
||||
{
|
||||
design: 'JWT with refresh tokens',
|
||||
estimatedTime: '2 hours',
|
||||
dependencies: ['jsonwebtoken', 'bcrypt']
|
||||
},
|
||||
taskId
|
||||
);
|
||||
|
||||
// Get conversation history
|
||||
const conversation = await enhancedMemory.getAgentConversation(taskId);
|
||||
console.log('Agent conversation:', conversation.length, 'messages');
|
||||
}
|
||||
|
||||
// === 6. Knowledge Graph ===
|
||||
async function exampleKnowledgeGraph() {
|
||||
console.log('\n=== Knowledge Graph ===');
|
||||
|
||||
// Add entities and relationships
|
||||
await enhancedMemory.addKnowledgeEntity(
|
||||
'module',
|
||||
'AuthModule',
|
||||
'src/auth/index.js',
|
||||
['UserModel', 'JWTService', 'AuthMiddleware'],
|
||||
{
|
||||
exports: ['authenticate', 'authorize', 'refreshToken'],
|
||||
dependencies: 4,
|
||||
complexity: 'medium'
|
||||
}
|
||||
);
|
||||
|
||||
await enhancedMemory.addKnowledgeEntity(
|
||||
'service',
|
||||
'JWTService',
|
||||
'src/auth/jwt.service.js',
|
||||
['AuthModule', 'ConfigService'],
|
||||
{
|
||||
methods: ['sign', 'verify', 'decode'],
|
||||
tokenExpiry: '1h'
|
||||
}
|
||||
);
|
||||
|
||||
// Find related entities
|
||||
const related = await enhancedMemory.findRelatedEntities('AuthModule');
|
||||
console.log('Related entities:', related.map(e => e.entity_name));
|
||||
}
|
||||
|
||||
// === 7. Error Learning ===
|
||||
async function exampleErrorLearning() {
|
||||
console.log('\n=== Error Learning ===');
|
||||
|
||||
// Record an error and its resolution
|
||||
await enhancedMemory.recordError(
|
||||
'DatabaseError',
|
||||
'Connection timeout',
|
||||
'at Database.connect (db.js:45)',
|
||||
{
|
||||
operation: 'startup',
|
||||
config: { host: 'localhost', port: 5432 }
|
||||
},
|
||||
'Increased connection timeout to 30s and added retry logic'
|
||||
);
|
||||
|
||||
// Later, get solutions for similar errors
|
||||
const solutions = await enhancedMemory.getErrorSolutions('DatabaseError');
|
||||
console.log('Known solutions:', solutions.map(s => s.resolution));
|
||||
}
|
||||
|
||||
// === 8. Performance Monitoring ===
|
||||
async function examplePerformanceTracking() {
|
||||
console.log('\n=== Performance Tracking ===');
|
||||
|
||||
// Record performance metrics
|
||||
await enhancedMemory.recordPerformance(
|
||||
'file_analysis',
|
||||
{ files: 150, totalSize: '45MB' },
|
||||
3420, // duration in ms
|
||||
125.5, // memory in MB
|
||||
45.2 // CPU %
|
||||
);
|
||||
|
||||
// Get performance trends
|
||||
const trends = await enhancedMemory.getPerformanceTrends('file_analysis', 7);
|
||||
console.log('Performance trends:', trends);
|
||||
}
|
||||
|
||||
// === 9. User Preference Learning ===
|
||||
async function examplePreferenceLearning() {
|
||||
console.log('\n=== Preference Learning ===');
|
||||
|
||||
// Learn from user actions
|
||||
await enhancedMemory.learnPreference(
|
||||
'indent_style',
|
||||
'spaces',
|
||||
'coding_style',
|
||||
'inferred',
|
||||
0.95 // high confidence based on consistent usage
|
||||
);
|
||||
|
||||
await enhancedMemory.learnPreference(
|
||||
'test_framework',
|
||||
'jest',
|
||||
'tool_usage',
|
||||
'explicit',
|
||||
1.0 // user explicitly stated preference
|
||||
);
|
||||
|
||||
// Get learned preferences
|
||||
const codingPrefs = await enhancedMemory.getPreferences('coding_style');
|
||||
console.log('Coding preferences:', codingPrefs);
|
||||
}
|
||||
|
||||
// === 10. Comprehensive Session Export ===
|
||||
async function exampleSessionExport() {
|
||||
console.log('\n=== Session Export ===');
|
||||
|
||||
const sessionId = 'session-example';
|
||||
const exportData = await enhancedMemory.exportSessionData(sessionId);
|
||||
|
||||
console.log('Exported data includes:');
|
||||
console.log('- Session state:', exportData.session ? 'Yes' : 'No');
|
||||
console.log('- Tool usage:', exportData.tools.length, 'records');
|
||||
console.log('- Performance:', exportData.performance.length, 'benchmarks');
|
||||
console.log('- Interactions:', exportData.interactions.length, 'messages');
|
||||
}
|
||||
|
||||
// Run all examples
|
||||
async function runAllExamples() {
|
||||
await exampleSessionManagement();
|
||||
await exampleToolTracking();
|
||||
await exampleTrainingData();
|
||||
await exampleCodePatterns();
|
||||
await exampleAgentCollaboration();
|
||||
await exampleKnowledgeGraph();
|
||||
await exampleErrorLearning();
|
||||
await examplePerformanceTracking();
|
||||
await examplePreferenceLearning();
|
||||
await exampleSessionExport();
|
||||
|
||||
// Show database statistics
|
||||
const stats = await enhancedMemory.getDatabaseStats();
|
||||
console.log('\n=== Database Statistics ===');
|
||||
console.log(stats);
|
||||
|
||||
enhancedMemory.close();
|
||||
}
|
||||
|
||||
// Export for testing
|
||||
export {
|
||||
exampleSessionManagement,
|
||||
exampleToolTracking,
|
||||
exampleTrainingData,
|
||||
exampleCodePatterns,
|
||||
exampleAgentCollaboration,
|
||||
exampleKnowledgeGraph,
|
||||
exampleErrorLearning,
|
||||
examplePerformanceTracking,
|
||||
examplePreferenceLearning,
|
||||
exampleSessionExport,
|
||||
runAllExamples
|
||||
};
|
||||
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* Enhanced Memory Functions for Comprehensive Swarm Coordination
|
||||
*/
|
||||
|
||||
import { SqliteMemoryStore } from './sqlite-store.js';
|
||||
|
||||
export class EnhancedMemory extends SqliteMemoryStore {
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
await super.initialize();
|
||||
// Apply enhanced schema
|
||||
try {
|
||||
const { readFileSync } = await import('fs');
|
||||
const schemaPath = new URL('./enhanced-schema.sql', import.meta.url);
|
||||
const schema = readFileSync(schemaPath, 'utf-8');
|
||||
this.db.exec(schema);
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [enhanced-memory] Failed to apply enhanced schema:`, error);
|
||||
// Continue with basic schema only
|
||||
}
|
||||
}
|
||||
|
||||
// === SESSION MANAGEMENT ===
|
||||
|
||||
async saveSessionState(sessionId, state) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO session_state
|
||||
(session_id, user_id, project_path, active_branch, last_activity, state, context, environment)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
sessionId,
|
||||
state.userId || process.env.USER,
|
||||
state.projectPath || process.cwd(),
|
||||
state.activeBranch || 'main',
|
||||
Date.now(),
|
||||
state.state || 'active',
|
||||
JSON.stringify(state.context || {}),
|
||||
JSON.stringify(state.environment || process.env)
|
||||
);
|
||||
}
|
||||
|
||||
async resumeSession(sessionId) {
|
||||
const stmt = this.db.prepare('SELECT * FROM session_state WHERE session_id = ?');
|
||||
const session = stmt.get(sessionId);
|
||||
if (session) {
|
||||
session.context = JSON.parse(session.context);
|
||||
session.environment = JSON.parse(session.environment);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
async getActiveSessions() {
|
||||
const stmt = this.db.prepare('SELECT * FROM active_sessions');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
// === MCP TOOL TRACKING ===
|
||||
|
||||
async trackToolUsage(toolName, args, result, executionTime, success = true, error = null) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO mcp_tool_usage
|
||||
(tool_name, session_id, arguments, result_summary, execution_time_ms, success, error_message)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
toolName,
|
||||
this.currentSessionId,
|
||||
JSON.stringify(args),
|
||||
result ? JSON.stringify(result).substring(0, 500) : null,
|
||||
executionTime,
|
||||
success ? 1 : 0,
|
||||
error
|
||||
);
|
||||
}
|
||||
|
||||
async getToolStats() {
|
||||
const stmt = this.db.prepare('SELECT * FROM tool_effectiveness');
|
||||
return stmt.all();
|
||||
}
|
||||
|
||||
// === TRAINING DATA ===
|
||||
|
||||
async recordTrainingExample(patternType, inputContext, actionTaken, outcome, score, feedback = null) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO training_data
|
||||
(pattern_type, input_context, action_taken, outcome, success_score, model_version, feedback)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
patternType,
|
||||
JSON.stringify(inputContext),
|
||||
JSON.stringify(actionTaken),
|
||||
JSON.stringify(outcome),
|
||||
score,
|
||||
this.modelVersion || '1.0',
|
||||
feedback
|
||||
);
|
||||
}
|
||||
|
||||
async getTrainingData(patternType, limit = 100) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM training_data
|
||||
WHERE pattern_type = ?
|
||||
ORDER BY success_score DESC, timestamp DESC
|
||||
LIMIT ?
|
||||
`);
|
||||
return stmt.all(patternType, limit);
|
||||
}
|
||||
|
||||
// === CODE PATTERNS ===
|
||||
|
||||
async recordCodePattern(filePath, patternName, content, language) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO code_patterns (file_path, pattern_name, pattern_content, language, last_used)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(file_path, pattern_name) DO UPDATE SET
|
||||
frequency = frequency + 1,
|
||||
last_used = ?
|
||||
`);
|
||||
|
||||
const now = Date.now();
|
||||
return stmt.run(filePath, patternName, content, language, now, now);
|
||||
}
|
||||
|
||||
async findSimilarPatterns(language, limit = 10) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM code_patterns
|
||||
WHERE language = ?
|
||||
ORDER BY effectiveness_score DESC, frequency DESC
|
||||
LIMIT ?
|
||||
`);
|
||||
return stmt.all(language, limit);
|
||||
}
|
||||
|
||||
// === AGENT COLLABORATION ===
|
||||
|
||||
async recordAgentInteraction(sourceAgent, targetAgent, messageType, content, taskId) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO agent_interactions
|
||||
(source_agent, target_agent, message_type, content, task_id, correlation_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const correlationId = `${taskId}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
return stmt.run(sourceAgent, targetAgent, messageType, JSON.stringify(content), taskId, correlationId);
|
||||
}
|
||||
|
||||
async getAgentConversation(taskId) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM agent_interactions
|
||||
WHERE task_id = ?
|
||||
ORDER BY timestamp ASC
|
||||
`);
|
||||
return stmt.all(taskId);
|
||||
}
|
||||
|
||||
// === KNOWLEDGE GRAPH ===
|
||||
|
||||
async addKnowledgeEntity(entityType, entityName, entityPath, relationships = [], metadata = {}) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO knowledge_graph
|
||||
(entity_type, entity_name, entity_path, relationships, metadata, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
entityType,
|
||||
entityName,
|
||||
entityPath,
|
||||
JSON.stringify(relationships),
|
||||
JSON.stringify(metadata),
|
||||
Date.now()
|
||||
);
|
||||
}
|
||||
|
||||
async findRelatedEntities(entityName, depth = 1) {
|
||||
// Simple implementation - could be enhanced with recursive CTEs
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM knowledge_graph
|
||||
WHERE entity_name = ? OR relationships LIKE ?
|
||||
`);
|
||||
return stmt.all(entityName, `%"${entityName}"%`);
|
||||
}
|
||||
|
||||
// === ERROR LEARNING ===
|
||||
|
||||
async recordError(errorType, errorMessage, stackTrace, context, resolution = null) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO error_patterns
|
||||
(error_type, error_message, stack_trace, context, resolution)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(error_type, error_message) DO UPDATE SET
|
||||
occurrence_count = occurrence_count + 1,
|
||||
last_seen = strftime('%s', 'now'),
|
||||
resolution = COALESCE(?, resolution)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
errorType,
|
||||
errorMessage,
|
||||
stackTrace,
|
||||
JSON.stringify(context),
|
||||
resolution,
|
||||
resolution
|
||||
);
|
||||
}
|
||||
|
||||
async getErrorSolutions(errorType) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM error_patterns
|
||||
WHERE error_type = ? AND resolution IS NOT NULL
|
||||
ORDER BY occurrence_count DESC
|
||||
`);
|
||||
return stmt.all(errorType);
|
||||
}
|
||||
|
||||
// === TASK DEPENDENCIES ===
|
||||
|
||||
async addTaskDependency(taskId, dependsOn, dependencyType = 'blocking') {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO task_dependencies
|
||||
(task_id, depends_on, dependency_type, status)
|
||||
VALUES (?, ?, ?, 'pending')
|
||||
`);
|
||||
|
||||
return stmt.run(taskId, dependsOn, dependencyType);
|
||||
}
|
||||
|
||||
async updateDependencyStatus(taskId, dependsOn, status) {
|
||||
const stmt = this.db.prepare(`
|
||||
UPDATE task_dependencies
|
||||
SET status = ?
|
||||
WHERE task_id = ? AND depends_on = ?
|
||||
`);
|
||||
|
||||
return stmt.run(status, taskId, dependsOn);
|
||||
}
|
||||
|
||||
async getTaskDependencies(taskId) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM task_dependencies
|
||||
WHERE task_id = ?
|
||||
`);
|
||||
return stmt.all(taskId);
|
||||
}
|
||||
|
||||
// === PERFORMANCE TRACKING ===
|
||||
|
||||
async recordPerformance(operationType, details, duration, memoryUsed, cpuPercent) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT INTO performance_benchmarks
|
||||
(operation_type, operation_details, duration_ms, memory_used_mb, cpu_percent, session_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(
|
||||
operationType,
|
||||
JSON.stringify(details),
|
||||
duration,
|
||||
memoryUsed,
|
||||
cpuPercent,
|
||||
this.currentSessionId
|
||||
);
|
||||
}
|
||||
|
||||
async getPerformanceTrends(operationType, days = 7) {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT DATE(timestamp, 'unixepoch') as date,
|
||||
AVG(duration_ms) as avg_duration,
|
||||
AVG(memory_used_mb) as avg_memory,
|
||||
COUNT(*) as operation_count
|
||||
FROM performance_benchmarks
|
||||
WHERE operation_type = ?
|
||||
AND timestamp > strftime('%s', 'now', '-' || ? || ' days')
|
||||
GROUP BY date
|
||||
ORDER BY date DESC
|
||||
`);
|
||||
return stmt.all(operationType, days);
|
||||
}
|
||||
|
||||
// === USER PREFERENCES ===
|
||||
|
||||
async learnPreference(key, value, category, source = 'inferred', confidence = 0.8) {
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO user_preferences
|
||||
(preference_key, preference_value, category, learned_from, confidence_score)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
return stmt.run(key, value, category, source, confidence);
|
||||
}
|
||||
|
||||
async getPreferences(category = null) {
|
||||
if (category) {
|
||||
const stmt = this.db.prepare('SELECT * FROM user_preferences WHERE category = ?');
|
||||
return stmt.all(category);
|
||||
} else {
|
||||
const stmt = this.db.prepare('SELECT * FROM user_preferences');
|
||||
return stmt.all();
|
||||
}
|
||||
}
|
||||
|
||||
// === UTILITY METHODS ===
|
||||
|
||||
async getDatabaseStats() {
|
||||
const tables = [
|
||||
'memory_entries', 'session_state', 'mcp_tool_usage', 'training_data',
|
||||
'code_patterns', 'agent_interactions', 'knowledge_graph', 'error_patterns',
|
||||
'task_dependencies', 'performance_benchmarks', 'user_preferences'
|
||||
];
|
||||
|
||||
const stats = {};
|
||||
for (const table of tables) {
|
||||
try {
|
||||
const result = this.db.prepare(`SELECT COUNT(*) as count FROM ${table}`).get();
|
||||
stats[table] = result.count;
|
||||
} catch (e) {
|
||||
stats[table] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
async exportSessionData(sessionId) {
|
||||
const data = {
|
||||
session: await this.resumeSession(sessionId),
|
||||
tools: this.db.prepare('SELECT * FROM mcp_tool_usage WHERE session_id = ?').all(sessionId),
|
||||
performance: this.db.prepare('SELECT * FROM performance_benchmarks WHERE session_id = ?').all(sessionId),
|
||||
interactions: this.db.prepare('SELECT * FROM agent_interactions WHERE correlation_id LIKE ?').all(`${sessionId}%`),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
export const enhancedMemory = new EnhancedMemory();
|
||||
|
||||
export default EnhancedMemory;
|
||||
@@ -0,0 +1,154 @@
|
||||
-- Enhanced SQLite Schema for .swarm/memory.db
|
||||
-- Additional tables for comprehensive swarm coordination
|
||||
|
||||
-- 1. Session Management (for resuming work)
|
||||
CREATE TABLE IF NOT EXISTS session_state (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
user_id TEXT,
|
||||
project_path TEXT,
|
||||
active_branch TEXT,
|
||||
last_activity INTEGER,
|
||||
state TEXT, -- active, paused, completed
|
||||
context TEXT, -- JSON with current task, open files, cursor positions
|
||||
environment TEXT -- JSON with env vars, tool versions
|
||||
);
|
||||
|
||||
-- 2. MCP Tool Usage Analytics
|
||||
CREATE TABLE IF NOT EXISTS mcp_tool_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tool_name TEXT NOT NULL,
|
||||
session_id TEXT,
|
||||
timestamp INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
arguments TEXT, -- JSON
|
||||
result_summary TEXT,
|
||||
execution_time_ms INTEGER,
|
||||
success BOOLEAN,
|
||||
error_message TEXT
|
||||
);
|
||||
|
||||
-- 3. Training Data for Neural Patterns
|
||||
CREATE TABLE IF NOT EXISTS training_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pattern_type TEXT, -- code_style, error_fix, refactor, etc
|
||||
input_context TEXT,
|
||||
action_taken TEXT,
|
||||
outcome TEXT,
|
||||
success_score REAL,
|
||||
timestamp INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
model_version TEXT,
|
||||
feedback TEXT -- user feedback if provided
|
||||
);
|
||||
|
||||
-- 4. Code Context and Patterns
|
||||
CREATE TABLE IF NOT EXISTS code_patterns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_path TEXT,
|
||||
pattern_name TEXT,
|
||||
pattern_content TEXT,
|
||||
language TEXT,
|
||||
frequency INTEGER DEFAULT 1,
|
||||
last_used INTEGER,
|
||||
effectiveness_score REAL,
|
||||
UNIQUE(file_path, pattern_name)
|
||||
);
|
||||
|
||||
-- 5. Agent Collaboration History
|
||||
CREATE TABLE IF NOT EXISTS agent_interactions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_agent TEXT,
|
||||
target_agent TEXT,
|
||||
message_type TEXT, -- request, response, broadcast
|
||||
content TEXT,
|
||||
task_id TEXT,
|
||||
timestamp INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
correlation_id TEXT
|
||||
);
|
||||
|
||||
-- 6. Project Knowledge Graph
|
||||
CREATE TABLE IF NOT EXISTS knowledge_graph (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
entity_type TEXT, -- file, function, class, module, concept
|
||||
entity_name TEXT,
|
||||
entity_path TEXT,
|
||||
relationships TEXT, -- JSON array of related entities
|
||||
metadata TEXT, -- JSON with additional info
|
||||
embedding BLOB, -- Vector embedding for similarity search
|
||||
created_at INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
updated_at INTEGER DEFAULT (strftime('%s', 'now'))
|
||||
);
|
||||
|
||||
-- 7. Error Recovery and Learning
|
||||
CREATE TABLE IF NOT EXISTS error_patterns (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
error_type TEXT,
|
||||
error_message TEXT,
|
||||
stack_trace TEXT,
|
||||
context TEXT, -- What was being attempted
|
||||
resolution TEXT, -- How it was fixed
|
||||
prevention_strategy TEXT,
|
||||
occurrence_count INTEGER DEFAULT 1,
|
||||
last_seen INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
UNIQUE(error_type, error_message)
|
||||
);
|
||||
|
||||
-- 8. Task Dependencies and Flow
|
||||
CREATE TABLE IF NOT EXISTS task_dependencies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id TEXT,
|
||||
depends_on TEXT, -- task_id of dependency
|
||||
dependency_type TEXT, -- blocking, optional, parallel
|
||||
status TEXT, -- pending, satisfied, failed
|
||||
created_at INTEGER DEFAULT (strftime('%s', 'now'))
|
||||
);
|
||||
|
||||
-- 9. Performance Benchmarks
|
||||
CREATE TABLE IF NOT EXISTS performance_benchmarks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
operation_type TEXT,
|
||||
operation_details TEXT,
|
||||
duration_ms INTEGER,
|
||||
memory_used_mb REAL,
|
||||
cpu_percent REAL,
|
||||
timestamp INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
session_id TEXT,
|
||||
optimization_applied TEXT
|
||||
);
|
||||
|
||||
-- 10. User Preferences and Learning
|
||||
CREATE TABLE IF NOT EXISTS user_preferences (
|
||||
preference_key TEXT PRIMARY KEY,
|
||||
preference_value TEXT,
|
||||
category TEXT, -- coding_style, tool_usage, communication
|
||||
learned_from TEXT, -- explicit, inferred
|
||||
confidence_score REAL,
|
||||
last_updated INTEGER DEFAULT (strftime('%s', 'now'))
|
||||
);
|
||||
|
||||
-- Indexes for performance
|
||||
CREATE INDEX IF NOT EXISTS idx_session_activity ON session_state(last_activity);
|
||||
CREATE INDEX IF NOT EXISTS idx_mcp_tool_timestamp ON mcp_tool_usage(timestamp);
|
||||
CREATE INDEX IF NOT EXISTS idx_training_pattern ON training_data(pattern_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_task ON agent_interactions(task_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_knowledge_type ON knowledge_graph(entity_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_error_type ON error_patterns(error_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_deps ON task_dependencies(task_id);
|
||||
|
||||
-- Views for common queries
|
||||
CREATE VIEW IF NOT EXISTS active_sessions AS
|
||||
SELECT * FROM session_state
|
||||
WHERE state = 'active'
|
||||
ORDER BY last_activity DESC;
|
||||
|
||||
CREATE VIEW IF NOT EXISTS frequent_errors AS
|
||||
SELECT error_type, error_message, occurrence_count, resolution
|
||||
FROM error_patterns
|
||||
WHERE occurrence_count > 1
|
||||
ORDER BY occurrence_count DESC;
|
||||
|
||||
CREATE VIEW IF NOT EXISTS tool_effectiveness AS
|
||||
SELECT tool_name,
|
||||
COUNT(*) as usage_count,
|
||||
AVG(CASE WHEN success THEN 1 ELSE 0 END) * 100 as success_rate,
|
||||
AVG(execution_time_ms) as avg_time_ms
|
||||
FROM mcp_tool_usage
|
||||
GROUP BY tool_name;
|
||||
+4
-2
@@ -6,8 +6,10 @@
|
||||
* @module memory
|
||||
*/
|
||||
|
||||
export { SharedMemory } from './shared-memory.js';
|
||||
export { SwarmMemory, createSwarmMemory } from './swarm-memory.js';
|
||||
import SharedMemory from './shared-memory.js';
|
||||
import { SwarmMemory, createSwarmMemory } from './swarm-memory.js';
|
||||
|
||||
export { SharedMemory, SwarmMemory, createSwarmMemory };
|
||||
|
||||
// Re-export swarm namespaces for convenience
|
||||
export const SWARM_NAMESPACES = {
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* SQLite-based memory store for MCP server
|
||||
* Provides persistent storage that works with both local and remote npx execution
|
||||
*/
|
||||
|
||||
// @ts-ignore
|
||||
import Database from 'better-sqlite3';
|
||||
import path from 'path';
|
||||
import { promises as fs } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import os from 'os';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
class SqliteMemoryStore {
|
||||
constructor(options = {}) {
|
||||
this.options = {
|
||||
dbName: options.dbName || 'memory.db',
|
||||
directory: options.directory || this._getMemoryDirectory(),
|
||||
...options
|
||||
};
|
||||
|
||||
this.db = null;
|
||||
this.statements = new Map();
|
||||
this.isInitialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the best directory for memory storage
|
||||
* Uses .swarm directory in current working directory (consistent with hive-mind approach)
|
||||
*/
|
||||
_getMemoryDirectory() {
|
||||
// Always use .swarm directory in the current working directory
|
||||
// This ensures consistency whether running locally or via npx
|
||||
return path.join(process.cwd(), '.swarm');
|
||||
}
|
||||
|
||||
_directoryExists(dir) {
|
||||
try {
|
||||
const stats = require('fs').statSync(dir);
|
||||
return stats.isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
if (this.isInitialized) return;
|
||||
|
||||
try {
|
||||
// Ensure directory exists
|
||||
await fs.mkdir(this.options.directory, { recursive: true });
|
||||
|
||||
// Open database
|
||||
const dbPath = path.join(this.options.directory, this.options.dbName);
|
||||
this.db = new Database(dbPath);
|
||||
|
||||
// Enable WAL mode for better concurrency
|
||||
this.db.pragma('journal_mode = WAL');
|
||||
this.db.pragma('synchronous = NORMAL');
|
||||
|
||||
// Create tables
|
||||
this._createTables();
|
||||
|
||||
// Prepare statements
|
||||
this._prepareStatements();
|
||||
|
||||
this.isInitialized = true;
|
||||
|
||||
console.error(`[${new Date().toISOString()}] INFO [memory-store] Initialized SQLite at: ${dbPath}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Failed to initialize:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
_createTables() {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS memory_entries (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
namespace TEXT NOT NULL DEFAULT 'default',
|
||||
metadata TEXT,
|
||||
created_at INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
updated_at INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
accessed_at INTEGER DEFAULT (strftime('%s', 'now')),
|
||||
access_count INTEGER DEFAULT 0,
|
||||
ttl INTEGER,
|
||||
expires_at INTEGER,
|
||||
UNIQUE(key, namespace)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_memory_namespace ON memory_entries(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_memory_expires ON memory_entries(expires_at) WHERE expires_at IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_memory_accessed ON memory_entries(accessed_at);
|
||||
`);
|
||||
}
|
||||
|
||||
_prepareStatements() {
|
||||
// Store/update statement
|
||||
this.statements.set('upsert', this.db.prepare(`
|
||||
INSERT INTO memory_entries (key, value, namespace, metadata, ttl, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(key, namespace) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
metadata = excluded.metadata,
|
||||
ttl = excluded.ttl,
|
||||
expires_at = excluded.expires_at,
|
||||
updated_at = strftime('%s', 'now'),
|
||||
access_count = memory_entries.access_count + 1
|
||||
`));
|
||||
|
||||
// Retrieve statement
|
||||
this.statements.set('get', this.db.prepare(`
|
||||
SELECT * FROM memory_entries
|
||||
WHERE key = ? AND namespace = ? AND (expires_at IS NULL OR expires_at > strftime('%s', 'now'))
|
||||
`));
|
||||
|
||||
// List statement
|
||||
this.statements.set('list', this.db.prepare(`
|
||||
SELECT * FROM memory_entries
|
||||
WHERE namespace = ? AND (expires_at IS NULL OR expires_at > strftime('%s', 'now'))
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ?
|
||||
`));
|
||||
|
||||
// Delete statement
|
||||
this.statements.set('delete', this.db.prepare(`
|
||||
DELETE FROM memory_entries WHERE key = ? AND namespace = ?
|
||||
`));
|
||||
|
||||
// Search statement
|
||||
this.statements.set('search', this.db.prepare(`
|
||||
SELECT * FROM memory_entries
|
||||
WHERE namespace = ? AND (key LIKE ? OR value LIKE ?)
|
||||
AND (expires_at IS NULL OR expires_at > strftime('%s', 'now'))
|
||||
ORDER BY access_count DESC, updated_at DESC
|
||||
LIMIT ?
|
||||
`));
|
||||
|
||||
// Cleanup statement
|
||||
this.statements.set('cleanup', this.db.prepare(`
|
||||
DELETE FROM memory_entries WHERE expires_at IS NOT NULL AND expires_at <= strftime('%s', 'now')
|
||||
`));
|
||||
|
||||
// Update access statement
|
||||
this.statements.set('updateAccess', this.db.prepare(`
|
||||
UPDATE memory_entries
|
||||
SET accessed_at = strftime('%s', 'now'), access_count = access_count + 1
|
||||
WHERE key = ? AND namespace = ?
|
||||
`));
|
||||
}
|
||||
|
||||
async store(key, value, options = {}) {
|
||||
await this.initialize();
|
||||
|
||||
const namespace = options.namespace || 'default';
|
||||
const metadata = options.metadata ? JSON.stringify(options.metadata) : null;
|
||||
const ttl = options.ttl || null;
|
||||
const expiresAt = ttl ? Math.floor(Date.now() / 1000) + ttl : null;
|
||||
const valueStr = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
|
||||
try {
|
||||
const result = this.statements.get('upsert').run(
|
||||
key,
|
||||
valueStr,
|
||||
namespace,
|
||||
metadata,
|
||||
ttl,
|
||||
expiresAt
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
id: result.lastInsertRowid,
|
||||
size: valueStr.length
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Store failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async retrieve(key, options = {}) {
|
||||
await this.initialize();
|
||||
|
||||
const namespace = options.namespace || 'default';
|
||||
|
||||
try {
|
||||
const row = this.statements.get('get').get(key, namespace);
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Update access stats
|
||||
this.statements.get('updateAccess').run(key, namespace);
|
||||
|
||||
// Try to parse as JSON, fall back to raw string
|
||||
try {
|
||||
return JSON.parse(row.value);
|
||||
} catch {
|
||||
return row.value;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Retrieve failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async list(options = {}) {
|
||||
await this.initialize();
|
||||
|
||||
const namespace = options.namespace || 'default';
|
||||
const limit = options.limit || 100;
|
||||
|
||||
try {
|
||||
const rows = this.statements.get('list').all(namespace, limit);
|
||||
|
||||
return rows.map(row => ({
|
||||
key: row.key,
|
||||
value: this._tryParseJson(row.value),
|
||||
namespace: row.namespace,
|
||||
metadata: row.metadata ? JSON.parse(row.metadata) : null,
|
||||
createdAt: new Date(row.created_at * 1000),
|
||||
updatedAt: new Date(row.updated_at * 1000),
|
||||
accessCount: row.access_count
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] List failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async delete(key, options = {}) {
|
||||
await this.initialize();
|
||||
|
||||
const namespace = options.namespace || 'default';
|
||||
|
||||
try {
|
||||
const result = this.statements.get('delete').run(key, namespace);
|
||||
return result.changes > 0;
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Delete failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async search(pattern, options = {}) {
|
||||
await this.initialize();
|
||||
|
||||
const namespace = options.namespace || 'default';
|
||||
const limit = options.limit || 50;
|
||||
const searchPattern = `%${pattern}%`;
|
||||
|
||||
try {
|
||||
const rows = this.statements.get('search').all(
|
||||
namespace,
|
||||
searchPattern,
|
||||
searchPattern,
|
||||
limit
|
||||
);
|
||||
|
||||
return rows.map(row => ({
|
||||
key: row.key,
|
||||
value: this._tryParseJson(row.value),
|
||||
namespace: row.namespace,
|
||||
score: row.access_count,
|
||||
updatedAt: new Date(row.updated_at * 1000)
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Search failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async cleanup() {
|
||||
await this.initialize();
|
||||
|
||||
try {
|
||||
const result = this.statements.get('cleanup').run();
|
||||
return result.changes;
|
||||
} catch (error) {
|
||||
console.error(`[${new Date().toISOString()}] ERROR [memory-store] Cleanup failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
_tryParseJson(value) {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
if (this.db) {
|
||||
this.db.close();
|
||||
this.db = null;
|
||||
this.isInitialized = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export a singleton instance for MCP server
|
||||
export const memoryStore = new SqliteMemoryStore();
|
||||
|
||||
export { SqliteMemoryStore };
|
||||
export default SqliteMemoryStore;
|
||||
Reference in new issue
Block a user