Doramagic Project Pack · Human Manual

claude-mem

Claude-Mem solves the context continuity problem in AI-assisted development by:

Introduction to Claude-Mem

Related topics: Key Features, System Architecture Overview

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section Plugin Modes

Continue reading this section for the full explanation and source context.

Related topics: Key Features, System Architecture Overview

Introduction to Claude-Mem

Claude-Mem is a persistent memory plugin for Claude Code that automatically captures tool usage observations, generates semantic summaries, and makes them available across sessions. It enables Claude to maintain continuity of knowledge about projects even after sessions end or reconnect.

Sources: README.md:1

Overview

Claude-Mem solves the context continuity problem in AI-assisted development by:

  • Automatically capturing tool usage observations during development sessions
  • Generating semantic summaries using configurable AI models
  • Persisting memory in a local SQLite database (~/.claude-mem)
  • Injecting relevant context into new Claude Code sessions automatically

The system operates as a background worker service that monitors Claude Code activity, processes observations through AI models, and serves memory context on demand.

Sources: README.md:1

Architecture

System Components

Claude-Mem consists of several interconnected components:

ComponentLocationPurpose
NPX CLIsrc/npx-cli/Installation, startup, and management commands
Worker Servicesrc/server/Background service for observation processing
SDKsrc/sdk/Prompt building and shared utilities
UI Viewersrc/ui/viewer/Web-based memory viewer interface
Smart File Readersrc/services/smart-file-read/Intelligent code parsing and symbol extraction

Sources: src/npx-cli/commands/install.ts:1

Data Flow

graph TD
    A[Claude Code Session] -->|Tool Usage Events| B[Claude-Mem Hooks]
    B -->|Observation Data| C[Worker Service]
    C -->|API Request| D[AI Provider<br/>Claude/Gemini]
    D -->|Structured Observation| E[SQLite Database<br/>~/.claude-mem]
    E -->|Context Injection| F[Next Claude Session]
    
    G[UI Viewer] <-->|Query/Display| E
    G -->|Settings Changes| C

Sources: src/server/generation/providers/shared/prompt-builder.ts:1

Plugin Modes

Claude-Mem supports different observation modes through the ModeConfig system. Each mode defines:

  • Prompt templates for observation generation
  • Observation types (e.g., code_change, investigation, learning)
  • XML output schema for structured responses
  • Mode-specific field guidance

Sources: src/sdk/prompts.ts:1

Installation

Standard Installation (Claude Code)

npx claude-mem install

Sources: README.md:11

Gemini CLI Installation

npx claude-mem install --ide gemini-cli

Sources: README.md:14

OpenCode Installation

npx claude-mem install --ide opencode

Sources: README.md:17

Claude Code Plugin Marketplace

/plugin marketplace add thedotmack/claude-mem
/plugin install claude-mem

Sources: README.md:20

Note: The npm package (npm install -g claude-mem) installs only the SDK/library—it does not register plugin hooks or set up the worker service. Always use npx claude-mem install or the /plugin commands.

Sources: README.md:27

Configuration Options

The memory context can be configured through environment variables or the UI settings modal:

SettingDefaultDescription
CLAUDE_MEM_CONTEXT_OBSERVATIONS50Number of recent observations to include (1-200)
CLAUDE_MEM_CONTEXT_SESSIONS10Number of recent sessions to pull from (1-50)
CLAUDE_MEM_PROVIDERclaudeAI provider: claude or gemini
CLAUDE_MEM_MODELhaikuClaude model: haiku, sonnet, or opus
CLAUDE_MEM_GEMINI_MODELgemini-2.5-flash-liteGemini model variant

Sources: src/ui/viewer/components/ContextSettingsModal.tsx:1

Data Models

Observation Structure

Observations are the core data unit in Claude-Mem:

interface Observation {
  id: string;
  tool_name: string;
  tool_input: string | object;
  tool_output: string | object;
  type: string;           // Observation type (e.g., "code_change")
  title: string;
  subtitle?: string;
  facts: string[];
  narrative?: string;
  concepts: string[];
  files_read: string[];
  files_modified: string[];
  project: string;
  created_at_epoch: number;
}

Sources: src/sdk/prompts.ts:1

Summary Structure

Session summaries provide high-level context:

interface Summary {
  id: string;
  request: string;        // What was requested
  investigated: string;   // What was explored
  learned: string;        // Key findings
  completed: string;      // What was accomplished
  next_steps: string;     // Suggested follow-ups
  notes?: string;         // Additional notes
  project: string;
  created_at_epoch: number;
}

Sources: src/ui/viewer/components/SummaryCard.tsx:1

Observation Generation

Prompt Building System

The SDK (src/sdk/prompts.ts) provides functions to construct structured prompts:

FunctionPurpose
buildFirstObservationPrompt()Initial observation for new sessions
buildContinuationPrompt()Continue observation from existing context
buildSummaryPrompt()Generate session summary
buildObservationPrompt()Process individual tool observations

Sources: src/sdk/prompts.ts:1

XML Output Schema

Observations are formatted using XML with the following structure:

<observation>
  <type>[ code_change | investigation | learning | error_fix ]</type>
  <title>Brief descriptive title</title>
  <subtitle>Optional context summary</subtitle>
  <facts>
    <fact>Key fact 1</fact>
    <fact>Key fact 2</fact>
  </facts>
  <narrative>Descriptive narrative of the action</narrative>
  <concepts>
    <concept>Technical concept 1</concept>
  </concepts>
  <files_read>
    <file>path/to/file.ts</file>
  </files_read>
  <files_modified>
    <file>path/to/modified.ts</file>
  </files_modified>
</observation>

Sources: src/server/generation/providers/shared/prompt-builder.ts:1

XML Escaping

The prompt builder includes proper XML escaping to prevent injection:

function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

Sources: src/server/generation/providers/shared/prompt-builder.ts:1

User Interface

Viewer Components

The web-based UI viewer provides several key components:

ComponentFileDescription
HeaderHeader.tsxNavigation bar with logo, status, and links
WelcomeCardWelcomeCard.tsxFirst-time user onboarding modal
SummaryCardSummaryCard.tsxDisplay session summaries with sections
ObservationCardObservationCard.tsxDisplay individual observations with toggle views
ContextSettingsModalContextSettingsModal.tsxConfiguration panel with live preview
LogsModalLogsModal.tsxReal-time worker log viewer

Sources: src/ui/viewer/components/Header.tsx:1 Sources: src/ui/viewer/components/WelcomeCard.tsx:1 Sources: src/ui/viewer/components/SummaryCard.tsx:1

Theme System

The viewer supports light and dark themes via CSS custom properties:

:root, [data-theme="light"] {
  --color-bg-primary: #ffffff;
  --color-bg-secondary: #efebe4;
  --color-bg-button: #0969da;
}

[data-theme="dark"] {
  --color-bg-primary: #0d1117;
  --color-bg-secondary: #161b22;
  --color-bg-button: #238636;
}

Sources: src/ui/viewer-template.html:1

Observation Card Display Modes

The observation card supports multiple view modes:

  1. Default View: Shows title and subtitle
  2. Facts View: Displays bullet-pointed facts with concepts and file references
  3. Narrative View: Shows the full narrative description

Sources: src/ui/viewer/components/ObservationCard.tsx:1

Smart File Reading

The smart-file-read service provides intelligent code parsing:

FeatureDescription
Symbol extractionIdentifies functions, classes, interfaces, variables
Markdown processingHandles code blocks, frontmatter, and references
JSDoc/Python docstring detectionExtracts documentation comments
Export trackingDetermines which symbols are exported
Duplicate code block detectionIdentifies repeated code blocks

Sources: src/services/smart-file-read/parser.ts:1

First-Time Usage

After installation:

  1. Start the worker: The install command automatically starts the background worker
  2. Open the dashboard: Navigate to http://localhost:<port> to view the memory viewer
  3. Start coding: Open Claude Code in any project
  4. Observe: Observations automatically stream in as you work
  5. Context injection: Memory becomes available in your second session in a project

