Skip to main content

Architecture Evolution

The Problem We Solved

Goal: Create a memory system that makes Claude smarter across sessions without the user noticing it exists. Challenge: How do you observe AI agent behavior, compress it intelligently, and serve it back at the right time - all without slowing down or interfering with the main workflow? This is the story of how claude-mem evolved from a simple idea to a production-ready system, and the key architectural decisions that made it work.

v5.x: Maturity and User Experience

After establishing the solid v4 architecture, v5.x focused on user experience, visualization, and polish.

v5.1.2: Theme Toggle (November 2025)

What Changed: Added light/dark mode theme toggle to viewer UI New Features:
  • User-selectable theme preference (light, dark, system)
  • Persistent theme settings in localStorage
  • Smooth theme transitions
  • System preference detection
Implementation:
Why It Matters: Users working in different lighting conditions can now customize the viewer for comfort.

v5.1.1: Worker Startup Fix (November 2025) - Now Deprecated

Note: This section describes a historical PM2-based approach that has been replaced with Bun in later versions. The Problem: Worker startup failed on Windows with ENOENT error when using PM2 Historical Solution: Used full path to PM2 binary instead of relying on PATH Current Approach: The project now uses Bun for process management, which provides better cross-platform compatibility and eliminates these PATH-related issues. Impact: Cross-platform compatibility restored, Windows users can now use claude-mem without issues.

v5.1.0: Web-Based Viewer UI (October 2025)

The Breakthrough: Real-time visualization of memory stream What We Built:
  • React-based web UI at http://localhost:37777
  • Server-Sent Events (SSE) for real-time updates
  • Infinite scroll pagination
  • Project filtering
  • Settings persistence (sidebar state, selected project)
  • Auto-reconnection with exponential backoff
  • GPU-accelerated animations
New Worker Endpoints (8 additions):
Database Enhancements: SessionStore gained paginated queries for recent prompts, observations, and summaries (filterable by project), plus database stats and project listing to back the viewer endpoints. (These viewer-specific methods were later replaced by the unified search layer.) React Architecture:
Build Process:
Why It Matters: Users can now see exactly what’s being captured in real-time, making the memory system transparent and debuggable.

v5.0.3: Smart Install Caching (October 2025)

The Problem: npm install ran on every SessionStart (2-5 seconds) The Insight: Dependencies rarely change between sessions The Solution: Version-based caching
Cached Check Logic:
  1. Does node_modules exist?
  2. Does .install-version match package.json version?
  3. Is better-sqlite3 present? (Legacy: now uses bun:sqlite which requires no installation)
Impact:
  • SessionStart hook: 2-5 seconds → 10ms (99.5% faster)
  • Only installs on: first run, version change, missing deps
  • Better Windows error messages with build tool help

v5.0.2: Worker Health Checks (October 2025)

What Changed: More robust worker startup and monitoring New Features:
Benefits:
  • Graceful degradation when worker is down
  • Auto-recovery from crashes
  • Better error messages for debugging

v5.0.1: Stability Improvements (October 2025)

What Changed: Various bug fixes and stability enhancements Key Fixes:
  • Fixed race conditions in observation queue processing
  • Improved error handling in SDK worker
  • Better cleanup of stale worker processes
  • Enhanced logging for debugging

v5.0.0: Hybrid Search Architecture (October 2025)

The Evolution: SQLite FTS5 + Chroma vector search What We Added:
New Dependencies:
  • chromadb - Vector database for semantic search
  • Python 3.8+ - Required by chromadb
MCP Tools Enhancement:
Why Hybrid:
  • FTS5: Fast keyword matching, no dependencies
  • Chroma: Semantic understanding, finds related concepts
  • Graceful degradation: Works without Chroma (FTS5 only)
Trade-offs:
  • Added Python dependency (optional)
  • Increased installation complexity
  • Better search relevance

MCP Architecture Simplification (December 2025)

The Problem: Complex MCP Implementation

Before:
The Insight: Progressive disclosure should be built into tool design itself, not something Claude has to remember.

The Solution: 3-Layer Workflow

After:

Migration: Skill-Based Search Removed

Previously: Used skill-based search
  • mem-search skill invoked via natural language
  • HTTP API called directly via curl
  • Progressive disclosure through skill loading
  • 17 skill documentation files
