diff --git a/go/internal/api/server.go b/go/internal/api/server.go index 39b1584..bad246f 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -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< 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, })