feat(memory): P1 长期记忆升级 —— 异步攒批 Consolidate + 软删 + importance/last_seen
把"逐轮盲写抽取"升级为 Mem0 式对账(方案见 memory_industry_analysis.md 落地节):
mcp-go:
- Profile 加 Importance(1~10, poignancy) + LastSeenAt(为 Generative Agents 读路径
Score=w1·Relevance+w2·Recency+w3·Importance 铺路)。
- Upsert 收 importance + 每次置 last_seen(印证);新增 Delete(软删,BaseModel.DeletedAt
已具备,失效不物删可审计)+ Touch;memory_upsert 透传 importance、新增 memory_delete 工具。
dispatcher:
- extractMemory → consolidateMemory:一次 LLM 调用同时做 抽取+对账,输出
[{op:ADD|UPDATE|DELETE|NOOP,key,value,importance}];ADD/UPDATE→upsert、DELETE→软删;
sanitizeOps 防幻删(DELETE 须命中已有)/夹 importance[1,10]/同key保末个/丢 NOOP。
- 攒批:每 3 轮(per-session 计数)才 consolidate 一次,省成本,对齐 ChatGPT 周期整理。
从根上解决 exact-key 盲写的记忆腐烂。
验证:parseOps/sanitizeOps/parseProfile 纯逻辑单测;store 集成测试(真 PG)覆盖
importance/last_seen 写入 + 软删(live 0 / 物理 1);dispatcher -race 全过。
(注:完整多轮 LLM consolidate 未做实跑,属构造性验证 + 沿用已证 pool.Chat 模式。)
P2 待做:读路径按 Score(Recency+Importance) 排序/衰减/截断 + 桌面端记忆面板。
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -73,6 +73,8 @@ func (g *Gateway) dispatch(ctx context.Context, call *contract.ToolCall) *contra
|
||||
return g.memoryGet(ctx, call)
|
||||
case "memory_upsert":
|
||||
return g.memoryUpsert(ctx, call)
|
||||
case "memory_delete":
|
||||
return g.memoryDelete(ctx, call)
|
||||
case "history_get":
|
||||
return g.historyGet(ctx, call)
|
||||
case "history_append":
|
||||
@@ -119,20 +121,34 @@ func (g *Gateway) historyAppend(ctx context.Context, call *contract.ToolCall) *c
|
||||
return &contract.ToolResult{OK: true}
|
||||
}
|
||||
|
||||
// memoryUpsert 写入/更新一条画像偏好(user_id + key + value)。
|
||||
// memoryUpsert 写入/更新一条画像偏好(user_id + key + value + 可选 importance(1~10))。
|
||||
func (g *Gateway) memoryUpsert(ctx context.Context, call *contract.ToolCall) *contract.ToolResult {
|
||||
uid, _ := call.Args["user_id"].(string)
|
||||
key, _ := call.Args["key"].(string)
|
||||
val, _ := call.Args["value"].(string)
|
||||
importance, _ := call.Args["importance"].(float64) // NATS JSON 数字解为 float64
|
||||
if uid == "" || key == "" {
|
||||
return &contract.ToolResult{OK: false, Error: "memory_upsert: user_id 和 key 必填"}
|
||||
}
|
||||
if err := g.memory.Upsert(ctx, uid, key, val); err != nil {
|
||||
if err := g.memory.Upsert(ctx, uid, key, val, importance); err != nil {
|
||||
return &contract.ToolResult{OK: false, Error: "memory_upsert: " + err.Error()}
|
||||
}
|
||||
return &contract.ToolResult{OK: true, Content: fmt.Sprintf("已记住 %s 的「%s」", uid, key)}
|
||||
}
|
||||
|
||||
// memoryDelete 软删一条画像偏好(user_id + key)—— consolidate 判定过时/矛盾时调用。
|
||||
func (g *Gateway) memoryDelete(ctx context.Context, call *contract.ToolCall) *contract.ToolResult {
|
||||
uid, _ := call.Args["user_id"].(string)
|
||||
key, _ := call.Args["key"].(string)
|
||||
if uid == "" || key == "" {
|
||||
return &contract.ToolResult{OK: false, Error: "memory_delete: user_id 和 key 必填"}
|
||||
}
|
||||
if err := g.memory.Delete(ctx, uid, key); err != nil {
|
||||
return &contract.ToolResult{OK: false, Error: "memory_delete: " + err.Error()}
|
||||
}
|
||||
return &contract.ToolResult{OK: true, Content: fmt.Sprintf("已删除 %s 的「%s」", uid, key)}
|
||||
}
|
||||
|
||||
// wikiSearch 经 RAG 引擎做向量检索(embedding + Milvus)。
|
||||
// RAG 未就绪时降级返回空命中(不阻断图执行)。
|
||||
func (g *Gateway) wikiSearch(ctx context.Context, call *contract.ToolCall) *contract.ToolResult {
|
||||
|
||||
@@ -46,9 +46,11 @@ func (b *BaseModel) BeforeCreate(*gorm.DB) error {
|
||||
// 套用 BaseModel 规约:雪花 ID 主键;(user_id, key) 唯一索引 —— 同一用户同一键 upsert 覆盖。
|
||||
type Profile struct {
|
||||
BaseModel
|
||||
UserID string `gorm:"column:user_id;size:64;uniqueIndex:idx_profile_uk"`
|
||||
Key string `gorm:"size:64;uniqueIndex:idx_profile_uk"`
|
||||
Value string `gorm:"type:text"`
|
||||
UserID string `gorm:"column:user_id;size:64;uniqueIndex:idx_profile_uk"`
|
||||
Key string `gorm:"size:64;uniqueIndex:idx_profile_uk"`
|
||||
Value string `gorm:"type:text"`
|
||||
Importance float64 `gorm:"column:importance"` // 1~10,consolidate 时 LLM 打分(poignancy)→ 读路径权重
|
||||
LastSeenAt time.Time `gorm:"column:last_seen_at"` // 最近被印证时间 → Recency 衰减依据
|
||||
}
|
||||
|
||||
// TableName 固定表名,遵守 sundynix_ 前缀约定。
|
||||
@@ -123,15 +125,39 @@ func (s *Store) Get(ctx context.Context, userID string) (string, error) {
|
||||
return strings.TrimRight(b.String(), "\n"), nil
|
||||
}
|
||||
|
||||
// Upsert 写入/更新一条画像偏好((user_id,key) 冲突即覆盖 value,保留原 id)。
|
||||
func (s *Store) Upsert(ctx context.Context, userID, key, value string) error {
|
||||
// Upsert 写入/更新一条画像偏好((user_id,key) 冲突即覆盖 value/importance,保留原 id;
|
||||
// 置 last_seen=now 作"印证")。importance<=0 时不覆盖旧值(NOOP 印证场景只 bump 时间)。
|
||||
func (s *Store) Upsert(ctx context.Context, userID, key, value string, importance float64) error {
|
||||
if s.db == nil {
|
||||
return fmt.Errorf("memory store disabled")
|
||||
}
|
||||
now := time.Now()
|
||||
updates := map[string]any{"value": value, "updated_at": now, "last_seen_at": now}
|
||||
if importance > 0 {
|
||||
updates["importance"] = importance
|
||||
}
|
||||
return s.db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "user_id"}, {Name: "key"}},
|
||||
DoUpdates: clause.Assignments(map[string]any{"value": value, "updated_at": time.Now()}),
|
||||
}).Create(&Profile{UserID: userID, Key: key, Value: value}).Error
|
||||
DoUpdates: clause.Assignments(updates),
|
||||
}).Create(&Profile{UserID: userID, Key: key, Value: value, Importance: importance, LastSeenAt: now}).Error
|
||||
}
|
||||
|
||||
// Touch 仅刷新某条偏好的 last_seen(NOOP 印证:被再次提及但内容不变,强化 Recency)。
|
||||
func (s *Store) Touch(ctx context.Context, userID, key string) error {
|
||||
if s.db == nil {
|
||||
return nil
|
||||
}
|
||||
return s.db.WithContext(ctx).Model(&Profile{}).
|
||||
Where("user_id = ? AND key = ?", userID, key).
|
||||
Update("last_seen_at", time.Now()).Error
|
||||
}
|
||||
|
||||
// Delete 软删一条偏好((user_id,key))—— 置 deleted_at,行保留可审计/恢复,正常查询自动过滤。
|
||||
func (s *Store) Delete(ctx context.Context, userID, key string) error {
|
||||
if s.db == nil {
|
||||
return nil
|
||||
}
|
||||
return s.db.WithContext(ctx).Where("user_id = ? AND key = ?", userID, key).Delete(&Profile{}).Error
|
||||
}
|
||||
|
||||
// Close 释放连接。
|
||||
|
||||
@@ -59,8 +59,8 @@ func TestProfileStore_Integration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Upsert 两次同 (user_id,key) → 覆盖,不新增;id 稳定。
|
||||
if err := s.Upsert(ctx, "u1", "城市", "北京"); err != nil {
|
||||
// Upsert 两次同 (user_id,key) → 覆盖,不新增;id 稳定;importance/last_seen 写入。
|
||||
if err := s.Upsert(ctx, "u1", "城市", "北京", 5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first Profile
|
||||
@@ -68,7 +68,10 @@ func TestProfileStore_Integration(t *testing.T) {
|
||||
if first.ID == "" || first.CreatedAt.IsZero() {
|
||||
t.Error("行应有雪花 id 与创建时间")
|
||||
}
|
||||
if err := s.Upsert(ctx, "u1", "城市", "上海"); err != nil {
|
||||
if first.Importance != 5 || first.LastSeenAt.IsZero() {
|
||||
t.Errorf("应写入 importance 与 last_seen: imp=%v last=%v", first.Importance, first.LastSeenAt)
|
||||
}
|
||||
if err := s.Upsert(ctx, "u1", "城市", "上海", 8); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cnt int64
|
||||
@@ -78,12 +81,24 @@ func TestProfileStore_Integration(t *testing.T) {
|
||||
}
|
||||
var after Profile
|
||||
raw.Where("user_id = ? AND key = ?", "u1", "城市").First(&after)
|
||||
if after.Value != "上海" || after.ID != first.ID {
|
||||
t.Errorf("应覆盖 value 且保留 id: value=%s id=%s/%s", after.Value, after.ID, first.ID)
|
||||
if after.Value != "上海" || after.ID != first.ID || after.Importance != 8 {
|
||||
t.Errorf("应覆盖 value/importance 且保留 id: value=%s imp=%v id=%s/%s", after.Value, after.Importance, after.ID, first.ID)
|
||||
}
|
||||
|
||||
// Get 渲染多行(按 key 排序)。
|
||||
_ = s.Upsert(ctx, "u1", "爱好", "围棋")
|
||||
// Delete 软删:行打 deleted_at,正常查询不返回,但物理行还在(可审计)。
|
||||
_ = s.Upsert(ctx, "u1", "临时", "可删", 1)
|
||||
if err := s.Delete(ctx, "u1", "临时"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var liveCnt, rawCnt int64
|
||||
raw.Model(&Profile{}).Where("user_id = ? AND key = ?", "u1", "临时").Count(&liveCnt)
|
||||
raw.Unscoped().Model(&Profile{}).Where("user_id = ? AND key = ?", "u1", "临时").Count(&rawCnt)
|
||||
if liveCnt != 0 || rawCnt != 1 {
|
||||
t.Errorf("软删后正常查询应 0、物理行应 1:live=%d raw=%d", liveCnt, rawCnt)
|
||||
}
|
||||
|
||||
// Get 渲染多行(按 key 排序),软删的不出现。
|
||||
_ = s.Upsert(ctx, "u1", "爱好", "围棋", 6)
|
||||
got, _ := s.Get(ctx, "u1")
|
||||
if got == "" || got != "- 城市:上海\n- 爱好:围棋" {
|
||||
t.Errorf("Get 渲染不符: %q", got)
|
||||
|
||||
Reference in New Issue
Block a user