Now: Removed skill-based approach
  • MCP-only architecture
  • Native MCP protocol (better Claude integration)
  • Works with both Claude Desktop and Claude Code
  • Simpler to maintain (no skill files)
  • All 19 mem-search skill files removed (~2,744 lines)

Key Architectural Changes

MCP Server Refactor: Before:
After:
Workflow Enforcement: Before: Claude had to remember progressive disclosure pattern After: Tool structure makes it impossible to skip steps
  • Can’t get details without IDs from search
  • Can’t search without seeing __IMPORTANT reminder
  • Timeline provides middle ground (context without full details)

Impact

Token Efficiency:
Code Simplicity:
  • MCP server: 2,718 lines → 312 lines (88% reduction)
  • Removed: 19 skill files (~2,744 lines)
  • Net reduction: ~5,150 lines of code removed
User Experience:
  • Same natural language interaction
  • Better token efficiency
  • Clearer architecture
  • Works identically on Claude Desktop and Claude Code

Design Philosophy

Progressive Disclosure Through Structure: The 3-layer workflow embodies progressive disclosure at the architectural level:
  1. Layer 1 (Index) - “What exists?” - Cheap survey of options
  2. Layer 2 (Timeline) - “What was happening?” - Context around specific points
  3. Layer 3 (Details) - “Tell me everything” - Full details only when justified
Each layer provides a decision point where Claude can:
  • Stop if irrelevant
  • Get more context if uncertain
  • Dive deep if confident
This makes it structurally difficult to waste tokens.

v1-v2: The Naive Approach

The First Attempt: Dump Everything

Architecture:
What we learned:
  • ❌ Context pollution (thousands of tokens of irrelevant data)
  • ❌ No compression (raw tool outputs are verbose)
  • ❌ No search (had to scan everything linearly)
  • ✅ Proved the concept: Memory across sessions is valuable
Example of what went wrong:

v3: Smart Compression, Wrong Architecture

The Breakthrough: AI-Powered Compression

New idea: Use Claude itself to compress observations Architecture:
What we added:
  1. Claude Agent SDK integration - Use AI to compress observations
  2. Background worker - Don’t block main session
  3. Structured observations - Extract facts, decisions, insights
  4. Session summaries - Generate comprehensive summaries
What worked:
  • ✅ Compression ratio: 10:1 to 100:1
  • ✅ Semantic understanding (not just keyword matching)
  • ✅ Background processing (hooks stayed fast)
  • ✅ Search became useful
What didn’t work:
  • ❌ Still loaded everything upfront
  • ❌ Session ID management was broken
  • ❌ Aggressive cleanup interrupted summaries
  • ❌ Multiple SDK sessions per Claude Code session

The Key Realizations

Realization 1: Progressive Disclosure

Problem: Even compressed observations can pollute context if you load them all. Insight: Humans don’t read everything before starting work. Why should AI? Solution: Show an index first, fetch details on-demand.
Impact:
  • 87% reduction in context usage
  • 100% relevance (only fetch what’s needed)
  • Agent autonomy (decides what’s relevant)

Realization 2: Session ID Chaos

Problem: SDK session IDs change on every turn. What we thought:
Reality:
Why this matters:
  • Can’t resume sessions without tracking ID updates
  • Session state gets lost between turns
  • Observations get orphaned
Solution:

Realization 3: Graceful vs Aggressive Cleanup

v3 approach:
Problems:
  • Summary generation interrupted mid-process
  • Pending observations lost
  • Race conditions everywhere
v4 approach:
Benefits:
  • Summaries complete successfully
  • No lost observations
  • Clean state transitions
Code:

Realization 4: One Session, Not Many

Problem: We were creating multiple SDK sessions per Claude Code session. What we thought:
Reality should be:
Why this matters:
  • SDK maintains conversation state
  • Context accumulates naturally
  • Much more efficient
Implementation:

v4: The Architecture That Works

The Core Design

The Five Hook Architecture

Purpose: Inject context from previous sessionsTiming: When Claude Code startsWhat it does:
  • Queries last 10 session summaries
  • Formats as progressive disclosure index
  • Injects into context via stdout
Key change from v3:
  • ✅ Index format (not full details)
  • ✅ Token counts visible
  • ✅ MCP search instructions included

Database Schema Evolution

v3 schema:
v4 schema:
What changed:
  • ✅ Structured fields (title, subtitle, type)
  • ✅ FTS5 full-text search
  • ✅ Project-scoped queries
  • ✅ Rich metadata for progressive disclosure

