π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat: bridge Claude Code auto-memory to AgentDB vector search (ADR-076)
Reuvena1df9dd7f125
diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjsindex 77a692add1..ff45ea468f 100644--- a/.claude/helpers/auto-memory-hook.mjs+++ b/.claude/helpers/auto-memory-hook.mjs@@ -255,6 +255,36 @@ async function doImport() {dim(`ββ Learning: ${config.learningBridge.enabled ? 'active' : 'disabled'}`);dim(`ββ Graph: ${config.memoryGraph.enabled ? 'active' : 'disabled'}`);dim(`ββ Agent scopes: ${config.agentScopes.enabled ? 'active' : 'disabled'}`);++ // Bridge to AgentDB: store entries with ONNX vector embeddings for semantic search+ let vectorized = 0;+ try {+ const cliDistPath = join(PROJECT_ROOT, 'v3/@claude-flow/cli/dist/src/memory/memory-initializer.js');+ if (existsSync(cliDistPath)) {+ const memInit = await import(`file://${cliDistPath}`);+ await memInit.initializeMemoryDatabase({ force: false, verbose: false });++ const entries = await backend.query({});+ for (const entry of entries) {+ if (!entry.content || entry.content.length < 10) continue;+ try {+ await memInit.storeEntry({+ key: entry.key || entry.id,+ value: entry.content,+ namespace: entry.namespace || 'auto-memory',+ generateEmbeddingFlag: true,+ });+ vectorized++;+ } catch { /* skip entries that fail to embed */ }+ }++ if (vectorized > 0) {+ success(`Vectorized ${vectorized} entries into AgentDB (ONNX 384-dim)`);+ }+ }+ } catch (vecErr) {+ dim(`AgentDB vectorization skipped: ${vecErr.message?.slice(0, 60)}`);+ }} catch (err) {dim(`Import failed (non-critical): ${err.message}`);}@@ -313,6 +343,21 @@ async function doSync() {// Curate MEMORY.md index with graph-aware orderingawait bridge.curateIndex();success('Curated MEMORY.md index');++ // Flush intelligence patterns to disk (SONA + ReasoningBank)+ try {+ const intPath = join(PROJECT_ROOT, 'v3/@claude-flow/cli/dist/src/memory/intelligence.js');+ if (existsSync(intPath)) {+ const intelligence = await import(`file://${intPath}`);+ if (intelligence.flushPatterns) {+ intelligence.flushPatterns();+ const stats = intelligence.getIntelligenceStats?.();+ if (stats && stats.patternsLearned > 0) {+ success(`Flushed ${stats.patternsLearned} learned patterns to disk`);+ }+ }+ }+ } catch { /* non-critical */ }} catch (err) {dim(`Sync failed (non-critical): ${err.message}`);}@@ -339,9 +384,158 @@ async function doStatus() {} catch { /* ignore */ }}+ // AgentDB vector status+ try {+ const dbPath = join(PROJECT_ROOT, '.claude-flow', 'memory', 'memory.db');+ const swarmDbPath = join(PROJECT_ROOT, '.swarm', 'memory.db');+ const hasDb = existsSync(dbPath) || existsSync(swarmDbPath);+ console.log(` AgentDB: ${hasDb ? 'β sql.js database exists' : 'βΈ Not initialized'}`);++ const intPath = join(PROJECT_ROOT, 'v3/@claude-flow/cli/dist/src/memory/intelligence.js');+ if (existsSync(intPath)) {+ const intelligence = await import(`file://${intPath}`);+ const stats = intelligence.getIntelligenceStats?.();+ if (stats) {+ console.log(` SONA: ${stats.sonaEnabled ? 'β Active' : 'βΈ Not initialized'}`);+ console.log(` Patterns: ${stats.patternsLearned} learned`);+ console.log(` Trajectories: ${stats.trajectoriesRecorded} recorded`);+ }+ }+ } catch { /* ignore */ }+console.log('');}+// ============================================================================+// Import ALL Claude Code memories from all projects into AgentDB+// ============================================================================++async function doImportAll() {+ log('Importing ALL Claude Code memories into AgentDB...');++ const { homedir } = await import('os');+ const { readdirSync } = await import('fs');+ const claudeProjectsDir = join(homedir(), '.claude', 'projects');++ if (!existsSync(claudeProjectsDir)) {+ dim('No Claude Code projects found at ' + claudeProjectsDir);+ return;+ }++ // Find all memory files across all projects+ const memoryFiles = [];+ try {+ const projects = readdirSync(claudeProjectsDir, { withFileTypes: true });+ for (const project of projects) {+ if (!project.isDirectory()) continue;+ const memDir = join(claudeProjectsDir, project.name, 'memory');+ if (!existsSync(memDir)) continue;+ const files = readdirSync(memDir).filter(f => f.endsWith('.md'));+ for (const file of files) {+ memoryFiles.push({+ path: join(memDir, file),+ project: project.name,+ file,+ });+ }+ }+ } catch (err) {+ dim('Error scanning projects: ' + err.message);+ return;+ }++ if (memoryFiles.length === 0) {+ dim('No memory files found');+ return;+ }++ log(`Found ${memoryFiles.length} memory files across ${new Set(memoryFiles.map(f => f.project)).size} projects`);++ // Load memory-initializer for vectorized storage+ let memInit = null;+ try {+ const cliDistPath = join(PROJECT_ROOT, 'v3/@claude-flow/cli/dist/src/memory/memory-initializer.js');+ if (existsSync(cliDistPath)) {+ memInit = await import(`file://${cliDistPath}`);+ await memInit.initializeMemoryDatabase({ force: false, verbose: false });+ }+ } catch (err) {+ dim('Memory initializer not available: ' + err.message?.slice(0, 60));+ }++ if (!memInit) {+ dim('Cannot vectorize without memory-initializer. Run: cd v3/@claude-flow/cli && npm run build');+ return;+ }++ let imported = 0;+ let skipped = 0;++ for (const memFile of memoryFiles) {+ try {+ const content = readFileSync(memFile.path, 'utf-8');++ // Parse YAML frontmatter + body+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);+ let name = memFile.file.replace('.md', '');+ let description = '';+ let type = 'auto-memory';+ let body = content;++ if (frontmatterMatch) {+ const yaml = frontmatterMatch[1];+ body = frontmatterMatch[2].trim();+ const nameMatch = yaml.match(/^name:\s*(.+)$/m);+ const descMatch = yaml.match(/^description:\s*(.+)$/m);+ const typeMatch = yaml.match(/^type:\s*(.+)$/m);+ if (nameMatch) name = nameMatch[1].trim();+ if (descMatch) description = descMatch[1].trim();+ if (typeMatch) type = typeMatch[1].trim();+ }++ // Split body into sections (## headers) for granular entries+ const sections = body.split(/^(?=## )/m).filter(s => s.trim().length > 20);++ if (sections.length === 0) {+ // Store whole file as one entry+ if (body.length > 10) {+ await memInit.storeEntry({+ key: `claude-memory:${memFile.project}:${name}`,+ value: body.slice(0, 4096),+ namespace: 'claude-memories',+ generateEmbeddingFlag: true,+ });+ imported++;+ }+ } else {+ // Store each section separately for better search granularity+ for (const section of sections) {+ const titleMatch = section.match(/^##\s+(.+)/);+ const sectionTitle = titleMatch ? titleMatch[1].trim() : name;+ const sectionBody = section.replace(/^##\s+.+\n/, '').trim();+ if (sectionBody.length < 10) continue;++ await memInit.storeEntry({+ key: `claude-memory:${memFile.project}:${name}:${sectionTitle.slice(0, 50)}`,+ value: sectionBody.slice(0, 4096),+ namespace: 'claude-memories',+ generateEmbeddingFlag: true,+ });+ imported++;+ }+ }++ dim(` β ${memFile.project}/${memFile.file} (${sections.length || 1} entries)`);+ } catch (err) {+ dim(` β ${memFile.project}/${memFile.file}: ${err.message?.slice(0, 60)}`);+ skipped++;+ }+ }++ success(`Imported ${imported} entries from ${memoryFiles.length} files (${skipped} skipped)`);+ success('All Claude Code memories now searchable via AgentDB vector search');+}+// ============================================================================// Main// ============================================================================@@ -355,6 +549,7 @@ process.on('unhandledRejection', () => {});try {switch (command) {case 'import': await doImport(); break;+ case 'import-all': await doImportAll(); break;case 'sync': await doSync(); break;case 'status': await doStatus(); break;default:diff --git a/v3/implementation/adrs/ADR-076-claude-code-memory-bridge.md b/v3/implementation/adrs/ADR-076-claude-code-memory-bridge.mdnew file mode 100644index 0000000000..fc31e11535--- /dev/null+++ b/v3/implementation/adrs/ADR-076-claude-code-memory-bridge.md@@ -0,0 +1,67 @@+# ADR-076: Bridge Claude Code Auto-Memory to AgentDB Vector Search++**Status**: Implemented+**Date**: 2026-04-07+**Branch**: `feat/claude-code-memory-bridge`+**Related**: ADR-048 (AutoMemoryBridge), ADR-075 (learning pipeline)++## Context++Claude Code's auto-memory system stores project knowledge in `~/.claude/projects/*/memory/MEMORY.md` files with YAML frontmatter. Ruflo's AgentDB stores data in sql.js with ONNX embeddings (all-MiniLM-L6-v2, 384d) for semantic vector search. These two systems were disconnected β data in one was invisible to the other.++The `auto-memory-hook.mjs` (SessionStart/SessionEnd) imported MEMORY.md entries into a flat JSON file (`auto-memory-store.json`) but never vectorized them. AgentDB's intelligence module (SONA, ReasoningBank) learned patterns but never fed them back to Claude Code's memory.++## Decision++Wire bidirectional bridge between Claude Code auto-memory and AgentDB:++### SessionStart (import)+1. `AutoMemoryBridge.importFromAutoMemory()` reads MEMORY.md files β JSON backend (existing)+2. **NEW**: Each imported entry gets stored into sql.js via `memory-initializer.storeEntry()` with `generateEmbeddingFlag: true` β ONNX 384-dim vector generated+3. Entries become searchable via AgentDB's semantic vector search++### SessionEnd (sync)+1. `AutoMemoryBridge.syncToAutoMemory()` writes insights back to MEMORY.md (existing)+2. **NEW**: `intelligence.flushPatterns()` persists SONA/ReasoningBank learned patterns to disk+3. Patterns survive across sessions++## Architecture++```+Claude Code Auto-Memory AgentDB (sql.js + ONNX)+~/.claude/projects/*/memory/*.md .swarm/memory.db+ β β²+ β SessionStart hook β+ βΌ β+auto-memory-hook.mjs βββ import βββΊ JSON store βββΊβ storeEntry()+ β (flat) β + generateEmbedding()+ β β β 384-dim ONNX vector+ β SessionEnd hook β+ βΌ β+auto-memory-hook.mjs βββ sync ββββΊ MEMORY.md β+ β β+ βββ flushPatterns() ββββββββββββββββββββββ+ Intelligence module+ (SONA + ReasoningBank)+```++## What This Enables++| Before | After |+|--------|-------|+| MEMORY.md searchable by keyword only | MEMORY.md entries searchable by semantic similarity |+| AgentDB can't see Claude Code memories | AgentDB indexes all auto-memory entries with vectors |+| Learned patterns lost between sessions | SONA/ReasoningBank patterns flushed to disk on session end |+| Two disconnected stores | Single query searches both stores |++## Files Changed++- `.claude/helpers/auto-memory-hook.mjs` β vectorization bridge + pattern flush+- `v3/implementation/adrs/ADR-076-claude-code-memory-bridge.md` β this ADR++## References++- [ruDevolution](https://github.com/ruvnet/rudevolution) β Claude Code internals analysis+- Research doc: `07-context-and-session-management.md` β auto-memory paths and env vars+- ADR-048: AutoMemoryBridge design+- ADR-075: Self-learning pipeline wiring