Sources: src/npx-cli/commands/install.ts:1

Troubleshooting

If experiencing issues, Claude Code can automatically diagnose problems:

cd ~/.claude/plugins/marketplaces/thedotmack
npm run bug-report

Sources: README.md:57

Development

For development and contribution guidelines, see the Development Guide.

License

Claude-Mem is licensed under the Apache License 2.0, enabling use in developer tools, local agents, MCP servers, enterprise systems, robotics stacks, and production agent harnesses.

Sources: README.md:82

Sources: README.md:1

Key Features

Related topics: Introduction to Claude-Mem, MCP Tools and Context Generation, Search Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 1. Observation Capture System

Continue reading this section for the full explanation and source context.

Section 2. Semantic Summary Generation

Continue reading this section for the full explanation and source context.

Section 3. Context Injection

Continue reading this section for the full explanation and source context.

Related topics: Introduction to Claude-Mem, MCP Tools and Context Generation, Search Architecture

Key Features

Claude-Mem provides persistent memory capabilities for AI coding assistants, enabling continuity of knowledge across sessions. This page documents the core architectural components and features that power the system.

System Overview

Claude-Mem seamlessly preserves context across sessions by automatically capturing tool usage observations, generating semantic summaries, and making them available to future sessions. This enables Claude to maintain continuity of knowledge about projects even after sessions end or reconnect.

Sources: README.md

Core Features

1. Observation Capture System

The observation system automatically records tool usage events during Claude Code sessions. Each observation captures structured data about file operations, command executions, and code modifications.

#### Observation Data Model

FieldTypeDescription
typestringCategory of observation (file_read, file_modified, command, etc.)
titlestringBrief title for the observation
subtitlestringAdditional context or description
factsstring[]Key facts extracted from the operation
narrativestringHuman-readable summary of the activity
conceptsstring[]Extracted concepts and patterns
files_readstring[]Files that were read during this operation
files_modifiedstring[]Files that were modified
idnumberUnique identifier for the observation
created_at_epochnumberUnix timestamp of creation

Sources: src/sdk/prompts.ts:24-42

#### XML Output Format

Observations are rendered in a structured XML format that the AI can easily parse:

<observation>
  <type>[ file_read | file_modified | command | code_change ]</type>
  <title>...</title>
  <subtitle>...</subtitle>
  <facts>
    <fact>...</fact>
  </facts>
  <narrative>...</narrative>
  <concepts>
    <concept>...</concept>
  </concepts>
  <files_read>
    <file>...</file>
  </files_read>
  <files_modified>
    <file>...</file>
  </files_modified>
</observation>

Sources: src/server/generation/providers/shared/prompt-builder.ts:75-89

2. Semantic Summary Generation

Session summaries provide high-level overviews of completed work. The summary system uses specialized prompts to extract key information from the session context.

#### Summary Data Model

FieldDescription
requestOriginal user request or task description
investigatedTopics researched during the session
learnedKey findings and discoveries
completedTasks that were successfully completed
next_stepsRecommended follow-up actions
notesAdditional relevant notes
projectAssociated project identifier
idUnique summary identifier

Sources: src/sdk/prompts.ts:85-96

#### Summary Output Format

<summary>
  <request>...</request>
  <investigated>...</investigated>
  <learned>...</learned>
  <completed>...</completed>
  <next_steps>...</next_steps>
  <notes>...</notes>
</summary>

Sources: src/sdk/prompts.ts:98-110

3. Context Injection

Claude-Mem injects relevant observations into new sessions, allowing Claude to recall previous work on the project.

#### Context Configuration Options

SettingDefaultRangeDescription
CLAUDE_MEM_CONTEXT_OBSERVATIONS501-200Number of recent observations to include
CLAUDE_MEM_CONTEXT_SESSIONS-1-50Number of recent sessions to pull from

Sources: src/ui/viewer/components/ContextSettingsModal.tsx:45-60

4. Multi-IDE Support

Claude-Mem supports installation across multiple AI coding environments:

IDEInstallation Command
Claude Codenpx claude-mem install
Gemini CLInpx claude-mem install --ide gemini-cli
OpenCodenpx claude-mem install --ide opencode

Sources: README.md

5. Smart File Parsing

The parser extracts meaningful symbols from code files, supporting intelligent code analysis:

interface CodeSymbol {
  name: string;
  kind: 'function' | 'class' | 'variable' | 'interface' | 'type' | 'code' | 'metadata' | 'reference';
  signature: string;
  jsdoc?: string;
  lineStart: number;
  lineEnd: number;
  exported: boolean;
  children?: CodeSymbol[];
}

Supported languages include JavaScript, TypeScript, Python, Markdown (with code block detection), and more.

Sources: src/services/smart-file-read/parser.ts:1-50

6. Web Viewer Interface

The built-in web viewer provides a graphical interface for browsing past observations and summaries.

#### Viewer Components

ComponentPurpose
SummaryCardDisplays session summaries with request title, sections, and metadata
ObservationCardShows individual observations with facts, narrative, and file references
ContextSettingsModalConfiguration panel for context injection settings
WelcomeCardFirst-time user introduction and feature overview
HeaderNavigation and status indicators
LogsModalApplication logs and debugging information

Sources: src/ui/viewer/App.tsx:1-100

#### Summary Card Display

The UI renders summary sections with animation delays for visual polish:

sections.map((section, index) => (
  <section
    key={section.key}
    className="summary-section"
    style={{ animationDelay: `${index * 50}ms` }}
  >
    <div className="summary-section-header">
      <img src={section.icon} alt={section.label} />
      <h3>{section.label}</h3>
    </div>
    <div className="summary-section-content">
      {section.content}
    </div>
  </section>
))

Sources: src/ui/viewer/components/SummaryCard.tsx:30-50

#### Observation Card Display

Observations support multiple view modes for flexible data presentation:

{showFacts && facts.length > 0 && (
  <ul className="facts-list">
    {facts.map((fact: string, i: number) => (
      <li key={i}>{fact}</li>
    ))}
  </ul>
)}

{showNarrative && observation.narrative && (
  <div className="narrative">
    {observation.narrative}
  </div>
)}

Sources: src/ui/viewer/components/ObservationCard.tsx:50-65

7. Theme System

The viewer supports light and dark themes with CSS custom properties:

Theme VariableLight ModeDark Mode
--color-bg-primary#ffffff#0d1117
--color-bg-secondary#efebe4#161b22
--color-bg-card#ffffff#161b22
--color-bg-button#0969da#238636

Sources: src/ui/viewer-template.html:20-40

Architecture Diagram

graph TD
    A[Claude Code Session] --> B[Observation Capture]
    B --> C[Worker Service]
    C --> D[SQLite Database]
    D --> E[Context Builder]
    E --> F[Prompt Injection]
    F --> A
    
    C --> G[Summary Generation]
    G --> D
    
    H[Web Viewer] --> E
    H --> D
    
    I[Smart File Parser] --> B

Data Flow

sequenceDiagram
    participant User
    participant Claude as Claude Code
    participant SDK as SDK/prompts.ts
    participant Worker as Worker Service
    participant DB as SQLite
    participant Viewer as Web Viewer
    
    User->>Claude: Start session
    Claude->>SDK: Generate observation
    SDK->>Worker: Send observation data
    Worker->>DB: Store observation
    
    User->>Viewer: Browse observations
    Viewer->>DB: Query observations
    DB-->>Viewer: Return data
    
    User->>Claude: End session
    Claude->>SDK: Request summary
    SDK->>Worker: Generate summary
    Worker->>DB: Store summary
    
    User->>Claude: New session
    Viewer->>Claude: Inject context
    Claude->>User: Respond with context

Key System Behaviors

Observation Types

The system recognizes several observation types that categorize different tool operations:

  1. file_read - When Claude reads a file
  2. file_modified - When Claude edits or creates a file
  3. command - When Claude runs shell commands
  4. code_change - When significant code modifications occur

XML Escaping

All user-generated content is properly escaped before insertion into XML output to prevent injection attacks:

