Understand how claude-mem selects, filters, and presents memories to maximize your persistent context system.

Loading Process Overview

Context loading provides relevant memories when Claude Code starts:

Core Components

Memory Index Structure

Memories stored in JSONL format for efficient processing:

Memory Entry Schema

interface MemoryEntry {
  // Core content
  text: string;              // Compressed insight or summary
  project: string;           // Project identifier
  timestamp: string;         // ISO 8601 timestamp

  // Memory classification
  type: 'memory' | 'overview' | 'session' | 'decision';
  entity_type?: string;      // Technical classification

  // Metadata
  document_id: string;       // Unique identifier
  keywords: string[];        // Searchable tags
  session_id?: string;       // Source session

  // Optional enrichment
  confidence?: number;       // Quality score (0-1)
  context?: string;         // Additional context
  relationships?: string[];  // Related memory IDs
}

Example Memory Entries

Project-Based Filtering

Project Identification

Cross-Project Knowledge

Some memories are intentionally shared across projects:

Memory Ranking Algorithm

Ranking Factors

The context loading system uses multiple factors to rank memory relevance:
1

Temporal Relevance (40% weight)

Recent memories rank higher:
function calculateTemporalScore(timestamp: string): number {
  const age = Date.now() - new Date(timestamp).getTime();
  const daysOld = age / (1000 * 60 * 60 * 24);

  // Exponential decay: newer memories score higher
  return Math.exp(-daysOld / 30); // 30-day half-life
}
  • Last 24 hours: Score 0.8-1.0
  • Last week: Score 0.6-0.8
  • Last month: Score 0.3-0.6
  • Older: Score < 0.3
2

Project Match Score (30% weight)

Project alignment scoring:
function calculateProjectScore(memoryProject: string, currentProject: string): number {
  if (memoryProject === currentProject) return 1.0;      // Perfect match
  if (memoryProject === null) return 0.7;               // Global knowledge
  if (isRelatedProject(memoryProject, currentProject)) return 0.4; // Related
  return 0.1; // Different project
}
3

Memory Type Priority (20% weight)

Content type weighting:
  • Overview memories: Score 1.0 (always high priority)
  • Decision records: Score 0.9 (architectural context)
  • Implementation insights: Score 0.8 (technical details)
  • General memories: Score 0.7 (standard insights)
  • Session metadata: Score 0.3 (background context)
4

Quality Indicators (10% weight)

Content quality scoring:
  • Memory length (optimal 50-200 characters)
  • Keyword richness
  • Explicit confidence scores
  • User engagement (manually saved vs auto-generated)

Final Ranking Formula

function calculateFinalScore(memory: MemoryEntry, context: LoadingContext): number {
  const temporal = calculateTemporalScore(memory.timestamp) * 0.4;
  const project = calculateProjectScore(memory.project, context.currentProject) * 0.3;
  const type = getTypeScore(memory.type) * 0.2;
  const quality = calculateQualityScore(memory) * 0.1;

  return temporal + project + type + quality;
}

Context Formatting

Session Start Format

When Claude Code starts, memories are formatted for optimal Claude understanding:
# 🧠 Context from Previous Sessions

**Project**: ecommerce-app | **Last Session**: 2 hours ago | **Memories**: 12 recent insights

## 📋 Project Overview
- E-commerce platform using React/TypeScript frontend, Node.js/Express backend
- PostgreSQL database with Prisma ORM
- JWT authentication with refresh token rotation

## 🔧 Recent Technical Insights
- Implemented user authentication with JWT refresh token rotation for security
- Chose Zustand over Redux for state management (simpler API, smaller bundle)
- Added input validation using Zod schemas for type safety

## 🏗️ Architecture Decisions
- Microservices architecture with API Gateway pattern
- Event-driven user notifications using WebSocket connections
- Docker containerization for consistent deployment environments

## 💡 Development Patterns
- Custom React hooks for API calls with error handling
- Consistent error response format: {error, code, details}
- Test-driven development for critical business logic

Context Injection Strategy

Loading Performance

Optimization Strategies

Performance Monitoring

# Check loading performance
time claude-mem load-context

# Monitor memory count
claude-mem load-context --format json | jq length

# Check index size
du -sh ~/.claude-mem/index/

# Profile memory loading
claude-mem load-context --verbose

Troubleshooting Context Loading

Common Issues

Configuration Options

# Adjust memory count
claude-mem load-context --count 5

# Filter by project explicitly
claude-mem load-context --project my-specific-project

# Get raw JSON for analysis
claude-mem load-context --format json

# Test session-start format
claude-mem load-context --format session-start

Advanced Context Loading

Custom Memory Queries

For advanced use cases, you can directly query the memory system:
// Custom memory loading logic
const memories = await loadMemoriesWhere({
  project: 'my-project',
  type: ['memory', 'decision'],
  after: '2024-09-01',
  keywords: ['authentication', 'security']
});

Integration with Development Workflow

# Load context for specific features
claude-mem load-context --project my-app | grep -i authentication

# Export memories for documentation
claude-mem load-context --format json > project-knowledge.json

# Create memory snapshots
claude-mem load-context --count 50 > milestone-context.md

The context loading system is designed to provide Claude with the most relevant and useful information from your previous sessions, ensuring continuity and building on past insights for more productive development sessions.