Worker Service Redesign

v3 worker:
v4 worker:
Benefits:
  • Maintains conversation state
  • SDK handles context automatically
  • More efficient (fewer API calls)
  • Natural multi-turn flow

Critical Fixes Along the Way

Fix 1: Context Injection Pollution (v4.3.1)

Problem: SessionStart hook output polluted with npm install logs
Why it broke:
  • Claude Code expects clean JSON or plain text
  • stderr/stdout from npm install mixed with hook output
  • Context didn’t inject properly
Solution:
Result: Clean JSON output, context injection works

Fix 2: Double Shebang Issue (v4.3.1)

Problem: Hook executables had duplicate shebangs
Why it happened:
  • Source files had shebang
  • esbuild added another shebang during build
Solution:
Result: Clean executables, no parsing errors

Fix 3: FTS5 Injection Vulnerability (v4.2.3)

Problem: User input passed directly to FTS5 query
Attack:
Solution:

Fix 4: NOT NULL Constraint Violation (v4.2.8)

Problem: Session creation failed when prompt was empty
Solution:
Schema change:

Performance Improvements

Optimization 1: Prepared Statements

Before:
After:
Impact: 5x faster bulk inserts

Optimization 2: FTS5 Indexing

Before:
After:
Impact: 100x faster searches on large datasets

Optimization 3: Index Format Default

Before:
After:
Impact: 25x reduction in average search result size

What We Learned

Lesson 1: Context is Precious

Principle: Every token you put in context window costs attention. Application:
  • Progressive disclosure reduces waste by 87%
  • Index-first approach gives agent control
  • Token counts make costs visible

Lesson 2: Session State is Complicated

Principle: Distributed state is hard. SDK handles it better than we can. Application:
  • Use SDK’s built-in session resumption
  • Don’t try to manually reconstruct state
  • Track session IDs from init messages

Lesson 3: Graceful Beats Aggressive

Principle: Let processes finish their work before terminating. Application:
  • Graceful cleanup prevents data loss
  • Workers finish important operations
  • Clean state transitions reduce bugs

Lesson 4: AI is the Compressor

Principle: Don’t compress manually. Let AI do semantic compression. Application:
  • 10:1 to 100:1 compression ratios
  • Semantic understanding, not keyword extraction
  • Structured outputs (XML parsing)

Lesson 5: Progressive Everything

Principle: Show metadata first, fetch details on-demand. Application:
  • Progressive disclosure in context injection
  • Index format in search results
  • Layer 1 (titles) → Layer 2 (summaries) → Layer 3 (full details)

The Road Ahead

Planned: Adaptive Index Size

Planned: Relevance Scoring

Planned: Multi-Project Context

Planned: Collaborative Memory


Migration Guide: v3 → v5

Step 1: Backup Database

Step 2: Update Plugin

Step 3: Update Plugin

What happens automatically:
  • Dependencies update (including new ones like chromadb for v5.0.0+)
  • Database schema migrations run automatically
  • Worker service restarts with new code
  • Smart install caching activates (v5.0.3+)

Step 4: Test

Step 5: Explore New Features


Key Metrics

v3 Performance

v4 Performance

v5 Performance

v3 → v4 Improvements:
  • 96% reduction in context waste
  • 12x increase in relevance
  • 4x faster hooks
  • 33x faster search
v4 → v5 Improvements:
  • 78% faster hooks (smart caching)
  • Real-time visualization (viewer UI)
  • Better search relevance (hybrid)
  • Enhanced UX (theme toggle, persistence)

Conclusion

The journey from v3 to v5 was about understanding these fundamental truths:
  1. Context is finite - Progressive disclosure respects attention budget
  2. AI is the compressor - Semantic understanding beats keyword extraction
  3. Agents are smart - Let them decide what to fetch
  4. State is hard - Use SDK’s built-in mechanisms
  5. Graceful wins - Let processes finish cleanly
The result is a memory system that’s both powerful and invisible. Users never notice it working - Claude just gets smarter over time. v5 adds visibility: Now users CAN see the memory system working if they want (via viewer UI), but it’s still non-intrusive.

Further Reading


This architecture evolution reflects hundreds of hours of experimentation, dozens of dead ends, and the invaluable experience of real-world usage. v5 is the architecture that emerged from understanding what actually works - and making it visible to users.