function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

Sources: src/server/generation/providers/shared/prompt-builder.ts:91-98

Error Handling

The viewer implements error boundaries to gracefully handle component failures:

class ErrorBoundary extends React.Component {
  state = { error: null, errorInfo: null };
  
  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    this.setState({ error, errorInfo });
  }
  
  render() {
    if (this.state.error) {
      return (
        
      );
    }
    return this.props.children;
  }
}

Sources: src/ui/viewer/components/ErrorBoundary.tsx:1-40

Installation & Setup

Quick Install

# Standard Claude Code
npx claude-mem install

# Gemini CLI
npx claude-mem install --ide gemini-cli

# OpenCode
npx claude-mem install --ide opencode

Post-Installation

  1. Keep the viewer URL open in a browser
  2. Open Claude Code in any project
  3. Observations stream automatically as Claude works
  4. Memory injection begins on the second session

Sources: src/npx-cli/commands/install.ts:15-30

Storage Location

All data is stored locally in ~/.claude-mem on the user's machine. No data is sent to external servers except through Claude API calls for observation generation.

See Also

Sources: README.md

System Architecture Overview

Related topics: Hooks System and Lifecycle, Worker Service Architecture, Database Schema and Storage, Data Flow and Processing

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 1. Worker Service (src/services/worker-service.ts)

Continue reading this section for the full explanation and source context.

Section 2. SDK Layer (src/sdk/prompts.ts)

Continue reading this section for the full explanation and source context.

Section 3. Prompt Builder (src/server/generation/providers/shared/prompt-builder.ts)

Continue reading this section for the full explanation and source context.

Related topics: Hooks System and Lifecycle, Worker Service Architecture, Database Schema and Storage, Data Flow and Processing

System Architecture Overview

Claude-Mem is a persistent memory system for AI coding assistants (Claude Code, Gemini CLI, OpenCode). It automatically captures tool usage observations during coding sessions, generates semantic summaries, and makes them available to future sessions—enabling continuity of knowledge across sessions. Sources: README.md

High-Level Architecture

The system follows a client-server architecture with a worker service that runs independently and a viewer UI for inspecting memory.

graph TD
    A[Claude Code / Gemini CLI] -->|Tool Hooks| B[claude-mem Plugin Hooks]
    B --> C[Worker Service :3000]
    C --> D[(SQLite Database<br/>~/.claude-mem)]
    C --> E[Prompt Builder]
    E --> F[Claude API]
    F --> G[Parsed Observations]
    C --> G
    H[Viewer UI :8080] --> C
    H --> D

Core Components

1. Worker Service (`src/services/worker-service.ts`)

The worker service is the central processing hub that:

  • Runs as a background process (default port 3000)
  • Receives tool usage observations from IDE plugins
  • Processes and stores observations in SQLite
  • Handles prompt generation and LLM interaction
  • Manages session context injection

Sources: src/npx-cli/commands/install.ts

2. SDK Layer (`src/sdk/prompts.ts`)

The SDK provides prompt building functions for different operation modes:

FunctionPurpose
buildObservationPrompt()Creates prompts for parsing tool observations into structured XML format
buildSummaryPrompt()Generates prompts for creating session summaries
buildContinuationPrompt()Builds prompts for continuing sessions with existing context

The SDK uses ModeConfig objects that define observation types, prompt templates, and output format guidelines specific to each IDE integration.

Sources: src/sdk/prompts.ts

3. Prompt Builder (`src/server/generation/providers/shared/prompt-builder.ts`)

Handles the generation of structured output schemas for LLM interactions:

function buildObservationOutputSchema(mode: ModeConfig): string {
  const types = mode.observation_types.map(t => t.id).join(' | ');
  return [
    '<observation>',
    `  <type>[ ${types} ]</type>`,
    '  <title>...</title>',
    '  <subtitle>...</subtitle>',
    '  <facts><fact>...</fact></facts>',
    '  <narrative>...</narrative>',
    '  <concepts><concept>...</concept></concepts>',
    '  <files_read><file>...</file></files_read>',
    '  <files_modified><file>...</file></files_modified>',
    '</observation>',
  ].join('\n');
}

Key features include XML escaping for safe output (escapeXml() function) and fallback to default observation types when mode configuration is unavailable.

Sources: src/server/generation/providers/shared/prompt-builder.ts:1-80

4. Viewer UI (`src/ui/viewer/App.tsx`)

The viewer is a React-based web application (default port 8080) providing:

  • Real-time observation streaming display
  • Session summary cards
  • Context settings configuration
  • Console log viewing
  • Welcome modal for first-time users
graph LR
    A[Viewer App] --> B[ObservationCard]
    A --> C[SummaryCard]
    A --> D[ContextSettingsModal]
    A --> E[LogsDrawer]

Sources: src/ui/viewer/App.tsx

Data Flow

Observation Capture Flow

sequenceDiagram
    participant IDE as Claude Code
    participant Hooks as Plugin Hooks
    participant Worker as Worker Service
    participant LLM as Claude API
    participant DB as SQLite DB

    IDE->>Hooks: Tool usage detected
    Hooks->>Worker: POST /observation
    Worker->>Worker: Parse tool_input
    Worker->>LLM: Generate structured observation
    LLM-->>Worker: XML observation
    Worker->>DB: Store observation
    Worker-->>Hooks: Acknowledge

Context Injection Flow

The system injects relevant observations into new sessions based on configurable settings:

SettingDefaultDescription
CLAUDE_MEM_CONTEXT_OBSERVATIONS50Number of recent observations to include (1-200)
CLAUDE_MEM_CONTEXT_SESSIONSvariesNumber of recent sessions to pull from (1-50)

Sources: src/ui/viewer/components/ContextSettingsModal.tsx

Observation Data Model

Observations captured include:

FieldTypeDescription
idintegerUnique identifier
tool_namestringName of the tool invoked
tool_inputstring/JSONInput parameters to the tool
tool_outputstring/JSONOutput from the tool
titlestringGenerated observation title
subtitlestringBrief description
factsstring[]Key facts extracted
narrativestringExtended narrative description
conceptsstring[]Concepts learned
files_readstring[]Files accessed during observation
files_modifiedstring[]Files changed during observation

Sources: src/ui/viewer/components/ObservationCard.tsx

Storage Architecture

Data is persisted locally in ~/.claude-mem:

  • SQLite Database: Primary storage for observations and summaries
  • Configuration: User preferences stored in localStorage (viewer) or environment variables
  • Logs: Application logs accessible via Viewer UI

Installation Architecture

The install command (npx claude-mem install) handles:

  1. Detection of target IDE (Claude Code, Gemini CLI, OpenCode)
  2. Installation of plugin hooks
  3. Worker service setup
  4. Initial startup verification

Supported installation targets:

IDECommandInstallation Method
Claude Codenpx claude-mem installNative plugin marketplace
Claude Code/plugin marketplace add thedotmack/claude-memBuilt-in plugin command
Gemini CLInpx claude-mem install --ide gemini-cliAuto-detects ~/.gemini
OpenCodenpx claude-mem install --ide opencodeCustom integration

Sources: README.md Sources: src/npx-cli/commands/install.ts

Error Handling

The Viewer UI implements an ErrorBoundary component that:

  • Catches React component errors
  • Displays user-friendly error messages
  • Shows detailed error information in expandable sections
  • Allows users to refresh and retry

Sources: src/ui/viewer/components/ErrorBoundary.tsx

Summary

Claude-Mem's architecture consists of three main layers:

  1. Integration Layer: Plugin hooks that intercept tool usage in the IDE
  2. Processing Layer: Worker service that captures, processes, and stores observations
  3. Presentation Layer: Web-based viewer for inspecting memory and configuring settings

The system is designed to be IDE-agnostic, supporting multiple AI coding assistants while maintaining a unified storage and processing backend.

Sources: src/npx-cli/commands/install.ts

Hooks System and Lifecycle

Related topics: System Architecture Overview, Worker Service Architecture, Data Flow and Processing

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview, Worker Service Architecture, Data Flow and Processing

