src — memory

Module: src-memory Cohesion: 0.80 Members: 0

src — memory

The src/memory module is the brain of the Code Buddy agent, providing a sophisticated, multi-layered system for storing, recalling, and learning from information. It encompasses various memory types, from short-term conversational context to long-term, semantically searchable knowledge, and even specialized memories for code style, decisions, and tasks.

This documentation outlines the purpose, architecture, and key components of the memory system, detailing how they interact to enable intelligent and context-aware agent behavior.

Memory System Overview

The memory system is designed to allow Code Buddy to:

At its core, the system leverages a combination of structured and unstructured storage, semantic embeddings for advanced retrieval, and various specialized modules for different types of knowledge.

High-Level Architecture

The following diagram illustrates the primary data flows and interactions between the core memory components:

graph TD
    subgraph Agent Interaction
        A[User Input] --> B(AutoCaptureManager)
        C[LLM Output] --> D(DecisionMemory)
        E[File Changes] --> F(CodingStyleAnalyzer)
    end

    subgraph Core Memory Systems
        B --> G(EnhancedMemory)
        D --> G
        F --> G
        G -- Entities/Relations --> H(KnowledgeGraph)
        I(Tasks/Goals) --> J(ProspectiveMemory)
    end

    subgraph Specialized Search
        K[Image Input] --> L(OCRMemoryPipeline)
        L -- Embeddings --> M(CrossModalSearch)
        G -- Embeddings --> M
        G -- Text Search --> N(HybridMemorySearch)
    end

    subgraph Integration
        O(Agent Runtime) --> P(MemoryLifecycleHooks)
        P -- Access/Update --> G
        P -- Access/Update --> J
        Q(External ICM) --> R(ICMBridge)
        R --> G
    end

Core Memory Systems

1. Enhanced Memory (EnhancedMemory - src/memory/enhanced-memory.ts)

EnhancedMemory is the central, most robust long-term memory store. It's designed for persistent, semantically searchable information and acts as a hub for various other memory components.

Key Features:

Usage Pattern:

  1. Initialization: getEnhancedMemory() retrieves the singleton instance, initializing the SQLite database and embedding provider.
  2. Storing: memory.store({ type, content, importance, tags, metadata, projectId, sessionId }) adds a new memory. An embedding is generated if enabled.
  3. Recalling: memory.recall({ query, types, tags, projectId, minImportance, limit }) retrieves relevant memories. If embeddings are enabled, it performs semantic search; otherwise, it falls back to keyword search.
  4. Project Context: memory.setProjectContext(projectPath) establishes the current project, allowing project-scoped memory operations.
  5. User Profile: memory.updateUserProfile(updates) and memory.getUserProfile() manage user-specific data.

2. Auto-Capture Memory (AutoCaptureManager - src/memory/auto-capture.ts)

Inspired by intelligent memory capture systems, AutoCaptureManager automatically detects and stores important information from conversations into EnhancedMemory.

Key Features:

Usage Pattern:

  1. Initialization: getAutoCaptureManager(enhancedMemoryInstance) creates an instance linked to EnhancedMemory.
  2. Processing Messages: manager.processMessage(role, content, context) analyzes incoming messages (typically user messages) for patterns.
  3. Custom Patterns: manager.addPattern(pattern) allows extending the built-in detection rules.

3. Decision Memory (DecisionMemory - src/memory/decision-memory.ts)

DecisionMemory specializes in extracting, persisting, and retrieving architectural and design decisions made during interactions. It uses a structured XML format within LLM responses.

Key Features:

Usage Pattern:

  1. Extraction: decisionMemory.extractDecisions(llmResponse) parses decisions from raw LLM text.
  2. Persistence: decisionMemory.persistDecisions(decisions) stores the extracted decisions.
  3. Recall for Context: decisionMemory.buildDecisionContext(query) retrieves relevant decisions and formats them for prompt injection.

4. Knowledge Graph (KnowledgeGraph - src/memory/knowledge-graph.ts)

Inspired by memU, the KnowledgeGraph captures entities and their relationships, providing a more structured and interconnected form of memory than flat entries. It aims to learn user preferences, habits, and project structures.

Key Features:

Usage Pattern:

  1. Initialization: getKnowledgeGraph() retrieves the singleton instance.
  2. Extraction & Storage: graph.extractAndStore(message, context) analyzes messages to identify and store new entities and relations.
  3. Querying: graph.query(graphQuery) allows traversing the graph to find related information.
  4. Context Building: graph.buildContext(query, temporalContext) generates a structured context block for LLMs, including facts, preferences, and temporal habits.

5. Prospective Memory (ProspectiveMemory - src/memory/prospective-memory.ts)

ProspectiveMemory manages tasks, goals, and reminders, enabling the agent to track ongoing work and proactively remind itself of future actions.

Key Features:

Usage Pattern:

  1. Initialization: getProspectiveMemory() retrieves the singleton instance.
  2. Task Management: memory.createTask(), memory.updateTask(), memory.getPendingTasks().
  3. Goal Management: memory.createGoal(), memory.updateGoalProgress().
  4. Reminder Management: memory.setReminder(), memory.getPendingReminders().
  5. Trigger Checking: memory.checkTriggers() is called periodically to activate reminders or tasks.

