fix conflict scan: use real vector of new content instead of zero vector for retrieving existing memories

This commit is contained in:
小唯
2026-09-20 00:10:03 +08:00
parent 3e8157307e
commit 835b308df6
+205 -177
View File
@@ -137,24 +137,30 @@ func NewServer() http.Handler {
// ─── 蒸馏引擎 ───────────────────────────────
llmEndpoint := os.Getenv("LLM_ENDPOINT")
llmModel := os.Getenv("LLM_MODEL")
if llmModel == "" { llmModel = "deepseek/deepseek-v4-pro" }
if llmModel == "" {
llmModel = "deepseek/deepseek-v4-pro"
}
llmAPIKey := os.Getenv("LLM_API_KEY")
if llmAPIKey == "" { llmAPIKey = os.Getenv("API_KEY") }
if llmAPIKey == "" {
llmAPIKey = os.Getenv("API_KEY")
}
distillEngine := distill.NewEngine(llmEndpoint, llmModel, llmAPIKey)
routes.DistillEngineRef = distillEngine
// 蒸馏完成 → 自动图谱更新 + 冲突检测 + 被动验证 + 回写内存
distill.OnDistillComplete = func(input distill.DistillInput, result distill.DistillResult) {
entityNames := make([]string, len(result.Entities))
for i, e := range result.Entities { entityNames[i] = e.Name }
for i, e := range result.Entities {
entityNames[i] = e.Name
}
graphUpdater.UpdateFromDistill(&governance.DistillInput{
Content: input.Content, Facts: result.Facts,
Entities: entityNames, Namespace: input.Namespace,
EpisodeID: input.EpisodeID,
})
// 回写蒸馏产物到记忆库(LanceDB)
// 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库,
// 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。
// 回写蒸馏产物到记忆库(LanceDB)
// 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库,
// 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。
for _, fact := range result.Facts {
// 2026-09-10 P0:直写路径同样脱敏(这里绕过 FilterQualityFacts,
// 事故里泄漏进镜像的记忆正是从这条路径入库的)。
@@ -187,9 +193,19 @@ func NewServer() http.Handler {
log.Printf("[distill] commit fact failed: %v", err)
}
}
// 冲突检测:加载同 namespace 已有记忆进行比较
zeroVec := make([]float32, 1024)
existingMems, _ := ldb.Search("memories", zeroVec, 100, input.Namespace)
// 冲突检测:加载已有记忆进行比较
// 必须用**新内容的真实向量**做语义检索取近邻;用零向量在语义索引上
// 返回的只是"范数最小"的任意行,真正的矛盾对象不在比对集里 → 永远检不出冲突。
existingMems := []models.MemoryRecord{}
if qv, eErr := emb.EncodeSingle(input.Content); eErr == nil {
if found, _ := ldb.Search("memories", qv, 100, input.Namespace); len(found) > 0 {
existingMems = found
}
}
if len(existingMems) == 0 {
zeroVec := make([]float32, 1024)
existingMems, _ = ldb.Search("memories", zeroVec, 100, input.Namespace)
}
conflictExisting := make([]map[string]interface{}, 0)
for _, m := range existingMems {
conflictExisting = append(conflictExisting, map[string]interface{}{
@@ -198,7 +214,9 @@ func NewServer() http.Handler {
})
}
for _, c := range conflictDetector.Scan(input.Content, entityNames, conflictExisting) {
if c.Strategy == "latest_wins" { conflictDetector.AutoResolve(c) }
if c.Strategy == "latest_wins" {
conflictDetector.AutoResolve(c)
}
}
// 被动验证:使用已加载的记忆进行 P1/P2/P3 匹配
validMems := make([]selfoptimize.MemoryForValidation, len(existingMems))
@@ -388,9 +406,9 @@ func NewServer() http.Handler {
break // Success, exit retry loop
}
// Check for rate limit error (429) - zhiyid returns rate_limit_exceeded
if strings.Contains(lastErr.Error(), "rate_limit_exceeded") || strings.Contains(lastErr.Error(), "429") {
if strings.Contains(lastErr.Error(), "rate_limit_exceeded") || strings.Contains(lastErr.Error(), "429") {
// Exponential backoff: 1s, 2s, 4s, 8s, 16s
backoff := time.Duration(1 << uint(attempt)) * time.Second
backoff := time.Duration(1<<uint(attempt)) * time.Second
time.Sleep(backoff)
continue
}
@@ -403,14 +421,14 @@ func NewServer() http.Handler {
dir := filepath.Dir(failedPath)
os.MkdirAll(dir, 0755)
failedEdge := map[string]interface{}{
"edge_id": edgeID,
"from": req.From,
"to": req.To,
"relation": req.Relation,
"edge_id": edgeID,
"from": req.From,
"to": req.To,
"relation": req.Relation,
"namespace": ns,
"weight": 1.0,
"weight": 1.0,
"timestamp": time.Now().UnixNano(),
"error": lastErr.Error(),
"error": lastErr.Error(),
}
jsonData, _ := json.Marshal(failedEdge)
// Append to jsonl file
@@ -421,7 +439,7 @@ func NewServer() http.Handler {
// Return success with warning that edge was queued for later retry
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "queued_for_retry",
"status": "queued_for_retry",
"edge_id": edgeID,
"message": "Edge write failed after max retries; queued to /tmp/memoryweave/failed_edges.jsonl",
})
@@ -586,13 +604,13 @@ func NewServer() http.Handler {
}
}
result = map[string]interface{}{
"query": query,
"entity_a": entityA,
"entity_b": entityB,
"direct_path": directPath,
"paths_from_a": len(paths),
"paths_from_b": len(relB),
"summary": fmt.Sprintf("%s 与 %s 存在 %d 条关联路径", entityA, entityB, len(paths)),
"query": query,
"entity_a": entityA,
"entity_b": entityB,
"direct_path": directPath,
"paths_from_a": len(paths),
"paths_from_b": len(relB),
"summary": fmt.Sprintf("%s 与 %s 存在 %d 条关联路径", entityA, entityB, len(paths)),
}
} else {
// 单实体查询:找 entity 的关系网
@@ -715,7 +733,9 @@ func NewServer() http.Handler {
mux.HandleFunc("/api/v1/feedback/useful", func(w http.ResponseWriter, r *http.Request) {
feedbackAPI.MarkUseful(w, r)
// 质量监控:useful → 质量上升
var req struct { MemoryID string `json:"memory_id"` }
var req struct {
MemoryID string `json:"memory_id"`
}
if r.Body != nil {
body, _ := io.ReadAll(r.Body)
json.Unmarshal(body, &req)
@@ -735,7 +755,9 @@ func NewServer() http.Handler {
mux.HandleFunc("/api/v1/feedback/not-useful", func(w http.ResponseWriter, r *http.Request) {
feedbackAPI.MarkNotUseful(w, r)
// 质量监控:not-useful → 检查是否需要降权
var req struct { MemoryID string `json:"memory_id"` }
var req struct {
MemoryID string `json:"memory_id"`
}
if r.Body != nil {
body, _ := io.ReadAll(r.Body)
json.Unmarshal(body, &req)
@@ -837,37 +859,37 @@ func NewServer() http.Handler {
})
// 管理
// ?task=full 触发完整整合(DBSCAN + 衰减校准 + 质量回溯),默认 cluster_only
mux.HandleFunc("/api/v1/admin/consolidate", func(w http.ResponseWriter, r *http.Request) {
task := r.URL.Query().Get("task")
if task == "" {
task = "cluster_only"
}
// full 模式给 5 分钟;cluster_only 保持 30 秒
timeout := 30 * time.Second
if task == "full" {
timeout = 5 * time.Minute
}
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
done := make(chan *routes.ConsolidationReport, 1)
go func() {
report, _ := consolPipe.RunWithMode(task)
done <- report
}()
select {
case <-ctx.Done():
respondJSON(w, 408, map[string]string{"error": "consolidation timeout", "task": task})
// ?task=full 触发完整整合(DBSCAN + 衰减校准 + 质量回溯),默认 cluster_only
mux.HandleFunc("/api/v1/admin/consolidate", func(w http.ResponseWriter, r *http.Request) {
task := r.URL.Query().Get("task")
if task == "" {
task = "cluster_only"
}
// full 模式给 5 分钟;cluster_only 保持 30 秒
timeout := 30 * time.Second
if task == "full" {
timeout = 5 * time.Minute
}
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
done := make(chan *routes.ConsolidationReport, 1)
go func() {
report, _ := consolPipe.RunWithMode(task)
done <- report
}()
select {
case <-ctx.Done():
respondJSON(w, 408, map[string]string{"error": "consolidation timeout", "task": task})
return
case report := <-done:
if report == nil {
respondJSON(w, 500, map[string]string{"error": "consolidation failed", "task": task})
return
case report := <-done:
if report == nil {
respondJSON(w, 500, map[string]string{"error": "consolidation failed", "task": task})
return
}
respondJSON(w, 200, report)
go governance.PushDistillationComplete(report.Merged, report.ConflictsFound)
}
})
respondJSON(w, 200, report)
go governance.PushDistillationComplete(report.Merged, report.ConflictsFound)
}
})
mux.HandleFunc("/api/v1/admin/forget", adminAPI.Forget)
mux.HandleFunc("/api/v1/admin/dedup", api.Dedup)
mux.HandleFunc("/api/v1/admin/backup", adminAPI.Backup)
@@ -910,8 +932,12 @@ func NewServer() http.Handler {
respondJSON(w, 400, map[string]string{"error": "content required"})
return
}
if req.Namespace == "" { req.Namespace = "hermes-main" }
if req.AgentID == "" { req.AgentID = "hermes-a06" }
if req.Namespace == "" {
req.Namespace = "hermes-main"
}
if req.AgentID == "" {
req.AgentID = "hermes-a06"
}
epID := fmt.Sprintf("ep_manual_%d", time.Now().UnixNano())
routes.AutoDistillTrigger(epID, req.Content, req.Category, req.Namespace, req.AgentID)
respondJSON(w, 200, map[string]string{"status": "queued", "episode_id": epID})
@@ -1037,12 +1063,12 @@ func NewServer() http.Handler {
}
respondJSON(w, 200, map[string]interface{}{
"status": "ok",
"processed": processed,
"updated": updated,
"deleted": deleted,
"ignored": ignored,
"errors": errors_,
"status": "ok",
"processed": processed,
"updated": updated,
"deleted": deleted,
"ignored": ignored,
"errors": errors_,
"total_memories": len(mems),
})
})
@@ -1097,7 +1123,7 @@ func NewServer() http.Handler {
// Skills(G7)
mux.HandleFunc("/api/v1/skills", routes.Skills.List)
mux.HandleFunc("POST /api/v1/skills", routes.Skills.Register) // 注册新 skill
mux.HandleFunc("/api/v1/skills/stats", routes.Skills.Stats) // skill 统计
mux.HandleFunc("/api/v1/skills/stats", routes.Skills.Stats) // skill 统计
mux.HandleFunc("/api/v1/skills/bayes", func(w http.ResponseWriter, r *http.Request) {
list := routes.BayesianSkills.List()
respondJSON(w, 200, list)
@@ -1106,8 +1132,8 @@ func NewServer() http.Handler {
mux.HandleFunc("/api/v1/skills/{name}/trial", routes.Skills.Trial)
mux.HandleFunc("/api/v1/skills/{name}/execute", routes.ExecuteSkill) // G7.3 skill执行
// G7.2: 结晶路由
mux.HandleFunc("/api/v1/crystallize/candidates", routes.GetSkillCandidates) // 获取候选
mux.HandleFunc("/api/v1/crystallize/memory/{id}", routes.CrystallizeSkill) // 对记忆执行结晶
mux.HandleFunc("/api/v1/crystallize/candidates", routes.GetSkillCandidates) // 获取候选
mux.HandleFunc("/api/v1/crystallize/memory/{id}", routes.CrystallizeSkill) // 对记忆执行结晶
// 评估 + 自调参
mux.HandleFunc("/api/v1/eval/run", evalAPI.Run)
@@ -1154,7 +1180,9 @@ func NewServer() http.Handler {
for _, mid := range req.MemoryIDs {
v := selfoptimize.VProp.GetMemVValue(mid)
lamb := 0.1
if ldb, ok := ldb.(interface{ UpdateQualityScore(id string, delta float64) error }); ok {
if ldb, ok := ldb.(interface {
UpdateQualityScore(id string, delta float64) error
}); ok {
_ = ldb.UpdateQualityScore(mid, lamb*v)
}
}
@@ -1353,126 +1381,126 @@ func NewServer() http.Handler {
go func(triggerID, action string) {
var err error
switch action {
case "distill":
// distill 保持 cluster_only(高频触发,只做快速聚类)
_, err = consolPipe.Run()
case "consolidation", "backtrack":
// full 模式:含 prune + decay + 质量回溯(Step 4)
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
_, err = consolPipe.RunWithMode("full")
case "merge":
_, err = consolPipe.RunMerge()
case "prune":
graphStore.Prune(0.15)
case "decay":
// 扫描所有记忆,按衰减率计算 freshness
// 2026-09-06 P1 fix: 每 tick 限量评估(maxDecayBatch),优先处理
// 最久未访问的(last_recalled_at 最早 → 最该遗忘),防全表单次拉取
// 内存翻倍 + 长时间阻塞触发器循环。
memories, e := ldb.GetCandidatesForForgetting()
decayScanned := 0
decayForgotten := 0
if e == nil {
const maxDecayBatch = 2000
if len(memories) > maxDecayBatch {
sort.SliceStable(memories, func(a, b int) bool {
return memoryTimeVal(memories[a], "last_recalled_at", "created_at") <
memoryTimeVal(memories[b], "last_recalled_at", "created_at")
})
memories = memories[:maxDecayBatch]
}
for _, m := range memories {
decayScanned++
// 🔒 2026-09-07 修复(误删事故): episodes(原始对话)不参与遗忘——
// 它们是蒸馏原料/审计历史, 不是可遗忘的记忆。曾因未过滤 category
// 导致 67 条 8月对话被 auto_forget 清掉(已恢复)。仅 distilled/general 等记忆可遗忘。
if cat, ok := m["category"].(string); ok && cat == "episodes" {
continue
case "distill":
// distill 保持 cluster_only(高频触发,只做快速聚类)
_, err = consolPipe.Run()
case "consolidation", "backtrack":
// full 模式:含 prune + decay + 质量回溯(Step 4)
// 48h cooldown 保护,不会真正每分钟跑 full(cooldown 内 CanFire 仍返回 false)
_, err = consolPipe.RunWithMode("full")
case "merge":
_, err = consolPipe.RunMerge()
case "prune":
graphStore.Prune(0.15)
case "decay":
// 扫描所有记忆,按衰减率计算 freshness
// 2026-09-06 P1 fix: 每 tick 限量评估(maxDecayBatch),优先处理
// 最久未访问的(last_recalled_at 最早 → 最该遗忘),防全表单次拉取
// 内存翻倍 + 长时间阻塞触发器循环。
memories, e := ldb.GetCandidatesForForgetting()
decayScanned := 0
decayForgotten := 0
if e == nil {
const maxDecayBatch = 2000
if len(memories) > maxDecayBatch {
sort.SliceStable(memories, func(a, b int) bool {
return memoryTimeVal(memories[a], "last_recalled_at", "created_at") <
memoryTimeVal(memories[b], "last_recalled_at", "created_at")
})
memories = memories[:maxDecayBatch]
}
// 🔒 长内容保护: distilled >200 字(有实质信息)不参与 auto 遗忘
// (曾误删 405 字 CNB 修复经验; 长记忆应由蒸馏/整合管理, 非时间遗忘)
if cat, _ := m["category"].(string); cat != "episodes" {
if cs, ok := m["content"].(string); ok && len([]rune(cs)) > 200 {
for _, m := range memories {
decayScanned++
// 🔒 2026-09-07 修复(误删事故): episodes(原始对话)不参与遗忘——
// 它们是蒸馏原料/审计历史, 不是可遗忘的记忆。曾因未过滤 category
// 导致 67 条 8月对话被 auto_forget 清掉(已恢复)。仅 distilled/general 等记忆可遗忘。
if cat, ok := m["category"].(string); ok && cat == "episodes" {
continue
}
}
// 解析 last_recalled_at
lastAccessed := time.Now().Add(-30 * 24 * time.Hour) // 默认30天前
if t, ok := m["last_recalled_at"].(string); ok && t != "" {
if parsed, err := time.Parse(time.RFC3339, t); err == nil {
lastAccessed = parsed
// 🔒 长内容保护: distilled >200 字(有实质信息)不参与 auto 遗忘
// (曾误删 405 字 CNB 修复经验; 长记忆应由蒸馏/整合管理, 非时间遗忘)
if cat, _ := m["category"].(string); cat != "episodes" {
if cs, ok := m["content"].(string); ok && len([]rune(cs)) > 200 {
continue
}
}
// 解析 last_recalled_at
lastAccessed := time.Now().Add(-30 * 24 * time.Hour) // 默认30天前
if t, ok := m["last_recalled_at"].(string); ok && t != "" {
if parsed, err := time.Parse(time.RFC3339, t); err == nil {
lastAccessed = parsed
}
}
// 2026-09-07 方案A 碎片快速道: <30 字且 >20 天未访问 → 直接遗忘
// (绕过 ShouldForget 的 recallCount 保命——碎片 recall_count 可能虚高)。
// 碎片无记忆价值(审计: 30.9% <20字 + 43% <50字 = 蒸馏无门槛产物)。
contentStr := ""
if cs, ok := m["content"].(string); ok {
contentStr = cs
}
if len([]rune(contentStr)) < 30 && time.Since(lastAccessed).Hours()/24 > 20 {
if id, ok := m["id"].(string); ok {
_ = ldb.SoftDelete(id, "auto_forget_fragment")
decayForgotten++
}
continue
}
recallCount := 0
if rc, ok := m["recall_count"].(int); ok {
recallCount = rc
}
tier := "normal"
if ts, ok := m["tier"].(string); ok {
tier = ts
}
// E4.3: 获取实体图谱度(namespace 作为实体)
entity := ""
if ns, ok := m["namespace"].(string); ok {
entity = ns
}
degree := 0
if entity != "" {
degree = graphStore.GetEntityDegree(entity)
}
if forgetter.ShouldForget(lastAccessed, recallCount, tier, degree) {
if id, ok := m["id"].(string); ok {
forgetter.ScanAndForget(id)
// 实际执行软删除(持久化到 LanceDB)
_ = ldb.SoftDelete(id, "auto_forget")
decayForgotten++
}
}
}
// 2026-09-07 方案A 碎片快速道: <30 字且 >20 天未访问 → 直接遗忘
// (绕过 ShouldForget 的 recallCount 保命——碎片 recall_count 可能虚高)。
// 碎片无记忆价值(审计: 30.9% <20字 + 43% <50字 = 蒸馏无门槛产物)。
contentStr := ""
if cs, ok := m["content"].(string); ok {
contentStr = cs
}
// AC-1 验收日志(P1 修复 type 断言后 last_recalled_at 可解析;batch<=2000)
if decayScanned > 0 {
log.Printf("[decay] scanned=%d forgotten=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten)
}
case "gap_scan":
// 检查已有缺口:过期 7 天的自动关闭
gaps := gapDetector.List()
for _, g := range gaps {
if !g.Closed && time.Since(g.CreatedAt) > 7*24*time.Hour {
gapDetector.Close(g.Topic)
}
if len([]rune(contentStr)) < 30 && time.Since(lastAccessed).Hours()/24 > 20 {
if id, ok := m["id"].(string); ok {
_ = ldb.SoftDelete(id, "auto_forget_fragment")
decayForgotten++
}
// 自动修复开放的缺口
for _, g := range gaps {
if !g.Closed && routes.GapRepair != nil {
if routes.GapRepair.AutoRepair(g) {
selfoptimize.Dash.RecordGapClosed()
}
continue
}
recallCount := 0
if rc, ok := m["recall_count"].(int); ok {
recallCount = rc
}
tier := "normal"
if ts, ok := m["tier"].(string); ok {
tier = ts
}
// E4.3: 获取实体图谱度(namespace 作为实体)
entity := ""
if ns, ok := m["namespace"].(string); ok {
entity = ns
}
degree := 0
if entity != "" {
degree = graphStore.GetEntityDegree(entity)
}
if forgetter.ShouldForget(lastAccessed, recallCount, tier, degree) {
if id, ok := m["id"].(string); ok {
forgetter.ScanAndForget(id)
// 实际执行软删除(持久化到 LanceDB)
_ = ldb.SoftDelete(id, "auto_forget")
decayForgotten++
}
}
}
}
// AC-1 验收日志(P1 修复 type 断言后 last_recalled_at 可解析;batch<=2000)
if decayScanned > 0 {
log.Printf("[decay] scanned=%d forgotten=%d (batch<=2000, 最久未访问优先)", decayScanned, decayForgotten)
if err != nil {
routes.Triggers.RecordFail(triggerID)
}
case "gap_scan":
// 检查已有缺口:过期 7 天的自动关闭
gaps := gapDetector.List()
for _, g := range gaps {
if !g.Closed && time.Since(g.CreatedAt) > 7*24*time.Hour {
gapDetector.Close(g.Topic)
}
// Skill 结晶:每次蒸馏成功后记录
if action == "distill" || action == "consolidation" {
routes.Skills.RecordTrial("auto_distill", true)
}
// 自动修复开放的缺口
for _, g := range gaps {
if !g.Closed && routes.GapRepair != nil {
if routes.GapRepair.AutoRepair(g) {
selfoptimize.Dash.RecordGapClosed()
}
}
}
}
if err != nil {
routes.Triggers.RecordFail(triggerID)
}
// Skill 结晶:每次蒸馏成功后记录
if action == "distill" || action == "consolidation" {
routes.Skills.RecordTrial("auto_distill", true)
}
routes.WSBus.Broadcast("trigger.fired", map[string]string{
routes.WSBus.Broadcast("trigger.fired", map[string]string{
"trigger_id": triggerID,
"action": action,
})