f21ea97c39
* 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: 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 * 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> * test(sqlite): add comprehensive test suite for SQLite repositories Add 44 tests across 5 test files covering: - Sessions: CRUD operations and schema validation - Observations: creation, retrieval, filtering, and ordering - Prompts: persistence and association with observations - Summaries: generation tracking and session linkage - Transactions: context management and rollback behavior 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test(worker): add comprehensive test suites for worker agent modules Add test coverage for response-processor, observation-broadcaster, session-cleanup-helper, and fallback-error-handler agents. Fix type import issues across search module (use `import type` for type-only imports) and update worker-service main module detection for ESM/CJS compatibility. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test(search): add comprehensive test suites for search module Add test coverage for the refactored search architecture: - SearchOrchestrator: query coordination and caching - ResultFormatter: pagination, sorting, and field mapping - SQLiteSearchStrategy: database search operations - ChromaSearchStrategy: vector similarity search - HybridSearchStrategy: combined search with score fusion 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test(context): add comprehensive test suites for context-generator modules Add test coverage for the modular context-generator architecture: - context-builder.test.ts: Tests for context building and result assembly - observation-compiler.test.ts: Tests for observation compilation with privacy tags - token-calculator.test.ts: Tests for token budget calculations - formatters/markdown-formatter.test.ts: Tests for markdown output formatting 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test(infrastructure): add comprehensive test suites for worker infrastructure modules Add test coverage for graceful-shutdown, health-monitor, and process-manager modules extracted during the worker-service refactoring. All 32 tests pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * test(server): add comprehensive test suites for server modules Add test coverage for Express server infrastructure: - error-handler.test.ts: Tests error handling middleware including validation errors, database errors, and async error handling - server.test.ts: Tests server initialization, middleware configuration, and route mounting for all API endpoints 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore(package): add test scripts for modular test suites Add npm run scripts to simplify running tests: - test: run all tests - test:sqlite, test:agents, test:search, test:context, test:infra, test:server 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * build assets * feat(tests): add detailed failure analysis reports for session ID refactor, validation, and store tests - Created reports for session ID refactor test failures, highlighting 8 failures due to design mismatches. - Added session ID usage validation report detailing 10 failures caused by outdated assumptions in tests. - Documented session store test failures, focusing on foreign key constraint violations in 2 tests. - Compiled a comprehensive test suite report summarizing overall test results, including 28 failing tests across various categories. * fix(tests): align session ID tests with NULL-based initialization Update test expectations to match implementation where memory_session_id starts as NULL (not equal to contentSessionId) per architecture decision that memory_session_id must NEVER equal contentSessionId. Changes: - session_id_refactor.test.ts: expect NULL initial state, add updateMemorySessionId() calls - session_id_usage_validation.test.ts: update placeholder detection to check !== null - session_store.test.ts: add updateMemorySessionId() before storeObservation/storeSummary 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(tests): update GeminiAgent tests with correct field names and mocks - Rename deprecated fields: claudeSessionId → contentSessionId, sdkSessionId → memorySessionId, pendingProcessingIds → pendingMessages - Add missing required ActiveSession fields - Add storeObservations mock (plural) for ResponseProcessor compatibility - Fix settings mock to use correct CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED key - Add await to rejects.toThrow assertion 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * feat(tests): add logger imports and fix coverage test exclusions Phase 3 of test suite fixes: - Add logger imports to 34 high-priority source files (SQLite, worker, context) - Exclude CLI-facing files from console.log check (worker-service.ts, integrations/*Installer.ts) as they use console.log intentionally for interactive user output 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * docs: update SESSION_ID_ARCHITECTURE for NULL-based initialization Update documentation to reflect that memory_session_id starts as NULL, not as a placeholder equal to contentSessionId. This matches the implementation decision that memory_session_id must NEVER equal contentSessionId to prevent injecting memory messages into user transcripts. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * chore(deps): update esbuild and MCP SDK - esbuild: 0.25.12 → 0.27.2 (fixes minifyIdentifiers issue) - @modelcontextprotocol/sdk: 1.20.1 → 1.25.1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * build assets and updates * chore: remove bun.lock and add to gitignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
325 lines
12 KiB
Markdown
325 lines
12 KiB
Markdown
# Session ID Usage Validation Test Failures Analysis
|
|
|
|
**Report Date:** 2026-01-04
|
|
**Test File:** `tests/session_id_usage_validation.test.ts`
|
|
**Category:** Session ID Usage Validation
|
|
**Total Failures:** 10 (of 21 tests in file)
|
|
|
|
---
|
|
|
|
## 1. Executive Summary
|
|
|
|
The 10 failing tests in the Session ID Usage Validation suite are caused by a **mismatch between the test expectations and the current implementation**. The tests were written based on an earlier design where `memory_session_id` was initialized as a placeholder equal to `content_session_id`. However, the current implementation initializes `memory_session_id` as `NULL`.
|
|
|
|
### Root Cause
|
|
The implementation was changed to use `NULL` for `memory_session_id` initially, but the tests and documentation (`SESSION_ID_ARCHITECTURE.md`) still describe the old "placeholder" design.
|
|
|
|
### Key Discrepancy
|
|
|
|
| Aspect | Tests Expect | Implementation Does |
|
|
|--------|--------------|---------------------|
|
|
| Initial `memory_session_id` | `= content_session_id` (placeholder) | `= NULL` |
|
|
| Placeholder detection | `memory_session_id !== content_session_id` | `!!memory_session_id` (truthy check) |
|
|
| FK for observations | Via `memory_session_id = content_session_id` | **Broken** - FK references NULL |
|
|
|
|
---
|
|
|
|
## 2. Test Analysis
|
|
|
|
### 2.1 Placeholder Detection Tests (3 failures)
|
|
|
|
**Test Group:** `Placeholder Detection - hasRealMemorySessionId Logic`
|
|
|
|
#### Test 1: "should identify placeholder when memorySessionId equals contentSessionId"
|
|
**Expectation:** `session.memory_session_id === session.content_session_id`
|
|
**Actual Result:** `session.memory_session_id = null`
|
|
**Assertion:** `expect(session?.memory_session_id).toBe(session?.content_session_id)` fails because `null !== "user-session-123"`
|
|
|
|
#### Test 2: "should identify real memory session ID after capture"
|
|
**Status:** PASSES - This test correctly captures a memory session ID and verifies the change.
|
|
|
|
#### Test 3: "should never use contentSessionId as resume parameter when in placeholder state"
|
|
**Expectation:** Test logic checks `hasRealMemorySessionId = memory_session_id !== content_session_id`
|
|
**Actual Result:** With `memory_session_id = null`, the expression evaluates incorrectly.
|
|
|
|
---
|
|
|
|
### 2.2 Observation Storage Tests (2 failures)
|
|
|
|
**Test Group:** `Observation Storage - ContentSessionId Usage`
|
|
|
|
#### Test 1: "should store observations with contentSessionId in memory_session_id column"
|
|
**Error:** `SQLiteError: FOREIGN KEY constraint failed`
|
|
**Root Cause:**
|
|
- Test stores observation with `contentSessionId` as the `memory_session_id`
|
|
- FK constraint: `FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id)`
|
|
- `sdk_sessions.memory_session_id` is `NULL`, not `contentSessionId`
|
|
- FK check fails because the value doesn't exist in the parent table
|
|
|
|
#### Test 2: "should be retrievable using contentSessionId"
|
|
**Error:** Same FK constraint failure as above
|
|
|
|
---
|
|
|
|
### 2.3 Resume Safety Tests (2 failures)
|
|
|
|
**Test Group:** `Resume Safety - Prevent contentSessionId Resume Bug`
|
|
|
|
#### Test 1: "should prevent resume with placeholder memorySessionId"
|
|
**Expectation:** `hasRealMemorySessionId = (memory_session_id && memory_session_id !== content_session_id)`
|
|
**Expected Result:** `false` (because they should be equal in placeholder state)
|
|
**Actual Result:** Expression evaluates to `null` (falsy but not `false`)
|
|
**Assertion:** `expect(hasRealMemorySessionId).toBe(false)` fails because `null !== false`
|
|
|
|
#### Test 2: "should allow resume only after memory session ID is captured"
|
|
**Same Issue:** The "before capture" state check fails with `null !== false`
|
|
|
|
---
|
|
|
|
### 2.4 Cross-Contamination Prevention (0 failures)
|
|
|
|
**Status:** Both tests PASS - These work because they test behavior after `updateMemorySessionId()` is called.
|
|
|
|
---
|
|
|
|
### 2.5 Foreign Key Integrity Tests (2 failures)
|
|
|
|
**Test Group:** `Foreign Key Integrity`
|
|
|
|
#### Test 1: "should cascade delete observations when session is deleted"
|
|
**Error:** `SQLiteError: FOREIGN KEY constraint failed`
|
|
**Root Cause:** Cannot store observation because FK references `sdk_sessions.memory_session_id` which is `NULL`.
|
|
|
|
#### Test 2: "should maintain FK relationship between observations and sessions"
|
|
**Error:** Same FK constraint failure when storing valid observation.
|
|
|
|
---
|
|
|
|
### 2.6 Session Lifecycle Flow (1 failure)
|
|
|
|
**Test Group:** `Session Lifecycle - Memory ID Capture Flow`
|
|
|
|
#### Test: "should follow correct lifecycle: create -> capture -> resume"
|
|
**Expectation:** Initial `memory_session_id` equals `content_session_id` (placeholder)
|
|
**Actual:** `memory_session_id = NULL`
|
|
**Assertion:** `expect(session?.memory_session_id).toBe(contentSessionId)` fails
|
|
|
|
---
|
|
|
|
### 2.7 1:1 Transcript Mapping Guarantees (2 failures)
|
|
|
|
**Test Group:** `CRITICAL: 1:1 Transcript Mapping Guarantees`
|
|
|
|
#### Test 1: "should enforce UNIQUE constraint on memory_session_id"
|
|
**Status:** PASSES - Works because it tests behavior after capture
|
|
|
|
#### Test 2: "should prevent memorySessionId from being changed after real capture"
|
|
**Status:** PASSES but with a TODO note - Documents that the database layer doesn't prevent second updates
|
|
|
|
#### Test 3: "should use same memorySessionId for all prompts in a conversation"
|
|
**Error:** Initial placeholder assertion fails (`null !== "multi-prompt-session"`)
|
|
|
|
#### Test 4: "should lookup session by contentSessionId and retrieve memorySessionId for resume"
|
|
**Status:** PASSES - Works because it tests after capture
|
|
|
|
---
|
|
|
|
## 3. Current Implementation Status
|
|
|
|
### 3.1 SessionStore.createSDKSession()
|
|
|
|
**Location:** `src/services/sqlite/SessionStore.ts` lines 1164-1182
|
|
|
|
```typescript
|
|
createSDKSession(contentSessionId: string, project: string, userPrompt: string): number {
|
|
// ...
|
|
// NOTE: memory_session_id starts as NULL. It is captured by SDKAgent from the first SDK
|
|
// response and stored via updateMemorySessionId(). CRITICAL: memory_session_id must NEVER
|
|
// equal contentSessionId - that would inject memory messages into the user's transcript!
|
|
this.db.prepare(`
|
|
INSERT OR IGNORE INTO sdk_sessions
|
|
(content_session_id, memory_session_id, project, user_prompt, started_at, started_at_epoch, status)
|
|
VALUES (?, NULL, ?, ?, ?, ?, 'active')
|
|
`).run(contentSessionId, project, userPrompt, now.toISOString(), nowEpoch);
|
|
// ...
|
|
}
|
|
```
|
|
|
|
**Key Point:** The comment explicitly states `memory_session_id` starts as `NULL` and warns against it ever equaling `contentSessionId`.
|
|
|
|
### 3.2 SDKAgent.startSession()
|
|
|
|
**Location:** `src/services/worker/SDKAgent.ts` line 69
|
|
|
|
```typescript
|
|
const hasRealMemorySessionId = !!session.memorySessionId;
|
|
```
|
|
|
|
**Current Implementation:** Uses truthy check (`!!`), not equality comparison.
|
|
|
|
### 3.3 Documentation Mismatch
|
|
|
|
**Location:** `docs/SESSION_ID_ARCHITECTURE.md`
|
|
|
|
The documentation describes the OLD design where:
|
|
- `memory_session_id = content_session_id` initially (placeholder)
|
|
- `hasRealMemorySessionId = memory_session_id !== content_session_id`
|
|
|
|
This documentation is now **incorrect** and mismatches the implementation.
|
|
|
|
---
|
|
|
|
## 4. Root Cause Analysis
|
|
|
|
### The Architecture Evolution
|
|
|
|
1. **Original Design (documented, tested):**
|
|
- `memory_session_id` initialized to `content_session_id` as placeholder
|
|
- Placeholder detection: `memory_session_id !== content_session_id`
|
|
- Observations could use `content_session_id` value because FK matched
|
|
|
|
2. **Current Design (implemented):**
|
|
- `memory_session_id` initialized to `NULL`
|
|
- Placeholder detection: `!!memory_session_id` (truthy check)
|
|
- Observations CANNOT use `content_session_id` because FK requires valid reference
|
|
|
|
### Why the Change Was Made
|
|
|
|
The implementation comment reveals the reasoning:
|
|
> "CRITICAL: memory_session_id must NEVER equal contentSessionId - that would inject memory messages into the user's transcript!"
|
|
|
|
The change was made to prevent a potential security/data integrity issue where using `contentSessionId` for the memory session's resume parameter could cause messages to appear in the wrong conversation.
|
|
|
|
### The FK Problem
|
|
|
|
The observations table has:
|
|
```sql
|
|
FOREIGN KEY(memory_session_id) REFERENCES sdk_sessions(memory_session_id)
|
|
```
|
|
|
|
With `memory_session_id = NULL`:
|
|
- Cannot store observations using `content_session_id` as the FK value
|
|
- Cannot store observations at all until `memory_session_id` is captured
|
|
- This may be **intentional** (observations only valid after SDK session established)
|
|
|
|
---
|
|
|
|
## 5. Recommended Fixes
|
|
|
|
### Option A: Update Tests to Match Implementation (Recommended)
|
|
|
|
The current implementation is safer. Update tests to reflect the NULL-based design:
|
|
|
|
1. **Placeholder Detection Tests:**
|
|
- Change expectations from `memory_session_id === content_session_id` to `memory_session_id === null`
|
|
- Change `hasRealMemorySessionId` logic to `!!memory_session_id`
|
|
|
|
2. **Observation Storage Tests:**
|
|
- Must call `updateMemorySessionId()` before storing observations
|
|
- Or use a different test approach that captures memory session ID first
|
|
|
|
3. **Resume Safety Tests:**
|
|
- Change expected value from `false` to `null` or use `.toBeFalsy()`
|
|
|
|
4. **Update Documentation:**
|
|
- Rewrite `SESSION_ID_ARCHITECTURE.md` to reflect NULL-based initialization
|
|
|
|
### Option B: Revert to Placeholder Design
|
|
|
|
Change implementation back to initialize with placeholder:
|
|
|
|
1. **Modify createSDKSession():**
|
|
```typescript
|
|
VALUES (?, ?, ?, ?, ?, ?, 'active')
|
|
// Pass contentSessionId as memory_session_id placeholder
|
|
```
|
|
|
|
2. **Update SDKAgent hasRealMemorySessionId:**
|
|
```typescript
|
|
const hasRealMemorySessionId =
|
|
session.memorySessionId &&
|
|
session.memorySessionId !== session.contentSessionId;
|
|
```
|
|
|
|
3. **Risk:** Need to validate that this doesn't cause the "transcript injection" issue mentioned in comments.
|
|
|
|
### Option C: Hybrid FK Design
|
|
|
|
Keep NULL initialization but change FK relationship:
|
|
|
|
1. **Observations FK via content_session_id:**
|
|
```sql
|
|
FOREIGN KEY(content_session_id) REFERENCES sdk_sessions(content_session_id)
|
|
```
|
|
|
|
2. **Keep memory_session_id for data retrieval only**
|
|
|
|
3. **This requires schema migration**
|
|
|
|
---
|
|
|
|
## 6. Priority and Effort Estimate
|
|
|
|
### Priority: **HIGH**
|
|
|
|
These failures indicate a fundamental mismatch between expected and actual behavior. The FK constraint failures are particularly concerning as they could affect production observation storage.
|
|
|
|
### Effort Estimate
|
|
|
|
| Fix Option | Effort | Risk | Recommendation |
|
|
|------------|--------|------|----------------|
|
|
| Option A: Update Tests | 2-3 hours | Low | **Recommended** |
|
|
| Option B: Revert Implementation | 1-2 hours | Medium | Not recommended |
|
|
| Option C: Schema Change | 4-8 hours | High | Future consideration |
|
|
|
|
### Specific Changes for Option A
|
|
|
|
1. **`tests/session_id_usage_validation.test.ts`:**
|
|
- Lines 39, 78, 149, 168, 320, 421: Change placeholder expectations from `content_session_id` to `null`
|
|
- Lines 100, 127, 265, 285: Add `updateMemorySessionId()` call before storing observations
|
|
- Lines 43, 60, 78, 149, 168, 177: Use `.toBeFalsy()` instead of `.toBe(false)` where appropriate
|
|
|
|
2. **`docs/SESSION_ID_ARCHITECTURE.md`:**
|
|
- Update initialization flow diagram to show NULL initial state
|
|
- Update placeholder detection logic description
|
|
- Update observation storage section to clarify when observations can be stored
|
|
|
|
---
|
|
|
|
## 7. Test Summary
|
|
|
|
| Test Category | Total | Pass | Fail |
|
|
|--------------|-------|------|------|
|
|
| Placeholder Detection | 3 | 1 | 2 |
|
|
| Observation Storage | 2 | 0 | 2 |
|
|
| Resume Safety | 2 | 0 | 2 |
|
|
| Cross-Contamination | 2 | 2 | 0 |
|
|
| Foreign Key Integrity | 2 | 0 | 2 |
|
|
| Session Lifecycle | 2 | 1 | 1 |
|
|
| 1:1 Transcript Mapping | 4 | 3 | 1 |
|
|
| Edge Cases | 2 | 2 | 0 |
|
|
| **TOTAL** | **21** | **10** | **10** |
|
|
|
|
---
|
|
|
|
## 8. Files Requiring Changes
|
|
|
|
### If Fixing Tests (Option A)
|
|
|
|
1. `tests/session_id_usage_validation.test.ts` - Update test expectations
|
|
2. `docs/SESSION_ID_ARCHITECTURE.md` - Update documentation
|
|
|
|
### If Reverting Implementation (Option B)
|
|
|
|
1. `src/services/sqlite/SessionStore.ts` - Change `createSDKSession()` to use placeholder
|
|
2. `src/services/worker/SDKAgent.ts` - Change `hasRealMemorySessionId` logic
|
|
|
|
---
|
|
|
|
## 9. References
|
|
|
|
- **Test File:** `/Users/alexnewman/Scripts/claude-mem/tests/session_id_usage_validation.test.ts`
|
|
- **Implementation:** `/Users/alexnewman/Scripts/claude-mem/src/services/sqlite/SessionStore.ts`
|
|
- **SDKAgent:** `/Users/alexnewman/Scripts/claude-mem/src/services/worker/SDKAgent.ts`
|
|
- **Documentation:** `/Users/alexnewman/Scripts/claude-mem/docs/SESSION_ID_ARCHITECTURE.md`
|