Hooks System and Lifecycle

Overview

The Hooks System is the core mechanism by which Claude-Mem captures observations, user interactions, and session events from Claude Code to build persistent memory across sessions. The system integrates with Claude Code's plugin hook API to monitor and record agent activities at strategic points in the conversation lifecycle.

Claude-Mem registers multiple hook handlers that fire at different stages: session initialization, user message processing, tool execution, and session termination. Each handler extracts relevant context and stores observations that inform future sessions about project state and progress.

Sources: cursor-hooks/README.md

Sources: cursor-hooks/README.md

Worker Service Architecture

Related topics: System Architecture Overview, Database Schema and Storage, MCP Tools and Context Generation

Section Related Pages

Continue reading this section for the full explanation and source context.

Section WorkerService

Continue reading this section for the full explanation and source context.

Section Session Manager

Continue reading this section for the full explanation and source context.

Section Provider Comparison

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview, Database Schema and Storage, MCP Tools and Context Generation

Worker Service Architecture

The Worker Service is the core backend component of claude-mem, responsible for processing, storing, and serving memory observations across Claude Code sessions. It runs as a persistent background service that handles LLM inference, observation generation, and semantic search operations.

Overview

The Worker Service operates independently from Claude Code sessions, maintaining a long-running process that:

  • Receives tool usage observations from Claude Code via plugin hooks
  • Generates semantic summaries using configured LLM providers (Claude, Gemini, OpenRouter)
  • Stores observations in a local SQLite database with Chroma vector embeddings
  • Serves a web-based viewer UI and REST API for browsing and querying memories
graph TD
    subgraph "Claude Code"
        A[Tool Execution] --> B[Plugin Hooks]
        B --> C[Tool Result Persist Event]
    end
    
    subgraph "Worker Service"
        D[HTTP Server :37777] --> E[Route Handlers]
        E --> F[Session Manager]
        F --> G[Observation Generator]
        G --> H[LLM Providers]
        H --> I[Database Manager]
        I --> J[SQLite + Chroma]
    end
    
    C -->|SSE/WebSocket| D
    D -->|Viewer UI| K[Browser Client]
    D -->|REST API| L[External Clients]

Core Components

WorkerService

The main service orchestrator located in src/services/worker-service.ts. It initializes all sub-components, registers HTTP routes, manages lifecycle events, and coordinates between the UI and backend processing.

Key Responsibilities:

ResponsibilityDescription
Lifecycle ManagementCoordinates startup/shutdown of all service components
Route RegistrationRegisters ViewerRoutes, SessionRoutes, DataRoutes, SettingsRoutes, LogsRoutes, MemoryRoutes
MiddlewareImplements initialization check middleware (returns 503 during DB init)
Database InitializationEnsures SQLite and Chroma are ready before accepting requests
SSE BroadcastingManages real-time event streaming to connected clients

Sources: src/services/worker-service.ts

Session Manager

Manages individual Claude Code session lifecycles, tracking active sessions and coordinating observation generation per session.

Sources: src/services/worker/SessionManager.ts

LLM Provider Architecture

The Worker Service supports multiple LLM backends through a provider abstraction pattern.

Provider Comparison

ProviderClassPurposeAPI Endpoint
Anthropic ClaudeClaudeProviderPrimary observation generationapi.anthropic.com
Google GeminiGeminiProviderAlternative generationGenerative Language API
OpenRouterOpenRouterProviderUnified multi-model accessopenrouter.ai

Sources: - src/services/worker/ClaudeProvider.ts

Provider Selection

The system automatically selects providers based on:

  1. Configuration in ~/.claude-mem/settings.json
  2. Available API keys in environment variables
  3. Fallback to Claude as primary provider

HTTP Route Architecture

The Worker Service exposes REST endpoints through registered route handlers:

graph LR
    A[HTTP :37777] --> B[ViewerRoutes]
    A --> C[SessionRoutes]
    A --> D[DataRoutes]
    A --> E[SettingsRoutes]
    A --> F[LogsRoutes]
    A --> G[MemoryRoutes]
    A --> H[ServerV1Routes]

Route Groups

RouteFilePurpose
ViewerViewerRoutesServes the web-based memory viewer UI
SessionSessionRoutesManages session lifecycle, continuation prompts
DataDataRoutesPagination, filtering, observation retrieval
SettingsSettingsRoutesUser preferences and configuration
LogsLogsRoutesService logging and diagnostics
MemoryMemoryRoutesMemory CRUD operations, search
V1 APIServerV1RoutesLegacy compatibility endpoints

Sources: src/services/worker/http/routes/MemoryRoutes.ts

Job Queue System

Observation generation is handled asynchronously through a BullMQ-based job queue system.

Queue Configuration

interface QueueConfig {
  connection: RedisConnectionConfig;
  prefix: string;
  defaultJobOptions: {
    attempts: number;
    backoff: { type: 'exponential'; delay: number };
    removeOnComplete: boolean;
  };
}

Sources: src/server/jobs/ServerJobQueue.ts

Event Handling

The queue emits events for observability:

EventHandlerDescription
completedonCompletedJob finished successfully
failedonFailedJob failed after all retries
progressonProgressJob reported progress percentage
stallednotifyStalledJob became unresponsive

Process Management

The Worker Service can run in multiple modes:

graph TD
    A[Start Command] --> B{IDE Type}
    B -->|claude-code| C[Claude Code Plugin Mode]
    B -->|gemini-cli| D[Gemini CLI Mode]
    B -->|opencode| E[OpenCode Mode]
    
    C --> F[Persistent Background Process]
    D --> F
    E --> F
    F --> G[Supervisor Process]
    G --> H[Worker Service :37777]

Runtime Modes

ModeActivationBehavior
Auto-startDefaultWorker starts automatically on first session
Manualnpx claude-mem startExplicit user initiation
BackgroundSupervisor-managedPersistent daemon with health monitoring

Sources: src/npx-cli/commands/runtime.ts

Process Manager

The ProcessManager handles:

  • Spawning and monitoring worker processes
  • Health check endpoints (/health, /readiness)
  • Automatic restart on crash
  • Graceful shutdown handling

Sources: src/services/infrastructure/ProcessManager.ts

Configuration

Environment Variables

VariableDefaultDescription
CLAUDE_MEM_WORKER_PORT37777Worker HTTP server port
CLAUDE_MEM_WORKER_HOSTlocalhostWorker binding host
CLAUDE_MEM_MODE-Active mode configuration
CLAUDE_MEM_WELCOME_HINT_ENABLEDtrueShow first-use hints

Service Endpoints

EndpointMethodDescription
/healthGETBasic health check
/readinessGETReadiness probe (DB initialized)
/versionGETService version info
/chroma/statusGETVector database status

Startup Sequence

sequenceDiagram
    participant User
    participant Plugin as Claude Code Plugin
    participant Worker as Worker Service
    participant DB as SQLite/Chroma
    participant Queue as Job Queue

    User->>Plugin: First Claude Code session
    Plugin->>Worker: Tool result events
    Worker->>DB: Initialize connections
    DB-->>Worker: Ready
    Worker->>Queue: Start worker process
    Queue->>Worker: Ready
    Worker-->>Plugin: Service available
    Plugin->>Worker: Stream observations
    Worker->>Queue: Enqueue generation jobs
    Queue->>Worker: Process observations
    Worker->>DB: Store summaries

Data Flow

Observation Lifecycle

  1. Capture: Plugin captures tool execution events (read, edit, shell commands)
  2. Transmission: Events sent via SSE to Worker Service
  3. Queuing: Jobs added to BullMQ generation queue
  4. Processing: LLM provider generates semantic summary
  5. Storage: SQLite stores structured data, Chroma stores vector embeddings
  6. Retrieval: Future sessions query relevant observations via semantic search

Sources: src/services/worker-service.ts

Error Handling

Initialization Guard

During startup, the service returns HTTP 503 for all requests except health/readiness checks:

