From 2439d4a645ebd4052d734c673d9f49f1a3768935 Mon Sep 17 00:00:00 2001 From: Christian Gick Date: Tue, 20 Jan 2026 10:17:53 +0200 Subject: [PATCH] fix(CF-306): Validate session_id in memory_add to prevent FK violations Added validation to check if session_id exists in sessions table before inserting memories. Falls back to NULL if session not found, preventing foreign key constraint violations while preserving memory content. Logs warning when invalid session_id provided for debugging. Co-Authored-By: Claude Sonnet 4.5 --- src/tools/memories.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/tools/memories.ts b/src/tools/memories.ts index 84930d0..4484bed 100644 --- a/src/tools/memories.ts +++ b/src/tools/memories.ts @@ -43,10 +43,24 @@ interface MemoryListArgs { /** * Add a new memory/learning (enhanced with session_id and task_id) + * CF-306: Validates session_id exists before inserting to prevent foreign key violations */ export async function memoryAdd(args: MemoryAddArgs): Promise { const { category, title, content, context, project, session_id, task_id } = args; + // CF-306: Validate session_id exists if provided + let validSessionId = session_id || null; + if (session_id) { + const sessionExists = await queryOne<{ exists: boolean }>( + `SELECT EXISTS(SELECT 1 FROM sessions WHERE id = $1) as exists`, + [session_id] + ); + if (!sessionExists?.exists) { + console.warn(`[CF-306] Session ${session_id} not found in database - using NULL instead`); + validSessionId = null; + } + } + // Generate embedding for semantic search const embedText = `${title}. ${content}`; const embedding = await getEmbedding(embedText); @@ -56,13 +70,13 @@ export async function memoryAdd(args: MemoryAddArgs): Promise { await execute( `INSERT INTO memories (category, title, content, context, project, session_id, task_id, embedding) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, - [category, title, content, context || null, project || null, session_id || null, task_id || null, embeddingValue] + [category, title, content, context || null, project || null, validSessionId, task_id || null, embeddingValue] ); } else { await execute( `INSERT INTO memories (category, title, content, context, project, session_id, task_id) VALUES ($1, $2, $3, $4, $5, $6, $7)`, - [category, title, content, context || null, project || null, session_id || null, task_id || null] + [category, title, content, context || null, project || null, validSessionId, task_id || null] ); }