Files
claude-mem/MONOLITH_REFACTOR_REPORT.md
Alex Newman 2fc4153bef refactor: decompose monolithic services into modular architecture (#534)
* docs: add monolith refactor report with system breakdown

Comprehensive analysis of codebase identifying:
- 14 files over 500 lines requiring refactoring
- 3 critical monoliths (SessionStore, SearchManager, worker-service)
- 80% code duplication across agent files
- 5-phase refactoring roadmap with domain-based architecture

* fix: prevent memory_session_id from equaling content_session_id

The bug: memory_session_id was initialized to contentSessionId as a
"placeholder for FK purposes". This caused the SDK resume logic to
inject memory agent messages into the USER's Claude Code transcript,
corrupting their conversation history.

Root cause:
- SessionStore.createSDKSession initialized memory_session_id = contentSessionId
- SDKAgent checked memorySessionId !== contentSessionId but this check
  only worked if the session was fetched fresh from DB

The fix:
- SessionStore: Initialize memory_session_id as NULL, not contentSessionId
- SDKAgent: Simple truthy check !!session.memorySessionId (NULL = fresh start)
- Database migration: Ran UPDATE to set memory_session_id = NULL for 1807
  existing sessions that had the bug

Also adds [ALIGNMENT] logging across the session lifecycle to help debug
session continuity issues:
- Hook entry: contentSessionId + promptNumber
- DB lookup: contentSessionId → memorySessionId mapping proof
- Resume decision: shows which memorySessionId will be used for resume
- Capture: logs when memorySessionId is captured from first SDK response

UI: Added "Alignment" quick filter button in LogsModal to show only
alignment logs for debugging session continuity.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: improve error handling in worker-service.ts

- Fix GENERIC_CATCH anti-patterns by logging full error objects instead of just messages
- Add [ANTI-PATTERN IGNORED] markers for legitimate cases (cleanup, hot paths)
- Simplify error handling comments to be more concise
- Improve httpShutdown() error discrimination for ECONNREFUSED
- Reduce LARGE_TRY_BLOCK issues in initialization code

Part of anti-pattern cleanup plan (132 total issues)

* refactor: improve error logging in SearchManager.ts

- Pass full error objects to logger instead of just error.message
- Fixes PARTIAL_ERROR_LOGGING anti-patterns (10 instances)
- Better debugging visibility when Chroma queries fail

Part of anti-pattern cleanup (133 remaining)

* refactor: improve error logging across SessionStore and mcp-server

- SessionStore.ts: Fix error logging in column rename utility
- mcp-server.ts: Log full error objects instead of just error.message
- Improve error handling in Worker API calls and tool execution

Part of anti-pattern cleanup (133 remaining)

* Refactor hooks to streamline error handling and loading states

- Simplified error handling in useContextPreview by removing try-catch and directly checking response status.
- Refactored usePagination to eliminate try-catch, improving readability and maintaining error handling through response checks.
- Cleaned up useSSE by removing unnecessary try-catch around JSON parsing, ensuring clarity in message handling.
- Enhanced useSettings by streamlining the saving process, removing try-catch, and directly checking the result for success.

* refactor: add error handling back to SearchManager Chroma calls

- Wrap queryChroma calls in try-catch to prevent generator crashes
- Log Chroma errors as warnings and fall back gracefully
- Fixes generator failures when Chroma has issues
- Part of anti-pattern cleanup recovery

* feat: Add generator failure investigation report and observation duplication regression report

- Created a comprehensive investigation report detailing the root cause of generator failures during anti-pattern cleanup, including the impact, investigation process, and implemented fixes.
- Documented the critical regression causing observation duplication due to race conditions in the SDK agent, outlining symptoms, root cause analysis, and proposed fixes.

* fix: address PR #528 review comments - atomic cleanup and detector improvements

This commit addresses critical review feedback from PR #528:

## 1. Atomic Message Cleanup (Fix Race Condition)

**Problem**: SessionRoutes.ts generator error handler had race condition
- Queried messages then marked failed in loop
- If crash during loop → partial marking → inconsistent state

**Solution**:
- Added `markSessionMessagesFailed()` to PendingMessageStore.ts
- Single atomic UPDATE statement replaces loop
- Follows existing pattern from `resetProcessingToPending()`

**Files**:
- src/services/sqlite/PendingMessageStore.ts (new method)
- src/services/worker/http/routes/SessionRoutes.ts (use new method)

## 2. Anti-Pattern Detector Improvements

**Problem**: Detector didn't recognize logger.failure() method
- Lines 212 & 335 already included "failure"
- Lines 112-113 (PARTIAL_ERROR_LOGGING detection) did not

**Solution**: Updated regex patterns to include "failure" for consistency

**Files**:
- scripts/anti-pattern-test/detect-error-handling-antipatterns.ts

## 3. Documentation

**PR Comment**: Added clarification on memory_session_id fix location
- Points to SessionStore.ts:1155
- Explains why NULL initialization prevents message injection bug

## Review Response

Addresses "Must Address Before Merge" items from review:
 Clarified memory_session_id bug fix location (via PR comment)
 Made generator error handler message cleanup atomic
 Deferred comprehensive test suite to follow-up PR (keeps PR focused)

## Testing

- Build passes with no errors
- Anti-pattern detector runs successfully
- Atomic cleanup follows proven pattern from existing methods

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* fix: FOREIGN KEY constraint and missing failed_at_epoch column

Two critical bugs fixed:

1. Missing failed_at_epoch column in pending_messages table
   - Added migration 20 to create the column
   - Fixes error when trying to mark messages as failed

2. FOREIGN KEY constraint failed when storing observations
   - All three agents (SDK, Gemini, OpenRouter) were passing
     session.contentSessionId instead of session.memorySessionId
   - storeObservationsAndMarkComplete expects memorySessionId
   - Added null check and clear error message

However, observations still not saving - see investigation report.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* Refactor hook input parsing to improve error handling

- Added a nested try-catch block in new-hook.ts, save-hook.ts, and summary-hook.ts to handle JSON parsing errors more gracefully.
- Replaced direct error throwing with logging of the error details using logger.error.
- Ensured that the process exits cleanly after handling input in all three hooks.

* docs: update monolith report post session-logging merge

- SessionStore grew to 2,011 lines (49 methods) - highest priority
- SearchManager reduced to 1,778 lines (improved)
- Agent files reduced by ~45 lines combined
- Added trend indicators and post-merge observations
- Core refactoring proposal remains valid

* refactor(sqlite): decompose SessionStore into modular architecture

Extract the 2011-line SessionStore.ts monolith into focused, single-responsibility
modules following grep-optimized progressive disclosure pattern:

New module structure:
- sessions/ - Session creation and retrieval (create.ts, get.ts, types.ts)
- observations/ - Observation storage and queries (store.ts, get.ts, recent.ts, files.ts, types.ts)
- summaries/ - Summary storage and queries (store.ts, get.ts, recent.ts, types.ts)
- prompts/ - User prompt management (store.ts, get.ts, types.ts)
- timeline/ - Cross-entity timeline queries (queries.ts)
- import/ - Bulk import operations (bulk.ts)
- migrations/ - Database migrations (runner.ts)

New coordinator files:
- Database.ts - ClaudeMemDatabase class with re-exports
- transactions.ts - Atomic cross-entity transactions
- Named re-export facades (Sessions.ts, Observations.ts, etc.)

Key design decisions:
- All functions take `db: Database` as first parameter (functional style)
- Named re-exports instead of index.ts for grep-friendliness
- SessionStore retained as backward-compatible wrapper
- Target file size: 50-150 lines (60% compliance)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(agents): extract shared logic into modular architecture

Consolidate duplicate code across SDKAgent, GeminiAgent, and OpenRouterAgent
into focused utility modules. Total reduction: 500 lines (29%).

New modules in src/services/worker/agents/:
- ResponseProcessor.ts: Atomic DB transactions, Chroma sync, SSE broadcast
- ObservationBroadcaster.ts: SSE event formatting and dispatch
- SessionCleanupHelper.ts: Session state cleanup and stuck message reset
- FallbackErrorHandler.ts: Provider error detection for fallback logic
- types.ts: Shared interfaces (WorkerRef, SSE payloads, StorageResult)

Bug fix: SDKAgent was incorrectly using obs.files instead of obs.files_read
and hardcoding files_modified to empty array.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(search): extract search strategies into modular architecture

Decompose SearchManager into focused strategy pattern with:
- SearchOrchestrator: Coordinates strategy selection and fallback
- ChromaSearchStrategy: Vector semantic search via ChromaDB
- SQLiteSearchStrategy: Filter-only queries for date/project/type
- HybridSearchStrategy: Metadata filtering + semantic ranking
- ResultFormatter: Markdown table formatting for results
- TimelineBuilder: Chronological timeline construction
- Filter modules: DateFilter, ProjectFilter, TypeFilter

SearchManager now delegates to new infrastructure while maintaining
full backward compatibility with existing public API.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(context): decompose context-generator into modular architecture

Extract 660-line monolith into focused components:
- ContextBuilder: Main orchestrator (~160 lines)
- ContextConfigLoader: Configuration loading
- TokenCalculator: Token budget calculations
- ObservationCompiler: Data retrieval and query building
- MarkdownFormatter/ColorFormatter: Output formatting
- Section renderers: Header, Timeline, Summary, Footer

Maintains full backward compatibility - context-generator.ts now
delegates to new ContextBuilder while preserving public API.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(worker): decompose worker-service into modular infrastructure

Split 2000+ line monolith into focused modules:

Infrastructure:
- ProcessManager: PID files, signal handlers, child process cleanup
- HealthMonitor: Port checks, health polling, version matching
- GracefulShutdown: Coordinated cleanup on exit

Server:
- Server: Express app setup, core routes, route registration
- Middleware: Re-exports from existing middleware
- ErrorHandler: Centralized error handling with AppError class

Integrations:
- CursorHooksInstaller: Full Cursor IDE integration (registry, hooks, MCP)

WorkerService now acts as thin coordinator wiring all components together.
Maintains full backward compatibility with existing public API.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Refactor session queue processing and database interactions

- Implement claim-and-delete pattern in SessionQueueProcessor to simplify message handling and eliminate duplicate processing.
- Update PendingMessageStore to support atomic claim-and-delete operations, removing the need for intermediate processing states.
- Introduce storeObservations method in SessionStore for simplified observation and summary storage without message tracking.
- Remove deprecated methods and clean up session state management in worker agents.
- Adjust response processing to accommodate new storage patterns, ensuring atomic transactions for observations and summaries.
- Remove unnecessary reset logic for stuck messages due to the new queue handling approach.

* Add duplicate observation cleanup script

Script to clean up duplicate observations created by the batching bug
where observations were stored once per message ID instead of once per
observation. Includes safety checks to always keep at least one copy.

Usage:
  bun scripts/cleanup-duplicates.ts           # Dry run
  bun scripts/cleanup-duplicates.ts --execute # Delete duplicates
  bun scripts/cleanup-duplicates.ts --aggressive # Ignore time window

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-03 21:22:27 -05:00

11 KiB

Monolith Refactor Report

Last Updated: 2026-01-03 (post session-logging merge)

Executive Summary

The claude-mem codebase contains ~21,000 lines of TypeScript across 71+ files. Analysis reveals several monolithic files that violate single-responsibility principles and create tight coupling. This report identifies refactoring targets and proposes a modular architecture.

Recent Changes: The session-logging branch merge improved error handling across the codebase. SearchManager was reduced by ~180 lines, but SessionStore grew by ~110 lines due to new migrations and logging.


Part 1: Monolith Files Identified

Critical Priority (>1500 lines)

File Lines Methods Primary Issues Trend
src/services/worker-service.ts 2,034 - Server init, process management, Cursor hooks, MCP setup all mixed ↓ -28
src/services/sqlite/SessionStore.ts 2,011 49 Migrations + CRUD + queries + transformations all in one class ↑ +108
src/services/worker/SearchManager.ts 1,778 17 Three search strategies crammed together, formatting mixed in ↓ -178

High Priority (500-1500 lines)

File Lines Issues Trend
src/services/sync/ChromaSync.ts 870 Sync and query operations mixed
src/services/context-generator.ts 659 23 standalone functions, no class structure
src/services/worker/http/routes/SessionRoutes.ts 625 Provider selection mixed with business logic ↑ +7
src/services/worker/OpenRouterAgent.ts 599 80% code duplicated from other agents ↓ -15
src/services/worker/GeminiAgent.ts 574 80% code duplicated from other agents ↓ -15
src/services/worker/SDKAgent.ts 546 Base patterns duplicated across all agents ↓ -15
src/services/sqlite/SessionSearch.ts 526 FTS5 tables maintained for backward compat
src/services/sqlite/migrations.ts 509 All 11 migrations in single file
src/services/sqlite/PendingMessageStore.ts 447 Message queue operations ↑ +21
src/services/worker/http/routes/SettingsRoutes.ts 414 File I/O, validation, git ops mixed

Code Duplication Issue

The three agent files (SDKAgent, GeminiAgent, OpenRouterAgent) share ~80% duplicate code:

  • Message building logic
  • Result parsing
  • Context updating
  • Database sync patterns

Part 2: System Breakdown Proposal

Domain-Based Module Architecture

src/
├── domains/                    # Business domain modules
│   ├── sessions/               # Session lifecycle
│   │   ├── SessionRepository.ts
│   │   ├── SessionService.ts
│   │   └── types.ts
│   │
│   ├── observations/           # Observation management
│   │   ├── ObservationRepository.ts
│   │   ├── ObservationService.ts
│   │   └── types.ts
│   │
│   ├── summaries/              # Summary generation
│   │   ├── SummaryRepository.ts
│   │   ├── SummaryService.ts
│   │   └── types.ts
│   │
│   ├── prompts/                # Prompt storage
│   │   ├── PromptRepository.ts
│   │   └── types.ts
│   │
│   └── search/                 # Search subsystem
│       ├── strategies/
│       │   ├── ChromaSearchStrategy.ts
│       │   ├── FilterSearchStrategy.ts
│       │   └── SearchStrategy.ts (interface)
│       ├── SearchOrchestrator.ts
│       ├── ResultFormatter.ts
│       └── TimelineBuilder.ts
│
├── infrastructure/             # Cross-cutting infrastructure
│   ├── database/
│   │   ├── DatabaseConnection.ts
│   │   ├── TransactionManager.ts
│   │   └── migrations/
│   │       ├── MigrationRunner.ts
│   │       ├── 001_initial.ts
│   │       ├── 002_add_prompts.ts
│   │       └── ...
│   │
│   ├── vector/
│   │   ├── ChromaClient.ts
│   │   ├── ChromaSyncManager.ts
│   │   └── ChromaQueryEngine.ts
│   │
│   └── agents/
│       ├── BaseAgent.ts        # Shared agent logic
│       ├── AgentFactory.ts
│       ├── MessageBuilder.ts
│       ├── ResponseParser.ts
│       ├── providers/
│       │   ├── ClaudeProvider.ts
│       │   ├── GeminiProvider.ts
│       │   └── OpenRouterProvider.ts
│       └── types.ts
│
├── api/                        # HTTP layer
│   ├── routes/
│   │   ├── sessions.ts
│   │   ├── data.ts
│   │   ├── search.ts
│   │   ├── settings.ts
│   │   └── viewer.ts
│   ├── middleware/
│   └── server.ts
│
├── context/                    # Context injection
│   ├── ContextBuilder.ts
│   ├── ContextConfigLoader.ts
│   ├── ObservationCompiler.ts
│   └── TokenCalculator.ts
│
└── shared/                     # Shared utilities (existing)
    ├── logger.ts
    ├── settings.ts
    └── ...

Part 3: Refactoring Targets by Priority

Phase 1: Database Layer Decomposition

Target: src/services/sqlite/SessionStore.ts (2,011 lines, 49 methods → ~5 files)

Extract To Responsibility Est. Lines
domains/sessions/SessionRepository.ts Session CRUD ops ~300
domains/observations/ObservationRepository.ts Observation storage/retrieval ~400
domains/summaries/SummaryRepository.ts Summary storage/retrieval ~200
infrastructure/database/migrations/MigrationRunner.ts Schema migrations ~250

Benefits:

  • Single responsibility per file
  • Testable in isolation
  • Reduces coupling

Phase 2: Agent Consolidation

Target: 3 agent files (1,719 lines → ~800 lines total)

Extract To Responsibility
infrastructure/agents/BaseAgent.ts Common agent logic, prompt building
infrastructure/agents/MessageBuilder.ts Message construction
infrastructure/agents/ResponseParser.ts Result parsing (observations, summaries)
infrastructure/agents/providers/*.ts Provider-specific API calls only

Benefits:

  • Eliminates 80% code duplication
  • Easy to add new providers
  • Centralized message format changes

Phase 3: Search Strategy Pattern

Target: src/services/worker/SearchManager.ts (1,778 lines → ~5 files)

Extract To Responsibility
domains/search/SearchOrchestrator.ts Coordinates search strategies
domains/search/strategies/ChromaSearchStrategy.ts Vector search via Chroma
domains/search/strategies/FilterSearchStrategy.ts SQLite filter-based search
domains/search/ResultFormatter.ts Formats search results
domains/search/TimelineBuilder.ts Constructs timeline views

Benefits:

  • Strategy pattern for extensibility
  • Clear fallback logic
  • Testable strategies

Phase 4: Context Generator Restructure

Target: src/services/context-generator.ts (659 lines → ~4 files)

Extract To Responsibility
context/ContextBuilder.ts Main builder class
context/ContextConfigLoader.ts Config loading/validation
context/ObservationCompiler.ts Compiles observations for injection
context/TokenCalculator.ts Token budget calculations

Benefits:

  • Class-based structure
  • Clear dependencies
  • Easier testing

Phase 5: Server/Infrastructure Split

Target: src/services/worker-service.ts (2,034 lines → ~4 files)

Extract To Responsibility
api/server.ts Express app, route registration
infrastructure/ProcessManager.ts PID files, signal handlers
infrastructure/CursorHooksInstaller.ts Cursor integration
infrastructure/MCPClientManager.ts MCP client lifecycle

Part 4: Dependency Reduction Strategy

Current Pain Points

  1. SessionStore imported by 7+ files directly
  2. No abstraction between routes and data access
  3. All routes depend on DatabaseManager which exposes raw SessionStore

Proposed Dependency Injection

// infrastructure/container.ts
export interface ServiceContainer {
  sessions: SessionService;
  observations: ObservationService;
  summaries: SummaryService;
  search: SearchOrchestrator;
  agents: AgentFactory;
}

// Usage in routes
app.post('/sessions', (req, res) => {
  const { sessions } = getContainer();
  sessions.create(req.body);
});

Part 5: Migration Strategy

Incremental Approach

Each phase can be done independently without breaking the system:

  1. Create new modules alongside existing code
  2. Migrate routes one at a time to use new modules
  3. Deprecate old code once all routes migrated
  4. Remove deprecated code after testing

Testing Requirements

  • Unit tests for each extracted module
  • Integration tests for repository operations
  • End-to-end tests for API routes

Appendix: File Size Distribution

2,034  src/services/worker-service.ts          ████████████████████
2,011  src/services/sqlite/SessionStore.ts     ████████████████████
1,778  src/services/worker/SearchManager.ts    █████████████████
  870  src/services/sync/ChromaSync.ts         ████████
  659  src/services/context-generator.ts       ██████
  625  src/services/worker/http/routes/SessionRoutes.ts  ██████
  599  src/services/worker/OpenRouterAgent.ts  █████
  574  src/services/worker/GeminiAgent.ts      █████
  546  src/services/worker/SDKAgent.ts         █████
  526  src/services/sqlite/SessionSearch.ts    █████
  509  src/services/sqlite/migrations.ts       █████
  466  src/services/worker/http/routes/DataRoutes.ts     ████
  447  src/services/sqlite/PendingMessageStore.ts        ████
  414  src/services/worker/http/routes/SettingsRoutes.ts ████

Summary

Metric Current After Refactor
Files >500 lines 14 0-2
Max file size 2,034 ~400
Code duplication ~1,100 lines ~100 lines
Testable modules Low High

Recommended Start: Phase 1 (SessionStore decomposition) - highest impact, clearest boundaries, and growing (now 2,011 lines with 49 methods).

Key Observations Post-Merge

  1. SessionStore is still the top priority - it grew by 108 lines and is now the 2nd largest file
  2. SearchManager improved - down 178 lines from error handling refactor
  3. Agent files slightly smaller - ~45 lines combined reduction
  4. Core architecture unchanged - the proposed modular structure remains valid