diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 1326709..28c37a3 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -1729,6 +1729,26 @@ fn ensure_scheduler_schema(conn: &Connection) -> Result<(), StorageError> { } fn ensure_memory_scope_key_migration(conn: &Connection) -> Result<(), StorageError> { + // 步骤1:去重。多条记录 scope_key 不同,改为 "default" 后会违反唯一约束。 + // 对每个 (scope_kind, namespace, memory_key) 组合保留 updated_at 最新的一条。 + conn.execute( + " + DELETE FROM memories + WHERE rowid NOT IN ( + SELECT rowid FROM ( + SELECT rowid, ROW_NUMBER() OVER ( + PARTITION BY scope_kind, namespace, memory_key + ORDER BY updated_at DESC + ) AS rn + FROM memories + ) + WHERE rn = 1 + ) + ", + [], + )?; + + // 步骤2:统一 scope_key conn.execute( "UPDATE memories SET scope_key = 'default' WHERE scope_key != 'default'", [],