Request → Middleware Check → DB Initialized?
                              ├─ Yes → Pass through to routes
                              └─ No → 503 "Service initializing"

Queue Failure Handling

Failed jobs trigger listener callbacks:

w.on('failed', (jobId: string, error: Error) => {
  for (const l of this.listeners) {
    l.onFailed?.(jobId, attemptsMade, error.message);
  }
});

Sources: src/server/jobs/ServerJobQueue.ts

Extension Points

Custom LLM Providers

Providers implement a common interface allowing:

  • Custom API endpoints
  • Different authentication methods
  • Provider-specific prompt formatting
  • Rate limiting and retry policies

Mode System

The Worker Service supports configurable modes via ModeConfig that define:

  • Observation types to capture
  • Prompt templates for generation
  • Summary output formats
  • System identity instructions

Security Considerations

  • Service binds to localhost by default
  • No authentication on local-only deployments
  • All data stored in ~/.claude-mem directory
  • API keys loaded from environment variables

Sources: src/services/worker-service.ts

Database Schema and Storage

Related topics: System Architecture Overview, Data Flow and Processing, Search Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section schemaversions

Continue reading this section for the full explanation and source context.

Section sdksessions

Continue reading this section for the full explanation and source context.

Section observations

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview, Data Flow and Processing, Search Architecture

Database Schema and Storage

Overview

Claude-Mem uses SQLite as its primary persistent storage layer to maintain session continuity, store observations, and preserve learned context across sessions. The database schema captures the complete lifecycle of AI sessions, including tool usage, observations, summaries, and temporal data for timeline reconstruction.

The storage system is designed to support:

  • Multi-session tracking with unique identifiers
  • Observation persistence with semantic metadata
  • Session summarization storage
  • Timeline event reconstruction
  • Project-based organization

Architecture

graph TD
    A[Worker Service] --> B[DBManager]
    B --> C[SQLite Database]
    C --> D[schema_versions]
    C --> E[sdk_sessions]
    C --> F[observations]
    C --> G[session_summaries]
    C --> H[pending_messages]
    C --> I[user_prompts]
    C --> J[projects]
    
    K[SessionStore] -.-> E
    L[Observations] -.-> F
    M[Summaries] -.-> G
    N[Timeline] -.-> J

Core Tables

schema_versions

Tracks applied database migrations to ensure schema consistency across upgrades.

ColumnTypeDescription
versionINTEGER PRIMARY KEYMigration version number
applied_atTEXTISO timestamp of migration application

Sources: src/services/sqlite/migrations/runner.ts:1-50

sdk_sessions

Stores metadata about each Claude session managed by the SDK.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing row ID
memory_session_idTEXT NOT NULLUnique session identifier
content_session_idTEXT NOT NULLContent/session reference ID
projectTEXT NOT NULLProject name for grouping
statusTEXTSession status (active/completed/etc)
created_atTEXT NOT NULLCreation timestamp
created_at_epochINTEGER NOT NULLEpoch timestamp for sorting

Sources: src/services/sqlite/migrations/runner.ts:60-90

observations

Records tool usage observations captured during sessions. Observations are the primary mechanism for preserving learned context.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing observation ID
memory_session_idTEXT NOT NULLForeign key to sdk_sessions
tool_nameTEXTName of the tool used
tool_inputTEXTJSON-encoded tool input
tool_outputTEXTJSON-encoded tool output
observation_typeTEXTType classification (fact, decision, etc.)
titleTEXTObservation title
subtitleTEXTBrief description
narrativeTEXTDetailed narrative
conceptsTEXTJSON array of concept tags
files_readTEXTJSON array of files read
files_modifiedTEXTJSON array of files modified
created_atTEXT NOT NULLCreation timestamp
created_at_epochINTEGER NOT NULLEpoch timestamp

Sources: src/services/sqlite/SessionStore.ts, src/services/sqlite/Observations.ts

session_summaries

Stores AI-generated summaries of completed sessions, capturing requests, findings, and next steps.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing summary ID
memory_session_idTEXT NOT NULLForeign key to sdk_sessions
projectTEXT NOT NULLProject name
requestTEXTOriginal user request
investigatedTEXTWhat was investigated
learnedTEXTKey learnings
completedTEXTCompleted work
next_stepsTEXTPlanned next steps
files_readTEXTFiles read during session
files_editedTEXTFiles modified during session
notesTEXTAdditional notes
prompt_numberINTEGERSession prompt sequence number
created_atTEXT NOT NULLCreation timestamp
created_at_epochINTEGER NOT NULLEpoch timestamp

Sources: src/services/sqlite/migrations/runner.ts:50-80, src/services/sqlite/Summaries.ts

pending_messages

Queue table for messages awaiting processing by the worker service.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing message ID
content_session_idTEXT NOT NULLSession reference
message_idINTEGERClaude message ID
message_typeTEXTMessage type (observation/summarize)
payloadTEXTJSON message payload
statusTEXTProcessing status
created_atTEXT NOT NULLCreation timestamp
created_at_epochINTEGER NOT NULLEpoch timestamp
failed_at_epochINTEGEREpoch timestamp of last failure

Sources: src/services/sqlite/migrations/runner.ts:200-230

user_prompts

Stores original user prompts for each session.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing prompt ID
content_session_idTEXT NOT NULLSession reference
promptTEXT NOT NULLUser prompt text
created_atTEXT NOT NULLCreation timestamp
created_at_epochINTEGER NOT NULLEpoch timestamp

projects

Maintains project registry for organizing sessions and observations.

ColumnTypeDescription
idINTEGER PRIMARY KEYAuto-incrementing project ID
nameTEXT NOT NULL UNIQUEProject name
created_atTEXT NOT NULLCreation timestamp

Sources: src/storage/sqlite/schema.ts, src/services/sqlite/Timeline.ts

Schema Migrations

The system uses a versioned migration system to handle schema evolution. Migrations are applied sequentially and tracked in the schema_versions table.

Migration Version History

VersionDescription
7Session summaries table creation with UNIQUE constraint removal
17Column renames: sdk_session_idmemory_session_id, claude_session_idcontent_session_id
20Added failed_at_epoch column to pending_messages

Sources: src/services/sqlite/migrations/runner.ts:40-45, src/services/sqlite/migrations/runner.ts:150-180, src/services/sqlite/migrations/runner.ts:195-220

Migration Execution

Migrations are executed via the MigrationRunner class which:

  1. Checks current schema version from schema_versions
  2. Applies pending migrations in order
  3. Records each applied version with timestamp
  4. Handles safe column renaming (only if column exists)
private addFailedAtEpochColumn(): void {
  const applied = this.db.prepare('SELECT version FROM schema_versions WHERE version = ?').get(20);
  if (applied) return;
  
  const tableInfo = this.db.query('PRAGMA table_info(pending_messages)').all();
  const hasColumn = tableInfo.some(col => col.name === 'failed_at_epoch');
  
  if (!hasColumn) {
    this.db.run('ALTER TABLE pending_messages ADD COLUMN failed_at_epoch INTEGER');
  }
}

Sources: src/services/sqlite/migrations/runner.ts:195-215

Session ID Naming Convention

The system underwent a terminology migration in version 17:

Old NameNew NamePurpose
sdk_session_idmemory_session_idPrimary session identifier across memory system
claude_session_idcontent_session_idClaude/Content API session reference

This rename reflects the system's expansion beyond Claude Code to support other AI platforms (Gemini CLI, OpenClaw).

Sources: src/services/sqlite/migrations/runner.ts:145-170

Data Access Layer

SessionStore

Provides CRUD operations for session management:

interface SessionStore {
  createSession(session: Session): Promise<number>;
  getSession(memorySessionId: string): Promise<Session | null>;
  updateSessionStatus(sessionDbId: number, status: string): Promise<void>;
  listSessions(project?: string): Promise<Session[]>;
}

Observations

Handles observation persistence and retrieval:

interface ObservationsStore {
  createObservation(obs: Observation): Promise<number>;
  getObservationsBySession(memorySessionId: string): Promise<Observation[]>;
  searchObservations(query: SearchQuery): Promise<Observation[]>;
  getRecentObservations(limit: number): Promise<Observation[]>;
}