Specialized Memory & Search Components

6. Coding Style Analyzer (CodingStyleAnalyzer - src/memory/coding-style-analyzer.ts)

This module analyzes source code files to automatically detect coding conventions and style preferences using regex-based heuristics.

Key Features:

Usage Pattern:

  1. Initialization: getCodingStyleAnalyzer() retrieves the singleton instance.
  2. Analysis: analyzer.analyzeContent(content, filePath) for a single file, or analyzer.analyzeDirectory(dirPath) for a project.
  3. Persistence: analyzer.persistToMemory(profile, projectPath) stores the profile.
  4. Prompt Integration: analyzer.buildPromptSnippet(profile) generates the prompt text.

7. OCR Memory Pipeline (OCRMemoryPipeline - src/memory/ocr-memory-pipeline.ts)

The OCRMemoryPipeline processes images (e.g., screenshots) by performing Optical Character Recognition (OCR) to extract text, generating embeddings for the extracted text, and indexing them for search.

Key Features:

Usage Pattern:

  1. Initialization: getOCRMemoryPipeline() retrieves the singleton instance.
  2. Processing: pipeline.processImage(imagePath, metadata) performs OCR and embedding.
  3. Retrieval: pipeline.getAllEntries() to get all indexed image memories.

8. Cross-Modal Search (CrossModalSearch - src/memory/cross-modal-search.ts)

CrossModalSearch enables searching across different modalities (text and images) using multimodal embeddings. This allows queries like "find screenshots of the login form" to return relevant images.

Key Features:

Usage Pattern:

  1. Initialization: getCrossModalSearch() retrieves the singleton instance.
  2. Search: search.search(query, options) performs a cross-modal search, returning a mix of text and image results.

9. Hybrid Memory Search (HybridMemorySearch - src/memory/hybrid-search.ts)

HybridMemorySearch combines the strengths of traditional keyword-based search (BM25) with modern semantic vector search for robust memory retrieval.

Key Features:

Usage Pattern:

  1. Initialization: HybridMemorySearch.getInstance() retrieves the singleton.
  2. Indexing: search.index(entries) adds documents to both the BM25 index and (asynchronously) generates embeddings.
  3. Searching: search.search(query, limit) performs a hybrid search.

10. Semantic Memory Search (SemanticMemorySearch - src/memory/semantic-memory-search.ts)

This module provides a dedicated semantic search capability over a collection of text memories, often used by other components that need to query text embeddings.

Key Features:

Usage Pattern:

  1. Initialization: getSemanticMemorySearch() retrieves the singleton.
  2. Indexing: search.scanMemoryFiles(directory) builds the semantic index.
  3. Searching: search.search(query, options) performs a semantic search.

Integration & Lifecycle

11. Memory Lifecycle Hooks (MemoryLifecycleHooks - src/memory/memory-lifecycle-hooks.ts)

This module defines and manages hooks that allow the memory system to interact with the agent's execution flow at critical points (e.g., before executing a command, after receiving a response, at session end).

Key Features:

Usage Pattern:

  1. Initialization: getMemoryLifecycleHooks(autoCaptureManager, decisionMemory, knowledgeGraph) creates an instance with dependencies.
  2. Hook Invocation: The agent runtime calls hooks.beforeExecute(), hooks.afterResponse(), and hooks.sessionEnd() at appropriate times.

12. ICM Bridge (ICMBridge - src/memory/icm-bridge.ts)

The ICMBridge provides an integration point with an external "Infinite Context Memory" (ICM) system, allowing Code Buddy to leverage an external persistent memory store if available.

Key Features:

Usage Pattern:

  1. Initialization: bridge.initialize(mcpCaller) checks for ICM server connectivity.
  2. Conditional Usage: Agent logic checks bridge.isAvailable() before attempting ICM operations.

Legacy/Alternative Memory Systems

13. Persistent Memory Manager (PersistentMemoryManager - src/memory/persistent-memory.ts)

PersistentMemoryManager is a simpler, file-based memory system that stores memories in Markdown files (MEMORY.md) within user and project-specific directories. It's a more human-readable and directly editable form of memory.

Key Features:

Usage Pattern:

  1. Initialization: getMemoryManager(projectDir) retrieves the singleton instance.
  2. Storing: manager.remember(key, value, category) adds a memory.
  3. Recalling: manager.recall(key, category) retrieves a memory by key.

14. Auto-Memory System (AutoMemoryManager - src/memory/auto-memory.ts)

AutoMemoryManager is another file-based system that automatically extracts and stores memories from agent interactions into MEMORY.md files. It uses predefined patterns for analysis. While AutoCaptureManager feeds into EnhancedMemory, AutoMemoryManager writes directly to Markdown files. It might be considered a legacy or specialized alternative for simpler, file-based auto-extraction.

Key Features:

Usage Pattern:

  1. Initialization: getAutoMemoryManager(projectDir) retrieves the singleton instance.
  2. Analysis: manager.analyzeForMemories(context, response) extracts potential memories.
  3. Writing: manager.writeMemory(key, value, scope) persists a memory.

Key Concepts & Patterns