UPDATE ias_long_term_memories
SET scope_key = channel || ':' || account_id || ':' || from_user_id;

UPDATE ias_context_sessions
SET scope_key = channel || ':' || account_id || ':' || from_user_id;

UPDATE ias_context_summaries AS summary
SET scope_key = session.scope_key
FROM ias_context_sessions AS session
WHERE summary.source_session_id = session.id;

WITH ranked AS (
    SELECT
        id,
        ROW_NUMBER() OVER (
            PARTITION BY scope_key
            ORDER BY started_at DESC, id DESC
        ) AS rank
    FROM ias_context_sessions
    WHERE ended_at IS NULL
)
UPDATE ias_context_sessions AS session
SET
    ended_at = last_message_at,
    end_reason = 'scope_normalized',
    summary = COALESCE(summary, '旧上下文 scope 合并时自动结束。')
FROM ranked
WHERE session.id = ranked.id
    AND ranked.rank > 1;