Summaries

Manages session summary storage:

interface SummariesStore {
  createSummary(summary: SessionSummary): Promise<number>;
  getSummaryBySession(memorySessionId: string): Promise<SessionSummary | null>;
  listSummaries(project?: string, limit?: number): Promise<SessionSummary[]>;
}

Timeline

Provides temporal queries for reconstructing session history:

interface TimelineStore {
  getEventsByDateRange(start: Date, end: Date): Promise<TimelineEvent[]>;
  getSessionTimeline(memorySessionId: string): Promise<TimelineEvent[]>;
  getProjectTimeline(projectName: string): Promise<TimelineEvent[]>;
}

Indexes

The schema includes optimized indexes for common query patterns:

Index NameTableColumns
idx_session_summaries_sdk_sessionsession_summariesmemory_session_id
idx_session_summaries_projectsession_summariesproject
idx_session_summaries_createdsession_summariescreated_at_epoch

Sources: src/services/sqlite/migrations/runner.ts:85-95

Database Initialization Flow

sequenceDiagram
    participant App as Worker Service
    participant DB as DBManager
    participant Migrate as MigrationRunner
    participant SQLite as SQLite DB
    
    App->>DB: Initialize database connection
    DB->>Migrate: Run pending migrations
    Migrate->>SQLite: SELECT version FROM schema_versions
    SQLite-->>Migrate: Current versions
    Migrate->>SQLite: Apply missing migrations
    Migrate->>SQLite: INSERT INTO schema_versions
    DB->>SQLite: Register prepared statements
    DB-->>App: Database ready

Configuration

The database location is determined by environment variables:

VariableDefaultDescription
CLAUDE_MEM_DB_PATH~/.claude-mem/memory.dbSQLite database file path
CLAUDE_MEM_WORKER_PORT37777Worker service port (related service)

Data Flow

graph LR
    A[Claude Session] -->|Tool Usage| B[Observation Capture]
    B --> C[pending_messages]
    C -->|Processing| D[Worker Service]
    D -->|Store| E[observations]
    D -->|Generate| F[session_summaries]
    E -->|Retrieve| G[Future Sessions]
    F -->|Retrieve| G

Sources: src/services/sqlite/migrations/runner.ts:1-50

Data Flow and Processing

Related topics: System Architecture Overview, Database Schema and Storage, Hooks System and Lifecycle

Section Related Pages

Continue reading this section for the full explanation and source context.

Section 1. Transcript Watching

Continue reading this section for the full explanation and source context.

Section 2. Observation Generation

Continue reading this section for the full explanation and source context.

Section 3. Context Building

Continue reading this section for the full explanation and source context.

Related topics: System Architecture Overview, Database Schema and Storage, Hooks System and Lifecycle

Data Flow and Processing

Overview

Claude-Mem implements a sophisticated data pipeline that captures, processes, stores, and retrieves contextual information from Claude Code sessions. The system transforms raw transcript data into structured observations and summaries that can be injected into future sessions, enabling persistent memory across sessions.

The data flow architecture spans multiple layers: ingestion (capturing session activity), processing (generating structured observations), storage (persisting to local filesystem), retrieval (searching and filtering), and injection (presenting relevant context to Claude).

System Architecture

graph TD
    subgraph Ingestion ["Ingestion Layer"]
        TW[Transcript Watcher] --> TP[Transcript Processor]
        TP --> OG[Observation Generator]
    end
    
    subgraph Processing ["Processing Layer"]
        OG --> CB[Context Builder]
        CB --> OC[Observation Compiler]
        OC --> Q[Job Queue]
        Q --> QW[Queue Worker]
    end
    
    subgraph Storage ["Storage Layer"]
        QW --> FS[File System<br/>~/.claude-mem]
        FS --> OBS[Observations DB]
        FS --> SUMM[Summary DB]
    end
    
    subgraph Retrieval ["Retrieval Layer"]
        CLI[CLI Context Handler] --> SR[Search & Retrieval]
        SR --> CB
        CB --> CONTEXT[Context Injection]
    end
    
    subgraph Output ["Output Layer"]
        CONTEXT --> UI[Viewer UI]
        CONTEXT --> SDK[SDK Prompts]
    end

Core Data Flow Pipeline

1. Transcript Watching

The transcript watcher monitors Claude Code sessions in real-time, capturing all activity as it occurs.

Key Components:

ComponentFilePurpose
TranscriptWatchersrc/services/transcripts/watcher.tsMonitors transcript files for changes
TranscriptProcessorsrc/services/transcripts/processor.tsParses and extracts events from transcripts

The watcher detects when new content is written to transcript files and triggers processing. Events captured include:

  • Tool invocations (Read, Write, Edit, Bash, etc.)
  • User prompts
  • Assistant responses
  • System events

2. Observation Generation

Observations are generated from processed transcript events using LLM providers.

graph LR
    subgraph Input
        EV[Event Data] --> PG[Prompt Builder]
        MC[Mode Config] --> PG
    end
    
    subgraph Generation
        PG --> LLM[LLM Provider]
        LLM --> XML[XML Output]
    end
    
    subgraph Output
        XML --> OBS[Observation Record]
        XML --> PRIV[Private Data Check]
    end

ProviderObservationGenerator handles the generation flow:

  1. Builds prompts using ModeConfig and observation types
  2. Sends requests to configured LLM provider (Claude by default)
  3. Parses XML-structured responses
  4. Validates and sanitizes output

The generated observation schema follows this structure:

<observation>
  <type>[ observation | decision | change | how-it-works ]</type>
  <title>...</title>
  <subtitle>...</subtitle>
  <facts>
    <fact>...</fact>
    <fact>...</fact>
  </facts>
  <narrative>...</narrative>
  <concepts>
    <concept>...</concept>
  </concepts>
  <files_read>
    <file>...</file>
  </files_read>
  <files_modified>
    <file>...</file>
  </files_modified>
</observation>

Sources: src/server/generation/providers/shared/prompt-builder.ts

3. Context Building

The ContextBuilder assembles relevant observations and summaries for injection into new sessions.

MethodPurpose
buildContext()Constructs complete context from observations
getRecentContext()Retrieves most recent observations
getContextByProject()Filters context by project identifier
getContextByFile()Retrieves observations related to specific files

Context building supports multiple retrieval strategies:

  • Timeline-based: Recent observations first
  • Concept-based: Match by extracted concepts
  • File-based: Related to currently accessed files
  • Hybrid: Combination of above strategies

Sources: src/services/context/ContextBuilder.ts

4. Observation Compilation

The ObservationCompiler aggregates and formats observations for different output contexts.

graph TD
    OBS[Raw Observations] --> COMP[ObservationCompiler]
    COMP --> FORM[Format Selection]
    FORM --> MD[Markdown Format]
    FORM --> SDK[SDK Prompt Format]
    FORM --> API[API JSON Format]
    
    MD --> OUT1[Claude.md Files]
    SDK --> OUT2[Session Injection]
    API --> OUT3[REST API Response]

Compilation includes:

  • Deduplication: Removes duplicate observations
  • Ranking: Scores by relevance and recency
  • Truncation: Limits context size for token budgets
  • Formatting: Converts to target output format

Sources: src/services/context/ObservationCompiler.ts

Job Queue Processing

Observations and summaries are processed asynchronously through BullMQ job queues.

sequenceDiagram
    participant Watcher
    participant Queue as Job Queue
    participant Worker
    participant Storage
    
    Watcher->>Queue: Add observation job
    Queue->>Worker: Distribute job
    Worker->>Storage: Store observation
    Worker->>Queue: Mark complete
    Queue->>Watcher: Notify success
    
    Note over Worker: Retry on failure<br/>Max 3 attempts

ServerJobQueue manages job lifecycle:

FeatureDescription
Retry PolicyAutomatic retry with exponential backoff
Progress TrackingReal-time job progress events
Stalled DetectionMonitors for stuck jobs
Cross-Process EventsRedis pub/sub for distributed workers

Sources: src/server/jobs/ServerJobQueue.ts

Storage Architecture

All data persists to ~/.claude-mem/ on the local filesystem.

graph TD
    subgraph "~/.claude-mem"
        OBS[observations/]
        SUMM[summary/]
        CONTEXT[context/]
        CONFIG[config.json]
        MODES[modes/]
    end
    
    OBS --> |JSON files| RECORDS[Individual records]
    SUMM --> |JSON files| SESSION_SUMM[Session summaries]
    CONTEXT --> |Compiled| READY[Ready for injection]

File Structure

DirectoryContentFormat
observations/Individual observationsJSON with metadata
summary/Session summariesJSON with sections
context/Compiled context bundlesJSON arrays
modes/Mode configurationsJSON
transcripts/Raw session transcriptsText/markdown

Summary Generation Flow

Summaries are generated at session end to provide high-level overviews.

graph TD
    subgraph SessionEnd
        END[Session Complete] --> EXTRACT[Extract Key Events]
        EXTRACT --> BUILD[Build Summary Prompt]
    end
    
    subgraph Generation
        BUILD --> LLM[LLM Generation]
        LLM --> PARSE[Parse Summary XML]
    end
    
    subgraph Output
        PARSE --> STRUCT[Structured Summary]
        STRUCT --> STORE[Store to summary/]
        STRUCT --> DISPLAY[Display in UI]
    end

Summary output format:

<summary>
  <request>Original user request</request>
  <investigated>What was explored</investigated>
  <learned>Key discoveries</learned>
  <completed>Tasks accomplished</completed>
  <next_steps>Follow-up items</next_steps>
  <notes>Additional context</notes>
</summary>

Sources: src/sdk/prompts.ts

CLI Context Handler

The CLI provides programmatic access to context operations.

Available Commands:

CommandPurpose
/learn-codebaseIngest entire repository
/context injectManually inject context
/context searchSearch observations
/context clearClear project context

Sources: src/cli/handlers/context.ts

Data Models

Observation Model

interface Observation {
  id: string;
  type: ObservationType;
  title: string;
  subtitle?: string;
  facts: string[];
  narrative?: string;
  concepts: string[];
  files_read: string[];
  files_modified: string[];
  created_at_epoch: number;
  project?: string;
  session_id?: string;
}

Summary Model

interface Summary {
  id: string;
  request: string;
  investigated: string;
  learned: string;
  completed: string;
  next_steps: string;
  notes?: string;
  project: string;
  created_at_epoch: number;
}

Context Injection Flow

When a new session starts, relevant context is automatically injected:

sequenceDiagram
    participant Session as New Session
    participant Builder as ContextBuilder
    participant Store as Storage
    participant Claude as Claude LLM
    
    Session->>Builder: Request context
    Builder->>Store: Query observations
    Store->>Builder: Return ranked results
    Builder->>Builder: Compile context
    Builder->>Session: Inject context
    Session->>Claude: Request with context
    Claude->>Session: Contextual response

Injection includes:

  • Recent observations (configurable count)
  • Project-specific summaries
  • Related file history
  • Concept tags for relevance

Configuration Options

Environment VariableDefaultPurpose
CLAUDE_MEM_WORKER_PORT37777Worker service port
RAGTIME_TRANSCRIPT_MAX_AGE24Transcript retention (hours)
RAGTIME_SESSION_DELAY2000Delay between sessions (ms)

Sources: ragtime/README.md

Key Processing Pipelines

1. Passive Observation Capture

Session Activity → Watcher → Processor → Generator → Queue → Storage
  • Automatic, background processing
  • No user intervention required
  • Builds memory passively during work

2. Active Codebase Ingestion

User Command (/learn-codebase) → File Parser → Context Builder → Storage
  • Triggered manually by user
  • Parses entire codebase structure
  • Creates file-level observations

Sources: src/services/smart-file-read/parser.ts

3. Context Retrieval & Injection

New Session → Context Handler → Search → Compile → Inject → LLM
  • Triggered at session start
  • Selects relevant observations
  • Formats for LLM consumption

Security Considerations

Private Data Handling

The system implements safeguards for sensitive data:

  1. Pattern Detection: Identifies potential secrets before processing
  2. XML Escaping: All output properly escaped to prevent injection
  3. File Path Validation: Prevents写入 to protected directories
function escapeXml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

Sources: src/server/generation/providers/shared/prompt-builder.ts

Summary

The data flow and processing system in Claude-Mem consists of five integrated layers:

  1. Ingestion Layer - Captures session activity via transcript watching
  2. Processing Layer - Generates structured observations using LLM providers
  3. Storage Layer - Persists all data to local filesystem with JSON format
  4. Retrieval Layer - Searches and compiles relevant context on demand
  5. Injection Layer - Presents context to Claude Code sessions

The asynchronous job queue architecture ensures reliable processing even under high load, while the flexible context builder supports multiple retrieval strategies for optimal memory recall.

Sources: src/server/generation/providers/shared/prompt-builder.ts

Search Architecture

Related topics: MCP Tools and Context Generation, Database Schema and Storage

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: MCP Tools and Context Generation, Database Schema and Storage

Search Architecture

Overview

The Search Architecture in claude-mem provides a multi-strategy search system that enables semantic and structured querying across observations, sessions, and prompts. The architecture employs a plugin-based strategy pattern that allows combining different search backends—primarily Chroma (vector database) and SQLite—through a unified orchestration layer.

The search system serves as the foundation for context injection, enabling Claude Code to retrieve relevant historical observations from previous sessions and maintain knowledge continuity across session boundaries.

Source: https://github.com/thedotmack/claude-mem / Human Manual

MCP Tools and Context Generation

Related topics: Search Architecture, Worker Service Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Related topics: Search Architecture, Worker Service Architecture

MCP Tools and Context Generation

Overview

MCP (Model Context Protocol) Tools and Context Generation form the core infrastructure that enables claude-mem to provide persistent memory capabilities across Claude Code sessions. This system captures tool usage observations, generates semantic summaries, and makes them available to future sessions through a structured context injection mechanism.

The architecture consists of three primary layers:

  1. Observation Capture Layer - Captures tool interactions and state changes during Claude Code sessions
  2. Context Generation Layer - Transforms raw observations into structured, queryable context
  3. Context Injection Layer - Delivers relevant context to Claude Code when new sessions start

Sources: src/server/generation/providers/shared/prompt-builder.ts:1-50

Sources: src/server/generation/providers/shared/prompt-builder.ts:1-50

Installation Guide

Claude-Mem is a persistent memory plugin for Claude Code, enabling seamless context preservation across sessions. This guide covers all supported installation methods across different plat...

Section Quick Install

Continue reading this section for the full explanation and source context.

Section Post-Installation Steps

Continue reading this section for the full explanation and source context.

Section Gemini CLI

Continue reading this section for the full explanation and source context.

Section OpenCode

Continue reading this section for the full explanation and source context.

Claude-Mem is a persistent memory plugin for Claude Code, enabling seamless context preservation across sessions. This guide covers all supported installation methods across different platforms and integrated development environments.

Overview

Claude-Mem can be installed through multiple channels depending on your use case:

Installation MethodPlatformUse Case
npx claude-mem installmacOS, Linux, WindowsStandard installation for Claude Code
npx claude-mem install --ide gemini-cliAll platformsIntegration with Gemini CLI
npx claude-mem install --ide opencodeAll platformsIntegration with OpenCode
/plugin commandsClaude CodeIn-app plugin marketplace
OpenClaw GatewayOpenClawPersistent memory on OpenClaw gateways
DockerContainerizedIsolated deployment environments

All installations store data locally in ~/.claude-mem on the host machine. Sources: README.md

System Requirements

Before installation, ensure your environment meets the following prerequisites:

RequirementSpecification
Node.js18+
Package Managernpm, npx
Claude CodePro/Max subscription for CLI-based auth
API KeyANTHROPIC_API_KEY (optional alternative)

For API-based authentication in CI/CD environments, set the ANTHROPIC_API_KEY environment variable. Claude Code installations with authenticated Pro/Max subscriptions automatically use built-in authentication. Sources: README.md

Standard Installation (Claude Code)

Quick Install

The recommended installation method uses npx to install and configure the plugin:

npx claude-mem install

This command performs the following operations:

  1. Detects the Claude Code installation location
  2. Installs plugin hooks in the appropriate configuration directory
  3. Sets up the worker service for observation capture
  4. Configures the local memory storage at ~/.claude-mem

Post-Installation Steps

After installation completes:

  1. Keep the provided localhost URL open in a browser
  2. Open Claude Code in any project
  3. Observations stream automatically as Claude reads, edits, and runs commands
  4. Memory injection starts on your second session in a project

Two paths are available for building memory:

OptionApproachTime
A. PassiveJust start working; memory builds from your first promptOngoing
B. Front-loadRun /learn-codebase to ingest the entire repository~5 minutes

Sources: src/npx-cli/commands/install.ts

IDE-Specific Installations

Gemini CLI

npx claude-mem install --ide gemini-cli

This auto-detects the ~/.gemini configuration directory and installs the appropriate hooks for Gemini CLI integration.

OpenCode

npx claude-mem install --ide opencode

Configures hooks specifically for OpenCode IDE environments.

Sources: src/npx-cli/install/setup-runtime.ts

In-App Plugin Installation

For users who prefer the Claude Code interface:

  1. Open Claude Code and access the plugin marketplace
  2. Add the plugin: /plugin marketplace add thedotmack/claude-mem
  3. Install the plugin: /plugin install claude-mem
  4. Restart Claude Code or Gemini CLI

Context from previous sessions automatically appears in new sessions after installation completes. Sources: README.md

OpenClaw Gateway Installation

For persistent memory on OpenClaw gateways, a dedicated installation script is provided:

curl -fsSL https://install.cmem.ai/openclaw.sh | bash

This script configures claude-mem as a persistent memory plugin on OpenClaw gateways. Sources: openclaw/install.sh

OpenClaw Plugin Configuration

The OpenClaw integration uses a plugin manifest file that defines:

{
  "name": "claude-mem",
  "version": "1.0.0",
  "description": "Persistent memory for Claude Code"
}

Sources: openclaw/openclaw.plugin.json

Docker Installation

For containerized or isolated deployment environments, Docker installation is available.

Building the Docker Image

cd docker/claude-mem
docker build -t claude-mem .

Running the Container

docker run -d \
  --name claude-mem \
  -p 8080:8080 \
  -v ~/.claude-mem:/data \
  claude-mem

The Docker setup uses a multi-stage build with Node.js 20 as the base image and serves the worker service on port 8080. Sources: docker/claude-mem/Dockerfile

Docker Environment Variables

VariableDescriptionDefault
PORTWorker service port8080
CLAUDE_MEM_DATA_DIRMemory storage directory/data
ANTHROPIC_API_KEYAPI authenticationRequired if no Claude Code

Sources: docker/claude-mem/README.md

Installation Workflow

graph TD
    A[User runs npx claude-mem install] --> B{Detect Platform}
    B -->|macOS/Linux| C[Find Claude Code config]
    B -->|Windows| D[Find Claude Code config]
    B -->|Gemini CLI| E[Detect ~/.gemini]
    B -->|OpenCode| F[Detect OpenCode config]
    
    C --> G[Install hooks to config dir]
    D --> G
    E --> H[Install gemini-cli hooks]
    F --> I[Install opencode hooks]
    
    G --> J[Start worker service]
    H --> J
    I --> J
    
    J --> K[Display success URL]
    K --> L[User opens Claude Code]
    L --> M[Observations begin streaming]
    M --> N[Memory injection on 2nd session]

Verification and Status

After installation, verify the setup:

npx claude-mem status

If the worker is not yet ready:

npx claude-mem start

Manual startup may be required if the worker failed to start automatically on the configured port (default: 8080). Sources: src/npx-cli/commands/install.ts

Uninstallation

To uninstall claude-mem:

  1. Close all Claude Code sessions (prevents hooks from recreating configuration)
  2. Run the uninstall command or manually remove:
  • ~/.claude-mem directory
  • Plugin hooks from Claude Code config directory
  • Any installed Claude Code plugins

Sources: src/npx-cli/commands/install.ts

Troubleshooting

IssueSolution
Worker not readyWait ~30 seconds, then run npx claude-mem start
Hooks recreatedClose all Claude Code sessions before uninstalling
No observationsEnsure memory injection starts on second session
Auth issuesVerify ANTHROPIC_API_KEY or Claude Code Pro/Max subscription

First Session Hint

The welcome hint on first sessions can be disabled:

CLAUDE_MEM_WELCOME_HINT_ENABLED=false

Documentation

For additional help:

  • Documentation: https://docs.claude-mem.ai
  • How it works: /how-it-works in Claude Code

Sources: src/npx-cli/commands/install.ts

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)

First-time setup may fail or require extra isolation and rollback planning.

high Windows: cmd.exe /c uvx wrapper breaks Chroma MCP stdio on WinGet uv installs (regression after #1190 / #1199) --> FIX…

First-time setup may fail or require extra isolation and rollback planning.

high Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session

First-time setup may fail or require extra isolation and rollback planning.

high chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

First-time setup may fail or require extra isolation and rollback planning.

Doramagic Pitfall Log

Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.

1. Installation risk: Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0)

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Windows worker spawn silently fails when user home path contains a space (four stacked bugs, still present in v13.2.0). Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2521

2. Installation risk: Windows: cmd.exe /c uvx wrapper breaks Chroma MCP stdio on WinGet uv installs (regression after #1190 / #1199) --> FIX…

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Windows: cmd.exe /c uvx wrapper breaks Chroma MCP stdio on WinGet uv installs (regression after #1190 / #1199) --> FIX…. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2426

3. Installation risk: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session

  • Severity: high
  • Finding: Installation risk is backed by a source signal: Worker PID file not cleaned up after system sleep/hibernate, Worker fails to restart on new session. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2432

4. Installation risk: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

  • Severity: high
  • Finding: Installation risk is backed by a source signal: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2438

5. Installation risk: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote)

  • Severity: high
  • Finding: Installation risk is backed by a source signal: v13.0.0 marketplace install bundle ships without bundled node_modules (zod, shell-quote). Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2407

6. Installation risk: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing…

  • Severity: high
  • Finding: Installation risk is backed by a source signal: v13.2.0: smart_outline / smart_unfold / smart_search silently no-op — tree-sitter grammars unresolvable due to missing…. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2520

7. Installation risk: v13: merged_into_project migration silently skipped on pre-existing DBs (schema_versions ≤ 23)

  • Severity: high
  • Finding: Installation risk is backed by a source signal: v13: merged_into_project migration silently skipped on pre-existing DBs (schema_versions ≤ 23). Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2433

8. Configuration risk: Use node to run mcp for windows environment

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: Use node to run mcp for windows environment. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2446

9. Configuration risk: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection

  • Severity: high
  • Finding: Configuration risk is backed by a source signal: chroma-mcp fails to connect on Windows: cmd.exe misinterprets protobuf<7 as I/O redirection. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2438

10. Project risk: Project risk needs validation

  • Severity: high
  • Finding: Project risk is backed by a source signal: Project risk needs validation. Treat it as a review item until the current version is checked.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2441

11. Security or permission risk: Feature: Vertex AI support for Gemini provider

  • Severity: high
  • Finding: Security or permission risk is backed by a source signal: Feature: Vertex AI support for Gemini provider. Treat it as a review item until the current version is checked.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2522

12. Security or permission risk: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection

  • Severity: high
  • Finding: Security or permission risk is backed by a source signal: Windows: chroma-mcp connection fails instantly — cmd.exe interprets < > in version constraints as redirection. Treat it as a review item until the current version is checked.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/thedotmack/claude-mem/issues/2509

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using claude-mem with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence