diff --git a/go/internal/api/server.go b/go/internal/api/server.go index 8cfcdfe..5bc8649 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -233,6 +233,9 @@ func NewServer() http.Handler { CreatedAt: time.Now(), UpdatedAt: time.Now(), DerivedFrom: input.EpisodeID, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(蒸馏直写当前单亲, + // 单条证据;多 episode 聚合由 consolidate 路径补充) + SourceEvents: []string{input.EpisodeID}, Freshness: "fresh", Source: srcOrLLMDistill(input.Source), // 2026-09-26:有笔记出处→"wiki:<路径>";否则沿用 llm_distill(2026-09-07 方案C provenance) // 2026-10-08 (t_7e3577c5):血缘字段——写入方经 metadata 携带;缺省兜底 @@ -421,6 +424,9 @@ func NewServer() http.Handler { }) mux.HandleFunc("/api/v1/recall", api.Recall) mux.HandleFunc("/api/v1/recall/debug", api.RecallDebug) + // ⑤使用追踪(t_5aa4dcac):上报 + 手动触发。env 门控 ZHIYI_USAGE_TRACK,默认关。 + mux.HandleFunc("/api/v1/usage/report", api.UsageReport) + mux.HandleFunc("/api/v1/usage/detect", api.UsageDetect) // GA-P0-7 (t_dd64345a):裸 /api/v1/feedback 已退役——其 handler 曾写旧字段 not_useful_count。 // 反馈统一走 /api/v1/feedback/{useful,not-useful,deprecate,correct}(feedback.go,写拆分后新字段)。 mux.HandleFunc("/api/v1/bootstrap", api.Bootstrap) diff --git a/go/internal/api/server.go.bak.proofchain-20261014-005204 b/go/internal/api/server.go.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..5bc8649 --- /dev/null +++ b/go/internal/api/server.go.bak.proofchain-20261014-005204 @@ -0,0 +1,2025 @@ +// HTTP 服务器 — 多 Agent 架构(FileGraph + NetworkEventBus + 跨Agent缓存失效) +package api + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "path/filepath" + "runtime" + "sort" + "strconv" + "strings" + "time" + + "github.com/xiaoxue/memoryweave/internal/api/middleware" + "github.com/xiaoxue/memoryweave/internal/api/routes" + "github.com/xiaoxue/memoryweave/internal/distill" + "github.com/xiaoxue/memoryweave/internal/governance" + "github.com/xiaoxue/memoryweave/internal/metrics" + "github.com/xiaoxue/memoryweave/internal/models" + "github.com/xiaoxue/memoryweave/internal/redact" + "github.com/xiaoxue/memoryweave/internal/selfoptimize" + "github.com/xiaoxue/memoryweave/internal/storage" +) + +// cachedGraphStoreRef 全局图谱缓存引用(用于 graph write 操作时主动失效) +var cachedGraphStoreRef *storage.GraphCacheRef + +// skillByNameHandler GET/DELETE /api/v1/skills/{name} 的 method 分支分发器 +func skillByNameHandler(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + routes.Skills.Get(w, r) + case http.MethodDelete: + routes.Skills.Delete(w, r) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func NewServer() http.Handler { + mux := http.NewServeMux() + + // ─── 初始化依赖 ────────────────────────────── + emb := storage.NewEmbedder(os.Getenv("VLLM_ENDPOINT")) + rerank := storage.NewReranker(os.Getenv("RERANK_ENDPOINT"), emb) + + // 存储后端 + ldb := initStorageBackend(os.Getenv("STORAGE_BACKEND"), emb) + + // 召回元数据「累积延迟更新」缓冲(2026-09-12 优化B) + // 读路径不再逐条写 LanceDB(MVCC 每写一行一个版本 → _versions 膨胀根因), + // 改为窗口内合并 + 单事务批量提交(每批 1 个版本)。 + storage.InitRecallWriteBuffer(ldb) + + // 软删除累积延迟更新缓冲(2026-09-12 优化C) + // 软删除操作不再逐条写 LanceDB(每写一行一个版本 → _versions 膨胀), + // 改为窗口内合并 + 单事务批量提交(每批 1 个版本)。 + storage.InitSoftDeleteWriteBuffer(ldb) + + // 启动时数据目录一致性检查(防止路径混乱导致读取废弃数据) + runStartupChecks(os.Getenv("STORAGE_BACKEND")) + + // G7.2: 注册 LDB getter(供 skill crystallize 使用) + routes.RegisterLDBGetter(func() storage.LanceDB { return ldb }) + + // 冲突检测器(E4.1: Commit 时矛盾检测依赖此实例) + // 2026-09-20:改用带持久化的构造 —— 此前 active 是纯内存 map,zhiyid 重启即丢 + // (实测 17:17 重启后 pending 冲突全部消失)。落盘失败不致命,降级为内存模式并记日志。 + conflictDetector, cdErr := governance.NewPersistentConflictDetector("/var/lib/memoryweave/conflicts.json") + if cdErr != nil { + log.Printf("[conflict] 持久化加载失败,降级为内存模式: %v", cdErr) + } + // 注册全局实例,供 selfoptimize 触发器执行器读取(TConflict 判据) + governance.SetGlobalConflictDetector(conflictDetector) + + // 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速) + graphStore, cachedGraphStoreRef := storage.NewCachedGraphStore(initGraphStore()) + + // 整句→实体 拆解索引(节点名词表,TTL 10min;供 /api/v1/graph/notes 兜底。 + // 起因:调用方把整句提问当 entity 传,整句匹配不到节点 → 0 篇笔记) + entityIndex := routes.NewEntityIndex(func() map[string]float64 { + return graphStore.PageRank(0.85, 20) + }) + entityIndex.Degree = func(name string) int { return graphStore.GetEntityDegree(name) } + entityIndex.Warm(45 * time.Second) + + api := routes.NewAPI(ldb, emb, rerank, conflictDetector, graphStore) + + // G1: Recall 管线挂图谱扩展 + api.Pipeline.SetGraphExpander(graphStore) + + // 启动时初始化 Prometheus 指标 + // total_episodes 来自 Rust count_rows(真实值);旧 sidecar 回退 episodes_cached(非总量) + go func() { + time.Sleep(1 * time.Second) // 等待 Rust sidecar 就绪 + if stats, err := ldb.Stats(); err == nil { + if total, ok := stats["total_memories"].(float64); ok { + metrics.TotalMemories.Set(total) + } + if total, ok := stats["total_episodes"].(float64); ok { + metrics.TotalEpisodes.Set(total) + } else if cached, ok := stats["episodes_cached"].(float64); ok { + metrics.TotalEpisodes.Set(cached) // 旧 sidecar 回退,非真实总量 + } + log.Printf("[metrics] 初始化指标: memories=%.0f", stats["total_memories"]) + } + }() + + // 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速) + // 已在上面初始化 + graphUpdater := governance.NewAutoGraphUpdater(graphStore) + graphAPI := routes.NewGraphAPI(graphStore) + + // G4: 自动蒸馏 → 注入图谱更新器 + routes.SetGraphUpdater(graphUpdater) + + // 冲突 + conflictAPI := routes.NewConflictAPI(conflictDetector) + + // ─── 缺口 + gapDetector := selfoptimize.NewGapDetector(emb, ldb) + gapDetector.EnableGapRedisPersistence() + selfoptimize.SetGlobalGapDetector(gapDetector) // 注册全局实例供 recall 回调使用 + + // 因果追踪持久化 + routes.CascadeR.Tracker().EnableCausalRedisPersistence() + gapAPI := routes.NewGapAPI(gapDetector) + routes.InitGapRepair(gapDetector, ldb) // 共享同一个 GapDetector + LanceDB + // G1a: 挂缺隙记录器(0 结果 → 自动记录 miss) + api.Pipeline.SetMissRecorder(func(query, namespace string) { + gapDetector.RecordMiss(query + " [" + namespace + "]") + }) + + feedbackAPI := routes.NewFeedbackAPI(ldb) + // 遗忘器:支持按 Agent 类型设置衰减率 + forgetter := governance.NewForgetter() + adminAPI := routes.NewAdminAPI(ldb, forgetter, graphStore) + agentRegistry := routes.NewAgentRegistry(nil) + evalAPI := routes.NewEvalAPI(api.Pipeline, ldb) + l3API := routes.WM + consolPipe := routes.NewConsolidationPipeline(ldb, graphStore, conflictDetector) + consolPipe.SetDataDir("/var/lib/memoryweave/lancedb", "/var/lib/memoryweave/graph.db") + + // Obsidian + obsidian := routes.NewObsidianSyncer("", ldb) + + // ─── 蒸馏引擎 ─────────────────────────────── + llmEndpoint := os.Getenv("LLM_ENDPOINT") + llmModel := os.Getenv("LLM_MODEL") + if llmModel == "" { + llmModel = "deepseek/deepseek-v4-pro" + } + llmAPIKey := os.Getenv("LLM_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 + } + graphUpdater.UpdateFromDistill(&governance.DistillInput{ + Content: input.Content, Facts: result.Facts, + Entities: entityNames, Namespace: input.Namespace, + EpisodeID: input.EpisodeID, + Source: input.Source, // 2026-10-12 t_67d0279a 方案A:来源分档透传(auditSource 前缀归一后比对) + }) + + // 回写蒸馏产物到记忆库(LanceDB) + // 2026-09-07 方案B 质量门槛: 碎片(<20字)/噪声句(状态汇报/桥接/reflection)不入库, + // 与已有记忆完全重复跳过(蒸馏直写不走 commit exact_dup, 需本层查重)。 + // 2026-10-13 t_1c12e000:distilled facts 是 memories 表的唯一写入点。 + // 只要有任何一条真的 InsertMemory 成功 ⇒ 该 namespace 的 query 缓存作废 + //("先写再问" 场景:写完之后立刻可被之前问过但当时还没内容的答案命中)。 + factsLanded := false + // 2026-10-13 t_286d1310: 写库闸门同样感知准入分诊结论(lane)。 + // 此前这里独立跑 IsQualityFact 长度启发式——lane=keep 的决策类内容, + // 其 <20 字碎片在 insert 前仍被第三次独立丢弃(t_2ae69bb2 只穿透到 + // fact 级,没穿透到写库级)⇒ DB 里 derived_from= 0 行。 + // 复用 engine.go 同一函数 FilterQualityFactsWithLane(判据单一入口, + // 不复制): + // LaneKeep → 只保留 纯疑问/状态汇报 两条硬否定,跳过全部长度类规则 + // LaneDrop / LaneObserve → 委托 FilterQualityFacts,与 IsQualityFact 逐字一致 + // ClassifyAdmission 是确定性分诊(同一输入永远同一 lane),此处重算即 + // engine.go:537 在蒸馏时算出的同一条 lane。 + lane, laneWhy := distill.ClassifyAdmission(input.Content) + writeFacts := distill.FilterQualityFactsWithLane(result.Facts, lane) + if before := len(result.Facts); before > 0 && len(writeFacts) != before { + log.Printf("[distill][LANE] write-gate dropped %d/%d facts for %s (lane=%s, %s)", + before-len(writeFacts), before, input.EpisodeID, lane, laneWhy) + } + for _, fact := range writeFacts { + // 2026-09-10 P0:直写路径同样脱敏(FilterQualityFactsWithLane 已内部脱敏, + // 这里再脱一次为幂等保险——防止任何中间层注入明文密钥。事故里泄漏进 + // 镜像的记忆正是从这条路径入库的)。 + fact = redact.RedactSecrets(fact) + // 查重: 同 namespace 已存在**语义等价**记忆 → 跳过 + // 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等—— + // 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号) + // 会被判为两条不同事实双双入库,造成近重复堆积。 + var skip bool + if qvec, eErr := emb.EncodeSingle(fact); eErr == nil { + if sim, _ := ldb.Search("memories", qvec, 5, input.Namespace); len(sim) > 0 { + for _, ex := range sim { + if ex.Content == fact || cosineSimilarity(qvec, ex.Vector) >= 0.98 { + skip = true + break + } + } + } + } + if skip { + continue + } + mem := models.MemoryRecord{ + ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()), + AgentID: input.AgentID, + Namespace: input.Namespace, + Content: fact, + Category: "distilled", + Tier: "normal", + QualityScore: result.Overall, + Version: 1, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + DerivedFrom: input.EpisodeID, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(蒸馏直写当前单亲, + // 单条证据;多 episode 聚合由 consolidate 路径补充) + SourceEvents: []string{input.EpisodeID}, + Freshness: "fresh", + Source: srcOrLLMDistill(input.Source), // 2026-09-26:有笔记出处→"wiki:<路径>";否则沿用 llm_distill(2026-09-07 方案C provenance) + // 2026-10-08 (t_7e3577c5):血缘字段——写入方经 metadata 携带;缺省兜底 + // embedding_model→bge-m3(实际嵌入模型),script_version→unknown。 + EmbeddingModel: orDefault(input.EmbeddingModel, "bge-m3"), + ScriptVersion: orDefault(input.ScriptVersion, "unknown"), + // 2026-10-08 (Gap#2):信任等级透传到产物(nil 保持 NULL,不伪装 0.0) + Confidence: input.Confidence, + ConfidenceSource: input.ConfidenceSource, + } + log.Printf("[srcprobe] 蒸馏落库 episode=%s input.Source=%q → mem.Source=%q", input.EpisodeID, input.Source, mem.Source) + if err := ldb.InsertMemory(mem); err != nil { + log.Printf("[distill] commit fact failed: %v", err) + } else { + factsLanded = true // t_1c12e000:确有 distilled fact 落库 + } + } + // t_1c12e000:写路径缓存失效(方案 A)——distilled facts 是 memories 唯一写点。 + // 本进程 Invalidate(ns) 清 L1+L2;跨 Agent 广播复用 commit handler 的 + // PushCacheInvalidate(已注册 cache.invalidate 订阅),此处不重复广播。 + if factsLanded && storage.SearchCacheInstance != nil { + storage.SearchCacheInstance.Invalidate(input.Namespace) + log.Printf("[cache] 蒸馏落库后失效 namespace=%s(%d 条 facts,episode=%s)", + input.Namespace, len(result.Facts), input.EpisodeID) + } + // 冲突检测:加载已有记忆进行比较 + // 必须用**新内容的真实向量**做语义检索取近邻;用零向量在语义索引上 + // 返回的只是"范数最小"的任意行,真正的矛盾对象不在比对集里 → 永远检不出冲突。 + 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{}{ + "content": m.Content, + // 2026-10-09 修:此处原先填的是**新内容的实体**(同一个 entityNames 切片), + // 导致 Scan 的实体预筛 e1==e2 恒真、彻底失效 —— 每条候选都跑全量比对, + // 无关候选被纳入后 IsContradiction 误报(/var/lib/memoryweave/ + // conflicts-false-positive-*.json 现存 106 条已判假阳性即此产物)。 + // 改为**每条候选自己的实体**(从其正文抽取,与其它已存记忆同口径)。 + "entities": governance.ExtractEntities(m.Content), + }) + } + for _, c := range conflictDetector.Scan(input.Content, entityNames, conflictExisting) { + if c.Strategy == "latest_wins" { + conflictDetector.AutoResolve(c) + } + } + // 被动验证:使用已加载的记忆进行 P1/P2/P3 匹配 + validMems := make([]selfoptimize.MemoryForValidation, len(existingMems)) + for i, m := range existingMems { + validMems[i] = selfoptimize.MemoryForValidation{ + ID: m.ID, Content: m.Content, QualityScore: m.QualityScore, + } + } + validated := selfoptimize.Validator.Validate(input.Content, validMems) + // 被动验证结果写回 quality_score + // 修复(2026-09-20):原先用 GetRecords() 遍历【全部历史记录】并无条件写回 —— + // 每来一次输入就重写全库(≈6000 条),每次 Update 新增一个 LanceDB 版本快照 + // (manifest 引用全部 data 文件 ⇒ O(n²)),导致版本数每日 ~1.9 万、占用每日涨十几 G。 + // 现改为:只写【本次真正匹配】且【Confidence 实际发生变化】的记录。 + for _, r := range validated { + if r.Confidence > 0 && r.Changed { + _ = ldb.Update("memories", r.MemoryID, map[string]any{ + "quality_score": r.Confidence, + }) + } + } + } + + // ─── CO_OCCURS 追踪器(持久化到 Redis)─── + storage.CoOccurTrackerInstance = storage.NewCoOccurTracker(storage.RedisCoOccurPersist()) + storage.LoadCoOccurFromRedis() + + // ─── Dashboard 持久化到 Redis(restart 不丢指标)─── + selfoptimize.EnableRedisPersistence() + + // ─── VProp 持久化到 Redis(restart 不丢)─── + selfoptimize.VProp.EnableVPropRedisPersistence() + + // ─── Skill 持久化到 Redis(G7: restart 不丢 skills)─── + routes.BayesianSkills.EnableRedisPersistence() + + // ─── V 值传播器(竞争性架构核心)───────────── + vPropagator := selfoptimize.VProp + + // 注入 V 值查询函数到存储层(召回排序融合) + storage.VValueProvider = func(memoryID string) float64 { + // 2026-10-13:ep_* 是蒸馏自证(恒 1.0),零区分度且淹没真实 mem_* 信号 + // (实测 ep_* 4304 个 vs mem_* 24 个)。召回目标全是 mem_*,ep_* 的 V 值 + // 不参与排序即可,无需删 Redis 数据(保留可回溯)。 + if strings.HasPrefix(memoryID, "ep_") { + return 0 + } + return vPropagator.GetMemVValue(memoryID) + } + // 在蒸馏完成回调中记录 V 值 + originalOnComplete := distill.OnDistillComplete + distill.OnDistillComplete = func(input distill.DistillInput, result distill.DistillResult) { + // 调用已有的回调 + if originalOnComplete != nil { + originalOnComplete(input, result) + } + // 记录 V 值决策:蒸馏成功 = 有用 + if len(result.Facts) > 0 { + vPropagator.RecordDecision( + "distill_"+input.EpisodeID, + []string{input.EpisodeID}, + "distill", "success", "", + ) + } + // 更新仪表盘指标 + selfoptimize.Dash.RecordUseful() + // 记录蒸馏质量损失(avg_distill_loss = 1 - Overall) + // 仅记录真实蒸馏:Overall > 0 表示 LLM 成功返回,过滤 fallback (Overall=0) + if result.Overall > 0 { + loss := 1.0 - result.Overall + if loss < 0 { + loss = 0 + } + if loss > 1 { + loss = 1 + } + selfoptimize.Dash.RecordDistillLoss(loss) + } + } + + // ─── 跨 Agent 缓存失效回调 ─────────────────── + // 收到其他 Agent 的广播 → 失效本地缓存 + governance.GlobalEventBus.Subscribe("cache.invalidate", "self") + + // ─── 路由注册 ────────────────────────────── + + // ─── 静态文件服务(Web UI)───────────────────── + // webUIRoot 在函数顶部声明 + var webUIRoot string + // 后续在 catch-all 中处理(见文件末尾) + + mux.HandleFunc("/health", routes.HandleHealth) + mux.HandleFunc("/api/v1/health", routes.HandleHealth) + // 图谱缓存统计 + 搜索缓存统计(t_1c12e000:并入 search_cache 段, + // 暴露 hits/misses/invalidated/size/ttl,写频对命中率的影响可观测) + mux.HandleFunc("/api/v1/cache/stats", func(w http.ResponseWriter, r *http.Request) { + resp := map[string]interface{}{ + "graph_cache": nil, + } + if cachedGraphStoreRef != nil { + resp["graph_cache"] = cachedGraphStoreRef.Stats() + } + if storage.SearchCacheInstance != nil { + resp["search_cache"] = storage.SearchCacheInstance.Stats() + } + respondJSON(w, 200, resp) + }) + // ─── Prometheus /metrics ───────────────────── + mux.Handle("/metrics", metrics.Handler()) + + // 核心 API + mux.HandleFunc("/api/v1/commit", func(w http.ResponseWriter, r *http.Request) { + api.Commit(w, r) + // 跨 Agent 广播 + 自动蒸馏 + go func() { + var req struct { + AgentID string `json:"agent_id"` + Namespace string `json:"namespace"` + Content string `json:"content"` + } + if r.Body != nil { + body, _ := io.ReadAll(r.Body) + json.Unmarshal(body, &req) + r.Body = io.NopCloser(bytes.NewReader(body)) + } + if req.Namespace != "" { + // 通知其他 Agent:缓存失效 + 新记忆事件 + governance.PushCacheInvalidate(req.Namespace, "commit") + governance.PushMemoryCommitted(req.AgentID, req.Namespace, "") + } + }() + }) + mux.HandleFunc("/api/v1/recall", api.Recall) + mux.HandleFunc("/api/v1/recall/debug", api.RecallDebug) + // ⑤使用追踪(t_5aa4dcac):上报 + 手动触发。env 门控 ZHIYI_USAGE_TRACK,默认关。 + mux.HandleFunc("/api/v1/usage/report", api.UsageReport) + mux.HandleFunc("/api/v1/usage/detect", api.UsageDetect) + // GA-P0-7 (t_dd64345a):裸 /api/v1/feedback 已退役——其 handler 曾写旧字段 not_useful_count。 + // 反馈统一走 /api/v1/feedback/{useful,not-useful,deprecate,correct}(feedback.go,写拆分后新字段)。 + mux.HandleFunc("/api/v1/bootstrap", api.Bootstrap) + mux.HandleFunc("/api/v1/stats", api.Stats) + mux.HandleFunc("/api/v1/batch-commit", api.BatchCommit) + // 自优化指标(Dashboard,含 avg_distill_loss) + // total_episodes:Rust count_rows 真实值;旧 sidecar 回退 episodes_cached(进程内缓存,非总量) + mux.HandleFunc("/api/v1/metrics", func(w http.ResponseWriter, r *http.Request) { + m := selfoptimize.Dash.Metrics() + if stats, err := ldb.Stats(); err == nil { + if total, ok := stats["total_memories"].(float64); ok { + m["total_memories"] = total + } + if total, ok := stats["total_episodes"].(float64); ok { + m["total_episodes"] = total + } else if cached, ok := stats["episodes_cached"].(float64); ok { + // 旧 sidecar 回退:缓存值非真实总量,gauge 仍设值; + // 来源标记写入响应 JSON(/api/v1/metrics 的 m 类型是 map[string]float64, + // 无法直接加字符串字段,改为用 episodes_source=1.0 作为标记位) + m["total_episodes"] = cached + m["episodes_source_cached"] = 1 // 标记:此值来自进程内缓存(非 Rust count_rows) + } + } + respondJSON(w, 200, m) + }) + // ─── WebSocket 实时推送 ────────────────────── + mux.HandleFunc("/api/v1/ws/", routes.WSHandler) + // 社区发现(Louvain + 社区摘要) + mux.HandleFunc("/api/v1/community/summarize", api.HandleCommunitySummarize) + // 深度推理(人侧数据 → 三类清单) + mux.HandleFunc("/api/v1/deep-think", api.HandleDeepThink) + + mux.HandleFunc("/api/v1/ws", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"ok","protocol":"websocket","endpoint":"/api/v1/ws/{agent_id}"}`)) + }) + + // 知识图谱 + mux.HandleFunc("/api/v1/graph/stats", graphAPI.Stats) + mux.HandleFunc("/api/v1/graph/query", graphAPI.Query) + mux.HandleFunc("/api/v1/graph/navigate", graphAPI.Navigate) + // P2: 边反馈 + mux.HandleFunc("/api/v1/graph/edge/feedback", api.EdgeFeedback) + // 新增:添加关系边(POST JSON body: {"from":"实体A","to":"实体B","relation":"关系类型","namespace":""}) + mux.HandleFunc("/api/v1/graph/edge", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "POST only", 405) + return + } + var req struct { + From string `json:"from"` + To string `json:"to"` + Relation string `json:"relation"` + Namespace string `json:"namespace"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), 400) + return + } + if req.From == "" || req.To == "" || req.Relation == "" { + http.Error(w, "from, to, relation required", 400) + return + } + ns := req.Namespace + if ns == "" { + ns = "default" + } + edgeID := fmt.Sprintf("e_%s_%s_%d", req.From, req.Relation, time.Now().UnixNano()) + maxRetries := 5 + var lastErr error + for attempt := 0; attempt < maxRetries; attempt++ { + lastErr = graphStore.AddEdge(edgeID, req.From, req.To, req.Relation, ns, 1.0) + if lastErr == nil { + 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") { + // Exponential backoff: 1s, 2s, 4s, 8s, 16s + backoff := time.Duration(1< 0 { + limit = l + } + } + nodes, edges := graphStore.GetGraph(ns, limit) + respondJSON(w, 200, map[string]interface{}{ + "nodes": nodes, + "edges": edges, + "count": map[string]int{"nodes": len(nodes), "edges": len(edges)}, + }) + }) + + // 图谱导航 + Obsidian 笔记关联 + mux.HandleFunc("/api/v1/graph/notes", func(w http.ResponseWriter, r *http.Request) { + entity := r.URL.Query().Get("entity") + if entity == "" { + entity = r.URL.Query().Get("query") // 也接受整句 query + } + // 噪音闸门(t_689b6d38):系统通知/提示样板文本(如 "[IMPORTANT: You are running + // as a scheduled cron job..."、"[System note: ...")不进语义召回、不返回笔记。 + // 判定优先用结构化来源标记头,白名单(真实用户提问)照常召回,不误杀。 + if routes.IsSystemTemplateInput(entity) { + log.Printf("[graph/notes] 拦截系统样板入参(system_template):不拆实体、不返回笔记(入参 %q)", + strings.TrimSpace(entity)) + respondJSON(w, 200, map[string]interface{}{ + "entity": entity, + "graph_paths": []map[string]interface{}{}, + "notes": []map[string]interface{}{}, + "paths_count": 0, + "notes_count": 0, + "mode": "none", + "skipped": "system_template", + }) + return + } + maxHops := 2 + if h := r.URL.Query().Get("max_hops"); h != "" { + if parsed, err := strconv.Atoi(h); err == nil && parsed > 0 { + maxHops = parsed + } + } + maxNotes := 10 + if n := r.URL.Query().Get("max_notes"); n != "" { + if parsed, err := strconv.Atoi(n); err == nil && parsed > 0 { + maxNotes = parsed + } + } + + var noteResults []map[string]interface{} + var paths []map[string]interface{} + mode := "none" + var usedEntities []string + // 响应体积上限:调用方(hermes 插件 / openclaw 客户端 / dashboard)都只读 notes, + // 不读 graph_paths(2026-09-27 全仓核对 3 处调用点)。而单实体 2 跳可爆到 1.9 万条 + // ≈1.7MB/次 → 截断,仅作可观测样本。 + const maxGraphPaths = 50 + // union:同名两层并集展开(id=名字 的旧 entity 层 + id="n_"+名字 的新 concept 层)。 + // 图谱重名报告(2026-09-27):Navigate 按 id 匹配 ⇒ 只传名字时新层完全用不上(织忆: + // 旧层 6 出边 vs 新层 1674 出边)。兜底路径(整句提问)默认并集;直查路径用 union=1 显式开 + // —— 灰度:直查是稳定路径,先不动,等对比数据再决定默认值。 + unionParam := r.URL.Query().Get("union") + union := unionParam == "1" // 直查路径:显式 union=1 才开 + unionDefault := unionParam != "0" // 兜底路径:默认开,union=0 可关(验收对照用) + unionApplied := false + var unionIDs []string // 并集展开实际用到的节点 id(可观测:是否真的吃到新层) + addUnionID := func(id string) { + for _, x := range unionIDs { + if x == id { + return + } + } + unionIDs = append(unionIDs, id) + } + if entity != "" { + norm := routes.NormalizeEntity(entity) + p, err := graphStore.Navigate(norm, maxHops, "", nil) + if err == nil { + // union=1:同名跨层并集。必须按**原始名字**解析:norm 已带 n_ 前缀 + // (NormalizeEntity 行为),用它解析只得到新 concept 层(含 n_n_ 伪影), + // 恰恰漏掉旧 wiki 语义层(id=名字,7,466 条边,HTTP 上完全不可达)。 + if union { + seenP := make(map[string]bool, len(p)) + extra := []map[string]interface{}{} + for _, id := range routes.ResolveEntityIDs(graphStore, strings.TrimPrefix(norm, "n_")) { + addUnionID(id) + if id == norm { + continue + } + if p2, err2 := graphStore.Navigate(id, maxHops, "", nil); err2 == nil { + extra = routes.MergePaths(extra, p2, nil, 0) + } + } + // 跨层(旧 wiki 语义层)边放前面:主层 1.9 万条机器边会把 50 条样本窗口 + // 占满,排在后面等于被截断——并集就白做了。 + p = routes.MergePaths(extra, p, seenP, 0) + unionApplied = true + } + paths = p + // 邻居进笔记匹配:必须带上限 + 去重。2026-09-27 上线实测教训——不加限会把 + // 并集展开出的上万个邻居全丢给 SearchNotesByEntities(实体 × 全库笔记扫描), + // CPU 直接打满、HTTP 45s 超时。上限与兜底路径的 maxSearchEntities 同思路。 + const maxMatchEntities = 24 + entities := make([]string, 0, maxMatchEntities) + entsSeen := map[string]bool{norm: true} + entities = append(entities, norm) + for _, path := range p { + if len(entities) >= maxMatchEntities { + break + } + s, t, _ := routes.PathEnds(path) // 兼容 from/to 与 source/target 两套键名 + for _, e := range [2]string{s, t} { + if e == "" || entsSeen[e] { + continue + } + entsSeen[e] = true + entities = append(entities, e) + if len(entities) >= maxMatchEntities { + break + } + } + } + if obsidian != nil { + noteResults = obsidian.SearchNotesByEntities(entities, maxNotes) + } + // 笔记匹配已用完完整路径集 → 响应只留样本(见上方 maxGraphPaths 说明) + if len(paths) > maxGraphPaths { + paths = paths[:maxGraphPaths] + } + } + if len(noteResults) > 0 { + mode = "direct" + } else if cands := entityIndex.Extract(entity, 2); len(cands) > 0 { + // 兜底:entity 是整句自然语言(调用方原样传用户提问)→ 本地把它拆成候选实体 + // 2026-10-12 GA-P0-5:概念/实体提取路径接 echo 防线 —— 审计笔记把污染词当证据 + // 列出来 → 蒸馏成 episode → 兜底拆实体时会把已删除污染节点(n_galway / n_rothfuss / + // n_the_name_of_the_wind)重建。候选实体若只是 prompt 教学示例的回显残片 + // (逐字相等 / illustration 类 ≥4 字子串,判据与蒸馏侧 IsPromptEcho 同源) + // ⇒ 不入图;[ECHO-DROP] 日志供验证防线在跑。 + var echoDropped int + kept := cands[:0] + for _, c := range cands { + if distill.IsPromptEchoEntity(c) { + echoDropped++ + continue + } + kept = append(kept, c) + } + if echoDropped > 0 { + log.Printf("[graph/notes][ECHO-DROP] 剔除回显残片 %d 个(%q)→ 不参与笔记匹配/不入图", echoDropped, cands) + cands = kept + } + const maxSearchEntities = 8 // 参与笔记匹配的实体上限:候选 + 少量邻居,防噪声淹没 + ents := make([]string, 0, maxSearchEntities) + seen := make(map[string]bool, maxSearchEntities) + for _, cand := range cands { + ne := routes.NormalizeEntity(cand) + if ne == "" || seen[ne] { + continue + } + seen[ne] = true + ents = append(ents, ne) + // 并集:同名跨层(旧 wiki 语义层 + 新 concept 层)都展开, + // 按原始名字解析——ne 带 n_ 前缀会漏掉旧层(同直查路径注释)。 + ids := []string{ne} + if unionDefault { + ids = routes.ResolveEntityIDs(graphStore, strings.TrimPrefix(ne, "n_")) + unionApplied = true + for _, id := range ids { + addUnionID(id) + } + } + for _, id := range ids { + p, err := graphStore.Navigate(id, maxHops, "", nil) + if err != nil { + continue + } + if len(p) > 20 { // 单跳邻居即可,避免把整个二跳子图塞进响应 + p = p[:20] + } + if len(paths) < maxGraphPaths { + paths = append(paths, p...) + } + for _, path := range p { + if len(ents) >= maxSearchEntities { + break + } + s, t, _ := routes.PathEnds(path) // 同上:兼容两套键名 + if s != "" && !seen[s] { + seen[s] = true + ents = append(ents, s) + } + if t != "" && !seen[t] { + seen[t] = true + ents = append(ents, t) + } + } + } + } + if obsidian != nil && len(ents) > 0 { + noteResults = obsidian.SearchNotesByEntities(ents, maxNotes) + } + if len(noteResults) > 0 { + mode = "nl_extract" + usedEntities = cands + log.Printf("[graph/notes] 整句兜底拆实体 %v(实际匹配 %d 个)→ %d 篇笔记(入参 %q)", cands, len(ents), len(noteResults), entity) + } + } + } + resp := map[string]interface{}{ + "entity": entity, + "graph_paths": paths, + "notes": noteResults, + "paths_count": len(paths), + "notes_count": len(noteResults), + "mode": mode, + } + if len(usedEntities) > 0 { + resp["entities_used"] = usedEntities + } + if unionApplied { + resp["union"] = true // 本次响应走了同名两层并集展开 + } + if len(unionIDs) > 0 { + resp["entity_ids_used"] = unionIDs + } + respondJSON(w, 200, resp) + }) + + // 自然语言图谱查询 /api/v1/graph/nl_query + // 输入: {"query": "织忆和牧尘是什么关系"} + // 返回: 自然语言关系描述 + mux.HandleFunc("/api/v1/graph/nl_query", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "POST only", http.StatusMethodNotAllowed) + return + } + var req struct { + Query string `json:"query"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid body", http.StatusBadRequest) + return + } + query := strings.TrimSpace(req.Query) + if query == "" { + http.Error(w, "query is required", http.StatusBadRequest) + return + } + + // 1. 从 query 中提取可能的实体名(去掉问号、语气词) + cleanQuery := strings.TrimSuffix(strings.TrimSuffix(query, "?"), "?") + cleanQuery = strings.TrimPrefix(cleanQuery, "请问") + cleanQuery = strings.TrimPrefix(cleanQuery, "请说") + cleanQuery = strings.TrimSpace(cleanQuery) + + // 2. 尝试识别实体对("A和B的关系"、"A与B") + var entityA, entityB string + // 模式1: "A和B是什么关系" / "A和B有什么关系" / "A和B的关系" + hasAnd := strings.Contains(cleanQuery, "和") || strings.Contains(cleanQuery, "与") + if hasAnd && (strings.Contains(cleanQuery, "关系") || strings.Contains(cleanQuery, "关联")) { + delim := "和" + if strings.Contains(cleanQuery, "与") { + delim = "与" + } + parts := strings.Split(cleanQuery, delim) + if len(parts) == 2 { + entityA = strings.TrimSpace(parts[0]) + rawB := strings.TrimSpace(parts[1]) + // 去掉句末的问句模式得到 entityB + entityB = strings.TrimSuffix(rawB, "是什么关系") + entityB = strings.TrimSuffix(entityB, "有什么关系") + entityB = strings.TrimSuffix(entityB, "的") + entityB = strings.TrimSuffix(entityB, "是什么") + entityB = strings.TrimSpace(entityB) + // 如果去掉问句后为空(如"织忆和牧尘" -> entityB=""),则原始 query 可能是"A和B" + if entityB == "" { + entityB = rawB + } + } + } + + var result map[string]interface{} + if entityA != "" && entityB != "" { + // 双向查询:A → B 的关系 + paths, _ := graphStore.Navigate(routes.NormalizeEntity(entityA), 2, "", nil) + relB, _ := graphStore.Navigate(routes.NormalizeEntity(entityB), 2, "", nil) + // 找 A → B 的直接边 + var directPath map[string]interface{} + for _, p := range paths { + toNorm := routes.NormalizeEntity(p["to"].(string)) + targetNorm := routes.NormalizeEntity(entityB) + if toNorm == targetNorm { + directPath = p + break + } + } + 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)), + } + } else { + // 单实体查询:找 entity 的关系网 + entity := cleanQuery + paths, _ := graphStore.Navigate(routes.NormalizeEntity(entity), 2, "", nil) + // 按 relation 分组 + relCounts := make(map[string]int) + for _, p := range paths { + rel := p["relation"].(string) + if rel == "" { + rel = "unknown" + } + relCounts[rel]++ + } + // 生成自然语言描述 + var rels []string + for rel, cnt := range relCounts { + rels = append(rels, fmt.Sprintf("%s(%d条)", rel, cnt)) + } + sort.Strings(rels) + result = map[string]interface{}{ + "query": query, + "entity": entity, + "total_paths": len(paths), + "relation_summary": rels, + "summary": fmt.Sprintf("%s 共有 %d 条关联,分布在 %d 种关系类型", entity, len(paths), len(relCounts)), + } + } + respondJSON(w, 200, result) + }) + + // 图谱脏数据清理 /api/v1/graph/cleanup + mux.HandleFunc("/api/v1/graph/cleanup", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" && r.Method != "GET" { + http.Error(w, "GET or POST only", http.StatusMethodNotAllowed) + return + } + dryRun := r.URL.Query().Get("dry_run") != "false" // 默认为 dryRun + count, ids, err := graphStore.CleanupNoiseNodes(dryRun) + if err != nil { + http.Error(w, "cleanup failed: "+err.Error(), http.StatusInternalServerError) + return + } + // 实际执行后失效缓存(dry_run=true 时不执行,无需失效) + if !dryRun && cachedGraphStoreRef != nil && count > 0 { + cachedGraphStoreRef.InvalidateAll() + } + respondJSON(w, 200, map[string]interface{}{ + "dry_run": dryRun, + "removed": count, + "node_ids": ids, + "message": fmt.Sprintf("Found %d noise nodes", count), + }) + }) + + // 图谱多 agent 测试污染清理(namespace + 名称子串圈定,不碰全表编码规则) + // 2026-09-08 卫安/A03/A04 371 节点:openclaw-main/a06-main/hermes-main 中测试 agent 产生的概念/事实节点 + // GET/POST /api/v1/graph/cleanup/scoped?dry_run=true&namespace=a,b,c&name=a03,a04,卫安 + mux.HandleFunc("/api/v1/graph/cleanup/scoped", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" && r.Method != "GET" { + http.Error(w, "GET or POST only", http.StatusMethodNotAllowed) + return + } + dryRun := r.URL.Query().Get("dry_run") != "false" // 默认为 dryRun + nsParam := r.URL.Query().Get("namespace") + nameParam := r.URL.Query().Get("name") + if nsParam == "" || nameParam == "" { + http.Error(w, "namespace and name (comma separated) are required", http.StatusBadRequest) + return + } + namespaces := strings.Split(nsParam, ",") + nameContains := strings.Split(nameParam, ",") + + type scopedCleaner interface { + CleanupScopedNodes(dryRun bool, namespaces, nameContains []string) (int, []string, error) + } + cleaner, ok := graphStore.(scopedCleaner) + if !ok { + http.Error(w, "scoped cleanup not supported by current graph backend", http.StatusNotImplemented) + return + } + count, ids, err := cleaner.CleanupScopedNodes(dryRun, namespaces, nameContains) + if err != nil { + http.Error(w, "cleanup failed: "+err.Error(), http.StatusInternalServerError) + return + } + // 实际执行后失效缓存(dry_run=true 时不执行,无需失效) + if !dryRun && cachedGraphStoreRef != nil && count > 0 { + cachedGraphStoreRef.InvalidateAll() + } + respondJSON(w, 200, map[string]interface{}{ + "dry_run": dryRun, + "removed": count, + "node_ids": ids, + "namespaces": namespaces, + "name_contains": nameContains, + "message": fmt.Sprintf("Found %d scoped noise nodes", count), + }) + }) + + // 静态文件服务(知识图谱可视化 HTML) + staticDir := os.Getenv("STATIC_DIR") + if staticDir == "" { + staticDir = "/home/muc/projects/memoryweave/go/static" + } + fileServer := http.FileServer(http.Dir(staticDir)) + mux.Handle("/static/", http.StripPrefix("/static/", fileServer)) + + // 冲突 + mux.HandleFunc("/api/v1/conflicts", func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + conflictAPI.List(w, r) + } else { + http.NotFound(w, r) + } + }) + mux.HandleFunc("/api/v1/conflicts/resolve", conflictAPI.Resolve) + + // 反馈 — G5: 修正记忆时填充 version_history + 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"` + } + if r.Body != nil { + body, _ := io.ReadAll(r.Body) + json.Unmarshal(body, &req) + r.Body = io.NopCloser(bytes.NewReader(body)) + if req.MemoryID != "" { + selfoptimize.Dash.RecordUseful() + // V 值:useful = success + selfoptimize.VProp.RecordDecision( + "useful_"+req.MemoryID, + []string{req.MemoryID}, + "user_feedback", "success", "", + ) + selfoptimize.QualityMonitor.Check(req.MemoryID, 0, 5) // 清除潜在告警 + } + } + }) + 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"` + } + if r.Body != nil { + body, _ := io.ReadAll(r.Body) + json.Unmarshal(body, &req) + r.Body = io.NopCloser(bytes.NewReader(body)) + if req.MemoryID != "" { + selfoptimize.Dash.RecordNotUseful() + // V 值:not-useful = failure + selfoptimize.VProp.RecordDecision( + "notuseful_"+req.MemoryID, + []string{req.MemoryID}, + "user_feedback", "failure", "", + ) + score := selfoptimize.Dash.QualityScore() + if record := selfoptimize.QualityMonitor.Check(req.MemoryID, score, 5); record != nil { + _ = record // WebSocket 通知 + } + } + } + }) + mux.HandleFunc("/api/v1/feedback/deprecate", feedbackAPI.Deprecate) + mux.HandleFunc("/api/v1/feedback/correct", func(w http.ResponseWriter, r *http.Request) { + feedbackAPI.Correct(w, r) + var req struct { + MemoryID string `json:"memory_id"` + NewContent string `json:"new_content"` + Source string `json:"source"` + } + if r.Body != nil { + body, _ := io.ReadAll(r.Body) + json.Unmarshal(body, &req) + r.Body = io.NopCloser(bytes.NewReader(body)) + if req.MemoryID != "" && req.NewContent != "" { + routes.FillVersionHistory(req.MemoryID, "", req.NewContent, req.Source) + // 跨 Agent 通知 + governance.PushMemoryUpdated(req.MemoryID, 0, "corrected") + } + } + }) + + // 缺口 + mux.HandleFunc("/api/v1/gaps", gapAPI.List) + mux.HandleFunc("/api/v1/gaps/detect", gapAPI.Detect) + mux.HandleFunc("/api/v1/gaps/close/", func(w http.ResponseWriter, r *http.Request) { + gapAPI.Close(w, r) + topic := r.URL.Path[len("/api/v1/gaps/close/"):] + routes.PushGapFilled(topic, 1) + governance.PushGapFilled(topic, 1) + }) + mux.HandleFunc("/api/v1/gaps/repair", routes.GapRepair.FullRepairHandler) + + // Agent 注册 + mux.HandleFunc("/api/v1/agents/register", agentRegistry.Register) + mux.HandleFunc("/api/v1/agents", agentRegistry.List) + + // ─── 多 Agent EventBus 管理 ────────────────── + mux.HandleFunc("/api/v1/eventbus/subscribe", func(w http.ResponseWriter, r *http.Request) { + var req struct { + EventType string `json:"event_type"` + Callback string `json:"callback_url"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + governance.GlobalEventBus.Subscribe(req.EventType, req.Callback) + respondJSON(w, 200, map[string]string{"status": "subscribed"}) + }) + mux.HandleFunc("/api/v1/eventbus/unsubscribe", func(w http.ResponseWriter, r *http.Request) { + var req struct { + EventType string `json:"event_type"` + Callback string `json:"callback_url"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + governance.GlobalEventBus.Unsubscribe(req.EventType, req.Callback) + respondJSON(w, 200, map[string]string{"status": "unsubscribed"}) + }) + mux.HandleFunc("/api/v1/eventbus/list", func(w http.ResponseWriter, r *http.Request) { + subs := governance.GlobalEventBus.ListSubscribers() + respondJSON(w, 200, subs) + }) + + // 跨 Agent 缓存失效接收端点(供其他 Agent 实例 HTTP 回调) + mux.HandleFunc("/api/v1/cache/invalidate", func(w http.ResponseWriter, r *http.Request) { + var evt struct { + Type string `json:"type"` + Payload map[string]string `json:"payload"` + } + if err := json.NewDecoder(r.Body).Decode(&evt); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + ns := evt.Payload["namespace"] + storage.SearchCacheInstance.Invalidate(ns) + log.Printf("[cache] 跨 Agent 失效接收: %s", ns) + respondJSON(w, 200, map[string]string{"status": "invalidated"}) + }) + + // 管理 + // ?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 + } + respondJSON(w, 200, report) + go governance.PushDistillationComplete(report.Merged, report.ConflictsFound) + } + }) + mux.HandleFunc("/api/v1/admin/forget", adminAPI.Forget) + mux.HandleFunc("/api/v1/admin/purge-invalid", adminAPI.PurgeInvalid) + mux.HandleFunc("/api/v1/admin/dedup", api.Dedup) + mux.HandleFunc("/api/v1/admin/backup", adminAPI.Backup) + mux.HandleFunc("/api/v1/admin/restore", adminAPI.Restore) + mux.HandleFunc("/api/v1/admin/backups", adminAPI.ListBackups) + mux.HandleFunc("/api/v1/admin/audit", adminAPI.Audit) + // 遗忘器类型管理 + mux.HandleFunc("/api/v1/admin/forgetter/type", func(w http.ResponseWriter, r *http.Request) { + var req struct { + AgentType string `json:"agent_type"` + } + if r.Method == "POST" { + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + forgetter.SetAgentType(req.AgentType) + } + respondJSON(w, 200, map[string]interface{}{ + "agent_type": forgetter.AgentType(), + "decay_rate": AgentTypeDecayOrDefault(forgetter.AgentType()), + }) + }) + mux.HandleFunc("/api/v1/admin/distill/force", func(w http.ResponseWriter, r *http.Request) { + if routes.DistillEngineRef == nil { + respondJSON(w, 400, map[string]string{"error": "distill engine not initialized"}) + return + } + var req struct { + Content string `json:"content"` + Category string `json:"category"` + Namespace string `json:"namespace"` + AgentID string `json:"agent_id"` + // 2026-09-26:手动蒸馏也支持带出处(便于补跑 wiki 批时保留笔记路径) + Source string `json:"source"` + // 2026-10-08 (Gap#2):手动蒸馏同样可显式声明信任等级(补跑存量时用) + Confidence *float64 `json:"confidence"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + if req.Content == "" { + respondJSON(w, 400, map[string]string{"error": "content required"}) + return + } + 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, routes.CommitMeta{ + Source: req.Source, + Confidence: req.Confidence, + ConfidenceSource: confidenceSourceOf(req.Confidence), + }) + respondJSON(w, 200, map[string]string{"status": "queued", "episode_id": epID}) + }) + // 蒸馏队列状态端点(G8-G9 配套) + mux.HandleFunc("/api/v1/distill/status", func(w http.ResponseWriter, r *http.Request) { + if routes.DistillEngineRef == nil { + respondJSON(w, 200, map[string]interface{}{"status": "not_initialized", "queue_len": 0}) + return + } + respondJSON(w, 200, routes.DistillEngineRef.GetStatus()) + }) + mux.HandleFunc("/api/v1/distill/queue", func(w http.ResponseWriter, r *http.Request) { + if routes.DistillEngineRef == nil { + respondJSON(w, 200, map[string]interface{}{"queue": []interface{}{}, "count": 0}) + return + } + items := routes.DistillEngineRef.QueueItems() + respondJSON(w, 200, map[string]interface{}{"queue": items, "count": len(items)}) + }) + mux.HandleFunc("/api/v1/distill/quota", func(w http.ResponseWriter, r *http.Request) { + if routes.DistillEngineRef == nil { + respondJSON(w, 200, map[string]interface{}{"remaining": 0, "used": 0, "limit": 0, "status": "not_initialized"}) + return + } + respondJSON(w, 200, routes.DistillEngineRef.GetQuota()) + }) + mux.HandleFunc("/api/v1/distilled/{id}", func(w http.ResponseWriter, r *http.Request) { + if r.Method == "DELETE" { + adminAPI.DeleteDistilled(w, r) + } else { + http.NotFound(w, r) + } + }) + // P2: 记忆离线整合(LightMem UPDATE_PROMPT)— 手动触发 + // POST /api/v1/consolidate/memory {"namespace":"hermes-main"} + mux.HandleFunc("/api/v1/consolidate/memory", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "POST only", 405) + return + } + if routes.DistillEngineRef == nil { + respondJSON(w, 400, map[string]string{"error": "distill engine not initialized"}) + return + } + var req struct { + Namespace string `json:"namespace"` + Limit int `json:"limit"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + if req.Namespace == "" { + req.Namespace = "hermes-main" + } + if req.Limit <= 0 { + req.Limit = 50 + } + + // 取全部记忆(零向量搜索) + zeroVec := make([]float32, 1024) + mems, err := ldb.Search("memories", zeroVec, req.Limit, req.Namespace) + if err != nil || len(mems) == 0 { + respondJSON(w, 200, map[string]interface{}{"status": "ok", "processed": 0, "message": "no memories to consolidate"}) + return + } + + // 两两比较相似度(简单 Jaccard/词重叠启发式,避免调用嵌入) + // 真实场景:应使用向量相似度,此处用词重叠近似 + processed := 0 + updated := 0 + deleted := 0 + ignored := 0 + errors_ := 0 + + // 按目标分组整合:外层 i 为目标,内层收集所有高相似候选, + // 每个目标只调一次 LLM(UpdatePrompt 原生支持多候选),避免 O(n²) LLM 调用风暴。 + // 2026-09-06 fix(t_04 ④): 原实现每对相似记忆调一次 LLM → limit=100 产生 4950 对 + // → 跑 223s+ 未完成 → 每天 processed=0(不是 namespace 过滤 bug)。 + for i := 0; i < len(mems); i++ { + // 收集所有与 mems[i] 高相似的候选(j > i 且未处理) + var cands []distill.MemoryCandidate + for j := i + 1; j < len(mems); j++ { + if mems[j].Content == "" { + continue + } + sim := distill.TextSimilarity(mems[i].Content, mems[j].Content) + if sim < 0.5 { + continue + } + cands = append(cands, distill.MemoryCandidate{ID: mems[j].ID, Content: mems[j].Content}) + } + if len(cands) == 0 { + continue + } + + // 一次 LLM 决策:目标 mems[i] + 全部高相似候选 + result, err := routes.DistillEngineRef.ConsolidateMemory( + distill.MemoryCandidate{ID: mems[i].ID, Content: mems[i].Content}, + cands, + ) + if err != nil { + errors_++ + continue + } + processed++ + switch result.Action { + case "update": + if result.NewMemory != "" { + if err := ldb.UpdateMemoryContent(mems[i].ID, result.NewMemory, "consolidate"); err != nil { + log.Printf("[consolidate] update failed %s: %v", mems[i].ID, err) + } else { + updated++ + } + } + case "delete": + if err := ldb.SoftDelete(mems[i].ID, "consolidate: conflict"); err != nil { + log.Printf("[consolidate] delete failed %s: %v", mems[i].ID, err) + } else { + deleted++ + } + default: + ignored++ + } + } + + respondJSON(w, 200, map[string]interface{}{ + "status": "ok", + "processed": processed, + "updated": updated, + "deleted": deleted, + "ignored": ignored, + "errors": errors_, + "total_memories": len(mems), + }) + }) + // GET /api/v1/memories — list all memories (zero-vector search, for plugin compat) + mux.HandleFunc("/api/v1/memories", adminAPI.ListMemories) + mux.HandleFunc("/api/v1/memories/export", adminAPI.ExportMemoriesMD) + // /api/v1/memory/{id}/versions — existing version history endpoint + mux.HandleFunc("/api/v1/memory/", func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + adminAPI.Versions(w, r) + } else { + http.NotFound(w, r) + } + }) + + // L3 + mux.HandleFunc("/api/v1/l3/worldmodel", func(w http.ResponseWriter, r *http.Request) { + if r.Method == "GET" { + l3API.GetHandler(w, r) + } else if r.Method == "POST" { + l3API.UpdateHandler(w, r) + } else { + http.NotFound(w, r) + } + }) + + // 触发器 + mux.HandleFunc("/api/v1/triggers", routes.Triggers.List) + mux.HandleFunc("/api/v1/triggers/fire", routes.Triggers.Fire) + // 触发器 pause/resume — 手动解析路径 + mux.HandleFunc("/api/v1/admin/triggers/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + // 格式: /api/v1/admin/triggers/{id}/{action} + parts := strings.Split(strings.TrimPrefix(path, "/api/v1/admin/triggers/"), "/") + if len(parts) != 2 { + http.NotFound(w, r) + return + } + id, action := parts[0], parts[1] + // 构造一个新请求,让 Pause/Resume 能通过 PathValue 读取 + r.SetPathValue("id", id) + switch action { + case "pause": + routes.Triggers.Pause(w, r) + case "resume": + routes.Triggers.Resume(w, r) + default: + http.NotFound(w, r) + } + }) + + // 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/bayes", func(w http.ResponseWriter, r *http.Request) { + list := routes.BayesianSkills.List() + respondJSON(w, 200, list) + }) + mux.HandleFunc("/api/v1/skills/{name}", skillByNameHandler) // GET/DELETE /api/v1/skills/{name} + 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/eval/run", evalAPI.Run) + mux.HandleFunc("/api/v1/eval/history", evalAPI.History) + mux.HandleFunc("/api/v1/eval/generate", evalAPI.Generate) + mux.HandleFunc("/api/v1/eval/golden", evalAPI.RunGolden) + mux.HandleFunc("/api/v1/tuning/status", routes.Tuner.StatusHandler) + mux.HandleFunc("/api/v1/tuning/run", routes.Tuner.RunHandler) + mux.HandleFunc("/api/v1/tuning/analytics", routes.Tuner.AnalyticsHandler) + + // 仪表盘 + 验证 + V值 + 缓存 + 流水线 + mux.HandleFunc("/api/v1/metrics/self", func(w http.ResponseWriter, r *http.Request) { + metrics := selfoptimize.Dash.Metrics() + respondJSON(w, 200, metrics) + }) + mux.HandleFunc("/api/v1/validate/passive", func(w http.ResponseWriter, r *http.Request) { + records := selfoptimize.Validator.GetRecords() + respondJSON(w, 200, records) + }) + mux.HandleFunc("/api/v1/vvalue/decisions", func(w http.ResponseWriter, r *http.Request) { + decisions := selfoptimize.VProp.ListRecentDecisions(20) + respondJSON(w, 200, decisions) + }) + // G5.3: V 值查询 + 触发反向传播 + mux.HandleFunc("/api/v1/vvalue/memory/", func(w http.ResponseWriter, r *http.Request) { + memID := strings.TrimPrefix(r.URL.Path, "/api/v1/vvalue/memory/") + if memID == "" { + respondJSON(w, 400, map[string]string{"error": "memory_id required"}) + return + } + v := selfoptimize.VProp.GetMemVValue(memID) + respondJSON(w, 200, map[string]interface{}{"memory_id": memID, "v_value": v}) + }) + mux.HandleFunc("/api/v1/trace/vprop", func(w http.ResponseWriter, r *http.Request) { + var req struct { + MemoryIDs []string `json:"memory_ids"` + Action string `json:"action"` + Outcome string `json:"outcome"` + ParentID string `json:"parent_id"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err == nil && len(req.MemoryIDs) > 0 { + id := fmt.Sprintf("trace_%d", time.Now().UnixNano()) + selfoptimize.VProp.RecordDecision(id, req.MemoryIDs, req.Action, req.Outcome, req.ParentID) + // 更新相关记忆的 quality_score + 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 { + _ = ldb.UpdateQualityScore(mid, lamb*v) + } + } + respondJSON(w, 200, map[string]string{"status": "propagated"}) + return + } + respondJSON(w, 400, map[string]string{"error": "memory_ids and outcome required"}) + }) + mux.HandleFunc("/api/v1/admin/cache", func(w http.ResponseWriter, r *http.Request) { + stats := storage.SearchCacheInstance.Stats() + respondJSON(w, 200, stats) + }) + mux.HandleFunc("/api/v1/admin/pipeline", func(w http.ResponseWriter, r *http.Request) { + stats := selfoptimize.Flow.Stats() + respondJSON(w, 200, stats) + }) + + // G6: ephemeral namespace 管理 + mux.HandleFunc("/api/v1/admin/ephemeral/clean", func(w http.ResponseWriter, r *http.Request) { + now := time.Now().UnixMilli() + agents := agentRegistry.ListAgents() + var cleaned []string + for _, agent := range agents { + if now-agent.LastSeen > 5*60*1000 { + ns := agent.AgentID + "-ephemeral" + zeroVec := make([]float32, 1024) + memories, _ := ldb.Search("memories", zeroVec, 1000, ns) + for _, mem := range memories { + if err := ldb.SoftDelete(mem.ID, "ephemeral_expired"); err != nil { + log.Printf("[softdelete] failed id: %v", err) + } + } + if len(memories) > 0 { + cleaned = append(cleaned, ns) + log.Printf("[ephemeral] cleaned %d memories from %s (inactive for %ds)", + len(memories), ns, (now-agent.LastSeen)/1000) + } + } + } + respondJSON(w, 200, map[string]interface{}{ + "status": "cleaned", + "cleaned_namespaces": cleaned, + }) + }) + + // Obsidian + mux.HandleFunc("/api/v1/obsidian/push", obsidian.PushHandler) + mux.HandleFunc("/api/v1/obsidian/pull", obsidian.PullHandler) + mux.HandleFunc("/api/v1/obsidian/status", obsidian.StatusHandler) + + // 内部分支:跨 Agent 缓存失效回调 + mux.HandleFunc("/_internal/cache/invalidate", func(w http.ResponseWriter, r *http.Request) { + var evt struct { + Payload map[string]string `json:"payload"` + } + if err := json.NewDecoder(r.Body).Decode(&evt); err != nil { + http.Error(w, "invalid request body", http.StatusBadRequest) + return + } + ns := evt.Payload["namespace"] + storage.SearchCacheInstance.Invalidate(ns) + log.Printf("[cache] 内部跨 Agent 失效: %s", ns) + w.WriteHeader(200) + }) + + // ─── Redis 组件 ───────────────────────────── + heartbeat := storage.NewHeartbeat("zhiyid-primary") + _ = heartbeat // 后台 goroutine 自动心跳 + + // ─── 后台引擎启动 ────────────────────────── + selfoptimize.RegisterCommitFlow(selfoptimize.Flow) + selfoptimize.RegisterRecallFlow(selfoptimize.Flow) + selfoptimize.RegisterGapFlow(selfoptimize.Flow) + selfoptimize.RegisterCorrectFlow(selfoptimize.Flow) + selfoptimize.RegisterConsolidateFlow(selfoptimize.Flow) + // 注册真正的 consolidate 处理器:调用 ConsolidationPipeline + selfoptimize.Flow.Register("consolidate", func(task *selfoptimize.PipelineTask) error { + report, err := consolPipe.RunWithMode("full") + if err == nil && report != nil { + // 注入 consolidate 报告 → Dashboard + if report.Merged > 0 { + // 合并启发式: 按合并数比例缩放, 但限定单次贡献 ≤ 0.05, 防止污染 avg_distill_loss + loss := float64(report.Merged) * 0.002 + if loss > 0.05 { + loss = 0.05 + } + selfoptimize.Dash.RecordDistillLoss(loss) + } + if report.ConflictsFound > 0 { + selfoptimize.Dash.RecordConflictResolved(true) + } + for _, p := range report.Patterns { + if len(p) > 13 && p[:13] == "quality_score" { + // 解析 quality_score=0.50 → 注入 avg_distill_loss + var qs float64 + if _, e := fmt.Sscanf(p, "quality_score=%f", &qs); e == nil { + selfoptimize.Dash.RecordDistillLoss(1.0 - qs) + } + } + } + } + return err + }) + // 注册 conflict_muchen 处理器:自动裁决低信任差异冲突 + selfoptimize.Flow.Register("conflict_muchen", func(task *selfoptimize.PipelineTask) error { + conflicts := conflictAPI.Detector.ListActive() + for _, c := range conflicts { + if c.Status != "pending" { + continue + } + // 按策略自动裁决:latest_wins / primary_wins + resolution := conflictAPI.Detector.AutoResolve(c) + if resolution == "pending" { + // 2026-09-20 修复(链路空转):**不再静默 dismiss**。 + // + // 原实现把未匹配策略的冲突改写成 "dismiss" 再 Resolve,且记成 + // RecordConflictResolved(true) —— 后果是每条 pending 冲突最多活 10 分钟 + // 即消失、auto_resolve_rate 指标虚高,冲突从不进入任何人视野 + // (实测:17:19 新建冲突,同进程几分钟后 pending:0,未重启)。 + // + // 现改为:72 小时内保留 pending 供人工处置;超期才按 latest_wins 自动收敛 + // (这是真裁决,才记指标)。保留窗口内不再有任何自动处置。 + if time.Since(c.CreatedAt) < 72*time.Hour { + continue + } + resolution = "latest_wins" + } + if err := conflictAPI.Detector.Resolve(c.ID, resolution, ""); err == nil { + selfoptimize.Dash.RecordConflictResolved(true) + } + } + return nil + }) + go selfoptimize.Flow.Start() + selfoptimize.Executor.Start(selfoptimize.Flow) + + // G6: ephemeral 定时清理(每 5 分钟扫描一次,清理断开超过 5 分钟的 agent 的 ephemeral 记忆) + go func() { + for { + time.Sleep(5 * time.Minute) + now := time.Now().UnixMilli() + agents := agentRegistry.ListAgents() + for _, agent := range agents { + if now-agent.LastSeen > 5*60*1000 { + ns := agent.AgentID + "-ephemeral" + zeroVec := make([]float32, 1024) + memories, _ := ldb.Search("memories", zeroVec, 1000, ns) + for _, mem := range memories { + if err := ldb.SoftDelete(mem.ID, "ephemeral_expired"); err != nil { + log.Printf("[softdelete] failed id: %v", err) + } + } + if len(memories) > 0 { + log.Printf("[ephemeral] cleaned %d memories from %s (inactive for %ds)", + len(memories), ns, (now-agent.LastSeen)/1000) + } + } + } + } + }() + + // 质量下降监控:每 30 分钟扫描所有低质量记忆 + go func() { + for { + time.Sleep(30 * time.Minute) + zeroVec := make([]float32, 1024) + memories, err := ldb.Search("memories", zeroVec, 2000, "") + if err != nil || len(memories) == 0 { + continue + } + alerts := 0 + for _, m := range memories { + if m.QualityScore > 0 && m.QualityScore < 0.3 { + if record := selfoptimize.QualityMonitor.Check(m.ID, m.QualityScore, 2); record != nil { + alerts++ + if record.Status == "deprecating" { + log.Printf("[quality] memory %s quality=%.2f deprecating", m.ID[:20], m.QualityScore) + } + } + } + } + if alerts > 0 { + log.Printf("[quality] scan: %d low-quality memories flagged", alerts) + } + } + }() + + // 图持久化 — 确保启动后写入 + if saver, ok := graphStore.(interface{ Save() error }); ok { + saver.Save() + } + + // ─── 触发器自动执行循环(每 30 秒检查一次)──────── + go func() { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for range ticker.C { + for _, t := range []struct{ id, action string }{ + {"t_distill", "distill"}, + {"t_merge", "merge"}, + {"t_prune", "prune"}, + {"t_decay", "decay"}, + {"t_backtrack", "backtrack"}, + {"t_gap", "gap_scan"}, + {"t_consolidation", "consolidation"}, + } { + if !routes.Triggers.CanFire(t.id) { + continue + } + routes.Triggers.RecordFire(t.id) + 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") + // 2026-09-21 (t_4ce53193):冲突去重 + 保留策略 + // 去重:同 (L,R) 对只留最早一条,累加 dup_count,归档 + 审计 + conflictDetector.DedupeActive(governance.DefaultConflictRetentionConfig()) + // 保留:pending > 7d 无人处置 → 归档(不删除) + conflictDetector.RetainAndArchive(governance.DefaultConflictRetentionConfig()) + 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 + } + // 🔒 长内容保护: 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 { + // 🔴 2026-10-06:`ok` 断言会放行空串(DB 存在 id 全空的垃圾行)⇒ SoftDelete("") + // 被 Rust 拒绝、错误被吞 ⇒ 每轮刷错误日志 + 计数虚高。补 id != "" 且失败不计数。 + if id, ok := m["id"].(string); ok && id != "" { + if err := ldb.SoftDelete(id, "auto_forget_fragment"); err != nil { + log.Printf("[decay] softdelete failed id=%q: %v", id, err) + } else { + decayForgotten++ + } + } + continue + } + // GA-P0-2 (t_c6d41ac6):衰减/遗忘只认 recall_verified_count(正反馈才是 V 值)。 + // recall_count 已冻结(历史虚高保命来源),seen 只用于观测。 + recallCount := 0 + if rc, ok := m["recall_verified_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 && id != "" { + forgetter.ScanAndForget(id) + // 实际执行软删除(持久化到 LanceDB) + if err := ldb.SoftDelete(id, "auto_forget"); err != nil { + log.Printf("[decay] softdelete failed id=%q: %v", id, err) + } else { + decayForgotten++ + } + } + } + } + } + // 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) + } + } + // 自动修复开放的缺口 + 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{ + "trigger_id": triggerID, + "action": action, + }) + }(t.id, t.action) + } + } + }() + + // 自优化指标定时采集(每 30 分钟) + go func() { + for { + time.Sleep(30 * time.Minute) + m := selfoptimize.Dash.Metrics() + date := time.Now().Format("2006-01-02") + for k, v := range m { + storage.GlobalMetricsStore.Set(date, k, v) + } + } + }() + + // 首次指标采集 + m := selfoptimize.Dash.Metrics() + date := time.Now().Format("2006-01-02") + for k, v := range m { + storage.GlobalMetricsStore.Set(date, k, v) + } + + // Prometheus 指标定时同步(每 15s 采集一次系统指标) + go func() { + for { + time.Sleep(15 * time.Second) + // 同步 Dashboard → Prometheus gauges + metrics.SyncFromDashboard(selfoptimize.Dash.Metrics()) + // 采集 SQLite 数据库文件大小(Linux only) + if runtime.GOOS != "windows" { + gPath := os.Getenv("GRAPH_PATH") + if gPath == "" { + gPath = "/var/lib/memoryweave/graph.db" + } + if fi, err := os.Stat(gPath); err == nil { + metrics.SQLiteDBSizeBytes.Set(float64(fi.Size())) + } + } + // 采集进程 RSS 内存 + if data, err := os.ReadFile("/proc/self/status"); err == nil { + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "VmRSS:") { + // VmRSS: 12345 kB + f := strings.Fields(line) + if len(f) >= 2 { + if kb, err := strconv.ParseFloat(f[1], 64); err == nil { + metrics.MemoryRSSBytes.Set(kb * 1024) + } + } + break + } + } + } + } + }() + + log.Println("[zhiyid] 多 Agent 架构 — Redis + FileGraph + EventBus + vLLM — 已启动") + + // Web UI 静态文件根目录 + webUIRoot = os.Getenv("ZHIYI_WEB_UI_ROOT") + if webUIRoot == "" { + webUIRoot = "../web-ui" + } + + // Catch-all: 优先检查静态文件,再 JSON + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + + // 静态文件服务(安全检查,不允许 .. 遍历) + if p != "/" && !strings.Contains(p, "..") { + filePath := webUIRoot + p + if _, err := os.Stat(filePath); err == nil { + http.ServeFile(w, r, filePath) + return + } + } + + // 根路径 → index.html + if p == "/" || p == "" { + if _, err := os.Stat(webUIRoot + "/index.html"); err == nil { + http.ServeFile(w, r, webUIRoot+"/index.html") + return + } + respondJSON(w, 200, map[string]interface{}{ + "service": "zhiyid", "status": "ok", "version": "0.1.0", + }) + return + } + respondJSON(w, 404, map[string]interface{}{ + "error": "endpoint not found: " + p, + }) + }) + + return middleware.CORS()(middleware.Auth(mux)) +} + +// ─── 辅助 ────────────────────────────────────────── + +func respondJSON(w http.ResponseWriter, code int, data interface{}) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + json.NewEncoder(w).Encode(data) +} + +func AgentTypeDecayOrDefault(agentType string) float64 { + if rate, ok := governance.AgentTypeDecay[agentType]; ok { + return rate + } + return 0.015 +} + +// memoryTimeVal 取记忆时间戳用于排序(主 key 优先,空则回退副 key;均空返回 0)。 +// 2026-09-06 P1: decay 分批按"最久未访问优先"排序需要;兼容 RFC3339 string / time.Time / int。 +func memoryTimeVal(m map[string]interface{}, primary, fallback string) int64 { + for _, key := range []string{primary, fallback} { + v, ok := m[key] + if !ok || v == nil { + continue + } + switch val := v.(type) { + case string: + if val == "" { + continue + } + if t, err := time.Parse(time.RFC3339, val); err == nil { + return t.Unix() + } + if n, err := strconv.ParseInt(val, 10, 64); err == nil { + return n + } + case time.Time: + if !val.IsZero() { + return val.Unix() + } + case float64: + return int64(val) + case int64: + return val + case int: + return int64(val) + } + } + return 0 +} + +// runStartupChecks 启动时数据目录一致性检查 +// 检测废弃路径(如 /home/muc/data)并警告,防止数据源混乱 +func runStartupChecks(backend string) { + canonicalDataDir := "/var/lib/memoryweave" + deprecatedPaths := []string{ + "/home/muc/data", + "/home/muc/.local/share/memoryweave", + } + + for _, dep := range deprecatedPaths { + if _, err := os.Stat(dep); err == nil { + log.Printf("[WARN] 检测到废弃数据目录 %s,仍有数据残留(当前 canonical: %s)", dep, canonicalDataDir) + } + } + + // LanceDB 后端:检查 Rust sidecar socket 是否可达 + if backend == "lancedb" { + sockPath := os.Getenv("LANCEDB_SOCKET") + if sockPath == "" { + sockPath = "/tmp/zhiyi-ipc.sock" + } + if _, err := os.Stat(sockPath); os.IsNotExist(err) { + log.Printf("[WARN] LanceDB socket 不存在 (%s),Rust sidecar 可能未运行", sockPath) + } else { + log.Printf("[startup] LanceDB socket 就绪: %s", sockPath) + } + } + + // canonical 目录存在性检查 + if _, err := os.Stat(canonicalDataDir); os.IsNotExist(err) { + log.Printf("[WARN] canonical 数据目录不存在: %s(首次部署?)", canonicalDataDir) + } else { + log.Printf("[startup] 数据目录正常: %s", canonicalDataDir) + } +} + +// srcOrLLMDistill 2026-09-26:蒸馏产物来源判定。 +// 有笔记出处(commit 时带 source/metadata.source,如 wiki_curator 传的 .md 路径)→ 标 "wiki:<路径>", +// 使 recall 回来的每条记忆都能追溯到自己来自哪篇笔记;无出处则沿用历史值 llm_distill。 +func srcOrLLMDistill(src string) string { + if src != "" { + return "wiki:" + src + } + return "llm_distill" +} + +// orDefault 血缘字段缺省兜底:空值 → 默认值。 +// 2026-10-08 (t_7e3577c5):embedding_model→bge-m3,script_version→unknown, +// 使未发 metadata 的写入路径(worklog/cbm/会话蒸馏)也落非空血缘。 +func orDefault(v, def string) string { + if v == "" { + return def + } + return v +} + +// confidenceSourceOf 2026-10-08 (Gap#2):声明了信任等级 ⇒ authoritative;未声明 ⇒ 空 +// (不写 "estimated"——estimated 专指「事后回填的猜测值」,语义上不该由写入路径产生)。 +func confidenceSourceOf(c *float64) string { + if c != nil { + return "authoritative" + } + return "" +} diff --git a/go/internal/models/memory.go b/go/internal/models/memory.go index d66ebf2..4e65825 100644 --- a/go/internal/models/memory.go +++ b/go/internal/models/memory.go @@ -95,6 +95,16 @@ type MemoryRecord struct { DeleteReason string `json:"delete_reason,omitempty"` DependsOn []string `json:"depends_on,omitempty"` // 依赖的记忆 ID 列表 DerivedFrom string `json:"derived_from,omitempty"` // 蒸馏来源 episode ID + // 2026-10-13 (t_e9a4d18f P1) 证据链:一条蒸馏结论记录**全部**来源 episode ID(多证据)。 + // DerivedFrom 保留为单亲兼容字段;SourceEvents 是 superset。ProofCount 由它派生 + // (len(distinct),不单独存避免不同步)。存量行缺省 nil(无证据链)。 + SourceEvents []string `json:"source_events,omitempty"` + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被本条「取代」的旧记忆 ID 列表。 + // 新证据到来时不静默覆盖旧条目——写 supersedes 保留历史(Hindsight 原则)。 + // 反向语义:旧条目不删,标 fresh/被取代;本字段是「我取代了谁」。 + // 具体写时四操作的判定逻辑由 t_3e98b65a(写时 ADD/UPDATE/NOOP/CONFLICT)落地, + // 本卡只加 schema 列 + 保留语义(不静默覆盖)。 + Supersedes []string `json:"supersedes,omitempty"` } // HitEvent 真实 outcome 的 append-only 事件(GA-P0-4 t_bb10e8bc)。 diff --git a/go/internal/models/memory.go.bak.proofchain-20261014-005204 b/go/internal/models/memory.go.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..4e65825 --- /dev/null +++ b/go/internal/models/memory.go.bak.proofchain-20261014-005204 @@ -0,0 +1,198 @@ +// Package models 定义织忆 MemoryWeave 的核心数据模型。 +package models + +import "time" + +// Time 是 time.Time 的安全版本,支持空字符串解析 +type Time struct{ time.Time } + +// UnmarshalJSON 实现 json.Unmarshaler:空字符串解析为当前时间(而非报错) +func (t *Time) UnmarshalJSON(data []byte) error { + s := string(data) + if s == `""` || s == `"0001-01-01T00:00:00Z"` { + t.Time = time.Time{} + return nil + } + // 去掉前后引号 + if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' { + s = s[1 : len(s)-1] + } + if s == "" || s == "null" { + t.Time = time.Time{} + return nil + } + return t.Time.UnmarshalJSON(data) +} + +// VersionRecord 记忆版本记录(溯源链中的单次修改) +type VersionRecord struct { + Version int `json:"version"` + Content string `json:"content"` + UpdatedBy string `json:"updated_by"` + Source string `json:"source"` + Trigger string `json:"trigger"` + Reason string `json:"reason"` + Timestamp time.Time `json:"timestamp"` +} + +// MemoryRecord 织忆中的单条记忆(存储在 LanceDB memories 表中)。 +// v3.8 完整 Schema — 23 字段,与设计文档一致。 +type MemoryRecord struct { + ID string `json:"id"` + AgentID string `json:"agent_id"` + Namespace string `json:"namespace"` + Content string `json:"content"` + ContentMD5 string `json:"content_md5"` // content 的 MD5 前 12 字符,用于精确去重 + Category string `json:"category"` // system_fact, user_pref, proj_context, tool_usage, code_snippet + Vector []float32 `json:"vector"` // bge-m3 1024维,L2归一化 + Tier string `json:"tier"` // normal, core(core永不衰减) + Importance float64 `json:"importance"` // 重要性得分 = recency_factor × (1+log(1+recall_count)) + QualityScore float64 `json:"quality_score"` + UsefulCount int `json:"useful_count"` // 被标记 useful 的次数 + // GA-P0-1 (t_718d8707):not_useful_count 曾把两种语义混写—— + // 用户人工点「没用」(feedback.go MarkNotUseful) 与 dedup/合并流程自动降权 + // (core.go Dedup demote) 都写同一个字段。现拆分为 human_not_useful_count + // 与 dedup_downweight_count,两个写入点各写各的。not_useful_count 保留为 + // 历史列(deprecated),新代码不再读它(见 AC#3)。 + HumanNotUsefulCount int `json:"human_not_useful_count"` // 用户人工点「没用」的次数 + DedupDownweightCount int `json:"dedup_downweight_count"` // dedup/合并流程自动降权的次数 + NotUsefulCount int `json:"not_useful_count"` // [DEPRECATED] 历史混写列,勿再读 + Version int `json:"version"` // 当前版本号 + VersionHistory []VersionRecord `json:"version_history,omitempty"` // 完整修改链 + Source string `json:"source"` // 来源:牧尘口头 / 配置解析 / Agent推断 / LLM蒸馏 + VolatileFlag bool `json:"volatile_flag"` // 频繁变更标记(≥3次修正自动设置) + RecallCount int `json:"recall_count"` + // GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义(「出现在结果里」/「被验证使用」)。 + // recall_count 曾把两种语义混写 —— 每次召回命中都 ++,被当成 V 值喂给衰减/遗忘逻辑, + // 造成「被召回 500+ 次所以永不遗忘」的虚高保命。现拆分为: + // RecallSeenCount 出现即 ++(只用于观测/排序去偏,不参与 V 值/衰减权重) + // RecallVerifiedCount有正反馈(IncrementUseful)或下游引用才 ++(唯一参与 V 值/衰减) + // RecallCount 保留为历史列(deprecated),冻结不再增长,仅向后兼容读取历史值(AC#3)。 + RecallSeenCount int `json:"recall_seen_count"` // 出现在召回结果里即 ++(观测/排序去偏用) + RecallVerifiedCount int `json:"recall_verified_count"` // 有正反馈或下游引用才 ++(V 值/衰减唯一来源) + Freshness string `json:"freshness"` // fresh, stale, verified + // 2026-10-08 (t_7e3577c5):血缘字段。embedding_model=实际嵌入模型(bge-m3); + // script_version=写入脚本版本标识。写入方经 metadata 携带,server 蒸馏落库。 + EmbeddingModel string `json:"embedding_model"` + ScriptVersion string `json:"script_version"` + // 2026-10-08 (Gap#2 来源加权):confidence=写入方显式声明的信任等级(0.4~1.0), + // 不从 source 反推(source 是「哪条管道进来」,confidence 是「内容可不可信」,两者正交)。 + // 指针类型:nil ⇒ JSON null ⇒ Rust 写 NULL ⇒ 读路径 COALESCE→1.0(加权首日 no-op)。 + // ConfidenceSource=authoritative(写入时声明) | estimated(事后回填猜测),用于日后定向纠偏。 + Confidence *float64 `json:"confidence,omitempty"` + ConfidenceSource string `json:"confidence_source,omitempty"` + // 2026-10-11 (t_631ab13d):DB 原值直通通道。json:"-" 不参与任何 JSON 传输: + // Rust IPC Search 会把 QualityScore 融合成 0.4*importance+0.6*raw(排序用), + // 但 recall 响应需要展示 LanceDB 原始列值("响应值==库值"判据)。 + // 只在进程内携带,不落库、不序列化。 + RawQualityScore *float64 `json:"-"` + LastRecalledAt time.Time `json:"last_recalled_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + IsDeleted bool `json:"is_deleted"` + // GA-P0-3 (t_f785d7f2):删除原因枚举(merge_dup|contradiction|manual|retention|unknown)。 + // is_deleted=true 不再「不可分辨」—— 坏记忆被删 与 合并/整理被删 现可分列。additive 列。 + DeleteReason string `json:"delete_reason,omitempty"` + DependsOn []string `json:"depends_on,omitempty"` // 依赖的记忆 ID 列表 + DerivedFrom string `json:"derived_from,omitempty"` // 蒸馏来源 episode ID + // 2026-10-13 (t_e9a4d18f P1) 证据链:一条蒸馏结论记录**全部**来源 episode ID(多证据)。 + // DerivedFrom 保留为单亲兼容字段;SourceEvents 是 superset。ProofCount 由它派生 + // (len(distinct),不单独存避免不同步)。存量行缺省 nil(无证据链)。 + SourceEvents []string `json:"source_events,omitempty"` + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被本条「取代」的旧记忆 ID 列表。 + // 新证据到来时不静默覆盖旧条目——写 supersedes 保留历史(Hindsight 原则)。 + // 反向语义:旧条目不删,标 fresh/被取代;本字段是「我取代了谁」。 + // 具体写时四操作的判定逻辑由 t_3e98b65a(写时 ADD/UPDATE/NOOP/CONFLICT)落地, + // 本卡只加 schema 列 + 保留语义(不静默覆盖)。 + Supersedes []string `json:"supersedes,omitempty"` +} + +// HitEvent 真实 outcome 的 append-only 事件(GA-P0-4 t_bb10e8bc)。 +// 与计数列(useful_count / human_not_useful_count 等)不同:这是「按时间戳追加」 +// 的事件日志,**不覆盖式累加** —— 每次真实 outcome 追加一行,带 created_at 时间戳, +// 便于 P2 自适应阈值按周窗口聚合(WHERE created_at > 本周起点)。语义定义见 +// internal/storage/hit_event.go(什么算 hits+ / hits− / 什么不算)。 +type HitEvent struct { + ID int64 `json:"id"` + MemoryID string `json:"memory_id"` + Outcome string `json:"outcome"` // pos | neg(HitOutcome 枚举) + Reason string `json:"reason"` // HitReason 枚举:human_feedback|contradiction|replacement|downstream_use + Source string `json:"source,omitempty"` // 记录方标识(如端点名) + CreatedAt time.Time `json:"created_at"` +} + +// EpisodeRecord 原始对话/任务日志(存储在 LanceDB episodes 表中)。 +type EpisodeRecord struct { + ID string `json:"id"` + AgentID string `json:"agent_id"` + Namespace string `json:"namespace"` + Content string `json:"content"` + Category string `json:"category"` + CreatedAt time.Time `json:"created_at"` +} + +// TombstoneRecord 已删除/废弃记忆的墓碑记录。 +type TombstoneRecord struct { + ID string `json:"id"` + OriginalID string `json:"original_id"` + Reason string `json:"reason"` // deprecated, merged, corrected, evicted + CreatedAt time.Time `json:"created_at"` +} + +// RecallResult recall 接口返回的单条结果。 +type RecallResult struct { + ID string `json:"id"` + Content string `json:"content"` + Category string `json:"category"` + Score float64 `json:"score"` + Timestamp string `json:"timestamp"` + // 2026-09-22 新增:全库召回(namespace="" 时)调用方无法分辨记忆来源域, + // 会把分身的私有记忆当成自己的用。带上来源便于调用方按需过滤/标注。 + // omitempty:旧调用方无感;图谱扩展路径(graph_*.go)无 ns 概念,留空。 + Namespace string `json:"namespace,omitempty"` + AgentID string `json:"agent_id,omitempty"` + Source string `json:"source,omitempty"` + // 2026-10-08 (Gap#2):把信任等级直通给调用方。此前加列但不动本结构 ⇒ + // confidence 对排序/调用方零影响(「字段加了没接线」的经典静默 no-op)。 + // Confidence=nil 表示该条未声明(存量),调用方按 1.0 处理。 + Confidence *float64 `json:"confidence,omitempty"` + ConfidenceSource string `json:"confidence_source,omitempty"` + // 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。 + // 此前 RecallResult 缺这两个字段 ⇒ JSON 序列化不带出 ⇒ 插件 `r.get("quality_score", 0)` + // 恒得默认 0("显示 0"),与库里 74.88% 记忆有真实值矛盾。排序不受影响(排序用内存 + // candidates[i].QualityScore=库值,见 recall.go),本字段仅补"响应值==库值"的显示缺口。 + // quality_score 恒输出(含 0);v_value 为 VValueProvider 提供,未注入时 0。 + QualityScore float64 `json:"quality_score"` + // QualityScoreReliable:上面的 quality_score 是否可信。 + // 2026-10-12:存量 54.2% 的 quality_score 不可信(0=未打分 / 0.755=历史常量 bug), + // 该值原样返回供审计,但**不应被当作真实质量判断**。调用方须看本字段。 + QualityScoreReliable bool `json:"quality_score_reliable"` + VValue float64 `json:"v_value"` + // 2026-10-13 时间维检索(t_e9a4d18f P0):该条目是否可能过期。 + // 仅当 stale 标记开启(ZHIYI_STALE_AFTER_HOURS>0)且 updated_at 超期时为 true; + // 默认关闭 ⇒ 恒 false 且 omitempty 不输出 ⇒ 行为零变化(向后兼容)。 + Stale bool `json:"stale,omitempty"` +} + +// RerankResult rerank 重排后的单条结果。 +type RerankResult struct { + Index int `json:"index"` + Score float64 `json:"score"` + Text string `json:"text"` +} + +// GraphBFSResult BFS 图谱扩展结果(含汇总语句) +type GraphBFSResult struct { + ExpandedRelations []ExpandedRelation `json:"expanded_relations"` + Summary string `json:"summary"` +} + +// ExpandedRelation 单条扩展关系 +type ExpandedRelation struct { + From string `json:"from"` + To string `json:"to"` + Relation string `json:"relation"` + Hops int `json:"hops"` + Weight float64 `json:"weight"` + Score float64 `json:"score"` +} diff --git a/go/internal/storage/lancedb_ipc.go b/go/internal/storage/lancedb_ipc.go index 9890b60..55afe70 100644 --- a/go/internal/storage/lancedb_ipc.go +++ b/go/internal/storage/lancedb_ipc.go @@ -177,7 +177,11 @@ func (rc *RustLanceDBClient) InsertMemory(m models.MemoryRecord) error { // t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留 //(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。 "source": m.Source, "volatile_flag": false, "is_deleted": m.IsDeleted, - "depends_on": "[]", "derived_from": "", "last_recalled_at": "", + "depends_on": "[]", "derived_from": m.DerivedFrom, "last_recalled_at": "", + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串) + "source_events": seJSON(m.SourceEvents), + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID + "supersedes": seJSON(m.Supersedes), "embedding_model": m.EmbeddingModel, "script_version": m.ScriptVersion, // 2026-10-08 (t_7e3577c5) 血缘 // 2026-10-08 (Gap#2):nil ⇒ JSON null ⇒ Rust 写 NULL(不伪装成 0.0) "confidence": m.Confidence, "confidence_source": m.ConfidenceSource, @@ -1108,6 +1112,30 @@ func mapBool(m map[string]interface{}, key string) bool { return false } +// seJSON 2026-10-13 (t_e9a4d18f P1):SourceEvents → JSON 数组字符串。 +// nil/空 → "[]"(Rust 读路径 col_str 兜底)。显式转,避免 []string 直接进 +// map 后 json.Marshal 的嵌套转义([]string → 已是 JSON 数组)。 +func seJSON(events []string) string { + if len(events) == 0 { + return "[]" + } + b, _ := json.Marshal(events) + return string(b) +} + +// parseSourceEvents 2026-10-13 (t_e9a4d18f P1):JSON 数组字符串 → []string。 +// 解析失败回退 nil(存量 NULL/空 ⇒ 无证据链)。 +func parseSourceEvents(raw string) []string { + if raw == "" || raw == "[]" || raw == "null" { + return nil + } + var out []string + if err := json.Unmarshal([]byte(raw), &out); err != nil { + return nil + } + return out +} + func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) { resp, err := rc.rpc(ipcReq{ Type: "lancedb_query", @@ -1143,6 +1171,8 @@ func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models Source: mapStr(r, "source"), Freshness: mapStr(r, "freshness"), DerivedFrom: mapStr(r, "derived_from"), + SourceEvents: parseSourceEvents(mapStr(r, "source_events")), // 2026-10-13 P1 + Supersedes: parseSourceEvents(mapStr(r, "supersedes")), // 2026-10-13 P1 VersionHistory: nil, DependsOn: nil, } diff --git a/go/internal/storage/lancedb_ipc.go.bak.proofchain-20261014-005204 b/go/internal/storage/lancedb_ipc.go.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..55afe70 --- /dev/null +++ b/go/internal/storage/lancedb_ipc.go.bak.proofchain-20261014-005204 @@ -0,0 +1,1422 @@ +// 织忆 MemoryWeave — LanceDB IPC 桥接(Go ↔ Rust Unix Socket) +package storage + +import ( + "encoding/binary" + "encoding/json" + "fmt" + "io" + "log" + "math" + "net" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// RustLanceDBClient Unix Socket → zhiyi-consolidate +type RustLanceDBClient struct { + mu sync.Mutex + sockPath string + embedder *Embedder +} + +// NewRustLanceDBClient 创建 Rust IPC 客户端 +func NewRustLanceDBClient(sockPath string, emb *Embedder) *RustLanceDBClient { + if sockPath == "" { + sockPath = "/tmp/zhiyi-ipc.sock" + } + return &RustLanceDBClient{sockPath: sockPath, embedder: emb} +} + +// ─── IPC 协议 ──────────────────────────────────────────── + +type ipcReq struct { + Type string `json:"type"` + Table string `json:"table,omitempty"` + Records string `json:"records,omitempty"` + Vector []float32 `json:"vector,omitempty"` + TopK int `json:"top_k,omitempty"` + Namespace string `json:"namespace,omitempty"` + ID string `json:"id,omitempty"` + Fields string `json:"fields,omitempty"` + MinRecall int `json:"min_recall,omitempty"` + QueryLimit int `json:"limit,omitempty"` + // 2026-10-11 (t_a4b8fa52 方案 c′): 遗忘候选旋转窗口游标(last processed id) + AfterID string `json:"after_id,omitempty"` + Items string `json:"items,omitempty"` // lancedb_update_batch: [{"id":..,"delta":N}] + TS string `json:"ts,omitempty"` // lancedb_update_batch: last_recalled_at + // GA-P0-4 (t_bb10e8bc):hits+/hits− outcome 事件 IPC 参数 + Outcome string `json:"outcome,omitempty"` // hit_events: pos|neg + Reason string `json:"reason,omitempty"` // hit_events: human_feedback|contradiction|replacement|downstream_use + Source string `json:"source,omitempty"` // hit_events: 记录方标识 + Since string `json:"since,omitempty"` // hit_events 周窗口起点 (RFC3339) +} + +type ipcResp struct { + Status string `json:"status"` + ReportJSON string `json:"report_json"` // consolidator uses this + Result string `json:"result"` // lancedb search uses this + FailureStep string `json:"failure_step"` + ErrorDetail string `json:"error_detail"` +} + +// updateField lancedb_update 的单列更新项:Value 为 SQL 表达式 +// (字符串需用单引号包裹并转义,布尔用 true/false 字面量,数值裸写) +type updateField struct { + Column string `json:"column"` + Value string `json:"value"` +} + +func (rc *RustLanceDBClient) rpc(req ipcReq) (*ipcResp, error) { + conn, err := net.DialTimeout("unix", rc.sockPath, 5*time.Second) + if err != nil { + return nil, fmt.Errorf("ipc dial: %w", err) + } + defer conn.Close() + + body, _ := json.Marshal(req) + lenBuf := make([]byte, 4) + binary.BigEndian.PutUint32(lenBuf, uint32(len(body))) + conn.Write(lenBuf) + conn.Write(body) + + io.ReadFull(conn, lenBuf) + msgLen := binary.BigEndian.Uint32(lenBuf) + respBuf := make([]byte, msgLen) + io.ReadFull(conn, respBuf) + + var resp ipcResp + if err := json.Unmarshal(respBuf, &resp); err != nil { + return nil, err + } + if resp.Status != "ok" { + return nil, fmt.Errorf("ipc: %s", resp.ErrorDetail) + } + return &resp, nil +} + +// ─── LanceDB 接口 ──────────────────────────────────────── + +// 本地内存缓冲(LanceDB IPC 只做向量存储,元数据本地缓存) +type memCache struct { + mu sync.RWMutex + memories map[string]*models.MemoryRecord + episodes []models.EpisodeRecord + auditLog []map[string]interface{} +} + +var _local = &memCache{memories: make(map[string]*models.MemoryRecord)} + +func (rc *RustLanceDBClient) InsertEpisode(agentID, namespace, content, category string) (string, error) { + id := fmt.Sprintf("ep_%d", time.Now().UnixNano()) + now := time.Now() + // 本地缓存(保持原有行为) + _local.mu.Lock() + _local.episodes = append(_local.episodes, models.EpisodeRecord{ + ID: id, AgentID: agentID, Namespace: namespace, Content: content, Category: category, CreatedAt: now, + }) + _local.mu.Unlock() + + // 持久化到 Rust LanceDB episodes 表(24 字段,重启不丢) + record := map[string]interface{}{ + "id": id, "agent_id": agentID, "namespace": namespace, + "content": content, "category": category, + "tier": "episode", "importance": 1.0, "quality_score": 0.0, + "recall_count": 0, "useful_count": 0, "not_useful_count": 0, + // GA-P0-2 (t_c6d41ac6):拆分字段(episode 无召回/反馈,恒 0) + "recall_seen_count": 0, "recall_verified_count": 0, + // GA-P0-1 (t_718d8707):拆分字段(episode 无反馈,恒 0) + "human_not_useful_count": 0, "dedup_downweight_count": 0, + "freshness": "fresh", "version": 1, "version_history": "[]", + // t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留 + //(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。 + "source": "episode", "volatile_flag": false, "is_deleted": false, + "depends_on": "[]", "derived_from": "", "last_recalled_at": "", + "created_at": now.Format(time.RFC3339), + "updated_at": now.Format(time.RFC3339), + } + recJSON, _ := json.Marshal([]interface{}{record}) + if _, err := rc.rpc(ipcReq{Type: "lancedb_insert", Table: "episodes", Records: string(recJSON)}); err != nil { + // 持久化失败不阻断请求(保持"总是写入"语义),但记日志便于发现 + log.Printf("[ipc] InsertEpisode persist to LanceDB failed (id=%s): %v", id, err) + } + return id, nil +} + +func (rc *RustLanceDBClient) InsertMemory(m models.MemoryRecord) error { + // 编码向量 + if len(m.Vector) == 0 { + vec, err := rc.embedder.EncodeSingle(m.Content) + if err == nil { + m.Vector = vec + } + } + + // 本地缓存 + _local.mu.Lock() + cp := m + _local.memories[m.ID] = &cp + _local.mu.Unlock() + + // 写入 Rust LanceDB(完整 24 字段) + record := map[string]interface{}{ + "id": m.ID, "agent_id": m.AgentID, "namespace": m.Namespace, + "content": m.Content, "category": m.Category, "vector": m.Vector, + "tier": m.Tier, "importance": 1.0, "quality_score": m.QualityScore, + "recall_count": m.RecallCount, "useful_count": 0, "not_useful_count": 0, + // GA-P0-2 (t_c6d41ac6):拆分字段(新记忆按 model 携带,通常 0) + "recall_seen_count": m.RecallSeenCount, "recall_verified_count": m.RecallVerifiedCount, + // GA-P0-1 (t_718d8707):拆分字段(新记忆按 model 携带,通常 0) + "human_not_useful_count": m.HumanNotUsefulCount, "dedup_downweight_count": m.DedupDownweightCount, + "freshness": m.Freshness, "version": 1, "version_history": "[]", + // t_268b0353:volatile_flag 插入路径恒 false;下方 *0.5 惩罚分支是预留 + //(将来接「≥3 次修正自动置位」),当前不生效,勿依赖。 + "source": m.Source, "volatile_flag": false, "is_deleted": m.IsDeleted, + "depends_on": "[]", "derived_from": m.DerivedFrom, "last_recalled_at": "", + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串) + "source_events": seJSON(m.SourceEvents), + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID + "supersedes": seJSON(m.Supersedes), + "embedding_model": m.EmbeddingModel, "script_version": m.ScriptVersion, // 2026-10-08 (t_7e3577c5) 血缘 + // 2026-10-08 (Gap#2):nil ⇒ JSON null ⇒ Rust 写 NULL(不伪装成 0.0) + "confidence": m.Confidence, "confidence_source": m.ConfidenceSource, + "created_at": m.CreatedAt.Format(time.RFC3339), + "updated_at": m.UpdatedAt.Format(time.RFC3339), + } + recJSON, _ := json.Marshal([]interface{}{record}) + _, err := rc.rpc(ipcReq{Type: "lancedb_insert", Table: "memories", Records: string(recJSON)}) + return err +} + +func (rc *RustLanceDBClient) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) { + resp, err := rc.rpc(ipcReq{ + Type: "lancedb_search", Vector: vector, TopK: topK * 2, Namespace: namespaceFilter, + }) + if err != nil { + return rc.localSearch(vector, topK, namespaceFilter), nil + } + + var raw []struct { + ID string `json:"id"` + Content string `json:"content"` + Category string `json:"category"` + Namespace string `json:"namespace"` + IsDeleted bool `json:"is_deleted"` + DeleteReason string `json:"delete_reason"` // GA-P0-3 + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + QualityScore float64 `json:"quality_score"` + Importance float64 `json:"importance"` + RecallCount int64 `json:"recall_count"` + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + RecallSeenCount int64 `json:"recall_seen_count"` + RecallVerifiedCount int64 `json:"recall_verified_count"` + VolatileFlag bool `json:"volatile_flag"` + Tier string `json:"tier"` + LastRecalledAt string `json:"last_recalled_at"` + // 2026-09-26:出处(笔记路径)—— 此前**解包结构缺该字段** → IPC 主路径 Source 恒空 + // (本地兜底路径有 Source,主路径没有 → recall 永远拿不到出处,链路看似修好实则断在这一环) + Source string `json:"source"` + // 2026-10-08 (Gap#2):读侧投影 —— 不补这里,加列也读不出来(静默 no-op)。 + // 用 *float64 区分「NULL(存量未声明)」与「显式 0.0」。 + Confidence *float64 `json:"confidence"` + ConfidenceSource string `json:"confidence_source"` + // vector 必须解析:近重复去重(commit near_dup / 蒸馏写入 gate / + // admin/dedup 端点)全部依赖 records 携带向量做 cosine 比较。 + // 此前缺失该字段 → Vector 恒为空 → 所有 len(Vector)>0 判定失败 → + // 去重静默退化为「只比字符串相等」,端点恒报 merged≈0(假阴性)。 + Vector []float32 `json:"vector"` + } + json.Unmarshal([]byte(resp.ReportJSON), &raw) + if len(raw) == 0 { + log.Printf("[ipc] Search: resp.ReportJSON unmarshal gave 0 results, falling back to localSearch (Result=%q)", resp.Result) + return rc.localSearch(vector, topK, namespaceFilter), nil + } + log.Printf("[ipc] Search: got %d results from Rust IPC (Result=%q)", len(raw), resp.Result) + + // 解析时间(Rust 返回 RFC3339 字符串 → time.Time) + parseTime := func(s string) time.Time { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return time.Now() + } + return t + } + + // 客户端 namespace 过滤(Rust lancedb only_if 不可靠) + out := make([]models.MemoryRecord, 0, topK) + for _, r := range raw { + if r.IsDeleted { + continue + } + if namespaceFilter != "" && r.Namespace != namespaceFilter { + continue + } + // 重要性计算:recency_factor × (1 + log(1 + recall_count)) + daysSinceRecall := 30.0 // default for never-recalled + if r.LastRecalledAt != "" { + if lastT, err := time.Parse(time.RFC3339, r.LastRecalledAt); err == nil { + daysSinceRecall = time.Since(lastT).Hours() / 24.0 + } + } + recencyFactor := 1.0 + if daysSinceRecall > 7 { + recencyFactor = 0.5 // 7天内高权重,之后折半 + } + if daysSinceRecall > 30 { + recencyFactor = 0.2 // 30天以上权重很低 + } + // GA-P0-2 (t_c6d41ac6):排序去偏用 recall_seen_count(观测/选择信号); + // recall_verified_count 只参与衰减/遗忘决策,不参与排序。 + recallCount := float64(r.RecallSeenCount) + computedImportance := recencyFactor * (1.0 + math.Log(1.0+recallCount)) + + // VolatileFlag 惩罚 + if r.VolatileFlag { + computedImportance *= 0.5 + } + + // QualityScore 融合(归一化到 0-1 范围) + // t_631ab13d:先存原始 DB 值(r.QualityScore 是 LanceDB 列直接值), + // 融合后 finalQuality 写进 QualityScore(供排序),RawQualityScore 保留原值(供 recall 响应展示) + dbRawQS := r.QualityScore + finalQuality := math.Min(computedImportance, 1.0) + // 2026-10-12:存量 quality_score 有 54.2% 不可信(0=未打分 / 0.755=历史常量 bug)。 + // 修入口治不了存量 —— 消费端必须自己判定,不可信时把权重让给可信信号。 + qsTrusted := models.IsReliableQuality(r.QualityScore) + if qsTrusted { + // QualityScore from LLM (0-1) + computed importance, capped at 1.0 + finalQuality = math.Min(0.4*computedImportance+0.6*r.QualityScore, 1.0) + } else if qstrustVerbose { + log.Printf("[qstrust-ipc] 不可信质量分已剔除 id=%s rawQS=%.6f → 仅用 importance %.4f", + r.ID, r.QualityScore, computedImportance) + } + // V 值融合:用户决策信号(correct/useful/not-useful) + if VValueProvider != nil { + vVal := VValueProvider(r.ID) + if vVal > 0 { + if qsTrusted { + // 30% V值 + 30% importance + 40% LLM quality + finalQuality = 0.3*vVal + 0.3*computedImportance + 0.4*r.QualityScore + } else { + // 质量分不可信 → 去掉它的 40%,剩余 30:30 重新归一为 50:50。 + // 这样既不让假分数进来,也不因为"少了一项"而整体压沉。 + finalQuality = 0.5*vVal + 0.5*computedImportance + } + if finalQuality > 1.0 { + finalQuality = 1.0 + } + } + } + + out = append(out, models.MemoryRecord{ + ID: r.ID, Content: r.Content, Category: r.Category, Namespace: r.Namespace, + CreatedAt: parseTime(r.CreatedAt), UpdatedAt: parseTime(r.UpdatedAt), + QualityScore: finalQuality, Importance: r.Importance, + RecallCount: int(r.RecallCount), VolatileFlag: r.VolatileFlag, + Tier: r.Tier, + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + RecallSeenCount: int(r.RecallSeenCount), + RecallVerifiedCount: int(r.RecallVerifiedCount), + Source: r.Source, // 2026-09-26:出处透出(缺此行 → recall.source 恒空) + Vector: r.Vector, // 去重判据依赖,勿删 + // t_631ab13d:DB 原值直通 —— RecallResult 展示用它,排序用 QualityScore(融合值) + RawQualityScore: &dbRawQS, + // 2026-10-08 (Gap#2):解包结构有 ≠ 输出有。缺这两行 ⇒ 加列、改 schema、 + // 通 IPC 全做完,recall 拿到的 Confidence 仍是 nil(第 5 层静默断链, + // 端到端测试才抓得到)。 + Confidence: r.Confidence, + ConfidenceSource: r.ConfidenceSource, + }) + if len(out) >= topK { + break + } + } + return out, nil +} + +// Scan 全表扫描存活记忆(走 Rust IPC `lancedb_scan`:is_deleted=false + namespace 下推)。 +// 2026-09-21:为 /api/v1/memories 与 /api/v1/memories/export 提供正确底座。 +// 修前这两个端点用 `Search(zeroVec, ...)` 冒充列表:零向量没有方向, +// ANN 返回的是存储序前 N 行再按 ns 过滤 ⇒ 实测 hermes-main 报 1 条(真实 139+), +// 计数完全失真、导出内容残缺。 +// 注意:Rust 侧硬上限 5000;namespace 由 only_if 下推,limit 作用于**过滤后**结果集。 +func (rc *RustLanceDBClient) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) { + if limit <= 0 { + limit = 100 + } + if limit > 5000 { + limit = 5000 + } + resp, err := rc.rpc(ipcReq{Type: "lancedb_scan", QueryLimit: limit, Namespace: namespaceFilter}) + if err != nil { + return nil, err + } + + var raw []struct { + ID string `json:"id"` + Content string `json:"content"` + Category string `json:"category"` + Namespace string `json:"namespace"` + IsDeleted bool `json:"is_deleted"` + DeleteReason string `json:"delete_reason"` // GA-P0-3 + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + Importance float64 `json:"importance"` + QualityScore float64 `json:"quality_score"` + RecallCount int64 `json:"recall_count"` + // GA-P0-2 (t_c6d41ac6):拆分后的新字段,scan 也读 + RecallSeenCount int64 `json:"recall_seen_count"` + RecallVerifiedCount int64 `json:"recall_verified_count"` + NotUsefulCount int64 `json:"not_useful_count"` + // GA-P0-1 (t_718d8707):拆分后的新字段,scan 也读(迁移脚本 / 列表需要) + HumanNotUsefulCount int64 `json:"human_not_useful_count"` + DedupDownweightCount int64 `json:"dedup_downweight_count"` + Tier string `json:"tier"` + Freshness string `json:"freshness"` + Source string `json:"source"` + // 2026-10-08 (Gap#2):scan 路径同样要投影,否则该路径返回的 confidence 恒 nil + Confidence *float64 `json:"confidence"` + ConfidenceSource string `json:"confidence_source"` + } + if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil { + return nil, fmt.Errorf("scan unmarshal: %w", err) + } + parseTime := func(s string) time.Time { + if t, err := time.Parse(time.RFC3339, s); err == nil { + return t + } + return time.Time{} + } + out := make([]models.MemoryRecord, 0, limit) + for _, r := range raw { + if r.IsDeleted { + continue + } + // 兜底:Rust only_if 下推失效时客户端再过滤一次(同 Search 的做法) + if namespaceFilter != "" && r.Namespace != namespaceFilter { + continue + } + out = append(out, models.MemoryRecord{ + ID: r.ID, Content: r.Content, Category: r.Category, Namespace: r.Namespace, + CreatedAt: parseTime(r.CreatedAt), UpdatedAt: parseTime(r.UpdatedAt), + Importance: r.Importance, QualityScore: r.QualityScore, + RecallCount: int(r.RecallCount), Tier: r.Tier, Source: r.Source, + // GA-P0-3 (t_f785d7f2):scan 读侧接线 delete_reason + DeleteReason: r.DeleteReason, + // GA-P0-2 (t_c6d41ac6):scan 读侧接线拆分字段 + RecallSeenCount: int(r.RecallSeenCount), RecallVerifiedCount: int(r.RecallVerifiedCount), + // GA-P0-1 (t_718d8707):scan 读侧接线 + NotUsefulCount: int(r.NotUsefulCount), HumanNotUsefulCount: int(r.HumanNotUsefulCount), DedupDownweightCount: int(r.DedupDownweightCount), + Confidence: r.Confidence, ConfidenceSource: r.ConfidenceSource, // 2026-10-08 (Gap#2) + }) + if len(out) >= limit { + break + } + } + return out, nil +} + +// ScanAll 全表扫描(仅存活行,无 5000 上限——Rust 侧 scan_all 上限 200000)。 +// GA-P0-1 (t_718d8707):供 not_useful_count 拆分迁移脚本读取全部行做统计。 +func (rc *RustLanceDBClient) ScanAll() ([]models.MemoryRecord, error) { + resp, err := rc.rpc(ipcReq{Type: "lancedb_scan_all"}) + if err != nil { + return nil, err + } + var raw []models.MemoryRecord + if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil { + return nil, fmt.Errorf("scan_all unmarshal: %w", err) + } + // 同步到本地缓存(与 GetSkillCandidates 同款) + _local.mu.Lock() + for i := range raw { + cp := raw[i] + _local.memories[cp.ID] = &cp + } + _local.mu.Unlock() + return raw, nil +} + +// ScanDeleted 全表扫描**已删除**行(is_deleted=true)。GA-P0-3 (t_f785d7f2)。 +// 供 delete_reason 回填脚本枚举存量已删行 + 出直方图。只读,不落库。 +func (rc *RustLanceDBClient) ScanDeleted() ([]models.MemoryRecord, error) { + resp, err := rc.rpc(ipcReq{Type: "lancedb_scan_deleted"}) + if err != nil { + return nil, err + } + var raw []models.MemoryRecord + if err := json.Unmarshal([]byte(resp.ReportJSON), &raw); err != nil { + return nil, fmt.Errorf("scan_deleted unmarshal: %w", err) + } + return raw, nil +} + +func (rc *RustLanceDBClient) localSearch(vec []float32, topK int, ns string) []models.MemoryRecord { + _local.mu.RLock() + defer _local.mu.RUnlock() + + type sc struct { + mem *models.MemoryRecord + score float64 + } + var cs []sc + for _, m := range _local.memories { + if m.IsDeleted || (ns != "" && m.Namespace != ns) { + continue + } + cs = append(cs, sc{mem: m, score: cosineSim(vec, m.Vector)}) + } + // 选择排序 topK + for i := 0; i < len(cs) && i < topK; i++ { + best := i + for j := i + 1; j < len(cs); j++ { + if cs[j].score > cs[best].score { + best = j + } + } + cs[i], cs[best] = cs[best], cs[i] + } + if topK > len(cs) { + topK = len(cs) + } + out := make([]models.MemoryRecord, topK) + for i := 0; i < topK; i++ { + out[i] = *cs[i].mem + } + return out +} + +func (rc *RustLanceDBClient) Stats() (map[string]interface{}, error) { + resp, err := rc.rpc(ipcReq{Type: "lancedb_stats"}) + if err != nil { + return map[string]interface{}{"backend": "lancedb (Rust IPC offline)", "error": err.Error()}, nil + } + var s map[string]interface{} + json.Unmarshal([]byte(resp.ReportJSON), &s) + s["backend"] = "lancedb (Rust IPC)" + // Rust sidecar 统计 memories/tombstones/episodes(episodes 已持久化到 LanceDB) + // 若 Rust 返回的 total_episodes 计数缺失(旧 sidecar),回退到本地进程内缓存。 + // 回退值标记为 episodes_cached(非 total_episodes),避免消费者误以为是真实总量。 + // 真实总量以 Rust count_rows 结果为准(total_episodes);episodes_cached 仅反映 + // 本进程生命周期内 Insert 过的条数(重启即清零)。 + if _, ok := s["total_episodes"]; !ok { + _local.mu.RLock() + s["episodes_cached"] = len(_local.episodes) // ← 缓存值,改名标注 + _local.mu.RUnlock() + } + return s, nil +} + +func (rc *RustLanceDBClient) Insert(table string, record any) error { + if r, ok := record.(models.MemoryRecord); ok { + return rc.InsertMemory(r) + } + if r, ok := record.(models.EpisodeRecord); ok { + _local.mu.Lock() + _local.episodes = append(_local.episodes, r) + _local.mu.Unlock() + return nil + } + return fmt.Errorf("unknown type") +} + +// helper: get a counter field's current value from cache, returns cache+1 or 1 if not cached +func getIncCachedValue(id, field string, cache map[string]*models.MemoryRecord) int { + if m, ok := cache[id]; ok { + switch field { + case "recall_count": + return m.RecallCount + 1 + // GA-P0-2 (t_c6d41ac6):拆分字段 + case "recall_seen_count": + return m.RecallSeenCount + 1 + case "recall_verified_count": + return m.RecallVerifiedCount + 1 + case "useful_count": + return m.UsefulCount + 1 + case "not_useful_count": + return m.NotUsefulCount + 1 + case "human_not_useful_count": + return m.HumanNotUsefulCount + 1 + case "dedup_downweight_count": + return m.DedupDownweightCount + 1 + } + } + return 1 +} + +// Update 同步执行:整个操作在锁内(cache read + IPC call) +// 保证并发调用时不会 read stale value 再写回 +func (rc *RustLanceDBClient) Update(table, id string, fields map[string]any) error { + _local.mu.Lock() + + // 1. 更新本地内存缓存 + if m, ok := _local.memories[id]; ok { + // GA-P0-2 (t_c6d41ac6):recall_count 冻结,召回命中走 recall_seen_count,正反馈走 recall_verified_count。 + if v, ok := fields["recall_seen_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.RecallSeenCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.RecallSeenCount++ + } + case int: + m.RecallSeenCount = inc + } + } + if v, ok := fields["recall_verified_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.RecallVerifiedCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.RecallVerifiedCount++ + } + case int: + m.RecallVerifiedCount = inc + } + } + if v, ok := fields["recall_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.RecallCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.RecallCount++ + } + case int: + m.RecallCount = inc + } + } + if v, ok := fields["useful_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.UsefulCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.UsefulCount++ + } + case int: + m.UsefulCount = inc + } + } + if v, ok := fields["not_useful_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.NotUsefulCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.NotUsefulCount++ + } + case int: + m.NotUsefulCount = inc + } + } + // GA-P0-1 (t_718d8707):拆分后的新字段也要同步更新本地缓存 + if v, ok := fields["human_not_useful_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.HumanNotUsefulCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.HumanNotUsefulCount++ + } + case int: + m.HumanNotUsefulCount = inc + } + } + if v, ok := fields["dedup_downweight_count"]; ok { + switch inc := v.(type) { + case map[string]string: + if inc["$inc"] == "1" { + m.DedupDownweightCount++ + } + case map[string]interface{}: + if inc["$inc"] == "1" { + m.DedupDownweightCount++ + } + case int: + m.DedupDownweightCount = inc + } + } + if v, ok := fields["last_recalled_at"]; ok { + if s, ok := v.(string); ok { + if t, err := time.Parse(time.RFC3339, s); err == nil { + m.LastRecalledAt = t + } + } + } + } + + // 2. 通过 IPC 持久化到 Rust LanceDB(仍在锁内,防止并发写同一行) + var fieldList []updateField + for k, v := range fields { + switch val := v.(type) { + case string: + fieldList = append(fieldList, updateField{k, "'" + strings.ReplaceAll(val, "'", "''") + "'"}) + case map[string]string: + if val["$inc"] == "1" { + // 交给 Rust 侧做**真自增**:Rust 的 update() 识别 "col + N" + // 表达式时会先查该行当前值再计算(lancedb_ops.rs has_arith 分支)。 + // ⚠️不要改回用 getIncCachedValue 在 Go 侧算绝对值—— + // _local.memories 只在 Insert 路径填充、Search 不填, + // 缓存未命中时它返回 1,会把已有计数(如 5)**重置为 1**, + // 造成「越降权计数越小」的静默数据损坏。 + fieldList = append(fieldList, updateField{k, k + " + 1"}) + } + case map[string]interface{}: + if val["$inc"] == float64(1) || val["$inc"] == 1 { + fieldList = append(fieldList, updateField{k, k + " + 1"}) + } + case float64: + fieldList = append(fieldList, updateField{k, fmt.Sprintf("%f", val)}) + case bool: + if val { + fieldList = append(fieldList, updateField{k, "true"}) + } else { + fieldList = append(fieldList, updateField{k, "false"}) + } + } + } + if len(fieldList) > 0 { + fj, _ := json.Marshal(fieldList) + log.Printf("[ipc] Update: id=%s fields_count=%d", id, len(fieldList)) + log.Printf("[ipc] Update fields_json: %s", string(fj)) + _, err := rc.rpc(ipcReq{ + Type: "lancedb_update", + Table: table, + ID: id, + Fields: string(fj), + }) + if err != nil { + log.Printf("[ipc] Update FAILED: id=%s fields=%s error=%v", id, string(fj), err) + } else { + log.Printf("[ipc] Update OK: id=%s fields=%s", id, string(fj)) + } + } + _local.mu.Unlock() + return nil +} + +// UpdateRecallBatch 单事务批量更新召回元数据(2026-09-12 优化B)。 +// Rust 侧把整批按 delta 分组,每组一次 update(`recall_count + delta` + id IN (...))提交 +// (lance 不支持 CASE WHEN)→ 整批版本数 = 不同 delta 的个数,通常 1 个(旧实现:每行 1 个)。 +// 注:Rust 侧固定操作 memories 表,table 参数暂未使用。 +func (rc *RustLanceDBClient) UpdateRecallBatch(table string, items []RecallWriteItem, lastRecalledAt string) (int64, error) { + if len(items) == 0 { + return 0, nil + } + fj, err := json.Marshal(items) + if err != nil { + return 0, err + } + resp, err := rc.rpc(ipcReq{ + Type: "lancedb_update_batch", + Table: table, + Items: string(fj), + TS: lastRecalledAt, + }) + if err != nil { + return 0, err + } + var out struct { + Updated int64 `json:"updated"` + Items int `json:"items"` + } + if resp.ReportJSON != "" { + _ = json.Unmarshal([]byte(resp.ReportJSON), &out) + } + log.Printf("[ipc] UpdateRecallBatch: 合并 %d 条记忆 → 落盘 %d 行(单事务)", len(items), out.Updated) + return out.Updated, nil +} + +func (rc *RustLanceDBClient) GetTopByQuality(agentID string, limit int) ([]models.MemoryRecord, error) { + _local.mu.RLock() + defer _local.mu.RUnlock() + var out []models.MemoryRecord + for _, m := range _local.memories { + if m.IsDeleted { + continue + } + out = append(out, *m) + if len(out) >= limit { + break + } + } + return out, nil +} + +// ─── 有界冲突重试(2026-10-11 t_5b5a83de 方案 a)──────────────────────── +// +// LanceDB MVCC 写冲突(同一表并发提交)时返回 "Commit conflict ... rerun the operation"。 +// 旧实现 SoftDelete 遇冲突直接失败返回、无重试 ⇒ 那次 soft-delete 未落库(静默丢失), +// 靠下一轮轮转重扫兜底 → 遗忘/合并延迟 + 日志刷错误。方案(a):识别可重试错误 → 有界退避重试。 +// +// 重试语义: +// - N = softDeleteMaxRetries = 3 次重试(总 rpc 尝试 = N+1 = 4 次); +// - 退避 50/100/200ms(指数、cap 200ms),总最坏 +350ms(背景软删按分钟/小时节奏,可忽略); +// - 更新是 SET is_deleted=true, updated_at=... 纯赋值 → 对最新已提交版本重放安全(幂等不累加); +// - 仅「可重试冲突」重试;其余错误(空 id / "id required" / schema 错)立即返回、不重试。 +const ( + softDeleteMaxRetries = 3 + softDeleteBackoffBase = 50 * time.Millisecond + softDeleteBackoffCap = 200 * time.Millisecond +) + +// isRetryableLanceConflict 判断错误是否为 LanceDB「可重试的 MVCC 写冲突」。 +// 仅当错误串含官方建议重试的关键词才返回 true(大小写不敏感): +// "commit conflict" / "cannot be automatically resolved" / "rerun the operation"。 +// 其他错误(空 id、id required、schema 错、网络错等)一律 false,立即返回不重试。 +func isRetryableLanceConflict(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + for _, kw := range []string{"commit conflict", "cannot be automatically resolved", "rerun the operation"} { + if strings.Contains(msg, kw) { + return true + } + } + return false +} + +// retrySoftDeleteRPC 对 lancedb_update 调用做有界指数退避重试(仅可重试冲突)。 +// 返回:首次成功或重试后成功 = nil;耗尽 = 含尝试次数的明确错误;非可重试错误 = 原样立即返回。 +func (rc *RustLanceDBClient) retrySoftDeleteRPC(id, reason, fields string) error { + backoff := softDeleteBackoffBase + var lastErr error + for attempt := 0; attempt <= softDeleteMaxRetries; attempt++ { + if attempt > 0 { + // 第 attempt 次重试(1-based):attempt=1→50ms, 2→100ms, 3→200ms + log.Printf("[ipc] SoftDelete retry attempt %d/%d id=%s reason=%s error=%v", + attempt, softDeleteMaxRetries, id, reason, lastErr) + time.Sleep(backoff) + if backoff < softDeleteBackoffCap { + backoff *= 2 + if backoff > softDeleteBackoffCap { + backoff = softDeleteBackoffCap + } + } + } + _, err := rc.rpc(ipcReq{Type: "lancedb_update", Table: "memories", ID: id, Fields: fields}) + if err == nil { + if attempt > 0 { + log.Printf("[ipc] SoftDelete retried OK after %d id=%s reason=%s", attempt, id, reason) + } + return nil + } + if !isRetryableLanceConflict(err) { + return err // 非可重试错误:立即返回,不重试 + } + lastErr = err + } + return fmt.Errorf("soft delete persist (id=%s): retry exhausted after %d retries: %w", + id, softDeleteMaxRetries, lastErr) +} + +func (rc *RustLanceDBClient) SoftDelete(id, reason string) error { + // 🔴 2026-10-06 防御:空 id 会被 Rust IPC 直接拒绝("id required"), + // 而调用方曾忽略错误照样计数(admin.go forgotten++),造成「遗忘计数虚高 + 每轮刷错误日志」。 + // 根因:DB 里存在 id/content 全空的垃圾行 → 命中 <30 字碎片快速道 → SoftDelete("")。 + // 在入口直接挡掉,返回可辨识错误(调用方据此跳过、不计数)。 + if strings.TrimSpace(id) == "" { + return fmt.Errorf("soft delete: empty id rejected (reason=%s)", reason) + } + _local.mu.Lock() + if m, ok := _local.memories[id]; ok { + m.IsDeleted = true + } + _local.mu.Unlock() + + // 持久化 tombstone 到 Rust LanceDB(值按 SQL 表达式传递:true=布尔字面量,'...'=字符串字面量) + // GA-P0-3 (t_f785d7f2):同批写入 delete_reason(归一化枚举),让 is_deleted=true 可分原因。 + dr := NormalizeDeleteReason(reason) + fj, _ := json.Marshal([]updateField{ + {Column: "is_deleted", Value: "true"}, + {Column: "updated_at", Value: "'" + time.Now().Format(time.RFC3339) + "'"}, + {Column: "delete_reason", Value: "'" + dr + "'"}, + }) + if err := rc.retrySoftDeleteRPC(id, reason, string(fj)); err != nil { + log.Printf("[ipc] SoftDelete persist FAILED: id=%s reason=%s error=%v", id, reason, err) + return fmt.Errorf("soft delete persist (id=%s): %w", id, err) + } + log.Printf("[ipc] SoftDelete persisted: id=%s reason=%s", id, reason) + return nil +} + +// TODO: 需要 Rust 侧支持 lancedb_update 才能持久化 SoftDelete +// 当前仅标记内存,重启后失效。测试数据已直接通过 Python LanceDB API 清理。 + +// SoftDeleteBatch 批量软删(真实落库)。 +// +// 2026-09-20 修复:此前**只改内存缓存 `_local.memories`,完全不写 LanceDB**, +// 缓存又只在 Insert 路径填充、Search 不填 → 批量软删实际静默失效 +// (调用方拿到 updated=N 却无一行落库)。与 SoftDelete() 的区别仅在批量语义, +// 因此这里逐个委托给已验证的 SoftDelete()(它走 SoftDeleteWriteBuffer, +// 5 分钟窗口 / 256 条阈值攒批 → 单事务提交,避免每条一个 MVCC 版本)。 +// +// 注:Rust 侧的 lancedb_update_batch 只支持 recall_count 累加 +// (Item{id, delta}),不支持 is_deleted 批量置位,故不能下沉到那里。 +func (rc *RustLanceDBClient) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) { + if table != "memories" { + return 0, fmt.Errorf("unsupported table: %s", table) + } + var updated int64 + for _, id := range ids { + if err := rc.SoftDelete(id, "batch:"+updatedAt); err != nil { + log.Printf("[ipc] SoftDeleteBatch persist FAILED: id=%s error=%v", id, err) + continue + } + updated++ + } + return updated, nil +} + +// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08)。 +// 走 Rust IPC lancedb_purge_invalid:按 id=” 条件一次性软删(is_deleted=true + updated_at=now)。 +// 这些行 id/content/source 全空、无法按 id 软删,只能按条件清。返回受影响行数。 +func (rc *RustLanceDBClient) PurgeInvalid() (int64, error) { + now := time.Now().Format(time.RFC3339) + resp, err := rc.rpc(ipcReq{Type: "lancedb_purge_invalid", TS: now}) + if err != nil { + return 0, fmt.Errorf("purge_invalid rpc: %w", err) + } + var out struct { + Purged int64 `json:"purged"` + } + if resp.ReportJSON != "" { + _ = json.Unmarshal([]byte(resp.ReportJSON), &out) + } + log.Printf("[ipc] PurgeInvalid: 软删 %d 行 id 为空垃圾记录", out.Purged) + return out.Purged, nil +} + +func (rc *RustLanceDBClient) GetVersionHistory(id string) ([]map[string]interface{}, error) { + return nil, nil +} + +// forgetCursorPath 遗忘候选旋转窗口游标持久化文件(2026-10-11 t_a4b8fa52 方案 c′)。 +// 游标 = 上一轮扫描窗口的末 id(mem_);文件缺失/损坏/库回滚 → 空串(从头轮转,降级不崩)。 +var forgetCursorPath = "/var/lib/memoryweave/forget-cursor.json" + +// loadForgetCursor 读取持久化游标。缺失/空/损坏 → 返回 ""(降级为从头轮转,不崩)。 +func loadForgetCursor() string { + data, err := os.ReadFile(forgetCursorPath) + if err != nil { + if os.IsNotExist(err) { + return "" // 首次运行或文件被清,正常 + } + log.Printf("[ipc] loadForgetCursor read failed: %v → 降级从头轮转", err) + return "" + } + s := strings.TrimSpace(string(data)) + if s == "" { + return "" + } + if !strings.HasPrefix(s, "mem_") { + log.Printf("[ipc] loadForgetCursor corrupt (not mem_ prefix): %q → 降级从头轮转", s) + return "" + } + return s +} + +// persistForgetCursor 原子写游标(tmp+rename,复用 conflict-seen 的原子写模式)。 +func persistForgetCursor(cursor string) { + if cursor == "" { + return // wrapped → 下轮从头,无需落盘空游标(缺文件=从头) + } + dir := filepath.Dir(forgetCursorPath) + if err := os.MkdirAll(dir, 0o755); err != nil { + log.Printf("[ipc] persistForgetCursor mkdir failed: %v", err) + return + } + tmp := forgetCursorPath + ".tmp" + if err := os.WriteFile(tmp, []byte(cursor), 0o644); err != nil { + log.Printf("[ipc] persistForgetCursor write failed: %v", err) + return + } + if err := os.Rename(tmp, forgetCursorPath); err != nil { + log.Printf("[ipc] persistForgetCursor rename failed: %v", err) + } +} + +// GetCandidatesForForgetting 取遗忘候选:走 Rust `lancedb_forget_window` 旋转窗口扫描。 +// +// 2026-10-11 t_a4b8fa52 方案 c′:修复「固定 2000 窗口不轮转」。 +// 旧实现 lancedb_scan 无 ORDER BY ⇒ 返回物理存储序前 2000 条(compact/merge 后非创建序) +// ⇒ 新记忆落物理序后部 ⇒ 永不进遗忘候选池。方案 c′:Rust 列投影取全部存活 id → +// 内排序 → 连续窗口 → 区间过滤还原全字段;游标=窗口末 id,本函数持久化到 forget-cursor.json。 +// 每轮只评估一个 2000 窗口,全库覆盖上界 = ceil(live/2000)×6h(实测 ~72h 全覆盖,吞吐余量见卡 AC-7)。 +// IPC 失败/空 → fallback 缓存遍历(保持可用,回归安全)。 +func (rc *RustLanceDBClient) GetCandidatesForForgetting() ([]map[string]interface{}, error) { + // 读游标(缺失/损坏 → 空串 = 从头轮转) + cursor := loadForgetCursor() + resp, err := rc.rpc(ipcReq{Type: "lancedb_forget_window", QueryLimit: 2000, AfterID: cursor}) + if err == nil && resp.ReportJSON != "" { + var win struct { + Records []struct { + ID string `json:"id"` + Content string `json:"content"` + Namespace string `json:"namespace"` + Category string `json:"category"` + Tier string `json:"tier"` + IsDeleted bool `json:"is_deleted"` + Importance float64 `json:"importance"` + RecallCount int64 `json:"recall_count"` + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + RecallSeenCount int64 `json:"recall_seen_count"` + RecallVerifiedCount int64 `json:"recall_verified_count"` + LastRecalledAt string `json:"last_recalled_at"` + CreatedAt string `json:"created_at"` + } `json:"records"` + NextCursor string `json:"next_cursor"` + Wrapped bool `json:"wrapped"` + LiveTotal int `json:"live_total"` + } + uerr := json.Unmarshal([]byte(resp.ReportJSON), &win) + if uerr == nil && (len(win.Records) > 0 || win.LiveTotal > 0) { + // 持久化新游标(wrapped → 空串,下轮从头) + persistForgetCursor(win.NextCursor) + // 覆盖度与吞吐日志(AC-7 判据源:live_total 应随轮转被消耗,写入率 142/h < 窗口率 2000/6h≈333/h) + if win.LiveTotal > 0 { + log.Printf("[ipc] GetCandidatesForForgetting: window n=%d live_total=%d wrapped=%v next_cursor=%s(池内覆盖累计进度)", + len(win.Records), win.LiveTotal, win.Wrapped, truncID(win.NextCursor)) + } + log.Printf("[ipc] GetCandidatesForForgetting: Rust forget_window → %d candidates", len(win.Records)) + out := make([]map[string]interface{}, 0, len(win.Records)) + for _, r := range win.Records { + if r.IsDeleted || r.Tier == "core" { + continue + } + out = append(out, map[string]interface{}{ + "id": r.ID, + "content": r.Content, + "namespace": r.Namespace, + "category": r.Category, + "tier": r.Tier, + "importance": r.Importance, + "recall_count": int(r.RecallCount), // decay 侧 .(int) 断言 — int64 会恒 0 + // GA-P0-2 (t_c6d41ac6):衰减/遗忘决策读 recall_verified_count + "recall_seen_count": int(r.RecallSeenCount), + "recall_verified_count": int(r.RecallVerifiedCount), + "last_recalled_at": r.LastRecalledAt, + "created_at": r.CreatedAt, + }) + } + return out, nil + } + log.Printf("[ipc] GetCandidatesForForgetting: forget_window unmarshal empty (rpc=%v err=%v raw=%d) → fallback 缓存", err, uerr, len(win.Records)) + } + _local.mu.RLock() + defer _local.mu.RUnlock() + var out []map[string]interface{} + for id, m := range _local.memories { + if !m.IsDeleted && m.Tier != "core" { + out = append(out, map[string]interface{}{ + "id": id, + "content": m.Content, + "namespace": m.Namespace, + "category": m.Category, + "last_recalled_at": fmtTimeRFC3339(m.LastRecalledAt), + "created_at": fmtTimeRFC3339(m.CreatedAt), + "recall_count": m.RecallCount, + // GA-P0-2 (t_c6d41ac6):衰减/遗忘决策读 recall_verified_count + "recall_seen_count": m.RecallSeenCount, + "recall_verified_count": m.RecallVerifiedCount, + "tier": m.Tier, + "importance": m.Importance, + }) + } + } + return out, nil +} + +// fmtTimeRFC3339 统一时间输出契约:RFC3339 字符串;零值输出 ""。 +// 2026-09-06 P1 修复:此前直接放 time.Time → server.go decay 的 .(string) 断言 +// 恒失败 → lastAccessed 永远"默认30天前" → 遗忘判定失真(叠加数据年龄未到)。 +// 调用方一律按 string 解析(parseTimeStr / time.Parse RFC3339)。 +func fmtTimeRFC3339(t time.Time) string { + if t.IsZero() { + return "" + } + return t.Format(time.RFC3339) +} + +// truncID 截断长 id 用于日志(mem_ 19 位+前缀,全打印太长) +func truncID(id string) string { + if len(id) > 16 { + return id[:8] + "…" + id[len(id)-6:] + } + return id +} + +func mapStr(m map[string]interface{}, key string) string { + if v, ok := m[key]; ok { + if s, ok := v.(string); ok { + return s + } + } + return "" +} +func mapFloat(m map[string]interface{}, key string) float64 { + if v, ok := m[key]; ok { + if f, ok := v.(float64); ok { + return f + } + } + return 0 +} + +// mapFloatPtr 2026-10-08 (Gap#2):可空浮点。JSON null / 缺键 → nil(区别于显式 0.0)。 +// 用于 confidence:nil 表示「该条未声明信任等级」(存量行),调用方 COALESCE 到 1.0。 +func mapFloatPtr(m map[string]interface{}, key string) *float64 { + if v, ok := m[key]; ok { + if f, ok := v.(float64); ok { + return &f + } + } + return nil +} +func mapInt(m map[string]interface{}, key string) int { + if v, ok := m[key]; ok { + if f, ok := v.(float64); ok { + return int(f) + } + } + return 0 +} +func mapBool(m map[string]interface{}, key string) bool { + if v, ok := m[key]; ok { + if b, ok := v.(bool); ok { + return b + } + } + return false +} + +// seJSON 2026-10-13 (t_e9a4d18f P1):SourceEvents → JSON 数组字符串。 +// nil/空 → "[]"(Rust 读路径 col_str 兜底)。显式转,避免 []string 直接进 +// map 后 json.Marshal 的嵌套转义([]string → 已是 JSON 数组)。 +func seJSON(events []string) string { + if len(events) == 0 { + return "[]" + } + b, _ := json.Marshal(events) + return string(b) +} + +// parseSourceEvents 2026-10-13 (t_e9a4d18f P1):JSON 数组字符串 → []string。 +// 解析失败回退 nil(存量 NULL/空 ⇒ 无证据链)。 +func parseSourceEvents(raw string) []string { + if raw == "" || raw == "[]" || raw == "null" { + return nil + } + var out []string + if err := json.Unmarshal([]byte(raw), &out); err != nil { + return nil + } + return out +} + +func (rc *RustLanceDBClient) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) { + resp, err := rc.rpc(ipcReq{ + Type: "lancedb_query", + MinRecall: minRecalls, + QueryLimit: limit, + }) + if err != nil { + return nil, fmt.Errorf("lancedb_query: %w", err) + } + raw := resp.ReportJSON + if raw == "" { + return []models.MemoryRecord{}, nil + } + + // 用 raw JSON 反序列化,避免 time.Time 空字符串报错 + var rawRecords []map[string]interface{} + if err := json.Unmarshal([]byte(raw), &rawRecords); err != nil { + return nil, fmt.Errorf("parse lancedb_query result: %w", err) + } + if len(rawRecords) == 0 { + return []models.MemoryRecord{}, nil + } + + records := make([]models.MemoryRecord, 0, len(rawRecords)) + for _, r := range rawRecords { + m := models.MemoryRecord{ + ID: mapStr(r, "id"), + AgentID: mapStr(r, "agent_id"), + Namespace: mapStr(r, "namespace"), + Content: mapStr(r, "content"), + Category: mapStr(r, "category"), + Tier: mapStr(r, "tier"), + Source: mapStr(r, "source"), + Freshness: mapStr(r, "freshness"), + DerivedFrom: mapStr(r, "derived_from"), + SourceEvents: parseSourceEvents(mapStr(r, "source_events")), // 2026-10-13 P1 + Supersedes: parseSourceEvents(mapStr(r, "supersedes")), // 2026-10-13 P1 + VersionHistory: nil, + DependsOn: nil, + } + m.QualityScore = mapFloat(r, "quality_score") + m.Importance = mapFloat(r, "importance") + // 2026-10-08 (Gap#2):读侧接线(不补 ⇒ 加列也读不出来) + m.Confidence = mapFloatPtr(r, "confidence") + m.ConfidenceSource = mapStr(r, "confidence_source") + m.UsefulCount = mapInt(r, "useful_count") + m.NotUsefulCount = mapInt(r, "not_useful_count") + // GA-P0-1 (t_718d8707):读侧接线拆分后的新字段(漏接线 ⇒ 加列也读不出,静默 no-op) + m.HumanNotUsefulCount = mapInt(r, "human_not_useful_count") + m.DedupDownweightCount = mapInt(r, "dedup_downweight_count") + m.RecallCount = mapInt(r, "recall_count") + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + m.RecallSeenCount = mapInt(r, "recall_seen_count") + m.RecallVerifiedCount = mapInt(r, "recall_verified_count") + m.Version = mapInt(r, "version") + m.VolatileFlag = mapBool(r, "volatile_flag") + m.IsDeleted = mapBool(r, "is_deleted") + // 时间字段:空字符串 → 零值 time.Time + if t := mapStr(r, "last_recalled_at"); t != "" { + if pt, err := time.Parse(time.RFC3339, t); err == nil { + m.LastRecalledAt = pt + } + } + if t := mapStr(r, "created_at"); t != "" { + if pt, err := time.Parse(time.RFC3339, t); err == nil { + m.CreatedAt = pt + } + } + if t := mapStr(r, "updated_at"); t != "" { + if pt, err := time.Parse(time.RFC3339, t); err == nil { + m.UpdatedAt = pt + } + } + records = append(records, m) + } + + // 同步到本地缓存 + _local.mu.Lock() + for _, m := range records { + cp := m + _local.memories[m.ID] = &cp + } + _local.mu.Unlock() + return records, nil +} + +// Backup 备份存储。 +// +// 2026-09-20:此前是 `return nil` 空实现 —— 任何人调用它都会拿到"成功", +// 而实际没有任何备份发生(与 IncrementNotUseful 同类:静默假成功)。 +// 当前 Rust sidecar 未提供 backup 能力,也无调用方(全仓 grep .Backup( 为 0), +// 因此这里改为**显式报错**:一旦将来有人调用,会立刻发现而不是以为备份成功。 +// 需要备份时正确做法是外部对 /var/lib/memoryweave 做文件级快照 +// (见 scripts/dual-backup-push.sh)。 +func (rc *RustLanceDBClient) Backup(path string) error { + return fmt.Errorf("RustLanceDBClient.Backup: not supported by Rust sidecar; "+ + "snapshot the data dir instead (requested path=%s)", path) +} +func (rc *RustLanceDBClient) GetAuditLog(limit int) ([]map[string]interface{}, error) { + _local.mu.RLock() + defer _local.mu.RUnlock() + if limit > len(_local.auditLog) { + limit = len(_local.auditLog) + } + return _local.auditLog[:limit], nil +} + +// IncrementUseful 递增 useful_count + recall_count(用户标记"有用")。 +// +// 2026-09-20 修复(双重 bug): +// +// ① 此前只改内存缓存、不落库 → 与 IncrementNotUseful 同类的假成功; +// ② 此前改的是 RecallCount,**完全没碰 UsefulCount** → 用户点"有用" +// 时 V 值评分的分子永远不涨,同时把"有用反馈"错记成一次"召回", +// 污染召回统计(召回率/新鲜度衰减都基于 recall_count)。 +// 对照 MemLanceClient.IncrementUseful:UsefulCount++ 且 RecallCount++。 +func (rc *RustLanceDBClient) IncrementUseful(id string) error { + // GA-P0-2 (t_c6d41ac6):正反馈 → useful_count+1 且 recall_verified_count+1。 + // 不再碰 recall_count(冻结,保留历史值——虚高保命来源已被切断)。 + if err := rc.Update("memories", id, map[string]any{ + "useful_count": map[string]string{"$inc": "1"}, + "recall_verified_count": map[string]string{"$inc": "1"}, + }); err != nil { + log.Printf("[ipc] IncrementUseful failed id=%s: %v", id, err) + return err + } + return nil +} + +// IncrementNotUseful [DEPRECATED] 递增 not_useful_count(GA-P0-1 t_718d8707)。 +// +// 历史(2026-09-20 修复):此前是**空实现** `{}`,导致 feedback/not-useful 端点与 +// 一切降权类清理(zhiyi-dedup.py 等)全是**假成功**——HTTP 200 返回正常, +// 但 not_useful_count 从未落库。实测:dedup --apply 报「已降权 34 条, +// 失败 0」,回读 32 条 dropped 记录的 not_useful_count 全为 0。 +// +// 2026-10-12 (GA-P0-1 t_718d8707):not_useful_count 曾把两种语义混写—— +// 人工点「没用」(feedback.go)与 dedup 自动降权(core.go dedup 路径)都写它。 +// 现拆分为 human_not_useful_count / dedup_downweight_count 两个字段, +// 两个写入点各写各的(IncrementHumanNotUseful / IncrementDedupDownweight)。 +// 本方法仅向后兼容,**新代码不再调用它**。 +func (rc *RustLanceDBClient) IncrementNotUseful(id string) error { + if err := rc.Update("memories", id, map[string]any{ + "not_useful_count": map[string]string{"$inc": "1"}, + }); err != nil { + log.Printf("[ipc] IncrementNotUseful failed id=%s: %v", id, err) + return err + } + return nil +} + +// IncrementHumanNotUseful 递增 human_not_useful_count(用户人工点「没用」,GA-P0-1)。 +func (rc *RustLanceDBClient) IncrementHumanNotUseful(id string) error { + if err := rc.Update("memories", id, map[string]any{ + "human_not_useful_count": map[string]string{"$inc": "1"}, + }); err != nil { + log.Printf("[ipc] IncrementHumanNotUseful failed id=%s: %v", id, err) + return err + } + return nil +} + +// IncrementDedupDownweight 递增 dedup_downweight_count(dedup/合并流程自动降权,GA-P0-1)。 +func (rc *RustLanceDBClient) IncrementDedupDownweight(id string) error { + if err := rc.Update("memories", id, map[string]any{ + "dedup_downweight_count": map[string]string{"$inc": "1"}, + }); err != nil { + log.Printf("[ipc] IncrementDedupDownweight failed id=%s: %v", id, err) + return err + } + return nil +} + +// AppendHitEvent 追加一条真实 outcome 事件(GA-P0-4 t_bb10e8bc,走 Rust IPC)。 +func (rc *RustLanceDBClient) AppendHitEvent(memoryID, outcome, reason string) error { + outcome = NormalizeHitOutcome(outcome) + if !ValidHitOutcomes[outcome] { + return fmt.Errorf("AppendHitEvent: invalid outcome %q (must be pos/neg); dedup-demote/recall-appearance are NOT outcomes", outcome) + } + reason = NormalizeHitReason(reason) + _, err := rc.rpc(ipcReq{ + Type: "lancedb_append_hit_event", + ID: memoryID, + Outcome: outcome, + Reason: reason, + Source: "append_hit_event", + }) + if err != nil { + log.Printf("[ipc] AppendHitEvent failed id=%s: %v", memoryID, err) + return err + } + return nil +} + +// CountHitEvents 统计某 memory 在某窗口起点的 outcome 事件数(周窗口聚合,P2 自适应阈值用)。 +func (rc *RustLanceDBClient) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) { + outcome = NormalizeHitOutcome(outcome) + if !ValidHitOutcomes[outcome] { + return 0, fmt.Errorf("CountHitEvents: invalid outcome %q", outcome) + } + resp, err := rc.rpc(ipcReq{ + Type: "lancedb_count_hit_events", + ID: memoryID, + Outcome: outcome, + Since: since.Format(time.RFC3339), + }) + if err != nil { + return 0, err + } + var out struct { + Count int `json:"count"` + } + if err := json.Unmarshal([]byte(resp.Result), &out); err != nil { + return 0, err + } + return out.Count, nil +} + +// GetHitEvents 读回某 memory 的事件明细(read-back 取证,非只看函数返回)。 +func (rc *RustLanceDBClient) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) { + if limit <= 0 { + limit = 100 + } + resp, err := rc.rpc(ipcReq{ + Type: "lancedb_get_hit_events", + ID: memoryID, + QueryLimit: limit, + }) + if err != nil { + return nil, err + } + var events []models.HitEvent + if err := json.Unmarshal([]byte(resp.Result), &events); err != nil { + return nil, err + } + return events, nil +} + +// UpdateMemoryContent 修正记忆内容(重新编码向量)并**持久化**。 +// +// 2026-09-20 修复:此前只改内存缓存 `_local.memories`,不写 LanceDB, +// 且缓存只在 Insert 路径填充 → 修正后的内容重启即丢、且大多数情况下 +// 根本没生效(缓存未命中直接 return nil)。同时补齐 MemLanceClient +// 版本所具有的语义:Version 递增、VersionHistory 追加、Source 更新。 +func (rc *RustLanceDBClient) UpdateMemoryContent(id, newContent, source string) error { + _local.mu.Lock() + var newVec []float32 + if m, ok := _local.memories[id]; ok { + m.Version++ + m.VersionHistory = append(m.VersionHistory, models.VersionRecord{ + Version: m.Version, + Content: newContent, + Source: source, + Reason: "corrected", + Trigger: "update_memory_content", + UpdatedBy: source, + Timestamp: time.Now(), + }) + m.Content = newContent + m.Source = source + if rc.embedder != nil { + if vec, err := rc.embedder.EncodeSingle(newContent); err == nil { + m.Vector = vec + newVec = vec + } + } + } + _local.mu.Unlock() + + // 持久化内容(及向量,若已重编码) + vecJSON, _ := json.Marshal(newVec) + fields := map[string]any{ + "content": newContent, + "source": source, + } + if len(newVec) > 0 { + fields["vector"] = string(vecJSON) + } + if err := rc.Update("memories", id, fields); err != nil { + log.Printf("[ipc] UpdateMemoryContent persist FAILED: id=%s error=%v", id, err) + return fmt.Errorf("update memory content (id=%s): %w", id, err) + } + return nil +} diff --git a/go/internal/storage/quality_from_proof.go b/go/internal/storage/quality_from_proof.go new file mode 100644 index 0000000..e42a0ab --- /dev/null +++ b/go/internal/storage/quality_from_proof.go @@ -0,0 +1,79 @@ +package storage + +import ( + "os" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// 2026-10-13 (t_e9a4d18f P1) 证据链 + proof_count。 +// +// 背景:实测 quality_score 半灌水 —— 24.0% 是 0(未打分)+ 27.1% 恒 0.755 +// (历史 echo 常量 bug,见 engine.go IsEchoScore)⇒ 排序公式 0.3*QualityScore +// 这一路不可信。本文件提供**有原理的替代**:支持证据条数(proof_count)→ +// 质量分,而非一个拍出来的分数。 + +// proofSaturation 饱和常数 K:QualityFromProof 用 sat(x)=x/(x+K)。 +// 证据条数无上界,必须压进 [0,1) 才能当权重用。K 可配(默认 5,即 +// 5 条证据 → 0.5 分;10 条 → 0.67)。 +var proofSaturation = envFloat("ZHIYI_PROOF_SATURATION", 5) + +// ProofCount 由 SourceEvents 派生的证据条数(distinct 去重后)。 +// nil/空 → 0。不单独存储,避免与 SourceEvents 不同步。 +func ProofCount(m *models.MemoryRecord) int { + if m == nil || len(m.SourceEvents) == 0 { + // 兼容单亲字段:DerivedFrom 非空也算 1 条证据(存量行缺 SourceEvents) + if m != nil && m.DerivedFrom != "" { + return 1 + } + return 0 + } + seen := make(map[string]bool) + for _, e := range m.SourceEvents { + if e != "" { + seen[e] = true + } + } + if len(seen) == 0 && m.DerivedFrom != "" { + return 1 + } + return len(seen) +} + +// QualityFromProof 用证据条数计算质量分(饱和 x/(x+K))。 +// 与 quality_score 不同:不依赖 LLM 打分(可能 echo/未打分),只依赖 +// 「这条结论被几条独立 episode 支持」—— 结构性、可验证。 +func QualityFromProof(m *models.MemoryRecord) float64 { + n := float64(ProofCount(m)) + if n <= 0 { + return 0 + } + return n / (n + proofSaturation) +} + +// proofQualityFallback 2026-10-13:quality_score 不可信(0 或恒 0.755 echo) +// 时,用 QualityFromProof 作为**展示/排序的兜底替代**。env 门控: +// ZHIYI_PROOF_FALLBACK=1 开启(默认关 ⇒ 行为零变化)。 +// 注意:这是「兜底」不是「替换」—— 已有可信 quality_score 的条目不受影响。 +var proofFallbackEnabled = os.Getenv("ZHIYI_PROOF_FALLBACK") == "1" + +// ResolveQuality 供召回排序/展示调用的统一质量解析: +// - 已有可信 quality_score → 原样返回 +// - 不可信(0/0.755 echo)且 fallback 开启 → 用 QualityFromProof +// - 不可信且 fallback 关闭 → 返回原值(行为零变化) +func ResolveQuality(m *models.MemoryRecord, dbQuality float64) float64 { + if m == nil { + return dbQuality + } + // 可信 → 不覆盖 + if models.IsReliableQuality(dbQuality) { + return dbQuality + } + // 不可信 → 仅当 fallback 开启时用 proof 兜底 + if proofFallbackEnabled { + if p := QualityFromProof(m); p > 0 { + return p + } + } + return dbQuality +} \ No newline at end of file diff --git a/go/internal/storage/quality_from_proof_test.go b/go/internal/storage/quality_from_proof_test.go new file mode 100644 index 0000000..7f693fc --- /dev/null +++ b/go/internal/storage/quality_from_proof_test.go @@ -0,0 +1,139 @@ +package storage + +import ( + "testing" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// TestProofCount 2026-10-13 t_e9a4d18f P1:ProofCount 派生正确性。 +func TestProofCount(t *testing.T) { + // 空证据 → 0 + if got := ProofCount(&models.MemoryRecord{}); got != 0 { + t.Fatalf("空记录 ProofCount=%d, 期望 0", got) + } + // nil 记录 → 0 + if got := ProofCount(nil); got != 0 { + t.Fatalf("nil 记录 ProofCount=%d, 期望 0", got) + } + // 仅单亲 DerivedFrom(存量)→ 1 + if got := ProofCount(&models.MemoryRecord{DerivedFrom: "ep_1"}); got != 1 { + t.Fatalf("仅 DerivedFrom ProofCount=%d, 期望 1", got) + } + // SourceEvents 多条 → distinct 计数 + m := &models.MemoryRecord{SourceEvents: []string{"ep_1", "ep_2", "ep_1", "ep_3"}} + if got := ProofCount(m); got != 3 { + t.Fatalf("SourceEvents[ep1,ep2,ep1,ep3] ProofCount=%d, 期望 3(distinct)", got) + } + // SourceEvents 含空串 → 排除空串计数 + m2 := &models.MemoryRecord{SourceEvents: []string{"ep_1", "", "ep_1"}} + if got := ProofCount(m2); got != 1 { + t.Fatalf("含空串 ProofCount=%d, 期望 1", got) + } + t.Log("ProofCount 派生 ✓ (distinct, 空串排除, 单亲兼容)") +} + +// TestQualityFromProof 2026-10-13 t_e9a4d18f P1:证据条数 → 饱和质量分。 +func TestQualityFromProof(t *testing.T) { + oldK := proofSaturation + proofSaturation = 5 + defer func() { proofSaturation = oldK }() + + // 0 证据 → 0 + if got := QualityFromProof(&models.MemoryRecord{}); got != 0 { + t.Fatalf("0 证据质量=%.4f, 期望 0", got) + } + // 1 证据 → 1/6 ≈ 0.167 + if got := QualityFromProof(&models.MemoryRecord{SourceEvents: []string{"e1"}}); got < 0.16 || got > 0.17 { + t.Fatalf("1 证据质量=%.4f, 期望≈0.167", got) + } + // 5 证据 → 5/10 = 0.5 + if got := QualityFromProof(&models.MemoryRecord{SourceEvents: []string{"e1", "e2", "e3", "e4", "e5"}}); got < 0.49 || got > 0.51 { + t.Fatalf("5 证据质量=%.4f, 期望≈0.5", got) + } + // 10 证据 → 10/15 ≈ 0.667 + m10 := make([]string, 10) + for i := range m10 { + m10[i] = "e" + string(rune('a'+i)) + } + if got := QualityFromProof(&models.MemoryRecord{SourceEvents: m10}); got < 0.66 || got > 0.68 { + t.Fatalf("10 证据质量=%.4f, 期望≈0.667", got) + } + t.Log("QualityFromProof 饱和 ✓ (x/(x+5): 0→0, 1→0.167, 5→0.5, 10→0.667)") +} + +// TestResolveQuality 2026-10-13 t_e9a4d18f P1:质量兜底行为。 +// - 可信 quality(非 0/0.755)→ 不被覆盖 +// - 不可信 quality(0/0.755)+ fallback 关 → 原值(行为零变化) +// - 不可信 quality + fallback 开 → 用 QualityFromProof +func TestResolveQuality(t *testing.T) { + oldFallback := proofFallbackEnabled + defer func() { proofFallbackEnabled = oldFallback }() + + // 可信 quality → 不被覆盖(无论 fallback 状态) + proofFallbackEnabled = true + mTrust := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0.8} + if got := ResolveQuality(mTrust, 0.8); got != 0.8 { + t.Fatalf("可信 quality 被覆盖: got=%.4f, 期望 0.8", got) + } + + // 不可信 quality(0) + fallback 关 → 原值 0 + proofFallbackEnabled = false + mZero := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0} + if got := ResolveQuality(mZero, 0); got != 0 { + t.Fatalf("fallback 关时 0 quality 被改: got=%.4f, 期望 0", got) + } + + // 不可信 quality(0) + fallback 开 → 用 QualityFromProof + proofFallbackEnabled = true + if got := ResolveQuality(mZero, 0); got <= 0 { + t.Fatalf("fallback 开时 0 quality 未兜底: got=%.4f", got) + } + + // 不可信 quality(0.755 echo) + fallback 开 → 兜底 + mEcho := &models.MemoryRecord{SourceEvents: []string{"e1", "e2", "e3"}, QualityScore: 0.755} + if got := ResolveQuality(mEcho, 0.755); got <= 0 { + t.Fatalf("fallback 开时 0.755 quality 未兜底: got=%.4f", got) + } + t.Log("ResolveQuality 兜底 ✓ (可信不覆盖, fallback关原值, fallback开proof替代)") +} + +// TestQualityFromProofSorter 2026-10-13 t_e9a4d18f P1 AC#3:区分度。 +// 构造:两条都是 0.755 echo 分、无 SourceEvents 的存量行(quality 恒 0.755 不可分), +// 一条带 2 条证据、一条带 1 条证据。开启 fallback 后两条的**可排序质量分**出现差。 +// 这是「区分度提升」的影子证据:fallback 前 0.755==0.755 无法区分,fallback 后 0.4 vs 0.167。 +func TestQualityFromProofSorter(t *testing.T) { + oldK := proofSaturation + oldFallback := proofFallbackEnabled + proofSaturation = 5 + proofFallbackEnabled = true + defer func() { proofSaturation = oldK; proofFallbackEnabled = oldFallback }() + + m1 := &models.MemoryRecord{SourceEvents: []string{"e1", "e2"}, QualityScore: 0.755} + m2 := &models.MemoryRecord{SourceEvents: []string{"e1"}, QualityScore: 0.755} + + q1 := ResolveQuality(m1, 0.755) + q2 := ResolveQuality(m2, 0.755) + if q1 <= q2 { + t.Fatalf("区分度未提升: q1(2证据)=%.4f <= q2(1证据)=%.4f, 期望 q1>q2", q1, q2) + } + t.Logf("区分度提升 ✓ fallback 后: 2证据=%.4f vs 1证据=%.4f(fallback 前两者恒 0.755 不可分)", q1, q2) +} + +// TestSourceEventsSerialization 2026-10-13 t_e9a4d18f P1:seJSON/parseSourceEvents 往返。 +func TestSourceEventsSerialization(t *testing.T) { + if got := seJSON(nil); got != "[]" { + t.Fatalf("seJSON(nil)=%q, 期望 []", got) + } + if got := seJSON([]string{"ep_1", "ep_2"}); got != `["ep_1","ep_2"]` { + t.Fatalf("seJSON=%q, 期望 [\"ep_1\",\"ep_2\"]", got) + } + round := parseSourceEvents(seJSON([]string{"ep_1", "ep_2"})) + if len(round) != 2 || round[0] != "ep_1" || round[1] != "ep_2" { + t.Fatalf("roundtrip=%v", round) + } + if got := parseSourceEvents(""); got != nil { + t.Fatalf("parseSourceEvents(\"\")=%v, 期望 nil", got) + } + t.Log("SourceEvents JSON 往返 ✓") +} \ No newline at end of file diff --git a/go/internal/storage/recall.go b/go/internal/storage/recall.go index 328c613..9d6eb60 100644 --- a/go/internal/storage/recall.go +++ b/go/internal/storage/recall.go @@ -313,15 +313,17 @@ func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diver } kwScore := ComputeBM25Score(query, candidates[i].Content) // 融合: vector score (quality) * 0.7 + keyword score * 0.3 - if models.IsReliableQuality(qsForTrust) { + // 2026-10-13 (t_e9a4d18f P1):不可信质量分(0/0.755 echo)时,若 + // ZHIYI_PROOF_FALLBACK=1 则用 QualityFromProof(证据条数)兜底替代。 + // 默认关 ⇒ 行为零变化。这是「兜底」不是「替换」——已有可信 quality 不受影响。 + effQuality := ResolveQuality(&candidates[i], dbQuality[i]) + if models.IsReliableQuality(effQuality) { candidates[i].QualityScore = dbQuality[i]*0.7 + kwScore*0.3 } else { // 存量分数不可信(0=未打分 / 0.755=历史常量 bug,见 models.IsReliableQuality) // → 不拿假分数参与排序,权重全部让给关键词分。 // 注意这是**中性**处理:既不奖励也不惩罚,只是不采信。 if qstrustVerbose { - // 默认静音:每次召回会命中上百条,全量打印是生产噪音。 - // 需要诊断时置环境变量 ZHIYI_QSTRUST_VERBOSE=1。 log.Printf("[qstrust] 不可信质量分已剔除 id=%s rawQS=%.6f → 回退纯关键词分 %.4f", candidates[i].ID, qsForTrust, kwScore) } diff --git a/go/internal/storage/recall.go.bak.proofchain-20261014-005204 b/go/internal/storage/recall.go.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..9d6eb60 --- /dev/null +++ b/go/internal/storage/recall.go.bak.proofchain-20261014-005204 @@ -0,0 +1,749 @@ +// Package storage 提供记忆召回完成管线:编码 → 向量搜索 → 重排 → MMR → 图谱扩展 → 预取推送 +package storage + +import ( + "encoding/json" + "fmt" + "log" + "math" + "os" + "strconv" + "strings" + "time" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// ── 2026-10-08 (Gap#2 来源加权):门控参数 ────────────────────────────── +// +// 设计取舍(MoA 评审采纳): +// +// · 默认 λ=0 ⇒ **首日 no-op**。存量 15105 条 confidence 全为 NULL, +// 此时任何加权都只是在噪声上做乘法。先接线、采分布,再定系数。 +// · 形式为**加性去中心偏置** base + λ(conf − mean),而非乘性 base*conf: +// memories 表 100% 经 LLM 蒸馏(server.go 唯一 InsertMemory 调用点), +// 乘性会把整批蒸馏产物一起压沉,并与 QualityScore 在同一根轴上二次惩罚。 +// 加性只平移均值、不缩方差,对尾部排序影响可控。 +// · 启用 = 改环境变量,不改代码(可回滚,无需重新构建)。 +// +// 启用前必做(护栏,见设计文档):跨 namespace 公平性检查 + distill 召回配额下限。 +var ( + confidenceLambda = envFloat("ZHIYI_CONFIDENCE_LAMBDA", 0) // 0 = 关闭 + confidenceMean = envFloat("ZHIYI_CONFIDENCE_MEAN", 0.7) // 去中心基准 + // t_be3e958a 来源分层偏置:决策类来源(wiki:decision 等)在 MMR 之前加性加分, + // 让「我们定了什么/阈值怎么定的」这类问题召回出决定本体而非流水。0 = 关闭。 + // 流水类(llm_distill/episode)不加分也不降权——偏置只抬决策,不动流水的相对位次。 + sourceTierBias = envFloat("ZHIYI_SOURCE_TIER_BIAS", 0) // 0 = 关闭 + // 2026-10-13 反馈回路接通(t_8f1f6e5e):per-memory 反馈计数加性偏置。 + // 0 = 关闭(默认)⇒ 与旧实现逐位等价,回滚只需把环境变量置 0。 + feedbackBias = envFloat("ZHIYI_FEEDBACK_BIAS", 0) + // 2026-10-13 时间维检索(t_e9a4d18f P0):recency 加性偏置。 + // 0 = 关闭(默认)⇒ 行为零变化,回滚只需置 0。 + // 形式:+timeDecayBias * recency(UpdatedAt),recency ∈ [0,1], + // 新条目趋 1(上移)、旧条目趋 0(不抬)。直接在 MMR 之前施加 + // (recall.go:325-331 的既有教训:加在 MMR 之后只改数字、不改结果集合)。 + // 半衰期决定「多旧算旧」:age 超过半衰期的条目 recency 降到 0.5 以下。 + timeDecayBias = envFloat("ZHIYI_TIME_DECAY", 0) + timeDecayHalflife = envFloat("ZHIYI_TIME_DECAY_HALFLIFE_HOURS", 24*30) // 默认 30 天 + // 2026-10-13 时间维检索(t_e9a4d18f P0):stale 标记。 + // updated_at 距今超过该小时数 ⇒ 响应带 stale:true,让调用方「看见」可能过期。 + // 0 = 关闭(默认)⇒ 不产生任何 stale 标记,行为零变化。 + staleAfterHours = envFloat("ZHIYI_STALE_AFTER_HOURS", 0) +) + +func envFloat(key string, def float64) float64 { + if v := os.Getenv(key); v != "" { + if f, err := strconv.ParseFloat(v, 64); err == nil { + return f + } + log.Printf("[confidence] %s=%q 无法解析为浮点,回落默认 %v", key, os.Getenv(key), def) + } + return def +} + +// coalesceConfidence 2026-10-08 (Gap#2):NULL(存量未声明)⇒ 1.0。 +// 这是「加权首日 no-op」的实现基础:存量行不因缺字段被系统性惩罚。 +// 注意这是**读时兜底**,不是回填——库里仍是 NULL,可随时区分「未声明」与「声明为 1.0」。 +func coalesceConfidence(c *float64) float64 { + if c == nil { + return 1.0 + } + return *c +} + +// isDecisionSource t_be3e958a:来源分层偏置的决策类判定。 +// source 归一后含 "decision"(wiki:decision / decision / wiki:decision:vault 等)即算决策来源。 +// 归一步骤:TrimSpace → TrimPrefix("wiki:") → ToLower,与 graph_auto.go 的 source 归一保持一致。 +func isDecisionSource(source string) bool { + s := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(source), "wiki:")) + return strings.Contains(s, "decision") +} + +// recency 2026-10-13 (t_e9a4d18f P0):把 updated_at 折成 [0,1] 的新鲜度。 +// 指数半衰:recency = 0.5^(age/halflife)。age=0 → 1(最新);age=halflife → 0.5; +// age→∞ → 0。零值时间(time.Time{})视为最新(不惩罚缺失时间戳的存量行)。 +// 半衰期 halflifeHours<=0 时回退 1.0(=不衰减,保守)。 +func recency(updated time.Time, halflifeHours float64) float64 { + if updated.IsZero() { + return 1.0 + } + if halflifeHours <= 0 { + return 1.0 + } + ageHours := time.Since(updated).Hours() + if ageHours <= 0 { + return 1.0 + } + return math.Pow(0.5, ageHours/halflifeHours) +} + +// isStale 2026-10-13 (t_e9a4d18f P0):updated_at 距今是否超过阈值(小时)。 +// threshold<=0 ⇒ 恒 false(stale 标记关闭,行为零变化)。 +func isStale(updated time.Time, thresholdHours float64) bool { + if thresholdHours <= 0 || updated.IsZero() { + return false + } + return time.Since(updated).Hours() > thresholdHours +} + +// MissRecorder 缺口记录接口(由 routes 层注入 gapDetector.RecordMiss) +type MissRecorder func(query, namespace string) + +// PrefetchPusher 预取推送接口(由 routes 层注入) +type PrefetchPusher interface { + PushPrefetch(agentID string, memories []models.RecallResult) +} + +// GraphExpander 图谱扩展接口(由 governance 层注入) +type GraphExpander interface { + ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult +} + +type RecallPipeline struct { + embedder *Embedder + lancedb LanceDB + reranker *Reranker + graph GraphExpander + prefetch PrefetchPusher + recordMiss MissRecorder +} + +func NewRecallPipeline(embedder *Embedder, lancedb LanceDB, reranker *Reranker) *RecallPipeline { + return &RecallPipeline{ + embedder: embedder, + lancedb: lancedb, + reranker: reranker, + } +} + +// SetGraphExpander 注入图谱扩展器 +func (p *RecallPipeline) SetGraphExpander(g GraphExpander) { + p.graph = g +} + +// SetPrefetchPusher 注入预取推送器 +func (p *RecallPipeline) SetPrefetchPusher(pf PrefetchPusher) { + p.prefetch = pf +} + +// SetMissRecorder 注入缺口记录器(gapDetector.RecordMiss) +func (p *RecallPipeline) SetMissRecorder(mr MissRecorder) { + p.recordMiss = mr +} + +// qstrustVerbose 控制"不可信质量分已剔除"的逐条日志。 +// 默认关闭:一次召回可命中上百条,全量打印会淹没生产日志。 +// 诊断时置 ZHIYI_QSTRUST_VERBOSE=1。 +var qstrustVerbose = os.Getenv("ZHIYI_QSTRUST_VERBOSE") == "1" + +// RecallMeta RecallWithMeta 返回的召回元数据(t_949840b1:candidates_scanned 名实相符)。 +// CandidatesScanned = 粗检索候选池真实大小(LanceDB ANN 检索返回 + 去重 + +// 原始对话过滤之后的候选数,在 rerank/MMR 截断之前捕获)。 +// 这才是 recall API 里 candidates_scanned 字段的真实语义——此前误用 +// len(results)(最终产出数)作代理值,字段名说 "scanned"(扫描候选池)值却是"产出数"。 +// +// CacheHit(t_1c12e000):本次结果是否直接来自缓存(未回源扫表)。 +// 事故根因之一是调用方无法区分 candidates_scanned=0 到底是「真没扫到」 +// 还是「读了 1h 前的旧快照」⇒ 响应里必须显式给出 cache_hit。 +// 约定:缓存命中无法重建候选池 ⇒ CandidatesScanned=0(保守)且 CacheHit=true; +// 回源扫表 ⇒ CacheHit=false(此时 CandidatesScanned 为真实候选池大小)。 +type RecallMeta struct { + CandidatesScanned int + CacheHit bool +} + +// RecallWithMeta 同 Recall,但额外返回召回元数据(候选池真实大小 + 是否命中缓存)。 +// 缓存命中时无法重建候选池 ⇒ CandidatesScanned = 0(保守:无法测量就报 0,不虚报)。 +func (p *RecallPipeline) RecallWithMeta(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) { + // topK 先归一:缓存键必须与写入侧用的 topK 一致。recallUncached 内部也会归一, + // 若此处不先归一,topK<=0 的调用读到的是"归一前的键"、永远命中不了自己写的条目。 + if topK <= 0 { + topK = 10 + } + // 缓存命中分支:直接返回,候选池不可重建 + if SearchCacheInstance != nil { + if cached, ok := SearchCacheInstance.Get(query, namespace, topK, diversity); ok { + var results []models.RecallResult + if err := json.Unmarshal(cached, &results); err == nil { + filtered := filterRecallRawCategories(results) + if len(filtered) == 0 && len(results) > 0 { + filtered = results + } + p.recordRecallWrites(filtered) + // t_1c12e000:命中缓存 ⇒ 显式告知调用方(candidates_scanned 恒 0) + return filtered, RecallMeta{CacheHit: true}, nil + } + } + } + return p.recallUncached(query, namespace, topK, diversity) +} + +// Recall 保持原签名(缓存 + 全量流程),行为不变。 +func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity float64) ([]models.RecallResult, error) { + results, _, err := p.RecallWithMeta(query, namespace, topK, diversity) + return results, err +} + +// recallUncached Recall 的非缓存路径。候选池大小在 Step 2.5 过滤后、 +// Step 3 截断前捕获(真实粗检索池,不是最终产出数)。 +func (p *RecallPipeline) recallUncached(query, namespace string, topK int, diversity float64) ([]models.RecallResult, RecallMeta, error) { + if topK <= 0 { + topK = 10 + } + + // Step 1: Encode query + queryVec, err := p.embedder.EncodeQuery(query) + if err != nil { + return nil, RecallMeta{}, fmt.Errorf("recall encode: %w", err) + } + + // Step 2: Coarse search — own namespace + shared(§1.3 召回规则) + // 默认搜自己的 namespace + shared,显式 include_namespaces 时才跨域 + // 2026-09-21 五修(t_24eceed0 返修):namespace=="" → 全库跨命名空间召回。 + // 根因:写入侧把记忆按 agent/域分到 *-main / wiki / soulful-xiaowei / domain:* 等 + // 19 个命名空间(实测 hermes-main 139、wiki-curator-main 35、wiki 30、soulful-xiaowei 27、 + // a06-main 11 …),而默认调用只搜 default-main + shared + // ⇒ 默认召回只能看到极小一片(全表 10172 条,默认调用实测仅 11 个候选)。 + // 显式传 namespace / agent_id 时保持原作用域行为,不改变调用方语义。 + var candidates []models.MemoryRecord + if namespace == "" { + all, err := p.lancedb.Search("memories", queryVec, 200, "") // 空 ns = 不过滤 = 全库 + if err == nil { + candidates = append(candidates, all...) + } + } else { + namespaces := []string{namespace} + if namespace != "shared" { + namespaces = append(namespaces, "shared") + } + for _, ns := range namespaces { + nsResults, err := p.lancedb.Search("memories", queryVec, 50, ns) + if err != nil { + continue + } + candidates = append(candidates, nsResults...) + } + } + // 去重(按 ID) + seen := make(map[string]bool) + unique := make([]models.MemoryRecord, 0, len(candidates)) + for _, c := range candidates { + if !seen[c.ID] { + seen[c.ID] = true + unique = append(unique, c) + } + } + candidates = unique + + // Step 2.5: 过滤原始对话内容(category=episodes/对话/对话记录) + // 原因:原始对话未蒸馏,不应出现在 recall 结果中 + // 蒸馏产物通过 OnDistillComplete callback 写入 memories(category=distilled) + filtered := make([]models.MemoryRecord, 0, len(candidates)) + rawCategories := map[string]bool{ + "episodes": true, + "对话": true, + "对话记录": true, + "raw": true, + "episodic": true, + } + for _, c := range candidates { + if !rawCategories[c.Category] { + filtered = append(filtered, c) + } + } + // 过滤后若为空,降级回原行为(避免 recall 完全失效) + if len(filtered) == 0 && len(candidates) > 0 { + filtered = candidates + } + // 记录过滤数量(用于调试) + filteredCount := len(candidates) - len(filtered) + if filteredCount > 0 { + log.Printf("[recall] filtered %d raw episode/dialogue candidates, %d remain", filteredCount, len(filtered)) + } + candidates = filtered + + // 候选池真实大小捕获点:LanceDB ANN 返回 + 去重 + 原始对话过滤之后、 + // 截断/rerank/MMR 之前 —— 这才是 "scanned candidates" 的真实含义。 + poolSize := len(candidates) + + // 截断候选池(全库模式候选来自更多命名空间,池子放宽到 100) + candCap := 50 + if namespace == "" { + candCap = 100 + } + if len(candidates) > candCap { + candidates = candidates[:candCap] + } + + // Step 3.5: BM25 keyword scoring — amplify keyword-relevant results + // t_631ab13d: 先抓 DB 原始 quality_score(candidates[i].QualityScore), + // 因为下面会原地覆盖为 BM25 融合值(0.7*dbQuality + 0.3*kwScore)。 + // 响应需要展示 DB 原值("响应值==库值"),不能展示被融合改写后的值。 + dbQuality := make([]float64, len(candidates)) + if len(candidates) > 0 { + for i := range candidates { + dbQuality[i] = candidates[i].QualityScore + // 可信度判定必须用 **DB 原始列值**:candidates[i].QualityScore 在 IPC 路径下 + // 是**已融合且会饱和到 1.0** 的值(实测 candidateQS=1.0 / rawQS=0.755), + // 拿它去判永远"可信" ⇒ 修复不触发(2026-10-12 实测踩到)。 + // RawQualityScore 仅在 Rust IPC 路径携带;纯 Go 路径下候选值即 DB 原值。 + qsForTrust := dbQuality[i] + if candidates[i].RawQualityScore != nil { + qsForTrust = *candidates[i].RawQualityScore + } + kwScore := ComputeBM25Score(query, candidates[i].Content) + // 融合: vector score (quality) * 0.7 + keyword score * 0.3 + // 2026-10-13 (t_e9a4d18f P1):不可信质量分(0/0.755 echo)时,若 + // ZHIYI_PROOF_FALLBACK=1 则用 QualityFromProof(证据条数)兜底替代。 + // 默认关 ⇒ 行为零变化。这是「兜底」不是「替换」——已有可信 quality 不受影响。 + effQuality := ResolveQuality(&candidates[i], dbQuality[i]) + if models.IsReliableQuality(effQuality) { + candidates[i].QualityScore = dbQuality[i]*0.7 + kwScore*0.3 + } else { + // 存量分数不可信(0=未打分 / 0.755=历史常量 bug,见 models.IsReliableQuality) + // → 不拿假分数参与排序,权重全部让给关键词分。 + // 注意这是**中性**处理:既不奖励也不惩罚,只是不采信。 + if qstrustVerbose { + log.Printf("[qstrust] 不可信质量分已剔除 id=%s rawQS=%.6f → 回退纯关键词分 %.4f", + candidates[i].ID, qsForTrust, kwScore) + } + candidates[i].QualityScore = kwScore + } + } + } + + if len(candidates) == 0 { + // 自动记录召回缺口(gap_scan 触发器会在 30min 冷却后分类) + if p.recordMiss != nil { + p.recordMiss(query, namespace) + } + return []models.RecallResult{}, RecallMeta{CandidatesScanned: poolSize}, nil + } + + // Step 3: Rerank to top_k (graceful fallback) + // 2026-09-28:优先用「已有向量」重排 —— queryVec 来自 Step 1,候选记录自带 LanceDB + // 存储的 Vector,直接算 cosine 即可。旧实现把 query + 50~100 条候选文档重新送进 + // 嵌入服务(int8 ONNX CPU),占 recall 总耗时 90%+,是 Hermes 记忆预取 8s 预算 + // 被打爆的直接原因。向量不齐/维度不符时自动回退文本重排(行为与旧版一致)。 + docs := make([]string, len(candidates)) + docVecs := make([][]float32, len(candidates)) + for i, c := range candidates { + docs[i] = c.Content + docVecs[i] = c.Vector + } + reranked, err := p.reranker.RerankWithVectors(queryVec, docs, docVecs, topK*2) + if err != nil { + log.Printf("[recall] 向量重排跳过(%v),回退文本重排", err) + reranked, err = p.reranker.Rerank(query, docs, topK*2) + } + if err != nil { + // 重排不可用时降级:直接使用向量搜索的原始排序 + reranked = make([]models.RerankResult, len(candidates)) + for i := range candidates { + reranked[i] = models.RerankResult{Index: i, Score: 0.5, Text: candidates[i].Content} + } + } + + // Step 3.7: 来源加权偏置(2026-10-09 P0 修正) + // + // 修前的错位:λ 只加在 Step 4 之后的**展示分**上,而候选的取舍早已由 rerank+MMR 定死 + // ⇒ λ 无论取多大都只改返回的数字、不改结果集合。实测(λ=0.1 vs 0,同一批 14 条 query, + // 全部 cache-miss):逐条分数位移与理论吻合(legacy -0.0277 / conf1.0 +0.0294), + // 但 top-10 集合与 legacy 占比 33.57% 两轮完全相同 —— 典型的"接上了但接在阀门下游"。 + // + // 现在把偏置移到 MMR 之前:选择与展示共用同一套分数(rel = r.Score,见 MMRSelect)。 + // λ=0 时本循环不执行 ⇒ 与旧实现逐字节等价,回滚只需把环境变量置 0。 + if confidenceLambda > 0 { + for i := range reranked { + idx := reranked[i].Index + if idx >= 0 && idx < len(candidates) { + conf := coalesceConfidence(candidates[idx].Confidence) + reranked[i].Score += confidenceLambda * (conf - confidenceMean) + } + } + } + + // t_be3e958a 来源分层偏置(紧邻 confidenceLambda,同样在 MMR 之前): + // 决策类来源(source 含 "decision",如 wiki:decision / decision)加性加分 + // sourceTierBias。只抬决策、不动流水/其它来源 —— 避免偏置挤压本应排前的流水。 + // sourceTierBias=0 时本循环不执行 ⇒ 与旧实现逐位等价,回滚只需把环境变量置 0。 + if sourceTierBias > 0 { + for i := range reranked { + idx := reranked[i].Index + if idx >= 0 && idx < len(candidates) && isDecisionSource(candidates[idx].Source) { + reranked[i].Score += sourceTierBias + } + } + } + + // 2026-10-13 反馈回路接通(t_8f1f6e5e):per-memory 反馈计数加性偏置。 + // 与 confidenceLambda / sourceTierBias 同款:默认 0 ⇒ 本循环不执行 ⇒ + // 与旧实现逐位等价,回滚只需把 ZHIYI_FEEDBACK_BIAS 置 0。 + // 放在 MMR 之前 ⇒ 选择与展示共用同一套分数(recall.go:325-331 的既有教训: + // 偏置加在 MMR 之后就只改数字、不改结果集合)。 + if feedbackBias > 0 { + for i := range reranked { + idx := reranked[i].Index + if idx >= 0 && idx < len(candidates) { + reranked[i].Score += feedbackBias * FeedbackScore(&candidates[idx]) + } + } + } + + // 2026-10-13 时间维检索(t_e9a4d18f P0):recency 加性偏置。 + // 与 confidenceLambda / sourceTierBias / feedbackBias 同款:默认 0 ⇒ 本循环 + // 不执行 ⇒ 与旧实现逐位等价,回滚只需把 ZHIYI_TIME_DECAY 置 0。 + // 放在 MMR 之前 ⇒ 选择与展示共用同一套分数(见 recall.go:325-331 教训)。 + if timeDecayBias > 0 { + for i := range reranked { + idx := reranked[i].Index + if idx >= 0 && idx < len(candidates) { + reranked[i].Score += timeDecayBias * recency(candidates[idx].UpdatedAt, timeDecayHalflife) + } + } + } + + // Step 4: MMR diversity + finalIndices := MMRSelect(reranked, candidates, topK*2, diversity) + + results := make([]models.RecallResult, 0, topK) + for i, idx := range finalIndices { + if i >= topK { + break + } + if idx < len(candidates) { + c := candidates[idx] + score := 0.0 + for _, r := range reranked { + if r.Index == idx { + score = r.Score + break + } + } + // 2026-10-08 (Gap#2 来源加权):把信任等级直通给调用方,并按门控参与排序。 + // + // 为什么默认关闭(λ=0):存量 15105 条 confidence 全为 NULL,此时任何加权都只是 + // 在噪声上做乘法。按 MoA 评审:先跑一周采分布 → 定 λ 与形式 → 再带护栏启用。 + // 因此 P0 只接线不改行为(no-op),启用是改环境变量,不是改代码。 + // + // 为什么是**加性去中心偏置**而非乘性: + // 乘性 base*conf 会把全部 LLM 蒸馏产物整体压沉(memories 表 100% 经蒸馏, + // 见 server.go 唯一 InsertMemory 调用点),并与 QualityScore 在同一根轴上二次惩罚; + // 加性 base+λ(conf-mean) 只平移均值、不缩方差,对尾部排序影响可控。 + conf := coalesceConfidence(c.Confidence) + // 2026-10-09 (P0 修正):λ 已在 Step 3.7 偏置进 reranked[i].Score,选择与展示 + // 共用同一套分数;此处不再重复施加(否则 legacy 被双重扣分)。 + base := score*0.7 + c.QualityScore*0.3 + // 2026-10-11 (t_631ab13d):把库里的 quality_score / v_value 直通给调用方。 + // 展示 DB 原值("响应值==库值"判据):优先用 RawQualityScore(LanceDB 原始列, + // 仅 Rust IPC 路径携带,json:"-" 不落库);否则退回 DB 捕获值 dbQuality[idx] + // (纯 Go 后端候选的 QualityScore 即 DB 原值,未被融合改写)。 + // 排序用 c.QualityScore(IPC=融合值 / 纯Go=BM25融合值)不变,只补显示缺口。 + vv := 0.0 + if VValueProvider != nil { + vv = VValueProvider(c.ID) + } + var qs *float64 + if c.RawQualityScore != nil { + qs = c.RawQualityScore // LanceDB 原始列值(IPC 路径) + } else if idx >= 0 && idx < len(dbQuality) { + v := dbQuality[idx] + qs = &v // 纯 Go 后端:DB 捕获值 + } + qsVal := 0.0 + if qs != nil { + qsVal = *qs + } + results = append(results, models.RecallResult{ + ID: c.ID, + Content: c.Content, + Category: c.Category, + Score: base, + Timestamp: c.CreatedAt.Format(time.RFC3339), + Namespace: c.Namespace, + AgentID: c.AgentID, + Source: c.Source, + Confidence: &conf, + ConfidenceSource: c.ConfidenceSource, + QualityScore: qsVal, + QualityScoreReliable: models.IsReliableQuality(qsVal), + VValue: vv, + // 2026-10-13 (t_e9a4d18f P0):过期标记(默认关闭 ⇒ 恒 false 不输出) + Stale: isStale(c.UpdatedAt, staleAfterHours), + }) + } + } + + // Step 5: 图谱融合扩展(不再作为后备补丁,每次 recall 都跑 1 跳) + if p.graph != nil { + expanded := p.graph.ExpandFromResults(results, namespace, 1) + for _, e := range expanded { + already := false + for _, r := range results { + if r.ID == e.ID { + already = true + break + } + } + if !already { + results = append(results, e) + } + } + } + + // Step 6: 去重(相同 content 只保留最高分) + seenContent := make(map[string]bool) + deduped := make([]models.RecallResult, 0, len(results)) + for _, r := range results { + if !seenContent[r.Content] { + seenContent[r.Content] = true + deduped = append(deduped, r) + } + } + results = deduped + + // Step 6.5: 写搜索缓存(§2.6 — t_1c12e000 起 TTL=60s,下次相同 query+topK+diversity + // 直接返回;写路径落库后会 Invalidate 本 namespace,陈旧窗口上限=60s 双保险) + if SearchCacheInstance != nil { + SearchCacheInstance.Set(query, namespace, topK, diversity, results) + } + + // Step 7: 预取推送(CO_OCCURS 权重 > 0.6 的配套记忆 → WebSocket) + if p.prefetch != nil { + // 使用 CO_OCCURS 追踪器收集真实预取候选项 + var prefetchIDs []string + for _, r := range results { + if r.ID != "" { + prefetchIDs = append(prefetchIDs, r.ID) + } + } + if len(prefetchIDs) > 0 { + // 记录共访统计到 CO_OCCURS tracker + if CoOccurTrackerInstance != nil { + CoOccurTrackerInstance.RecordRecall(prefetchIDs, namespace) + candidates := CoOccurTrackerInstance.CollectCandidates(prefetchIDs) + if len(candidates) > 0 { + prefetchItems := make([]models.RecallResult, 0, len(candidates)) + for _, cid := range candidates { + prefetchItems = append(prefetchItems, models.RecallResult{ID: cid}) + } + p.prefetch.PushPrefetch("", prefetchItems) + } + } + } + } + + // 召回元数据写(2026-09-12 优化B:累积延迟更新) + // 旧实现:对每条结果同步 lancedb.Update → LanceDB MVCC 每写一行一个版本 + // (实测 15 版本/分钟 → _versions 膨胀到 17.7G,根因所在) + // 现在:只把命中 ID 放进 RecallWriteBuffer,后台按窗口批量单事务提交(每批 1 个版本) + p.recordRecallWrites(results) + + // 共访追踪(即使无 prefetch pusher 也运行,用于持久化) + go func() { + if len(results) == 0 { + return + } + var ids []string + for _, r := range results { + if r.ID != "" { + ids = append(ids, r.ID) + } + } + if len(ids) > 0 && CoOccurTrackerInstance != nil { + CoOccurTrackerInstance.RecordRecall(ids, namespace) + } + }() + + return results, RecallMeta{CandidatesScanned: poolSize}, nil +} + +// ComputeBM25Score 基于词频的关键词匹配分数 +func ComputeBM25Score(query, doc string) float64 { + queryTerms := strings.Fields(strings.ToLower(query)) + docLower := strings.ToLower(doc) + hitCount := 0 + for _, term := range queryTerms { + if len(term) < 2 { + continue + } + count := strings.Count(docLower, term) + if count > 0 { + hitCount += count + } + } + if hitCount == 0 { + return 0 + } + // 归一化到 [0, 1] + score := float64(hitCount) / float64(len(queryTerms)) + if score > 1.0 { + score = 1.0 + } + return score +} + +// jaccardBigramSimilarity 计算两个文本的字符 bigram Jaccard 相似度(用于 MMR 去重) +func jaccardBigramSimilarity(a, b string) float64 { + bgA := make(map[string]bool) + bgB := make(map[string]bool) + runes := []rune(a) + for i := 0; i < len(runes)-1; i++ { + bgA[string(runes[i:i+2])] = true + } + runes = []rune(b) + for i := 0; i < len(runes)-1; i++ { + bgB[string(runes[i:i+2])] = true + } + if len(bgA) == 0 && len(bgB) == 0 { + return 1.0 // 两个空文本视为相同 + } + if len(bgA) == 0 || len(bgB) == 0 { + return 0.0 + } + intersection := 0 + for k := range bgA { + if bgB[k] { + intersection++ + } + } + union := len(bgA) + len(bgB) - intersection + if union == 0 { + return 0.0 + } + return float64(intersection) / float64(union) +} + +// MMRSelect 多样性去重 — 使用文本 bigram Jaccard 相似度(向量由 Rust LanceDB 返回但为空,改用文本) +func MMRSelect(reranked []models.RerankResult, candidates []models.MemoryRecord, k int, lambda float64) []int { + if len(reranked) == 0 { + return nil + } + selected := make([]int, 0, k) + cand := make([]int, len(reranked)) + for i := range reranked { + cand[i] = reranked[i].Index + } + + for len(selected) < k && len(cand) > 0 { + bestIdx := 0 + bestScore := -math.MaxFloat64 + for i, ci := range cand { + rel := 0.0 + for _, r := range reranked { + if r.Index == ci { + rel = r.Score + break + } + } + maxSim := 0.0 + for _, si := range selected { + if si < len(candidates) && ci < len(candidates) { + sim := jaccardBigramSimilarity(candidates[ci].Content, candidates[si].Content) + if sim > maxSim { + maxSim = sim + } + } + } + // MMR = (1-λ)*rel + λ*(1-maxSim) + mmr := (1-lambda)*rel + lambda*(1-maxSim) + if mmr > bestScore { + bestScore = mmr + bestIdx = i + } + } + selected = append(selected, cand[bestIdx]) + cand = append(cand[:bestIdx], cand[bestIdx+1:]...) + } + return selected +} + +func cosineSimilarity(a, b []float32) float64 { + var sum float64 + n := len(a) + if len(b) < n { + n = len(b) + } + for i := 0; i < n; i++ { + sum += float64(a[i]) * float64(b[i]) + } + return sum +} + +// recordRecallWrites 记录召回元数据写。 +// 主路径:累积延迟更新缓冲(RecallWriteBufferInstance)——读路径零同步写、批量单事务落盘。 +// 兜底:缓冲未初始化(如单测/独立调用)时退回旧的逐条异步 Update。 +func (p *RecallPipeline) recordRecallWrites(results []models.RecallResult) { + ids := make([]string, 0, len(results)) + for _, r := range results { + if r.ID != "" { + ids = append(ids, r.ID) + } + } + if len(ids) == 0 { + return + } + if RecallWriteBufferInstance != nil { + RecallWriteBufferInstance.Record(ids) + return + } + go p.incrementRecallCount(results) +} + +// incrementRecallCount 旧版逐条同步写(每条结果 = 1 个 LanceDB 版本)。 +// 已不作为主路径,仅保留为缓冲不可用时的兜底。 +func (p *RecallPipeline) incrementRecallCount(results []models.RecallResult) { + now := time.Now().Format(time.RFC3339) + for _, r := range results { + if r.ID != "" { + // t_268b0353(治根):兜底路径同样不写 freshness=verified("被召回"≠"被验证") + // GA-P0-2 (t_c6d41ac6):召回命中 → recall_seen_count(recall_count 冻结) + _ = p.lancedb.Update("memories", r.ID, map[string]any{ + "recall_seen_count": map[string]string{"$inc": "1"}, + "last_recalled_at": now, + }) + } + } +} + +// filterRecallRawCategories 从 RecallResult 列表中过滤原始对话类别 +// 用于 cache hit 路径,防止旧缓存包含的 episodes/对话污染 recall 结果 +func filterRecallRawCategories(results []models.RecallResult) []models.RecallResult { + rawCategories := map[string]bool{ + "episodes": true, + "对话": true, + "对话记录": true, + "raw": true, + "episodic": true, + } + filtered := make([]models.RecallResult, 0, len(results)) + for _, r := range results { + if !rawCategories[r.Category] { + filtered = append(filtered, r) + } + } + if len(filtered) == 0 { + return results // 降级:过滤后为空则返回原结果 + } + return filtered +} diff --git a/go/internal/storage/sqlite.go b/go/internal/storage/sqlite.go index 309cbc1..63492ad 100644 --- a/go/internal/storage/sqlite.go +++ b/go/internal/storage/sqlite.go @@ -101,6 +101,8 @@ func (sc *SQLiteClient) migrate() error { delete_reason TEXT DEFAULT '', depends_on TEXT DEFAULT '[]', derived_from TEXT DEFAULT '', + source_events TEXT DEFAULT '[]', + supersedes TEXT DEFAULT '[]', last_recalled_at TEXT DEFAULT '', created_at TEXT NOT NULL, updated_at TEXT NOT NULL @@ -170,6 +172,10 @@ func (sc *SQLiteClient) migrate() error { {"recall_verified_count", "ALTER TABLE memories ADD COLUMN recall_verified_count INTEGER DEFAULT 0"}, // GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(additive,TEXT 存固定枚举) {"delete_reason", "ALTER TABLE memories ADD COLUMN delete_reason TEXT DEFAULT ''"}, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(additive,TEXT JSON 数组) + {"source_events", "ALTER TABLE memories ADD COLUMN source_events TEXT DEFAULT '[]'"}, + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(additive) + {"supersedes", "ALTER TABLE memories ADD COLUMN supersedes TEXT DEFAULT '[]'"}, } { rows, err := sc.query("PRAGMA table_info(memories)") if err != nil { @@ -350,9 +356,9 @@ func (sc *SQLiteClient) InsertMemory(m models.MemoryRecord) error { defer sc.mu.Unlock() return sc.execWithArgs( `INSERT INTO memories(id,agent_id,namespace,content,category,vector,tier,importance,quality_score, - source,depends_on,derived_from,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`, + source,depends_on,derived_from,source_events,supersedes,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`, m.ID, m.AgentID, m.Namespace, m.Content, m.Category, vecBlob, m.Tier, - 1.0, m.QualityScore, "", "[]", "", now, now, + 1.0, m.QualityScore, "", "[]", m.DerivedFrom, seJSON(m.SourceEvents), seJSON(m.Supersedes), now, now, ) } @@ -388,7 +394,7 @@ func (sc *SQLiteClient) Scan(limit int, namespaceFilter string) ([]models.Memory sc.mu.RLock() defer sc.mu.RUnlock() - q := "SELECT id, content, category, namespace, importance, quality_score, recall_count, recall_seen_count, recall_verified_count, not_useful_count, human_not_useful_count, dedup_downweight_count, tier, source, created_at, updated_at FROM memories WHERE is_deleted=0" + q := "SELECT id, content, category, namespace, importance, quality_score, recall_count, recall_seen_count, recall_verified_count, not_useful_count, human_not_useful_count, dedup_downweight_count, tier, source, created_at, updated_at, source_events, supersedes FROM memories WHERE is_deleted=0" if namespaceFilter != "" { q += " AND namespace='" + sanitizeIdent(namespaceFilter) + "'" } @@ -409,6 +415,12 @@ func (sc *SQLiteClient) Scan(limit int, namespaceFilter string) ([]models.Memory rec.QualityScore, _ = row["quality_score"].(float64) rec.Tier, _ = row["tier"].(string) rec.Source, _ = row["source"].(string) + if se, ok := row["source_events"].(string); ok { + rec.SourceEvents = parseSourceEvents(se) // 2026-10-13 P1 + } + if ss, ok := row["supersedes"].(string); ok { + rec.Supersedes = parseSourceEvents(ss) // 2026-10-13 P1 + } if n, ok := row["recall_count"].(int64); ok { rec.RecallCount = int(n) } diff --git a/go/internal/storage/sqlite.go.bak.proofchain-20261014-005204 b/go/internal/storage/sqlite.go.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..63492ad --- /dev/null +++ b/go/internal/storage/sqlite.go.bak.proofchain-20261014-005204 @@ -0,0 +1,1043 @@ +// 织忆 MemoryWeave — SQLite 持久存储后端(CGO,实现 LanceDB 接口) +package storage + +/* +#cgo LDFLAGS: -lsqlite3 +#include +#include +*/ +import "C" + +import ( + "bytes" + "encoding/binary" + "fmt" + "sort" + "sync" + "time" + "unsafe" + + "github.com/xiaoxue/memoryweave/internal/models" +) + +// SQLiteClient CGO 直连 SQLite3,实现 LanceDB 接口。 +// 生产环境持久化存储,替代 MemLanceClient。 +type SQLiteClient struct { + mu sync.RWMutex + db *C.sqlite3 + path string +} + +func NewSQLiteClient(dbPath string) (*SQLiteClient, error) { + if dbPath == "" { + dbPath = "/var/lib/zhiyi/data/memoryweave.db" + } + + cPath := C.CString(dbPath) + defer C.free(unsafe.Pointer(cPath)) + + var db *C.sqlite3 + rc := C.sqlite3_open(cPath, &db) + if rc != C.SQLITE_OK { + errMsg := C.GoString(C.sqlite3_errmsg(db)) + C.sqlite3_close(db) + return nil, fmt.Errorf("sqlite open: %s", errMsg) + } + + // 性能优化 + C.sqlite3_exec(db, C.CString("PRAGMA journal_mode=WAL"), nil, nil, nil) + C.sqlite3_exec(db, C.CString("PRAGMA synchronous=NORMAL"), nil, nil, nil) + C.sqlite3_exec(db, C.CString("PRAGMA busy_timeout=5000"), nil, nil, nil) + C.sqlite3_exec(db, C.CString("PRAGMA cache_size=-20000"), nil, nil, nil) + + sc := &SQLiteClient{db: db, path: dbPath} + if err := sc.migrate(); err != nil { + C.sqlite3_close(db) + return nil, err + } + return sc, nil +} + +func (sc *SQLiteClient) Close() error { + sc.mu.Lock() + defer sc.mu.Unlock() + if sc.db != nil { + C.sqlite3_close(sc.db) + sc.db = nil + } + return nil +} + +// ─── migration ──────────────────────────────────────── + +func (sc *SQLiteClient) migrate() error { + sqls := []string{ + `CREATE TABLE IF NOT EXISTS memories ( + id TEXT PRIMARY KEY, + agent_id TEXT NOT NULL, + namespace TEXT NOT NULL DEFAULT '', + content TEXT NOT NULL, + category TEXT NOT NULL DEFAULT 'general', + vector BLOB, + tier TEXT NOT NULL DEFAULT 'normal', + importance REAL DEFAULT 1.0, + quality_score REAL DEFAULT 0.0, + recall_count INTEGER DEFAULT 0, + -- GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义 + recall_seen_count INTEGER DEFAULT 0, + recall_verified_count INTEGER DEFAULT 0, + useful_count INTEGER DEFAULT 0, + not_useful_count INTEGER DEFAULT 0, + -- GA-P0-1 (t_718d8707):拆分 not_useful_count 的两种语义(人工没用 / dedup 自动降权) + human_not_useful_count INTEGER DEFAULT 0, + dedup_downweight_count INTEGER DEFAULT 0, + freshness TEXT DEFAULT 'fresh', + version INTEGER DEFAULT 1, + version_history TEXT DEFAULT '[]', + source TEXT DEFAULT '', + volatile_flag INTEGER DEFAULT 0, + is_deleted INTEGER DEFAULT 0, + -- GA-P0-3 (t_f785d7f2):删除原因枚举(merge_dup|contradiction|manual|retention|unknown) + delete_reason TEXT DEFAULT '', + depends_on TEXT DEFAULT '[]', + derived_from TEXT DEFAULT '', + source_events TEXT DEFAULT '[]', + supersedes TEXT DEFAULT '[]', + last_recalled_at TEXT DEFAULT '', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS episodes ( + id TEXT PRIMARY KEY, + agent_id TEXT NOT NULL, + namespace TEXT NOT NULL DEFAULT '', + content TEXT NOT NULL, + category TEXT NOT NULL DEFAULT 'general', + distilled_to TEXT DEFAULT '', + distill_status TEXT DEFAULT 'pending', + created_at TEXT NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS tombstones ( + id TEXT PRIMARY KEY, + original_id TEXT NOT NULL, + content_snapshot TEXT DEFAULT '', + namespace TEXT DEFAULT '', + reason TEXT NOT NULL DEFAULT '', + merged_into TEXT DEFAULT '', + deleted_at TEXT NOT NULL + )`, + `CREATE TABLE IF NOT EXISTS version_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + memory_id TEXT NOT NULL, + version INTEGER NOT NULL, + content TEXT NOT NULL, + source TEXT DEFAULT '', + reason TEXT DEFAULT '', + timestamp TEXT NOT NULL, + FOREIGN KEY (memory_id) REFERENCES memories(id) + )`, + `CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id)`, + `CREATE INDEX IF NOT EXISTS idx_memories_namespace ON memories(namespace)`, + `CREATE INDEX IF NOT EXISTS idx_memories_deleted ON memories(is_deleted)`, + // GA-P0-4 (t_bb10e8bc):hits+/hits− outcome 事件(append-only 事件表,语义定义见 hit_event.go)。 + // 每次真实 outcome 追加一行,带 created_at 时间戳,**不覆盖式累加** —— 便于按周窗口聚合。 + // 只由真实 outcome 写入(人工反馈/矛盾/取代/下游引用);dedup 降权 / 单纯召回出现禁止写入。 + `CREATE TABLE IF NOT EXISTS hit_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + memory_id TEXT NOT NULL, + outcome TEXT NOT NULL, + reason TEXT NOT NULL, + source TEXT DEFAULT '', + created_at TEXT NOT NULL, + FOREIGN KEY (memory_id) REFERENCES memories(id) + )`, + `CREATE INDEX IF NOT EXISTS idx_hit_events_memory ON hit_events(memory_id)`, + `CREATE INDEX IF NOT EXISTS idx_hit_events_memory_outcome_created ON hit_events(memory_id, outcome, created_at)`, + // 下面是原 migrate 里回忆 INDEX 占位,勿删(保持行号稳定)。 + `CREATE INDEX IF NOT EXISTS idx_episodes_agent ON episodes(agent_id)`, + `CREATE INDEX IF NOT EXISTS idx_version_history_mem ON version_history(memory_id)`, + } + + for _, s := range sqls { + if err := sc.exec(s); err != nil { + return fmt.Errorf("migrate: %w", err) + } + } + // GA-P0-1 (t_718d8707):存量表 add 拆分列(additive,不删旧列 not_useful_count) + for _, c := range []struct{ col, ddl string }{ + {"human_not_useful_count", "ALTER TABLE memories ADD COLUMN human_not_useful_count INTEGER DEFAULT 0"}, + {"dedup_downweight_count", "ALTER TABLE memories ADD COLUMN dedup_downweight_count INTEGER DEFAULT 0"}, + // GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义(additive,不删旧列 recall_count) + {"recall_seen_count", "ALTER TABLE memories ADD COLUMN recall_seen_count INTEGER DEFAULT 0"}, + {"recall_verified_count", "ALTER TABLE memories ADD COLUMN recall_verified_count INTEGER DEFAULT 0"}, + // GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(additive,TEXT 存固定枚举) + {"delete_reason", "ALTER TABLE memories ADD COLUMN delete_reason TEXT DEFAULT ''"}, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(additive,TEXT JSON 数组) + {"source_events", "ALTER TABLE memories ADD COLUMN source_events TEXT DEFAULT '[]'"}, + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(additive) + {"supersedes", "ALTER TABLE memories ADD COLUMN supersedes TEXT DEFAULT '[]'"}, + } { + rows, err := sc.query("PRAGMA table_info(memories)") + if err != nil { + return fmt.Errorf("migrate pragma: %w", err) + } + has := false + for _, r := range rows { + if r["name"] == c.col { + has = true + break + } + } + if !has { + if err := sc.exec(c.ddl); err != nil { + return fmt.Errorf("migrate add %s: %w", c.col, err) + } + } + } + return nil +} + +// ─── CGO helpers ────────────────────────────────────── + +func (sc *SQLiteClient) exec(sql string) error { + cSQL := C.CString(sql) + defer C.free(unsafe.Pointer(cSQL)) + + var errMsg *C.char + rc := C.sqlite3_exec(sc.db, cSQL, nil, nil, &errMsg) + if rc != C.SQLITE_OK { + msg := C.GoString(errMsg) + C.sqlite3_free(unsafe.Pointer(errMsg)) + return fmt.Errorf("sqlite: %s", msg) + } + return nil +} + +func (sc *SQLiteClient) execWithArgs(sql string, args ...interface{}) error { + cSQL := C.CString(sql) + defer C.free(unsafe.Pointer(cSQL)) + + var stmt *C.sqlite3_stmt + rc := C.sqlite3_prepare_v2(sc.db, cSQL, C.int(len(sql)), &stmt, nil) + if rc != C.SQLITE_OK { + return fmt.Errorf("sqlite prepare: %s", C.GoString(C.sqlite3_errmsg(sc.db))) + } + defer C.sqlite3_finalize(stmt) + + for i, arg := range args { + idx := C.int(i + 1) + switch v := arg.(type) { + case nil: + C.sqlite3_bind_null(stmt, idx) + case int: + C.sqlite3_bind_int64(stmt, idx, C.sqlite3_int64(v)) + case int64: + C.sqlite3_bind_int64(stmt, idx, C.sqlite3_int64(v)) + case float64: + C.sqlite3_bind_double(stmt, idx, C.double(v)) + case bool: + if v { + C.sqlite3_bind_int(stmt, idx, 1) + } else { + C.sqlite3_bind_int(stmt, idx, 0) + } + case string: + cStr := C.CString(v) + C.sqlite3_bind_text(stmt, idx, cStr, C.int(len(v)), (*[0]byte)(C.free)) + case []byte: + if len(v) == 0 { + C.sqlite3_bind_null(stmt, idx) + } else { + C.sqlite3_bind_blob(stmt, idx, unsafe.Pointer(&v[0]), C.int(len(v)), nil) + } + default: + return fmt.Errorf("unsupported arg type %T", arg) + } + } + + rc = C.sqlite3_step(stmt) + if rc != C.SQLITE_DONE && rc != C.SQLITE_ROW { + return fmt.Errorf("sqlite step: %s", C.GoString(C.sqlite3_errmsg(sc.db))) + } + return nil +} + +type sqliteRow map[string]interface{} + +func (sc *SQLiteClient) query(sql string) ([]sqliteRow, error) { + cSQL := C.CString(sql) + defer C.free(unsafe.Pointer(cSQL)) + + var stmt *C.sqlite3_stmt + rc := C.sqlite3_prepare_v2(sc.db, cSQL, C.int(len(sql)), &stmt, nil) + if rc != C.SQLITE_OK { + return nil, fmt.Errorf("sqlite prepare: %s", C.GoString(C.sqlite3_errmsg(sc.db))) + } + defer C.sqlite3_finalize(stmt) + + var rows []sqliteRow + for { + rc = C.sqlite3_step(stmt) + if rc == C.SQLITE_DONE { + break + } + if rc != C.SQLITE_ROW { + return nil, fmt.Errorf("sqlite step: %s", C.GoString(C.sqlite3_errmsg(sc.db))) + } + + colCount := int(C.sqlite3_column_count(stmt)) + row := make(sqliteRow, colCount) + for i := 0; i < colCount; i++ { + name := C.GoString(C.sqlite3_column_name(stmt, C.int(i))) + colType := C.sqlite3_column_type(stmt, C.int(i)) + switch colType { + case C.SQLITE_INTEGER: + row[name] = int64(C.sqlite3_column_int64(stmt, C.int(i))) + case C.SQLITE_FLOAT: + row[name] = float64(C.sqlite3_column_double(stmt, C.int(i))) + case C.SQLITE_TEXT: + row[name] = C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, C.int(i))))) + case C.SQLITE_BLOB: + n := int(C.sqlite3_column_bytes(stmt, C.int(i))) + ptr := C.sqlite3_column_blob(stmt, C.int(i)) + blob := make([]byte, n) + if n > 0 { + copy(blob, (*[1 << 30]byte)(ptr)[:n]) + } + row[name] = blob + case C.SQLITE_NULL: + row[name] = nil + } + } + rows = append(rows, row) + } + return rows, nil +} + +// ─── vector helpers ─────────────────────────────────── + +func vectorToBlob(v []float32) []byte { + buf := new(bytes.Buffer) + for _, f := range v { + binary.Write(buf, binary.LittleEndian, f) + } + return buf.Bytes() +} + +func blobToVector(b []byte) []float32 { + if len(b) == 0 { + return nil + } + vec := make([]float32, len(b)/4) + buf := bytes.NewReader(b) + for i := range vec { + binary.Read(buf, binary.LittleEndian, &vec[i]) + } + return vec +} + +// ─── LanceDB 接口 ───────────────────────────────────── + +func (sc *SQLiteClient) InsertEpisode(agentID, namespace, content, category string) (string, error) { + id := fmt.Sprintf("ep_%d", time.Now().UnixNano()) + now := time.Now().Format(time.RFC3339) + sc.mu.Lock() + defer sc.mu.Unlock() + return id, sc.execWithArgs( + "INSERT INTO episodes(id,agent_id,namespace,content,category,created_at) VALUES(?,?,?,?,?,?)", + id, agentID, namespace, content, category, now, + ) +} + +func (sc *SQLiteClient) InsertMemory(m models.MemoryRecord) error { + now := time.Now().Format(time.RFC3339) + vecBlob := vectorToBlob(m.Vector) + sc.mu.Lock() + defer sc.mu.Unlock() + return sc.execWithArgs( + `INSERT INTO memories(id,agent_id,namespace,content,category,vector,tier,importance,quality_score, + source,depends_on,derived_from,source_events,supersedes,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,1,?,?)`, + m.ID, m.AgentID, m.Namespace, m.Content, m.Category, vecBlob, m.Tier, + 1.0, m.QualityScore, "", "[]", m.DerivedFrom, seJSON(m.SourceEvents), seJSON(m.Supersedes), now, now, + ) +} + +func (sc *SQLiteClient) Insert(table string, record any) error { + sc.mu.Lock() + defer sc.mu.Unlock() + + now := time.Now().Format(time.RFC3339) + switch r := record.(type) { + case models.MemoryRecord: + return sc.InsertMemory(r) + case models.EpisodeRecord: + return sc.execWithArgs( + "INSERT INTO episodes(id,agent_id,namespace,content,category,distilled_to,distill_status,created_at) VALUES(?,?,?,?,?,?,?,?)", + r.ID, r.AgentID, r.Namespace, r.Content, r.Category, "", "pending", now, + ) + case models.TombstoneRecord: + delTime := r.CreatedAt.Format(time.RFC3339) + return sc.execWithArgs( + "INSERT INTO tombstones(id,original_id,content_snapshot,namespace,reason,merged_into,deleted_at) VALUES(?,?,?,?,?,?,?)", + r.ID, r.OriginalID, "", "", r.Reason, "", delTime, + ) + default: + return fmt.Errorf("sqlite: unsupported record type %T", record) + } +} + +// Scan SQLite 后端的全表扫描(is_deleted=0 + 可选 namespace,按 created_at 倒序)。 +func (sc *SQLiteClient) Scan(limit int, namespaceFilter string) ([]models.MemoryRecord, error) { + if limit <= 0 { + limit = 100 + } + sc.mu.RLock() + defer sc.mu.RUnlock() + + q := "SELECT id, content, category, namespace, importance, quality_score, recall_count, recall_seen_count, recall_verified_count, not_useful_count, human_not_useful_count, dedup_downweight_count, tier, source, created_at, updated_at, source_events, supersedes FROM memories WHERE is_deleted=0" + if namespaceFilter != "" { + q += " AND namespace='" + sanitizeIdent(namespaceFilter) + "'" + } + q += " ORDER BY created_at DESC LIMIT " + fmt.Sprintf("%d", limit) + + rows, err := sc.query(q) + if err != nil { + return nil, err + } + out := make([]models.MemoryRecord, 0, len(rows)) + for _, row := range rows { + rec := models.MemoryRecord{} + rec.ID, _ = row["id"].(string) + rec.Content, _ = row["content"].(string) + rec.Category, _ = row["category"].(string) + rec.Namespace, _ = row["namespace"].(string) + rec.Importance, _ = row["importance"].(float64) + rec.QualityScore, _ = row["quality_score"].(float64) + rec.Tier, _ = row["tier"].(string) + rec.Source, _ = row["source"].(string) + if se, ok := row["source_events"].(string); ok { + rec.SourceEvents = parseSourceEvents(se) // 2026-10-13 P1 + } + if ss, ok := row["supersedes"].(string); ok { + rec.Supersedes = parseSourceEvents(ss) // 2026-10-13 P1 + } + if n, ok := row["recall_count"].(int64); ok { + rec.RecallCount = int(n) + } + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + if n, ok := row["recall_seen_count"].(int64); ok { + rec.RecallSeenCount = int(n) + } + if n, ok := row["recall_verified_count"].(int64); ok { + rec.RecallVerifiedCount = int(n) + } + if n, ok := row["not_useful_count"].(int64); ok { + rec.NotUsefulCount = int(n) + } + if n, ok := row["human_not_useful_count"].(int64); ok { + rec.HumanNotUsefulCount = int(n) + } + if n, ok := row["dedup_downweight_count"].(int64); ok { + rec.DedupDownweightCount = int(n) + } + if ts, ok := row["created_at"].(string); ok { + if t, e := time.Parse(time.RFC3339, ts); e == nil { + rec.CreatedAt = t + } + } + if ts, ok := row["updated_at"].(string); ok { + if t, e := time.Parse(time.RFC3339, ts); e == nil { + rec.UpdatedAt = t + } + } + out = append(out, rec) + } + return out, nil +} + +func (sc *SQLiteClient) Search(table string, vector []float32, topK int, namespaceFilter string) ([]models.MemoryRecord, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + // 加载所有未被删除的记录 + 向量 (按 importance 加权排序) + query := "SELECT id, content, category, namespace, vector, importance, created_at FROM memories WHERE is_deleted=0" + if namespaceFilter != "" { + query += " AND namespace='" + sanitizeIdent(namespaceFilter) + "'" + } + + rows, err := sc.query(query) + if err != nil { + return nil, err + } + + type candidate struct { + rec models.MemoryRecord + score float64 + } + var candidates []candidate + for _, row := range rows { + vecBlob, _ := row["vector"].([]byte) + candVec := blobToVector(vecBlob) + sim := cosineSim(vector, candVec) + importance, _ := row["importance"].(float64) + if importance <= 0 { + importance = 1.0 + } + + createdAt, _ := time.Parse(time.RFC3339, strVal(row, "created_at")) + candidates = append(candidates, candidate{ + rec: models.MemoryRecord{ + ID: strVal(row, "id"), + Content: strVal(row, "content"), + Category: strVal(row, "category"), + Namespace: strVal(row, "namespace"), + CreatedAt: createdAt, + }, + score: sim * importance, // importance 加权 + }) + } + + sort.Slice(candidates, func(i, j int) bool { + return candidates[i].score > candidates[j].score + }) + if topK > len(candidates) { + topK = len(candidates) + } + results := make([]models.MemoryRecord, topK) + for i := 0; i < topK; i++ { + results[i] = candidates[i].rec + } + return results, nil +} + +func (sc *SQLiteClient) GetTopByQuality(agentID string, limit int) ([]models.MemoryRecord, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + rows, err := sc.query( + "SELECT id,content,category,namespace,created_at FROM memories WHERE is_deleted=0 ORDER BY quality_score DESC LIMIT " + itoa(limit), + ) + if err != nil { + return nil, err + } + return sc.rowsToMemories(rows), nil +} + +func (sc *SQLiteClient) Stats() (map[string]interface{}, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + var memCount, epCount, tombCount int64 + rows, _ := sc.query("SELECT COUNT(*) as cnt FROM memories WHERE is_deleted=0") + if len(rows) > 0 { + memCount, _ = rows[0]["cnt"].(int64) + } + rows, _ = sc.query("SELECT COUNT(*) as cnt FROM episodes") + if len(rows) > 0 { + epCount, _ = rows[0]["cnt"].(int64) + } + rows, _ = sc.query("SELECT COUNT(*) as cnt FROM tombstones") + if len(rows) > 0 { + tombCount, _ = rows[0]["cnt"].(int64) + } + + return map[string]interface{}{ + "memory_count": memCount, + "episode_count": epCount, + "tombstone_count": tombCount, + "backend": "sqlite3 (CGO)", + "db_path": sc.path, + }, nil +} + +func (sc *SQLiteClient) SoftDelete(id, reason string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + + now := time.Now().Format(time.RFC3339) + // GA-P0-3 (t_f785d7f2):写 delete_reason(归一化枚举),让 is_deleted=1 可分原因。 + dr := NormalizeDeleteReason(reason) + if err := sc.execWithArgs( + "UPDATE memories SET is_deleted=1, delete_reason=?, updated_at=? WHERE id=?", + dr, now, id, + ); err != nil { + return err + } + + tombID := fmt.Sprintf("tomb_%d", time.Now().UnixNano()) + return sc.execWithArgs( + "INSERT INTO tombstones(id,original_id,reason,deleted_at) VALUES(?,?,?,?)", + tombID, id, reason, now, + ) +} + +func (sc *SQLiteClient) SoftDeleteBatch(table string, ids []string, updatedAt string) (int64, error) { + if table != "memories" { + return 0, fmt.Errorf("unsupported table: %s", table) + } + sc.mu.Lock() + defer sc.mu.Unlock() + var updated int64 + // GA-P0-3 (t_f785d7f2):批量软删不携带逐条原因 ⇒ delete_reason=unknown(兜底)。 + for _, id := range ids { + res := sc.execWithArgs( + "UPDATE memories SET is_deleted=1, delete_reason=?, updated_at=? WHERE id=?", + DeleteReasonUnknown, updatedAt, id, + ) + if res != nil { + return updated, res + } + updated++ + } + return updated, nil +} + +func (sc *SQLiteClient) GetVersionHistory(id string) ([]map[string]interface{}, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + rows, err := sc.query( + "SELECT version,content,source,reason,timestamp FROM version_history WHERE memory_id=? ORDER BY version DESC", + ) + if err != nil { + return nil, err + } + // 用笨办法实现参数化查询避免重写 query 函数 + if len(rows) == 0 { + return nil, nil + } + + // 直接重新查询带参数 + cSQL := C.CString("SELECT version,content,source,reason,timestamp FROM version_history WHERE memory_id=? ORDER BY version DESC") + defer C.free(unsafe.Pointer(cSQL)) + var stmt *C.sqlite3_stmt + C.sqlite3_prepare_v2(sc.db, cSQL, -1, &stmt, nil) + defer C.sqlite3_finalize(stmt) + cID := C.CString(id) + defer C.free(unsafe.Pointer(cID)) + C.sqlite3_bind_text(stmt, 1, cID, C.int(len(id)), (*[0]byte)(C.free)) + + var result []map[string]interface{} + for C.sqlite3_step(stmt) == C.SQLITE_ROW { + result = append(result, map[string]interface{}{ + "version": int64(C.sqlite3_column_int64(stmt, 0)), + "content": C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 1)))), + "source": C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 2)))), + "reason": C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 3)))), + "timestamp": C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 4)))), + }) + } + return result, nil +} + +func (sc *SQLiteClient) GetCandidatesForForgetting() ([]map[string]interface{}, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + rows, err := sc.query( + "SELECT id, content, namespace, category, last_recalled_at, recall_count, recall_seen_count, recall_verified_count, tier, importance, created_at FROM memories WHERE is_deleted=0 AND tier!='core' ORDER BY last_recalled_at ASC LIMIT 200", + ) + if err != nil { + return nil, err + } + var results []map[string]interface{} + for _, r := range rows { + results = append(results, map[string]interface{}{ + "id": r["id"], + "content": r["content"], + "namespace": r["namespace"], + "category": r["category"], + "last_recalled_at": r["last_recalled_at"], + "recall_count": r["recall_count"], + // GA-P0-2 (t_c6d41ac6):衰减/遗忘决策读 recall_verified_count + "recall_seen_count": r["recall_seen_count"], + "recall_verified_count": r["recall_verified_count"], + "tier": r["tier"], + "importance": r["importance"], + "created_at": r["created_at"], + }) + } + return results, nil +} + +// G7.2: GetSkillCandidates 返回适合结晶为 skill 的记忆候选 +// 条件: recall_count >= minRecalls, quality_score >= 0.7, tier != 'core' +func (sc *SQLiteClient) GetSkillCandidates(minRecalls, limit int) ([]models.MemoryRecord, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + sql := `SELECT id, agent_id, namespace, content, category, + recall_count, quality_score, importance, tier, + last_recalled_at, created_at, updated_at, + not_useful_count, human_not_useful_count, dedup_downweight_count, + recall_seen_count, recall_verified_count + FROM memories + WHERE is_deleted = 0 AND tier != 'core' + -- GA-P0-2 (t_c6d41ac6):技能候选 = 观测/选择(被召回多次)→ 用 recall_seen_count + AND recall_seen_count >= ? AND quality_score >= 0.7 + ORDER BY recall_seen_count DESC, quality_score DESC + LIMIT ?` + cSQL := C.CString(sql) + defer C.free(unsafe.Pointer(cSQL)) + + var stmt *C.sqlite3_stmt + rc := C.sqlite3_prepare_v2(sc.db, cSQL, C.int(len(sql)), &stmt, nil) + if rc != C.SQLITE_OK { + return nil, fmt.Errorf("prepare skill candidates: %s", C.GoString(C.sqlite3_errmsg(sc.db))) + } + defer C.sqlite3_finalize(stmt) + + C.sqlite3_bind_int(stmt, 1, C.int(minRecalls)) + C.sqlite3_bind_int(stmt, 2, C.int(limit)) + + var results []models.MemoryRecord + for { + rc = C.sqlite3_step(stmt) + if rc == C.SQLITE_DONE { + break + } + if rc != C.SQLITE_ROW { + break + } + + rec := models.MemoryRecord{ + ID: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 0)))), + AgentID: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 1)))), + Namespace: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 2)))), + Content: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 3)))), + Category: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 4)))), + RecallCount: int(C.sqlite3_column_int64(stmt, 5)), + QualityScore: float64(C.sqlite3_column_double(stmt, 6)), + Importance: float64(C.sqlite3_column_double(stmt, 7)), + Tier: C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 8)))), + } + if lastRecalled := C.sqlite3_column_text(stmt, 9); lastRecalled != nil { + rec.LastRecalledAt, _ = time.Parse(time.RFC3339, C.GoString((*C.char)(unsafe.Pointer(lastRecalled)))) + } + if createdAt := C.sqlite3_column_text(stmt, 10); createdAt != nil { + rec.CreatedAt, _ = time.Parse(time.RFC3339, C.GoString((*C.char)(unsafe.Pointer(createdAt)))) + } + if updatedAt := C.sqlite3_column_text(stmt, 11); updatedAt != nil { + rec.UpdatedAt, _ = time.Parse(time.RFC3339, C.GoString((*C.char)(unsafe.Pointer(updatedAt)))) + } + // GA-P0-1 (t_718d8707):读侧接线拆分字段(追加在 SELECT 尾部,索引 12/13/14) + rec.NotUsefulCount = int(C.sqlite3_column_int64(stmt, 12)) + rec.HumanNotUsefulCount = int(C.sqlite3_column_int64(stmt, 13)) + rec.DedupDownweightCount = int(C.sqlite3_column_int64(stmt, 14)) + // GA-P0-2 (t_c6d41ac6):拆分字段(追加在 SELECT 尾部,索引 15/16) + rec.RecallSeenCount = int(C.sqlite3_column_int64(stmt, 15)) + rec.RecallVerifiedCount = int(C.sqlite3_column_int64(stmt, 16)) + results = append(results, rec) + } + + return results, nil +} + +func (sc *SQLiteClient) Backup(path string) error { + sc.mu.RLock() + defer sc.mu.RUnlock() + + // SQLite 在线备份 API + var pBackup *C.sqlite3_backup + cDestPath := C.CString(path) + defer C.free(unsafe.Pointer(cDestPath)) + + var destDB *C.sqlite3 + rc := C.sqlite3_open(cDestPath, &destDB) + if rc != C.SQLITE_OK { + return fmt.Errorf("backup open dest: %s", C.GoString(C.sqlite3_errmsg(destDB))) + } + defer C.sqlite3_close(destDB) + + pBackup = C.sqlite3_backup_init(destDB, C.CString("main"), sc.db, C.CString("main")) + if pBackup == nil { + return fmt.Errorf("backup init: %s", C.GoString(C.sqlite3_errmsg(destDB))) + } + C.sqlite3_backup_step(pBackup, -1) + C.sqlite3_backup_finish(pBackup) + return nil +} + +func (sc *SQLiteClient) GetAuditLog(limit int) ([]map[string]interface{}, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + + rows, err := sc.query( + "SELECT id,original_id,reason,deleted_at FROM tombstones ORDER BY deleted_at DESC LIMIT " + itoa(limit), + ) + if err != nil { + return nil, err + } + var results []map[string]interface{} + for _, r := range rows { + results = append(results, map[string]interface{}{ + "id": r["id"], + "original_id": r["original_id"], + "reason": r["reason"], + "deleted_at": r["deleted_at"], + }) + } + return results, nil +} + +func (sc *SQLiteClient) IncrementUseful(id string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + // GA-P0-2 (t_c6d41ac6):正反馈 → useful_count+1 且 recall_verified_count+1。 + // 不再碰 recall_count(冻结,保留历史值)。 + sc.execWithArgs( + "UPDATE memories SET useful_count=useful_count+1, recall_verified_count=recall_verified_count+1, updated_at=? WHERE id=?", + time.Now().Format(time.RFC3339), id, + ) + return nil +} + +// IncrementNotUseful [DEPRECATED](GA-P0-1 t_718d8707)递增 not_useful_count(历史混写列)。 +// 新代码走 IncrementHumanNotUseful(人工) / IncrementDedupDownweight(dedup 降权)。 +func (sc *SQLiteClient) IncrementNotUseful(id string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + sc.execWithArgs( + "UPDATE memories SET not_useful_count=not_useful_count+1, updated_at=? WHERE id=?", + time.Now().Format(time.RFC3339), id, + ) + return nil +} + +// IncrementHumanNotUseful 递增 human_not_useful_count(用户人工点「没用」,GA-P0-1)。 +func (sc *SQLiteClient) IncrementHumanNotUseful(id string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + sc.execWithArgs( + "UPDATE memories SET human_not_useful_count=human_not_useful_count+1, updated_at=? WHERE id=?", + time.Now().Format(time.RFC3339), id, + ) + return nil +} + +// IncrementDedupDownweight 递增 dedup_downweight_count(dedup/合并流程自动降权,GA-P0-1)。 +func (sc *SQLiteClient) IncrementDedupDownweight(id string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + sc.execWithArgs( + "UPDATE memories SET dedup_downweight_count=dedup_downweight_count+1, updated_at=? WHERE id=?", + time.Now().Format(time.RFC3339), id, + ) + return nil +} + +// AppendHitEvent 追加一条真实 outcome 事件(GA-P0-4 t_bb10e8bc)。 +// 铁律:outcome 必须是 pos/neg(非则报错不写库);dedup 降权 / 单纯召回出现禁止调用。 +func (sc *SQLiteClient) AppendHitEvent(memoryID, outcome, reason string) error { + outcome = NormalizeHitOutcome(outcome) + if !ValidHitOutcomes[outcome] { + return fmt.Errorf("AppendHitEvent: invalid outcome %q (must be pos/neg); dedup-demote/recall-appearance are NOT outcomes", outcome) + } + reason = NormalizeHitReason(reason) + sc.mu.Lock() + defer sc.mu.Unlock() + return sc.execWithArgs( + "INSERT INTO hit_events (memory_id, outcome, reason, source, created_at) VALUES (?,?,?,?,?)", + memoryID, outcome, reason, "append_hit_event", time.Now().UTC().Format(time.RFC3339), + ) +} + +// CountHitEvents 统计某 memory 在某时间窗起点之后的 outcome 事件数(P2 自适应阈值按周窗口用)。 +func (sc *SQLiteClient) CountHitEvents(memoryID, outcome string, since time.Time) (int, error) { + outcome = NormalizeHitOutcome(outcome) + if !ValidHitOutcomes[outcome] { + return 0, fmt.Errorf("CountHitEvents: invalid outcome %q", outcome) + } + sc.mu.RLock() + defer sc.mu.RUnlock() + // created_at 以 UTC 存储(AppendHitEvent 用 UTC().Format)。since 归一为 UTC 再字符串比较, + // 避免本地时区("+08:00")与 UTC("Z") 跨时区错位(与 Rust 侧 count_hit_events 一致)。 + rows, err := sc.query("SELECT COUNT(*) AS n FROM hit_events WHERE memory_id='" + sanitizeIdent(memoryID) + "' AND outcome='" + sanitizeIdent(outcome) + "' AND created_at >= '" + since.UTC().Format(time.RFC3339) + "'") + if err != nil { + return 0, err + } + if len(rows) == 0 { + return 0, nil + } + n, _ := rows[0]["n"].(int64) + return int(n), nil +} + +// GetHitEvents 读回某 memory 的事件明细(read-back 取证,非只看函数返回)。 +func (sc *SQLiteClient) GetHitEvents(memoryID string, limit int) ([]models.HitEvent, error) { + sc.mu.RLock() + defer sc.mu.RUnlock() + if limit <= 0 { + limit = 100 + } + rows, err := sc.query("SELECT id, memory_id, outcome, reason, source, created_at FROM hit_events WHERE memory_id='" + sanitizeIdent(memoryID) + "' ORDER BY created_at DESC LIMIT " + fmt.Sprintf("%d", limit)) + if err != nil { + return nil, err + } + events := make([]models.HitEvent, 0, len(rows)) + for _, r := range rows { + ev := models.HitEvent{ + MemoryID: r["memory_id"].(string), + Outcome: r["outcome"].(string), + Reason: r["reason"].(string), + Source: r["source"].(string), + } + if id, ok := r["id"].(int64); ok { + ev.ID = id + } + if ts, ok := r["created_at"].(string); ok { + if t, err := time.Parse(time.RFC3339, ts); err == nil { + ev.CreatedAt = t + } + } + events = append(events, ev) + } + return events, nil +} + +func (sc *SQLiteClient) UpdateMemoryContent(id, newContent, source string) error { + sc.mu.Lock() + defer sc.mu.Unlock() + + now := time.Now().Format(time.RFC3339) + + // 记录版本历史 + rows, _ := sc.query("SELECT version FROM memories WHERE id='" + sanitizeIdent(id) + "'") + version := int64(1) + if len(rows) > 0 { + if v, ok := rows[0]["version"].(int64); ok { + version = v + 1 + } + } + + sc.execWithArgs( + "INSERT INTO version_history(memory_id,version,content,source,reason,timestamp) VALUES(?,?,?,?,?,?)", + id, version, newContent, source, "corrected", now, + ) + + return sc.execWithArgs( + "UPDATE memories SET content=?, source=?, version=?, updated_at=? WHERE id=?", + newContent, source, version, now, id, + ) +} + +func (sc *SQLiteClient) Update(table, id string, fields map[string]any) error { + sc.mu.Lock() + defer sc.mu.Unlock() + + if table != "memories" { + return nil + } + + now := time.Now().Format(time.RFC3339) + // GA-P0-2 (t_c6d41ac6):recall_count 冻结,不再增长。召回命中改走 recall_seen_count; + // 正反馈(IncrementUseful)走 recall_verified_count。 + if _, ok := fields["recall_seen_count"]; ok { + return sc.execWithArgs( + "UPDATE memories SET recall_seen_count=recall_seen_count+1, updated_at=? WHERE id=?", + now, id, + ) + } + if _, ok := fields["recall_verified_count"]; ok { + return sc.execWithArgs( + "UPDATE memories SET recall_verified_count=recall_verified_count+1, updated_at=? WHERE id=?", + now, id, + ) + } + if _, ok := fields["recall_count"]; ok { + return sc.execWithArgs( + "UPDATE memories SET recall_count=recall_count+1, updated_at=? WHERE id=?", + now, id, + ) + } + if _, ok := fields["useful_count"]; ok { + return sc.execWithArgs( + "UPDATE memories SET useful_count=useful_count+1, updated_at=? WHERE id=?", + now, id, + ) + } + // generic update + for k, v := range fields { + if err := sc.execWithArgs( + "UPDATE memories SET "+sanitizeIdent(k)+"=?, updated_at=? WHERE id=?", + v, now, id, + ); err != nil { + return err + } + } + return nil +} + +// PurgeInvalid 清理 id 为空的垃圾行(P1-1 2026-10-08,SQLite 兜底实现)。 +// 软删(is_deleted=1 + updated_at=now)而非硬删,语义与 Rust LanceDB 一致。 +// execWithArgs 只返回 error,受影响行数用前后 COUNT 差值近似(空 id 行必然 is_deleted=0 才被清, +// 且这些行不参与任何读取路径,直接用 UPDATE 前的空 id 存活计数作为「受影响行数」)。 +func (sc *SQLiteClient) PurgeInvalid() (int64, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + rows, err := sc.query("SELECT COUNT(*) as cnt FROM memories WHERE is_deleted=0 AND (id='' OR trim(id)='')") + if err != nil { + return 0, err + } + before := int64(0) + if len(rows) > 0 { + before, _ = rows[0]["cnt"].(int64) + } + if before == 0 { + return 0, nil + } + + now := time.Now().Format(time.RFC3339) + // GA-P0-3 (t_f785d7f2):清理 id 为空垃圾行 = 保留策略清理 ⇒ delete_reason=retention。 + if err := sc.execWithArgs( + "UPDATE memories SET is_deleted=1, delete_reason=?, updated_at=? WHERE id='' OR trim(id)=''", + DeleteReasonRetention, now, + ); err != nil { + return 0, err + } + return before, nil +} + +// ─── helpers ────────────────────────────────────────── + +func strVal(row sqliteRow, key string) string { + if v, ok := row[key]; ok { + if s, ok := v.(string); ok { + return s + } + } + return "" +} + +func (sc *SQLiteClient) rowsToMemories(rows []sqliteRow) []models.MemoryRecord { + results := make([]models.MemoryRecord, 0, len(rows)) + for _, row := range rows { + createdAt, _ := time.Parse(time.RFC3339, strVal(row, "created_at")) + results = append(results, models.MemoryRecord{ + ID: strVal(row, "id"), + Content: strVal(row, "content"), + Category: strVal(row, "category"), + Namespace: strVal(row, "namespace"), + CreatedAt: createdAt, + }) + } + return results +} + +func itoa(n int) string { + if n <= 0 { + return "10" + } + return fmt.Sprintf("%d", n) +} + +func sanitizeIdent(s string) string { + // 简单防注入:仅允许字母、数字、下划线 + for _, c := range s { + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-') { + return "'invalid'" + } + } + return s +} diff --git a/rust/src/lancedb_ops.rs b/rust/src/lancedb_ops.rs index 818aa62..4bd95da 100644 --- a/rust/src/lancedb_ops.rs +++ b/rust/src/lancedb_ops.rs @@ -55,6 +55,11 @@ pub struct MemoryRecord { // 存量行是 NULL(读路径 col_str 兜底 ""),回填脚本以 tombstones 为据尽力判定。 pub delete_reason: String, pub depends_on: String, pub derived_from: String, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID 的 JSON 数组字符串。 + // 与 depends_on 同款(JSON 串列),additive 新列,存量由 schema 演进补 NULL。 + pub source_events: String, + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(JSON 数组字符串) + pub supersedes: String, pub last_recalled_at: String, pub created_at: String, pub updated_at: String, } @@ -121,6 +126,11 @@ fn arrow_schema() -> Schema { // GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(固定枚举)。additive 新列, // nullable 容纳存量 NULL;回填脚本以 tombstones 为据尽力判定,判不出写 unknown。 Field::new("delete_reason", DataType::Utf8, true), + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)。 + // additive 新列,存量由 schema 演进补 NULL(与 depends_on 同款)。 + Field::new("source_events", DataType::Utf8, true), + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留(additive) + Field::new("supersedes", DataType::Utf8, true), ]) } @@ -267,6 +277,8 @@ impl LanceDBOps { delete_reason: col_str(&batch, i, "delete_reason"), depends_on: String::new(), derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 last_recalled_at: String::new(), created_at: col_str(&batch, i, "created_at"), updated_at: col_str(&batch, i, "updated_at"), @@ -328,6 +340,8 @@ impl LanceDBOps { delete_reason: col_str(&batch, i, "delete_reason"), depends_on: String::new(), derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 last_recalled_at: String::new(), created_at: col_str(&batch, i, "created_at"), updated_at: col_str(&batch, i, "updated_at"), @@ -364,6 +378,9 @@ impl LanceDBOps { // GA-P0-3 (t_f785d7f2):删除原因(additive) let mut delete_reasons: Vec<&str> = Vec::new(); let mut depends_ons = Vec::new(); let mut derived_froms = Vec::new(); + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串) + let mut source_events_col = Vec::new(); + let mut supersedes_col = Vec::new(); let mut last_recalled_ats = Vec::new(); let mut created_ats = Vec::new(); let mut updated_ats = Vec::new(); // 2026-10-08 (Gap#2):nullable 列用 Option,未声明时写 None → 库里是 NULL let mut confidences: Vec> = Vec::new(); @@ -401,6 +418,8 @@ impl LanceDBOps { delete_reasons.push(r["delete_reason"].as_str().unwrap_or("")); // GA-P0-3 depends_ons.push(r["depends_on"].as_str().unwrap_or("[]")); derived_froms.push(r["derived_from"].as_str().unwrap_or("")); + source_events_col.push(r["source_events"].as_str().unwrap_or("[]")); // 2026-10-13 P1 + supersedes_col.push(r["supersedes"].as_str().unwrap_or("[]")); // 2026-10-13 P1 last_recalled_ats.push(r["last_recalled_at"].as_str().unwrap_or("")); created_ats.push(r["created_at"].as_str().unwrap_or("")); updated_ats.push(r["updated_at"].as_str().unwrap_or("")); @@ -459,6 +478,10 @@ impl LanceDBOps { Arc::new(Int64Array::from(recall_verified_counts)), // GA-P0-3 (t_f785d7f2):delete_reason 列,与 arrow_schema 顺序一致(additive) Arc::new(StringArray::from(delete_reasons)), + // 2026-10-13 (t_e9a4d18f P1):source_events 列,与 arrow_schema 顺序一致(additive) + Arc::new(StringArray::from(source_events_col)), + // 2026-10-13 (t_e9a4d18f P1):supersedes 列,与 arrow_schema 顺序一致(additive) + Arc::new(StringArray::from(supersedes_col)), ]; let batch = RecordBatch::try_new(schema.clone(), columns)?; @@ -930,6 +953,8 @@ impl LanceDBOps { delete_reason: col_str(batch, i, "delete_reason"), depends_on: String::new(), derived_from: String::new(), + source_events: col_str(batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(batch, i, "supersedes"), // 2026-10-13 P1 last_recalled_at: col_str(batch, i, "last_recalled_at"), created_at: col_str(batch, i, "created_at"), updated_at: col_str(batch, i, "updated_at"), @@ -1000,6 +1025,8 @@ impl LanceDBOps { delete_reason: col_str(&batch, i, "delete_reason"), depends_on: String::new(), derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 last_recalled_at: String::new(), created_at: col_str(&batch, i, "created_at"), updated_at: col_str(&batch, i, "updated_at"), @@ -1075,6 +1102,8 @@ impl LanceDBOps { delete_reason: col_str(&batch, i, "delete_reason"), depends_on: String::new(), derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 last_recalled_at: col_str(&batch, i, "last_recalled_at"), created_at: col_str(&batch, i, "created_at"), updated_at: col_str(&batch, i, "updated_at"), diff --git a/rust/src/lancedb_ops.rs.bak.proofchain-20261014-005204 b/rust/src/lancedb_ops.rs.bak.proofchain-20261014-005204 new file mode 100644 index 0000000..4bd95da --- /dev/null +++ b/rust/src/lancedb_ops.rs.bak.proofchain-20261014-005204 @@ -0,0 +1,1475 @@ +use std::sync::OnceLock; + +fn rt() -> &'static tokio::runtime::Runtime { + static RT: OnceLock = OnceLock::new(); + RT.get_or_init(|| tokio::runtime::Runtime::new().unwrap()) +} + +// LanceDB 原生读写 — lancedb crate 0.15 +// 使用 pollster::block_on 处理 async API +// API: connect(path) → create_empty_table/table_names → vector_search → add(arrow_data) + +use std::path::PathBuf; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use arrow::array::{Array, ArrayRef, BooleanArray, FixedSizeListArray, Float32Array, Float64Array, Int64Array, StringArray}; +use arrow::datatypes::{DataType, Field, Schema}; +use arrow::record_batch::{RecordBatch, RecordBatchIterator}; +use futures::StreamExt; +use lancedb::query::{ExecutableQuery, QueryBase, Select}; +use lancedb::table::NewColumnTransform; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemoryRecord { + pub id: String, pub agent_id: String, pub namespace: String, + pub content: String, pub category: String, pub vector: Vec, + pub tier: String, pub importance: f64, pub quality_score: f64, + pub recall_count: i64, pub useful_count: i64, pub not_useful_count: i64, + // GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义(「出现在结果里」/「被验证使用」)。 + // recall_count 曾把两种语义混写 —— 每次召回命中都 ++,被当成 V 值喂给衰减/遗忘逻辑, + // 造成「被召回 500+ 次所以永不遗忘」的虚高保命。现拆分为: + // recall_seen_count 出现即 ++(只用于观测/排序去偏,不参与 V 值/衰减权重) + // recall_verified_count有正反馈(IncrementUseful)或下游引用才 ++(唯一参与 V 值/衰减) + // recall_count 保留(deprecated),冻结不再增长,仅向后兼容读取历史值。 + pub recall_seen_count: i64, pub recall_verified_count: i64, + // GA-P0-1 (t_718d8707):拆分 not_useful_count 的两种语义(人工「没用」/ dedup 自动降权)。 + // not_useful_count 保留(deprecated),新代码不再读它;human_not_useful_count 与 + // dedup_downweight_count 是新写入点。arrow_schema 尾部新增列(nullable,存量补 NULL)。 + pub human_not_useful_count: i64, pub dedup_downweight_count: i64, + pub freshness: String, pub version: i64, + pub version_history: String, pub source: String, + // 2026-10-08 (t_7e3577c5):血缘字段 + pub embedding_model: String, pub script_version: String, + // 2026-10-08 (Gap#2):信任等级。Option —— 存量行是 NULL,必须与「显式 0.0」区分。 + // 漏了这里 ⇒ IPC 响应无该字段 ⇒ Go 侧解包恒 nil ⇒ 加列也白加(静默 no-op)。 + #[serde(default)] + pub confidence: Option, + #[serde(default)] + pub confidence_source: String, + pub volatile_flag: bool, pub is_deleted: bool, + // GA-P0-3 (t_f785d7f2):拆分 is_deleted 的删除原因。is_deleted=true 不再「不可分辨」—— + // 坏记忆被删(contradiction/manual/retention) 与 合并/整理被删(merge_dup) 现可分列。 + // 固定枚举: merge_dup | contradiction | manual | retention | unknown。additive 新列, + // 存量行是 NULL(读路径 col_str 兜底 ""),回填脚本以 tombstones 为据尽力判定。 + pub delete_reason: String, + pub depends_on: String, pub derived_from: String, + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID 的 JSON 数组字符串。 + // 与 depends_on 同款(JSON 串列),additive 新列,存量由 schema 演进补 NULL。 + pub source_events: String, + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留:被取代的旧记忆 ID(JSON 数组字符串) + pub supersedes: String, + pub last_recalled_at: String, pub created_at: String, pub updated_at: String, +} + +#[derive(Clone)] +pub struct LanceDBOps { + data_dir: PathBuf, +} + +/// 遗忘候选「旋转窗口」返回(方案 c′ 2026-10-11 t_a4b8fa52)。 +/// - records: 本窗口全字段记录(已按 id 排序) +/// - next_cursor: 新游标 = 窗口末 id;wrapped=true 时为空串(下轮从 0 起) +/// - wrapped: 窗口不足 limit(取到存活集合末尾)⇒ 本轮遍历结束 +/// - live_total: 存活 mem_ id 总数(排除 episode),供覆盖度量与 AC-7 吞吐判据 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ForgetWindow { + pub records: Vec, + pub next_cursor: String, + pub wrapped: bool, + pub live_total: usize, +} + +fn arrow_schema() -> Schema { + Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + Field::new("agent_id", DataType::Utf8, false), + Field::new("namespace", DataType::Utf8, false), + Field::new("content", DataType::Utf8, false), + Field::new("category", DataType::Utf8, false), + Field::new("vector", DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 1024), true), + Field::new("tier", DataType::Utf8, false), + Field::new("importance", DataType::Float64, false), + Field::new("quality_score", DataType::Float64, false), + Field::new("recall_count", DataType::Int64, false), + Field::new("useful_count", DataType::Int64, false), + Field::new("not_useful_count", DataType::Int64, false), + Field::new("freshness", DataType::Utf8, false), + Field::new("version", DataType::Int64, false), + Field::new("version_history", DataType::Utf8, true), + Field::new("source", DataType::Utf8, true), + Field::new("embedding_model", DataType::Utf8, true), + Field::new("script_version", DataType::Utf8, true), + Field::new("volatile_flag", DataType::Boolean, false), + Field::new("is_deleted", DataType::Boolean, false), + Field::new("depends_on", DataType::Utf8, true), + Field::new("derived_from", DataType::Utf8, true), + Field::new("last_recalled_at", DataType::Utf8, true), + Field::new("created_at", DataType::Utf8, false), + Field::new("updated_at", DataType::Utf8, false), + // 2026-10-08 (Gap#2):来源加权。confidence=写入方显式声明的信任等级(不从 source 反推); + // confidence_source=authoritative|estimated,用于区分「写入时声明」与「事后回填猜测」, + // 是日后批量纠偏的唯一手段(否则无法定向打 estimated 行)。 + // 均 nullable:存量行保持 NULL,读路径 COALESCE→1.0,使加权上线首日即 no-op。 + Field::new("confidence", DataType::Float64, true), + Field::new("confidence_source", DataType::Utf8, true), + // GA-P0-1 (t_718d8707):拆分 not_useful_count 的两种语义。additive 新列; + // 存量表由 open() 的 schema 演进迁移自动补列(nullable 容纳存量 NULL, + // 与 t_3df364b8 血缘列 / Gap#2 confidence 的迁移模式一致)。 + Field::new("human_not_useful_count", DataType::Int64, true), + Field::new("dedup_downweight_count", DataType::Int64, true), + // GA-P0-2 (t_c6d41ac6):拆分 recall_count 的两种语义。additive 新列; + // 存量表由 open() 的 schema 演进自动补列(nullable 容纳存量 NULL)。 + Field::new("recall_seen_count", DataType::Int64, true), + Field::new("recall_verified_count", DataType::Int64, true), + // GA-P0-3 (t_f785d7f2):is_deleted 的删除原因(固定枚举)。additive 新列, + // nullable 容纳存量 NULL;回填脚本以 tombstones 为据尽力判定,判不出写 unknown。 + Field::new("delete_reason", DataType::Utf8, true), + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串)。 + // additive 新列,存量由 schema 演进补 NULL(与 depends_on 同款)。 + Field::new("source_events", DataType::Utf8, true), + // 2026-10-13 (t_e9a4d18f P1) 矛盾保留(additive) + Field::new("supersedes", DataType::Utf8, true), + ]) +} + +// GA-P0-4 (t_bb10e8bc):hits+/hits− outcome 事件记录(append-only 事件表)。 +// 与 MemoryRecord 计数列不同:这是「按时间戳追加」的事件,**不覆盖式累加**, +// 便于 P2 自适应阈值按周窗口聚合。语义定义见 Go 侧 internal/storage/hit_event.go。 +// 只由真实 outcome 写入(human_feedback|contradiction|replacement|downstream_use); +// dedup 降权 / 单纯召回出现禁止写入。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HitEventRecord { + pub id: String, + pub memory_id: String, + pub outcome: String, // pos | neg + pub reason: String, // human_feedback|contradiction|replacement|downstream_use + pub source: String, + pub created_at: String, // RFC3339 +} + +fn hit_event_arrow_schema() -> Schema { + Schema::new(vec![ + Field::new("id", DataType::Utf8, false), + Field::new("memory_id", DataType::Utf8, false), + Field::new("outcome", DataType::Utf8, false), + Field::new("reason", DataType::Utf8, false), + Field::new("source", DataType::Utf8, true), + Field::new("created_at", DataType::Utf8, false), + ]) +} + +/// 生成 hit_event 行的唯一 id(memory_id + 微秒时间戳;同微秒追加几乎不可能)。 +fn hit_event_id(memory_id: &str) -> String { + let micros = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_micros()) + .unwrap_or(0); + format!("{}-{}", memory_id, micros) +} + +/// SQL 单引号转义(用于 hit_events 过滤条件的字符串字面量)。 +fn sql_escape(s: &str) -> String { + s.replace('\'', "''") +} + +impl LanceDBOps { + pub fn open(data_dir: &str) -> Result> { + let path = PathBuf::from(data_dir); + std::fs::create_dir_all(&path)?; + let db = rt().block_on(lancedb::connect(path.to_str().unwrap()).execute())?; + let tables = rt().block_on(db.table_names().execute())?; + let target = arrow_schema(); + for name in ["memories", "episodes", "tombstones"] { + if !tables.iter().any(|t| t == name) { + rt().block_on(db.create_empty_table(name, Arc::new(arrow_schema())).execute()).ok(); + eprintln!("[lancedb] created table: {}", name); + continue; + } + // 已存在表 → schema 演进迁移:补齐 arrow_schema() 中有而实际表缺失的列 + // (2026-10-08 t_3df364b8:commit 5038d19 加 2 血缘列后 episodes 仍 23 列, + // 每次 Append 25 列 ⇒ schema 不匹配 ⇒ 静默丢数据。这里统一补列,三表共用一套 schema。) + let tbl = rt().block_on(db.open_table(name).execute())?; + let tbl_schema = rt().block_on(tbl.schema())?; + let mut missing: Vec<(String, String)> = Vec::new(); + for f in target.fields() { + if tbl_schema.field_with_name(f.name()).is_err() { + // 缺失列一律补**可空**(2026-10-08 修正:原先字符串给 '', + // 而 add_columns 的 SQL 字面量默认值会把列标成 **non-null** —— + // 与 arrow_schema 的 nullable=true 冲突,写入 NULL 会被 lance 拒绝: + // "contained null values even though the field is marked non-null" + // 实测对照:embedding_model/script_version(历史迁移列)都是 nullable=true。 + let default = match f.data_type() { + DataType::Float64 => "CAST(NULL AS DOUBLE)", + DataType::Float32 => "CAST(NULL AS FLOAT)", + DataType::Int64 => "CAST(NULL AS BIGINT)", + DataType::Boolean => "CAST(NULL AS BOOLEAN)", + _ => "CAST(NULL AS STRING)", + }; + missing.push((f.name().to_string(), default.to_string())); + } + } + if !missing.is_empty() { + let cols: Vec = missing.iter().map(|(c, _)| c.clone()).collect(); + eprintln!("[lancedb] migrating {}: adding missing cols {:?}", name, cols); + rt().block_on(tbl.add_columns( + NewColumnTransform::SqlExpressions(missing), + None, + ))?; + eprintln!("[lancedb] migrated {}: added {:?}", name, cols); + } + } + // GA-P0-4 (t_bb10e8bc):hits+/hits− outcome 事件表(append-only,独立 schema)。 + if !tables.iter().any(|t| t == "hit_events") { + rt().block_on(db.create_empty_table("hit_events", Arc::new(hit_event_arrow_schema())).execute()).ok(); + eprintln!("[lancedb] created table: hit_events"); + } + eprintln!("[lancedb] opened at {:?} ({} tables)", path, tables.len()); + Ok(Self { data_dir: path }) + } + + pub fn init_tables(&self) -> Result<(), Box> { + Ok(()) + } + + pub fn search(&self, query_vec: &[f32], top_k: usize, namespace: Option<&str>) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + let mut q = tbl.vector_search(query_vec.to_vec())?.limit(top_k); + if let Some(ns) = namespace { + q = q.only_if(&format!("namespace = '{}'", ns)); + } + q = q.only_if("is_deleted = false"); + + let mut results = Box::pin(rt().block_on(q.execute())?); + let mut records = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + records.push(MemoryRecord { + id: col_str(&batch, i, "id"), + agent_id: col_str(&batch, i, "agent_id"), + namespace: col_str(&batch, i, "namespace"), + content: col_str(&batch, i, "content"), + category: col_str(&batch, i, "category"), + vector: col_vector(&batch, i, "vector"), + tier: col_str(&batch, i, "tier"), + importance: col_f64(&batch, i, "importance"), + quality_score: col_f64(&batch, i, "quality_score"), + recall_count: col_i64(&batch, i, "recall_count"), + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + recall_seen_count: col_i64(&batch, i, "recall_seen_count"), + recall_verified_count: col_i64(&batch, i, "recall_verified_count"), + useful_count: col_i64(&batch, i, "useful_count"), + not_useful_count: col_i64(&batch, i, "not_useful_count"), + // GA-P0-1 (t_718d8707):拆分字段读侧接线 + human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"), + dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"), + freshness: col_str(&batch, i, "freshness"), + version: col_i64(&batch, i, "version"), + version_history: String::new(), + source: col_str(&batch, i, "source"), + embedding_model: col_str(&batch, i, "embedding_model"), + script_version: col_str(&batch, i, "script_version"), + volatile_flag: col_bool(&batch, i, "volatile_flag"), + is_deleted: col_bool(&batch, i, "is_deleted"), + delete_reason: col_str(&batch, i, "delete_reason"), + depends_on: String::new(), + derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 + last_recalled_at: String::new(), + created_at: col_str(&batch, i, "created_at"), + updated_at: col_str(&batch, i, "updated_at"), + // 2026-10-08 (Gap#2):读侧接线。col_f64_opt 保留 NULL 语义 + confidence: col_f64_opt(&batch, i, "confidence"), + confidence_source: col_str(&batch, i, "confidence_source"), + }); + } + } + eprintln!("[lancedb] search top_k={} → {} results", top_k, records.len()); + Ok(records) + } + + /// 查询记忆(支持 min_recall_count 过滤),供 GetSkillCandidates 使用 + pub fn query_memories(&self, min_recall: i64, limit: usize) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + // GA-P0-2 (t_c6d41ac6):技能候选 = 观测/选择(被召回多次)→ 用 recall_seen_count。 + // recall_count 已冻结,不再增长,不能再当选择依据。 + let filter = format!("recall_seen_count >= {} AND is_deleted = false AND tier != 'core'", min_recall); + let mut results = Box::pin(rt().block_on( + tbl.query() + .only_if(&filter) + .limit(limit) + .execute() + )?); + + let mut records = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + records.push(MemoryRecord { + id: col_str(&batch, i, "id"), + agent_id: col_str(&batch, i, "agent_id"), + namespace: col_str(&batch, i, "namespace"), + content: col_str(&batch, i, "content"), + category: col_str(&batch, i, "category"), + vector: col_vector(&batch, i, "vector"), + tier: col_str(&batch, i, "tier"), + importance: col_f64(&batch, i, "importance"), + quality_score: col_f64(&batch, i, "quality_score"), + recall_count: col_i64(&batch, i, "recall_count"), + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + recall_seen_count: col_i64(&batch, i, "recall_seen_count"), + recall_verified_count: col_i64(&batch, i, "recall_verified_count"), + useful_count: col_i64(&batch, i, "useful_count"), + not_useful_count: col_i64(&batch, i, "not_useful_count"), + // GA-P0-1 (t_718d8707):拆分字段读侧接线 + human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"), + dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"), + freshness: col_str(&batch, i, "freshness"), + version: col_i64(&batch, i, "version"), + version_history: String::new(), + source: col_str(&batch, i, "source"), + embedding_model: col_str(&batch, i, "embedding_model"), + script_version: col_str(&batch, i, "script_version"), + volatile_flag: col_bool(&batch, i, "volatile_flag"), + is_deleted: col_bool(&batch, i, "is_deleted"), + delete_reason: col_str(&batch, i, "delete_reason"), + depends_on: String::new(), + derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 + last_recalled_at: String::new(), + created_at: col_str(&batch, i, "created_at"), + updated_at: col_str(&batch, i, "updated_at"), + // 2026-10-08 (Gap#2):读侧接线。col_f64_opt 保留 NULL 语义 + confidence: col_f64_opt(&batch, i, "confidence"), + confidence_source: col_str(&batch, i, "confidence_source"), + }); + } + } + Ok(records) + } + + pub fn insert_batch(&self, table: &str, records_json: &str) -> Result> { + let values: serde_json::Value = serde_json::from_str(records_json)?; + let records: Vec = values.as_array().ok_or("expected JSON array")?.to_vec(); + let count = records.len(); + if count == 0 { + return Ok(0); + } + + // 构建 Arrow RecordBatch + let schema = Arc::new(arrow_schema()); + let mut ids = Vec::new(); let mut agent_ids = Vec::new(); let mut namespaces = Vec::new(); + let mut contents = Vec::new(); let mut categories = Vec::new(); let mut vectors = Vec::new(); + let mut tiers = Vec::new(); let mut importances = Vec::new(); let mut quality_scores = Vec::new(); + let mut recall_counts = Vec::new(); let mut recall_seen_counts = Vec::new(); let mut recall_verified_counts = Vec::new(); + let mut useful_counts = Vec::new(); let mut not_useful_counts = Vec::new(); + // GA-P0-1 (t_718d8707):拆分字段 + let mut human_not_useful_counts = Vec::new(); let mut dedup_downweight_counts = Vec::new(); + let mut freshnesses = Vec::new(); let mut versions = Vec::new(); + let mut version_histories = Vec::new(); let mut sources = Vec::new(); + let mut embedding_models = Vec::new(); let mut script_versions = Vec::new(); + let mut volatile_flags = Vec::new(); let mut is_deleteds = Vec::new(); + // GA-P0-3 (t_f785d7f2):删除原因(additive) + let mut delete_reasons: Vec<&str> = Vec::new(); + let mut depends_ons = Vec::new(); let mut derived_froms = Vec::new(); + // 2026-10-13 (t_e9a4d18f P1) 证据链:全量来源 episode ID(JSON 数组字符串) + let mut source_events_col = Vec::new(); + let mut supersedes_col = Vec::new(); + let mut last_recalled_ats = Vec::new(); let mut created_ats = Vec::new(); let mut updated_ats = Vec::new(); + // 2026-10-08 (Gap#2):nullable 列用 Option,未声明时写 None → 库里是 NULL + let mut confidences: Vec> = Vec::new(); + let mut confidence_sources: Vec<&str> = Vec::new(); + + for r in &records { + ids.push(r["id"].as_str().unwrap_or("")); + agent_ids.push(r["agent_id"].as_str().unwrap_or("")); + namespaces.push(r["namespace"].as_str().unwrap_or("")); + contents.push(r["content"].as_str().unwrap_or("")); + categories.push(r["category"].as_str().unwrap_or("")); + let v: Vec = if let Some(arr) = r["vector"].as_array() { + arr.iter().filter_map(|v| v.as_f64()).map(|v| v as f32).collect() + } else { vec![0.0_f32; 1024] }; + vectors.push(v); + tiers.push(r["tier"].as_str().unwrap_or("normal")); + importances.push(r["importance"].as_f64().unwrap_or(1.0)); + quality_scores.push(r["quality_score"].as_f64().unwrap_or(0.0)); + recall_counts.push(r["recall_count"].as_i64().unwrap_or(0)); + // GA-P0-2 (t_c6d41ac6):拆分字段写入 + recall_seen_counts.push(r["recall_seen_count"].as_i64().unwrap_or(0)); + recall_verified_counts.push(r["recall_verified_count"].as_i64().unwrap_or(0)); + useful_counts.push(r["useful_count"].as_i64().unwrap_or(0)); + not_useful_counts.push(r["not_useful_count"].as_i64().unwrap_or(0)); + human_not_useful_counts.push(r["human_not_useful_count"].as_i64().unwrap_or(0)); // GA-P0-1 + dedup_downweight_counts.push(r["dedup_downweight_count"].as_i64().unwrap_or(0)); // GA-P0-1 + freshnesses.push(r["freshness"].as_str().unwrap_or("fresh")); + versions.push(r["version"].as_i64().unwrap_or(1)); + version_histories.push(r["version_history"].as_str().unwrap_or("[]")); + sources.push(r["source"].as_str().unwrap_or("")); + embedding_models.push(r["embedding_model"].as_str().unwrap_or("")); + script_versions.push(r["script_version"].as_str().unwrap_or("")); + volatile_flags.push(r["volatile_flag"].as_bool().unwrap_or(false)); + is_deleteds.push(r["is_deleted"].as_bool().unwrap_or(false)); + delete_reasons.push(r["delete_reason"].as_str().unwrap_or("")); // GA-P0-3 + depends_ons.push(r["depends_on"].as_str().unwrap_or("[]")); + derived_froms.push(r["derived_from"].as_str().unwrap_or("")); + source_events_col.push(r["source_events"].as_str().unwrap_or("[]")); // 2026-10-13 P1 + supersedes_col.push(r["supersedes"].as_str().unwrap_or("[]")); // 2026-10-13 P1 + last_recalled_ats.push(r["last_recalled_at"].as_str().unwrap_or("")); + created_ats.push(r["created_at"].as_str().unwrap_or("")); + updated_ats.push(r["updated_at"].as_str().unwrap_or("")); + // confidence:显式声明才写,否则 NULL(不从 source 反推)—— + // **NULL 本身就是「未声明」的语义信号**,confidence_source 只是标签。 + confidences.push(r["confidence"].as_f64()); + // confidence_source 恒给字符串(未声明 ⇒ ""):迁移来的列可能是 non-null, + // 送 None 会被 lance 拒收。语义仍由 confidence=NULL 承担。 + confidence_sources.push(r["confidence_source"].as_str().unwrap_or("")); + } + + // 构建 vector 列 (FixedSizeList) + let flat: Vec = vectors.iter().flatten().copied().collect(); + let values_array = Float32Array::from_iter_values(flat.iter().cloned()); + let vec_array = FixedSizeListArray::try_new( + Arc::new(Field::new("item", DataType::Float32, true)), + 1024, + Arc::new(values_array), + None, + )?; + + let columns: Vec = vec![ + Arc::new(StringArray::from(ids)), + Arc::new(StringArray::from(agent_ids)), + Arc::new(StringArray::from(namespaces)), + Arc::new(StringArray::from(contents)), + Arc::new(StringArray::from(categories)), + Arc::new(vec_array), + Arc::new(StringArray::from(tiers)), + Arc::new(Float64Array::from(importances)), + Arc::new(Float64Array::from(quality_scores)), + Arc::new(Int64Array::from(recall_counts)), + Arc::new(Int64Array::from(useful_counts)), + Arc::new(Int64Array::from(not_useful_counts)), + Arc::new(StringArray::from(freshnesses)), + Arc::new(Int64Array::from(versions)), + Arc::new(StringArray::from(version_histories)), + Arc::new(StringArray::from(sources)), + Arc::new(StringArray::from(embedding_models)), + Arc::new(StringArray::from(script_versions)), + Arc::new(BooleanArray::from(volatile_flags)), + Arc::new(BooleanArray::from(is_deleteds)), + Arc::new(StringArray::from(depends_ons)), + Arc::new(StringArray::from(derived_froms)), + Arc::new(StringArray::from(last_recalled_ats)), + Arc::new(StringArray::from(created_ats)), + Arc::new(StringArray::from(updated_ats)), + // 2026-10-08 (Gap#2):顺序必须与 arrow_schema() 严格一致 + Arc::new(Float64Array::from(confidences)), + Arc::new(StringArray::from(confidence_sources)), + // GA-P0-1 (t_718d8707):顺序必须与 arrow_schema() 尾部新增列严格一致 + Arc::new(Int64Array::from(human_not_useful_counts)), + Arc::new(Int64Array::from(dedup_downweight_counts)), + // GA-P0-2 (t_c6d41ac6):拆分字段列追加在末尾,与 arrow_schema 顺序一致 + Arc::new(Int64Array::from(recall_seen_counts)), + Arc::new(Int64Array::from(recall_verified_counts)), + // GA-P0-3 (t_f785d7f2):delete_reason 列,与 arrow_schema 顺序一致(additive) + Arc::new(StringArray::from(delete_reasons)), + // 2026-10-13 (t_e9a4d18f P1):source_events 列,与 arrow_schema 顺序一致(additive) + Arc::new(StringArray::from(source_events_col)), + // 2026-10-13 (t_e9a4d18f P1):supersedes 列,与 arrow_schema 顺序一致(additive) + Arc::new(StringArray::from(supersedes_col)), + ]; + + let batch = RecordBatch::try_new(schema.clone(), columns)?; + + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table(table).execute())?; + let batches = RecordBatchIterator::new( + vec![batch].into_iter().map(Ok), + Arc::clone(&schema), + ); + rt().block_on(tbl.add(Box::new(batches)).execute())?; + + eprintln!("[lancedb] {}: inserted {} records", table, count); + Ok(count) + } + + /// 更新记忆记录的字段(通过 SQL UPDATE) + /// fields_json 格式: [{"column":"recall_count","value":"recall_count + 1"}, ...] + /// 支持算术表达式(value 包含 + 或 - 时),先查当前值再计算 + pub fn update(&self, table: &str, id: &str, fields_json: &str) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table(table).execute())?; + let fields: Vec = serde_json::from_str(fields_json)?; + let mut op = tbl.update().only_if(format!("id = '{}'", id.replace("\\'", "''"))); + + // 如果有算术表达式,先查当前值 + let has_arith = fields.iter().any(|f| { + f["value"].as_str().map(|v| v.contains('+') || v.contains('-')).unwrap_or(false) + }); + + let mut current_values: std::collections::HashMap = std::collections::HashMap::new(); + if has_arith { + // 查询当前值 + let mut results = Box::pin(rt().block_on( + tbl.query() + .only_if(&format!("id = '{}'", id.replace("\\'", "''"))) + .limit(1) + .execute(), + )?); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + for f in &fields { + let col = f["column"].as_str().unwrap_or(""); + if !col.is_empty() { + let val = col_i64(&batch, i, col); + current_values.insert(col.to_string(), val); + } + } + } + } + } + + for f in &fields { + let col = f["column"].as_str().unwrap_or(""); + let val = f["value"].as_str().unwrap_or(""); + if col.is_empty() { continue; } + + // 处理算术表达式: "column + N" 或 "column - N" + let final_val = if (val.contains('+') || val.contains('-')) && !val.starts_with("\\'") { + let parts: Vec<&str> = val.split_whitespace().collect(); + if parts.len() == 3 { + let operand_col = parts[0]; + let op_char = parts[1].chars().next().unwrap_or('+'); + if let Ok(delta) = parts[2].parse::() { + let current = *current_values.get(operand_col).unwrap_or(&0); + let new_val = match op_char { + '+' => current.saturating_add(delta), + '-' => current.saturating_sub(delta), + _ => current, + }; + eprintln!("[lancedb] update {}: col={} expr={} current={} -> {}", id, col, val, current, new_val); + new_val.to_string() + } else { + val.to_string() + } + } else { + val.to_string() + } + } else { + val.to_string() + }; + + eprintln!("[lancedb] UPDATE col={} val='{}'", col, final_val); + op = op.column(col, &final_val); + } + let updated = rt().block_on(op.execute())?; + eprintln!("[lancedb] UPDATE DONE: id={} fields={} rows={}", id, fields.len(), updated); + Ok(updated) + } + + /// 累积召回批量更新(2026-09-12 优化B)。 + /// + /// 背景:recall 读路径旧实现对每条结果调一次 update,而 LanceDB 是 MVCC—— + /// **每次 update 提交 = 一个版本**,实测 15 版本/分钟 → _versions 膨胀到 17.7G。 + /// + /// 做法(实测约束:lance 的 update 只支持基础 SQL 表达式,`CASE WHEN` 会被 + /// planner 拒绝 —— 见 2026-09-12 实测 `Expression 'CASE WHEN ...' is not supported SQL in lance`): + /// 把整批**按 delta 分组**,每组用一次 `recall_count + delta` 表达式 + `id IN (...)` 谓词提交。 + /// 真实召回流里 delta 绝大多数是 1(同一窗口内多次命中才 >1),所以 + /// N 条记忆的批量 ≈ **1 个版本**(旧实现:N 个版本)。 + /// + /// items_json: [{"id":"mem_xxx","delta":2}],ts: RFC3339(last_recalled_at) + pub fn update_recall_batch(&self, items_json: &str, ts: &str) -> Result> { + #[derive(serde::Deserialize)] + struct Item { + id: String, + delta: i64, + } + let items: Vec = serde_json::from_str(items_json)?; + if items.is_empty() { + return Ok(0); + } + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + let esc = |s: &str| s.replace("\\'", "''"); + let ts_lit = format!("'{}'", esc(ts)); + + // 按 delta 分组(BTreeMap 保证顺序稳定,便于日志/排障) + let mut groups: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for it in &items { + groups.entry(it.delta).or_default().push(it.id.clone()); + } + + let mut total: u64 = 0; + for (delta, ids) in &groups { + let predicate = format!( + "id IN ({})", + ids.iter().map(|id| format!("'{}'", esc(id))).collect::>().join(",") + ); + let op = tbl + .update() + .only_if(&predicate) + .column("recall_seen_count", &format!("recall_seen_count + {}", delta)) + .column("last_recalled_at", &ts_lit); + // GA-P0-2 (t_c6d41ac6):召回命中写 recall_seen_count(出现即 ++), + // 不再写 recall_count(冻结)。recall_count 只保留历史值,不再增长。 + // t_268b0353(治根):召回只更新 seen/last_recalled_at, + // 不再写 freshness='verified'。freshness=verified 语义是「经过校验/用户 + // 反馈」;「被召回」≠「被验证」。此前每次召回都盖 verified → 越常被召回 + // 的旧快照越「可信」,时效判断全被污染(过期快照被当现状的机制根因之一)。 + // 这是主写路径(zhiyi-consolidate sidecar)——Go 侧 write_buffer 只是兜底。 + match rt().block_on(op.execute()) { + Ok(n) => { + eprintln!( + "[lancedb] BATCH UPDATE recall DONE: delta={} ids={} rows={} (单事务)", + delta, + ids.len(), + n + ); + total += n; + } + Err(e) => { + // 兜底:谓词/表达式被拒时逐条更新(版本数退化为 N,但数据不丢、计数正确) + eprintln!( + "[lancedb] BATCH UPDATE(delta={}) failed ({}), fallback per-item ({} ids)", + delta, + e, + ids.len() + ); + for id in ids { + // GA-P0-2 (t_c6d41ac6):召回命中写 recall_seen_count;fallback 同主路径。 + let fields = format!( + r#"[{{"column":"recall_seen_count","value":"recall_seen_count + {}"}},{{"column":"last_recalled_at","value":"{}"}}]"#, + delta, ts_lit + ); + match self.update("memories", id, &fields) { + Ok(n) => total += n, + Err(e2) => eprintln!("[lancedb] fallback update {} failed: {}", id, e2), + } + } + } + } + } + Ok(total) + } + + /// 累积软删除批量更新(2026-09-12 优化C)。 + /// + /// 背景:软删除操作(SoftDelete)原先对**每条记忆**同步调用 lancedb.Update + /// (is_deleted = true + updated_at)。每次 update 提交产生一个版本。 + /// 实测生产:碎片快速道和 decay 触发产生大量 SoftDelete,导致 _versions 膨胀。 + /// + /// 方案: + /// + /// Record() 只把增量写进内存缓冲;**同一批次在一个窗口内多次 SoftDelete 合并为 一次批量提交** + /// Flush() 后台按窗口(默认 300s)+ 阈值(默认 256 条不同记忆)批量提交一次; + /// Rust 侧 lancedb_soft_delete_batch 把整批**设置相同字段**(is_deleted=true + updated_at=ts)一次提交; + /// → 每批版本数 = 1(旧实现:每行 1 个版本)。 + /// + /// 语义取舍(明确记录,便于日后审计): + /// - updated_at 最多延迟一个窗口(分钟级)。遗忘/衰减判定以「天」为单位,无影响。 + /// - 进程崩溃会丢最后一个窗口的增量(软删除标记,不是记忆数据本身),可接受。 + /// + /// items_json: [{"id":"mem_xxx"}],ts: RFC3339(updated_at) + pub fn soft_delete_batch(&self, items_json: &str, ts: &str) -> Result> { + #[derive(serde::Deserialize)] + struct Item { + id: String, + } + let items: Vec = serde_json::from_str(items_json)?; + if items.is_empty() { + return Ok(0); + } + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + let esc = |s: &str| s.replace("\\'", "''"); + let ts_lit = format!("'{}'", esc(ts)); + + // 按 id 分组(其实每个 id 只出现一次,但为了统一接口仍保持分组逻辑) + let mut groups: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for it in &items { + groups.entry(it.id.clone()).or_default().push(it.id.clone()); + } + + let mut total: u64 = 0; + for (_key, ids) in &groups { + let predicate = format!( + "id IN ({})", + ids.iter().map(|id| format!("'{}'", esc(id))).collect::>().join(",") + ); + let op = tbl + .update() + .only_if(&predicate) + .column("is_deleted", "true") + // GA-P0-3 (t_f785d7f2):批量软删不携带逐条原因 ⇒ delete_reason=unknown(兜底)。 + .column("delete_reason", "'unknown'") + .column("updated_at", &ts_lit); + match rt().block_on(op.execute()) { + Ok(n) => { + eprintln!( + "[lancedb] BATCH SOFT DELETE DONE: ids={} rows={} (单事务)", + ids.len(), + n + ); + total += n; + } + Err(e) => { + // 兜底:谓词/表达式被拒时逐条更新(版本数退化为 N,但数据不丢) + eprintln!( + "[lancedb] BATCH SOFT DELETE failed ({}), fallback per-item ({} ids)", + e, + ids.len() + ); + for id in ids { + let fields = format!( + r#"[{{"column":"is_deleted","value":"true"}},{{"column":"updated_at","value":"{}"}}]"#, + ts_lit + ); + match self.update("memories", id, &fields) { + Ok(n) => total += n, + Err(e2) => eprintln!("[lancedb] fallback soft delete {} failed: {}", id, e2), + } + } + } + } + } + Ok(total) + } + + /// 清理 id 为空的垃圾行(P1-1, 2026-10-08)。 + /// + /// 背景:DB 存在 id/content/source 全空的垃圾行 ⇒ 命中「<30 字碎片快速道」 + /// ⇒ SoftDelete("") 被 Rust IPC 拒绝("id required")⇒ 每轮刷错误日志 + 遗忘计数虚高。 + /// 这些行无 id 无法按 id 软删,只能按「id 为空」条件一次性软删(软删非硬删,is_deleted=true)。 + /// + /// 做法:一次 update 提交把 id 为空的存活行标记 is_deleted=true + updated_at=ts。 + /// 只匹配精确空串(id = '');不匹配纯空白(LanceDB SQL 的 trim 支持未验证, + /// 宁缺勿滥 —— 防御/计数代码已能安全跳过任何残留空 id,不会刷日志)。 + /// ts 由 Go 侧传入(与 soft_delete_batch 同构,避免 Rust 侧依赖时钟库)。 + pub fn purge_invalid(&self, ts: &str) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + let esc = |s: &str| s.replace("\\'", "''"); + let ts_lit = format!("'{}'", esc(ts)); + let op = tbl + .update() + .only_if("id = ''") + .column("is_deleted", "true") + .column("delete_reason", "'retention'") // GA-P0-3:id 为空垃圾行 = 保留策略清理 + .column("updated_at", &ts_lit); + let updated = rt().block_on(op.execute())?; + eprintln!("[lancedb] PURGE INVALID DONE: rows={}", updated); + Ok(updated) + } + + /// 全量扫描 memories 表(用于深整),上限 10000 条 + // P2 2026-09-06 安全版遗忘候选全表扫描(替代 febc2c9 风暴版): + // 1. 强制 limit(调用方传, main.rs 钳制硬上限 5000) + // 2. 不读 vector 列(1024 维 × 3000 条 ≈ 12MB+,IPC JSON 会卡) + // 3. 真读 last_recalled_at 列(scan_all 旧实现 String::new() 恒空 → 遗忘判定失真) + /// 全表扫描存活记忆(过滤 is_deleted,跳过 vector)。 + /// ⚠️ 名字来自历史用途(遗忘候选),语义实为「列出存活记忆」。 + /// 2026-09-21:新增 namespace 下推过滤 —— 修前 Go 侧 /memories 与 /memories/export + /// 用「零向量 ANN」冒充列表,零向量无方向 ⇒ 返回任意前 N 行再按 ns 过滤, + /// 计数完全失真(实测 hermes-main 报 1 条,实际 139+)。 + /// 用 only_if 下推过滤,limit 作用于**过滤后**的结果集,避免 5000 硬上限截断。 + pub fn scan_for_forgetting( + &self, + limit: usize, + namespace: Option<&str>, + ) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + let mut filter = String::from("is_deleted = false"); + if let Some(ns) = namespace { + if !ns.is_empty() { + let escaped = ns.replace('\\', "\\\\").replace('\'', "''"); + filter.push_str(&format!(" AND namespace = '{}'", escaped)); + } + } + + let mut results = Box::pin(rt().block_on( + tbl.query() + .only_if(&filter) + .limit(limit) + .execute() + )?); + + let mut records = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + records.push(Self::record_from_batch(&batch, i)); + } + } + eprintln!("[lancedb] scan_forgetting → {} records (limit={}, ns={:?})", records.len(), limit, namespace); + Ok(records) + } + + /// 遗忘候选「旋转窗口」扫描(2026-10-11 t_a4b8fa52 方案 c′)。 + /// + /// 修复「固定 2000 窗口不轮转」:LanceDB 0.15 查询**无 order_by**,`.limit(N)` + /// 返回的是**物理存储序**前 N 条(compact/merge 后重排,非创建序)⇒ 新记忆落物理序 + /// 后部 ⇒ 永不进遗忘候选池。方案 c′ 不依赖任何排序下推,只靠「列投影 + 集合成员」: + /// 1. 只读 id 列取**全部存活 id**:`select(["id"])` + `only_if("is_deleted = false")` + /// 2. Rust 内按字符串排序(id = mem_,定宽 ⇒ 字符串序 == 创建序严格单调) + /// 3. 取**连续窗口** `ids[start : start+limit]`,start 由游标 after_id 定位 + /// 4. 区间过滤把窗口还原成**全字段记录**:`only_if("is_deleted = false AND id >= lo AND id <= hi")` + /// 5. 新游标 = hi(窗口末 id);窗口不足 limit(取到末尾)⇒ 回绕,下次从 0 起 + /// 游标持久化在 Go 侧(/var/lib/memoryweave/forget-cursor.json,复用 conflict-seen 原子写), + /// Rust 无状态、只接收 after_id。 + pub fn scan_forgetting_window( + &self, + limit: usize, + after_id: Option<&str>, + ) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + // ── 1. 列投影:只读 id,取全部存活 id ── + // ⚠️ LanceDB 0.15 query() 默认 limit=10 —— 必须显式给大上限,否则只取 10 条 + // (spike 实测:无 limit ⇒ live_total=10;加 limit(200_000) ⇒ 22398) + let mut ids: Vec = Vec::new(); + { + let mut it = Box::pin(rt().block_on( + tbl.query() + .only_if("is_deleted = false") + .select(Select::columns(&["id"])) + .limit(200_000) + .execute() + )?); + while let Some(Ok(batch)) = rt().block_on(it.next()) { + for i in 0..batch.num_rows() { + let id = col_str(&batch, i, "id"); + // 只保留 mem_ 形态(排除 episode `ep_` 行 —— 本卡审定:episode 原始轮次不参与遗忘) + if id.starts_with("mem_") { + ids.push(id); + } + } + } + } + let live_total = ids.len(); + + // ── 2. 排序 + 去重断言(AC-9:过滤后 id 必须唯一,防未来重复 id 静默跳行)── + ids.sort(); + let before_dedup = ids.len(); + ids.dedup(); + if ids.len() != before_dedup { + eprintln!( + "[lancedb] WARN: forget window 过滤后出现 {} 条重复 id(已去重,不应发生)", + before_dedup - ids.len() + ); + } + + // ── 3. 游标定位窗口起点(纯逻辑,见 compute_forget_window)── + let (start, end, wrapped) = compute_forget_window(&ids, limit, after_id); + let window = &ids[start..end]; + + if window.is_empty() { + return Ok(ForgetWindow { + records: Vec::new(), + next_cursor: String::new(), + wrapped: true, + live_total, + }); + } + let lo = &window[0]; + let hi = &window[window.len() - 1]; + let esc = |s: &str| s.replace('\'', "''"); + let interval = format!( + "is_deleted = false AND id >= '{}' AND id <= '{}'", + esc(lo), + esc(hi) + ); + + // ── 4. 区间过滤还原全字段记录 ── + // ⚠️ 同样必须显式 limit(LanceDB 默认 10),否则窗口被截断 + let mut records: Vec = Vec::new(); + { + let mut it = Box::pin(rt().block_on( + tbl.query() + .only_if(&interval) + .limit(200_000) + .execute() + )?); + while let Some(Ok(batch)) = rt().block_on(it.next()) { + for i in 0..batch.num_rows() { + records.push(Self::record_from_batch(&batch, i)); + } + } + } + // 还原记录按 id 排序,与窗口切片一致(确定性输出) + records.sort_by(|a, b| a.id.cmp(&b.id)); + + let next_cursor = if wrapped { String::new() } else { hi.clone() }; + eprintln!( + "[lancedb] scan_forgetting_window: limit={} after={:?} window=[{}-{}] n={} live_total={} wrapped={}", + limit, after_id, lo, hi, records.len(), live_total, wrapped + ); + Ok(ForgetWindow { + records, + next_cursor, + wrapped, + live_total, + }) + } + + /// 从 RecordBatch 的一行构造 MemoryRecord(scan_forgetting / scan_forgetting_window 共用)。 + fn record_from_batch(batch: &RecordBatch, i: usize) -> MemoryRecord { + MemoryRecord { + id: col_str(batch, i, "id"), + agent_id: col_str(batch, i, "agent_id"), + namespace: col_str(batch, i, "namespace"), + content: col_str(batch, i, "content"), + category: col_str(batch, i, "category"), + vector: Vec::new(), // 不读 vector — 遗忘候选不需要向量 + tier: col_str(batch, i, "tier"), + importance: col_f64(batch, i, "importance"), + quality_score: col_f64(batch, i, "quality_score"), + recall_count: col_i64(batch, i, "recall_count"), + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + recall_seen_count: col_i64(batch, i, "recall_seen_count"), + recall_verified_count: col_i64(batch, i, "recall_verified_count"), + useful_count: col_i64(batch, i, "useful_count"), + not_useful_count: col_i64(batch, i, "not_useful_count"), + human_not_useful_count: col_i64(batch, i, "human_not_useful_count"), + dedup_downweight_count: col_i64(batch, i, "dedup_downweight_count"), + freshness: col_str(batch, i, "freshness"), + version: col_i64(batch, i, "version"), + version_history: String::new(), + source: col_str(batch, i, "source"), + embedding_model: col_str(batch, i, "embedding_model"), + script_version: col_str(batch, i, "script_version"), + volatile_flag: col_bool(batch, i, "volatile_flag"), + is_deleted: col_bool(batch, i, "is_deleted"), + delete_reason: col_str(batch, i, "delete_reason"), + depends_on: String::new(), + derived_from: String::new(), + source_events: col_str(batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(batch, i, "supersedes"), // 2026-10-13 P1 + last_recalled_at: col_str(batch, i, "last_recalled_at"), + created_at: col_str(batch, i, "created_at"), + updated_at: col_str(batch, i, "updated_at"), + confidence: col_f64_opt(batch, i, "confidence"), + confidence_source: col_str(batch, i, "confidence_source"), + } + } + + /// 全表扫描(元数据;2026-09-21 治本改造) + /// ① 用 Select 投影跳过 vector 列(1024 维 = 4KB/条,Step 3/4 都不需要) + /// ② 上限从 10000 提到 200000(原值会静默丢记录:库已有 10065 条) + pub fn scan_all(&self) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + const META_COLUMNS: &[&str] = &[ + "id", "agent_id", "namespace", "content", "category", + "tier", "importance", "quality_score", "recall_count", + "useful_count", "not_useful_count", "freshness", "version", + "source", "volatile_flag", "is_deleted", + // GA-P0-1 (t_718d8707):scan_all 投影裁剪,漏加 ⇒ col_i64 取不到列 ⇒ 恒 0 + "human_not_useful_count", "dedup_downweight_count", + // GA-P0-2 (t_c6d41ac6):拆分字段投影,漏加 ⇒ col_i64 取不到列 ⇒ 恒 0 + "recall_seen_count", "recall_verified_count", + "last_recalled_at", "created_at", "updated_at", + // 2026-10-08 (Gap#2):scan_all 用投影裁剪,漏加 ⇒ col_f64_opt 取不到列 ⇒ 恒 None + "confidence", "confidence_source", + ]; + + let mut results = Box::pin(rt().block_on( + tbl.query() + .only_if("is_deleted = false") + .select(Select::columns(META_COLUMNS)) + .limit(200_000) + .execute() + )?); + + let mut records = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + records.push(MemoryRecord { + id: col_str(&batch, i, "id"), + agent_id: col_str(&batch, i, "agent_id"), + namespace: col_str(&batch, i, "namespace"), + content: col_str(&batch, i, "content"), + category: col_str(&batch, i, "category"), + vector: Vec::new(), // 投影扫描:不读 vector(Step 3/4 不需要,省 4KB/条) + tier: col_str(&batch, i, "tier"), + importance: col_f64(&batch, i, "importance"), + quality_score: col_f64(&batch, i, "quality_score"), + recall_count: col_i64(&batch, i, "recall_count"), + // GA-P0-2 (t_c6d41ac6):拆分字段读侧接线 + recall_seen_count: col_i64(&batch, i, "recall_seen_count"), + recall_verified_count: col_i64(&batch, i, "recall_verified_count"), + useful_count: col_i64(&batch, i, "useful_count"), + not_useful_count: col_i64(&batch, i, "not_useful_count"), + // GA-P0-1 (t_718d8707):拆分字段读侧接线 + human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"), + dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"), + freshness: col_str(&batch, i, "freshness"), + version: col_i64(&batch, i, "version"), + version_history: String::new(), + source: col_str(&batch, i, "source"), + embedding_model: col_str(&batch, i, "embedding_model"), + script_version: col_str(&batch, i, "script_version"), + volatile_flag: col_bool(&batch, i, "volatile_flag"), + is_deleted: col_bool(&batch, i, "is_deleted"), + delete_reason: col_str(&batch, i, "delete_reason"), + depends_on: String::new(), + derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 + last_recalled_at: String::new(), + created_at: col_str(&batch, i, "created_at"), + updated_at: col_str(&batch, i, "updated_at"), + // 2026-10-08 (Gap#2):读侧接线。col_f64_opt 保留 NULL 语义 + confidence: col_f64_opt(&batch, i, "confidence"), + confidence_source: col_str(&batch, i, "confidence_source"), + }); + } + } + eprintln!("[lancedb] scan_all → {} records", records.len()); + Ok(records) + } + + /// 全量扫描**已删除**行(is_deleted=true)(GA-P0-3 t_f785d7f2)。 + /// + /// 背景:所有 scan 路径(scan / scan_all / scan_forgetting / scan_forgetting_window) + /// 都过滤 is_deleted=false —— 存量 11228 条 is_deleted=true 的行**没有任何读路径能看** + /// (唯独 stats 能 count)。回填脚本需要枚举已删除行以回填 delete_reason 并出直方图。 + /// + /// 只读元数据(跳 vector),上限 200000。带 delete_reason 列(供回填时跳过已回填的)。 + pub fn scan_deleted(&self) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("memories").execute())?; + + const META_COLUMNS: &[&str] = &[ + "id", "agent_id", "namespace", "content", "category", + "tier", "importance", "quality_score", "recall_count", + "useful_count", "not_useful_count", "freshness", "version", + "source", "volatile_flag", "is_deleted", + "human_not_useful_count", "dedup_downweight_count", + "recall_seen_count", "recall_verified_count", + "delete_reason", // GA-P0-3 + "last_recalled_at", "created_at", "updated_at", + "confidence", "confidence_source", + ]; + + let mut results = Box::pin(rt().block_on( + tbl.query() + .only_if("is_deleted = true") + .select(Select::columns(META_COLUMNS)) + .limit(200_000) + .execute() + )?); + + let mut records = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + records.push(MemoryRecord { + id: col_str(&batch, i, "id"), + agent_id: col_str(&batch, i, "agent_id"), + namespace: col_str(&batch, i, "namespace"), + content: col_str(&batch, i, "content"), + category: col_str(&batch, i, "category"), + vector: Vec::new(), + tier: col_str(&batch, i, "tier"), + importance: col_f64(&batch, i, "importance"), + quality_score: col_f64(&batch, i, "quality_score"), + recall_count: col_i64(&batch, i, "recall_count"), + recall_seen_count: col_i64(&batch, i, "recall_seen_count"), + recall_verified_count: col_i64(&batch, i, "recall_verified_count"), + useful_count: col_i64(&batch, i, "useful_count"), + not_useful_count: col_i64(&batch, i, "not_useful_count"), + human_not_useful_count: col_i64(&batch, i, "human_not_useful_count"), + dedup_downweight_count: col_i64(&batch, i, "dedup_downweight_count"), + freshness: col_str(&batch, i, "freshness"), + version: col_i64(&batch, i, "version"), + version_history: String::new(), + source: col_str(&batch, i, "source"), + embedding_model: col_str(&batch, i, "embedding_model"), + script_version: col_str(&batch, i, "script_version"), + volatile_flag: col_bool(&batch, i, "volatile_flag"), + is_deleted: col_bool(&batch, i, "is_deleted"), + delete_reason: col_str(&batch, i, "delete_reason"), + depends_on: String::new(), + derived_from: String::new(), + source_events: col_str(&batch, i, "source_events"), // 2026-10-13 P1 + supersedes: col_str(&batch, i, "supersedes"), // 2026-10-13 P1 + last_recalled_at: col_str(&batch, i, "last_recalled_at"), + created_at: col_str(&batch, i, "created_at"), + updated_at: col_str(&batch, i, "updated_at"), + confidence: col_f64_opt(&batch, i, "confidence"), + confidence_source: col_str(&batch, i, "confidence_source"), + }); + } + } + eprintln!("[lancedb] scan_deleted → {} records", records.len()); + Ok(records) + } +} + +#[derive(Debug, Serialize)] +pub struct LanceDBStats { + pub total_memories: usize, + pub total_episodes: usize, + pub tombstone_count: usize, + pub data_dir: String, +} + +impl LanceDBOps { + /// 追加一条真实 outcome 事件到 hit_events 表(GA-P0-4 t_bb10e8bc)。 + /// append-only:每次真实 outcome 追加一行(带 created_at),**不覆盖式累加**。 + pub fn append_hit_event(&self, memory_id: &str, outcome: &str, reason: &str, source: &str, ts: &str) -> Result> { + let id = hit_event_id(memory_id); + let schema = Arc::new(hit_event_arrow_schema()); + let columns: Vec = vec![ + Arc::new(StringArray::from(vec![id])), + Arc::new(StringArray::from(vec![memory_id.to_string()])), + Arc::new(StringArray::from(vec![outcome.to_string()])), + Arc::new(StringArray::from(vec![reason.to_string()])), + Arc::new(StringArray::from(vec![source.to_string()])), + Arc::new(StringArray::from(vec![ts.to_string()])), + ]; + let batch = RecordBatch::try_new(schema.clone(), columns)?; + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("hit_events").execute())?; + let batches = RecordBatchIterator::new(vec![batch].into_iter().map(Ok), Arc::clone(&schema)); + rt().block_on(tbl.add(Box::new(batches)).execute())?; + eprintln!("[lancedb] hit_events: appended id={} outcome={} reason={}", memory_id, outcome, reason); + Ok(1) + } + + /// 统计某 memory 在某时间窗起点(since, RFC3339)之后的 outcome 事件数(P2 自适应阈值按周窗口用)。 + pub fn count_hit_events(&self, memory_id: &str, outcome: &str, since: &str) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("hit_events").execute())?; + // created_at 恒以 UTC(RFC3339 "Z") 存储(append 侧 chrono::Utc 生成)。 + // since 可能是本地时区("+08:00")——字符串比较跨时区会错位,必须先归一到 UTC。 + let since_utc = chrono::DateTime::parse_from_rfc3339(since) + .map(|dt| dt.with_timezone(&chrono::Utc).to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) + .unwrap_or_else(|_| since.to_string()); + let filter = format!( + "memory_id = '{}' AND outcome = '{}' AND created_at >= '{}'", + sql_escape(memory_id), sql_escape(outcome), sql_escape(&since_utc) + ); + let mut results = Box::pin(rt().block_on(tbl.query().only_if(&filter).execute())?); + let mut n: u64 = 0; + while let Some(Ok(batch)) = rt().block_on(results.next()) { + n += batch.num_rows() as u64; + } + Ok(n) + } + + /// 读回某 memory 的事件明细(read-back 取证,非只看函数返回)。 + pub fn get_hit_events(&self, memory_id: &str, limit: usize) -> Result, Box> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tbl = rt().block_on(db.open_table("hit_events").execute())?; + let filter = format!("memory_id = '{}'", sql_escape(memory_id)); + let mut results = Box::pin(rt().block_on( + tbl.query().only_if(&filter).limit(limit).execute(), + )?); + let mut events = Vec::new(); + while let Some(Ok(batch)) = rt().block_on(results.next()) { + for i in 0..batch.num_rows() { + events.push(HitEventRecord { + id: col_str(&batch, i, "id"), + memory_id: col_str(&batch, i, "memory_id"), + outcome: col_str(&batch, i, "outcome"), + reason: col_str(&batch, i, "reason"), + source: col_str(&batch, i, "source"), + created_at: col_str(&batch, i, "created_at"), + }); + } + } + Ok(events) + } + + pub fn stats(&self) -> Result> { + let db = rt().block_on(lancedb::connect(self.data_dir.to_str().unwrap()).execute())?; + let tables = rt().block_on(db.table_names().execute())?; + let mut m = 0usize; let mut e = 0usize; let mut t = 0usize; + for name in &tables { + if let Ok(tbl) = rt().block_on(db.open_table(name).execute()) { + if name == "memories" { + if let Ok(cnt) = rt().block_on(tbl.count_rows(None)) { m = cnt; } + if let Ok(tc) = rt().block_on(tbl.count_rows(Some("is_deleted = true".to_string()))) { t = tc; } + } else if let Ok(cnt) = rt().block_on(tbl.count_rows(None)) { + match name.as_str() { + "episodes" => e = cnt, + _ => {} + } + } + } + } + Ok(LanceDBStats { + total_memories: m, total_episodes: e, tombstone_count: t, + data_dir: self.data_dir.to_string_lossy().to_string(), + }) + } +} + +// ── Arrow RecordBatch helpers ── +fn col_str(b: &RecordBatch, r: usize, c: &str) -> String { + b.column_by_name(c) + .and_then(|col| col.as_any().downcast_ref::()) + .map(|a| a.value(r).to_string()) + .unwrap_or_default() +} +fn col_f64(b: &RecordBatch, r: usize, c: &str) -> f64 { + b.column_by_name(c) + .and_then(|col| col.as_any().downcast_ref::()) + .map(|a| a.value(r)) + .unwrap_or(0.0) +} +/// col_f64_opt 2026-10-08 (Gap#2):可空浮点读法。 +/// 与 col_f64 的关键差别:**列不存在**或**该行是 NULL** 都返回 None,而不是 0.0。 +/// 对 confidence 这是必须的 —— 0.0 会被读成「极不信任」,而 NULL 表示「未声明」。 +fn col_f64_opt(b: &RecordBatch, r: usize, c: &str) -> Option { + b.column_by_name(c) + .and_then(|col| col.as_any().downcast_ref::()) + .and_then(|a| if a.is_null(r) { None } else { Some(a.value(r)) }) +} +fn col_i64(b: &RecordBatch, r: usize, c: &str) -> i64 { + b.column_by_name(c) + .and_then(|col| col.as_any().downcast_ref::()) + .map(|a| a.value(r)) + .unwrap_or(0) +} +fn col_bool(b: &RecordBatch, r: usize, c: &str) -> bool { + b.column_by_name(c) + .and_then(|col| col.as_any().downcast_ref::()) + .map(|a| a.value(r)) + .unwrap_or(false) +} + +/// 读取 vector 列 (兼容 FixedSizeListArray 和 Float32Array) +fn col_vector(b: &RecordBatch, r: usize, c: &str) -> Vec { + let col = match b.column_by_name(c) { + Some(col) => col, + None => return vec![0.0_f32; 1024], + }; + // 优先尝试 FixedSizeListArray (当前使用的格式) + if let Some(list_arr) = col.as_any().downcast_ref::() { + let item_arr = list_arr.value(r); + if let Some(float_arr) = item_arr.as_any().downcast_ref::() { + return float_arr.values().to_vec(); + } + } + // 回退: Float32Array (展平格式) + if let Some(float_arr) = col.as_any().downcast_ref::() { + let stride = 1024; + let start = r * stride; + if start + stride <= float_arr.len() { + return float_arr.values()[start..start + stride].to_vec(); + } + } + vec![0.0_f32; 1024] +} + +/// 纯逻辑:计算遗忘候选旋转窗口的下标区间。 +/// - 输入:已排序去重的存活 id 集合(仅 mem_ 形态)、limit、after_id(游标) +/// - 返回:(start, end, wrapped) +/// - 窗口 = ids[start..end] +/// - wrapped=true 表示**游标回绕回 0**(本次传了游标,且游标 ≥ 全部 id 或已到存活集合末尾) +/// ⇒ 一轮完整遍历结束,下次从 0 起。无论 live 是否能被 limit 整除都能正确发出信号 +/// (整除时靠「游标到末尾→下一轮回绕」触发,非整除时末窗口不足 limit 也回绕)。 +/// 不依赖 LanceDB 排序下推,纯字符串集合成员计算(方案 c′ 核心,可单测)。 +fn compute_forget_window( + ids: &[String], + limit: usize, + after_id: Option<&str>, +) -> (usize, usize, bool) { + let has_cursor = matches!(after_id, Some(a) if !a.is_empty()); + if ids.is_empty() { + // 空库/全删:无可扫,直接标记一轮遍历结束(回绕语义,使 Go 侧游标复位不卡) + return (0, 0, true); + } + let mut start = if has_cursor { + // 第一个 > after_id 的下标;after_id 已删除/不在集合中 → 仍续扫之后(不丢、不崩) + ids.partition_point(|x| x.as_str() <= after_id.unwrap()) + } else { + 0 + }; + // 游标 ≥ 全部 id(已到末尾)→ 回绕到 0,并标记「一轮遍历结束」 + let mut wrapped = false; + if start >= ids.len() { + start = 0; + wrapped = has_cursor; + } + let end = (start + limit).min(ids.len()); + (start, end, wrapped) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 构造 N 个连续 mem_ 形态 id(定宽前缀保证字符串序 == 数字序)。 + fn mk_ids(n: u64) -> Vec { + (0..n).map(|i| format!("mem_{:019}", i)).collect() + } + + /// 断言:连续 N 轮窗口的并集 == 全部存活 id(全覆盖判据,AC-1)。 + /// 轮数上界 = ceil(live/limit),模拟真实调度(每 6h 一轮)。 + fn union_covers_all(live: usize, limit: usize) -> bool { + let ids = mk_ids(live as u64); + let mut cursor = String::new(); + let mut union = std::collections::HashSet::new(); + let mut rounds = 0usize; + let max_rounds = live.div_ceil(limit) + 2; // 上界 + 余量 + loop { + let after = if cursor.is_empty() { None } else { Some(cursor.as_str()) }; + let (s, e, wrapped) = compute_forget_window(&ids, limit, after); + for x in &ids[s..e] { + union.insert(x.clone()); + } + rounds += 1; + if wrapped { + break; + } + cursor = ids[e - 1].clone(); // 窗口末 id = 新游标 + if rounds > max_rounds { + break; // 防死循环(理论不会触发) + } + } + union.len() == live && rounds <= max_rounds + } + + /// 断言:窗口内全部「不满足遗忘条件」时,下一轮窗口仍与上一轮不同(不卡死,AC-2)。 + fn not_stuck(live: usize, limit: usize) -> bool { + let ids = mk_ids(live as u64); + let after = Some(ids[0].as_str()); // 假设第 0 条已在窗口 + let (s0, e0, _) = compute_forget_window(&ids, limit, None); + let w0: Vec = ids[s0..e0].to_vec(); + let (s1, e1, _) = compute_forget_window(&ids, limit, after); + let w1: Vec = ids[s1..e1].to_vec(); + // 窗口前进 → 集合不同(不卡死) + w0 != w1 && !w1.is_empty() + } + + #[test] + fn test_window_full_coverage() { + // 小表(能整除):9 存活 / 3 窗口 → 3 轮全覆盖 + assert!(union_covers_all(9, 3), "9/3 应 3 轮全覆盖"); + // 非整除:10 存活 / 3 窗口 → 最后一轮不足 → 仍全覆盖 + assert!(union_covers_all(10, 3), "10/3 应 ceil=4 轮全覆盖"); + // 大表:22447 存活 / 2000 窗口 → ceil=12 轮全覆盖(贴近生产量级) + assert!(union_covers_all(22447, 2000), "22447/2000 应 12 轮全覆盖"); + // 单条 / 空边界不崩 + assert!(union_covers_all(1, 2000), "1 条应 1 轮全覆盖"); + } + + #[test] + fn test_window_not_stuck() { + // 窗口全不满足遗忘条件(模拟前 2000 条被高 recall 保护)→ 下轮仍换一批 + assert!(not_stuck(10, 3), "前 3 条保护 → 下轮应换一批"); + assert!(not_stuck(10000, 2000), "大表不卡死"); + } + + #[test] + fn test_window_wrap_boundary() { + // 空集合:window 为空,wrapped=true,不 panic + let empty: Vec = vec![]; + let (s, e, wrapped) = compute_forget_window(&empty, 2000, None); + assert_eq!(s, 0); + assert_eq!(e, 0); + assert!(wrapped); + // 单条:首轮返回该条(未 wrapped,游标=该 id);次轮游标回绕才 wrapped + let ids = mk_ids(1); + let (s, e, wrapped) = compute_forget_window(&ids, 2000, None); + assert_eq!(s, 0); + assert_eq!(e, 1); + assert!(!wrapped, "单条首轮覆盖完成,但游标尚未回绕 → 不标记"); + let only = ids[0].clone(); + let (s2, _e2, wrapped2) = compute_forget_window(&ids, 2000, Some(&only)); + assert_eq!(s2, 0); + assert!(wrapped2, "单条次轮游标回绕 → 标记一轮遍历结束"); + // 游标已到末尾(= 最后一个 id)→ 下轮回绕从 0 起,并标记一轮遍历结束 + let ids = mk_ids(10); + let last = ids.last().unwrap().clone(); + let (s, e, wrapped) = compute_forget_window(&ids, 3, Some(&last)); + assert_eq!(s, 0, "游标在末尾 → 应回绕到 0"); + assert_eq!(e, 3); + assert!(wrapped, "回绕到 0 → 标记一轮遍历结束"); + } + + #[test] + fn test_window_cursor_deleted_resilience() { + // 游标 id 已被删除(不在集合中)→ 降级续扫其后,不 panic(AC-8) + let mut ids = mk_ids(10); + // 真删掉 id=5(模拟 soft-delete 后该 id 不在存活集合) + ids.retain(|x| x != "mem_0000000000000000005"); + let gone = format!("mem_{:019}", 5); // 游标指向已删的 5 + let (s, e, _) = compute_forget_window(&ids, 3, Some(&gone)); + assert_eq!(s, 5, "游标=已删的5 → 应从第一个>5的下标续扫(不丢不崩)"); + assert_eq!(e, 8); + // 游标大于全部 id → 回绕从头 + let big = format!("mem_{:019}", 999); + let (s, e, wrapped) = compute_forget_window(&ids, 3, Some(&big)); + assert_eq!(s, 0, "游标大于全部 → 回绕从头"); + assert_eq!(e, 3); + assert!(wrapped, "游标越界 → 标记一轮遍历结束"); + } + + #[test] + fn test_window_dedup_assertion() { + // 排序后去重:重复 id 应被去重且不崩(AC-9) + let mut ids = mk_ids(5); + ids.push("mem_0000000000000000002".to_string()); // 重复 + ids.sort(); + let before = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), before - 1, "重复 id 应去重"); + // 去重后仍能正确轮转 + let (s, e, _) = compute_forget_window(&ids, 2000, None); + assert_eq!(s, 0); + assert_eq!(e, ids.len()); + } + + /// 真实库只读覆盖率测试(AC-1/2,需 LIVE_DB_WINDOW=1 才跑,避免污染常规 cargo test)。 + /// 用生产代码路径 scan_forgetting_window 循环取窗直到 wrapped,验证: + /// ① 连续窗口两两不同(不卡死) + /// ② 并集最终覆盖全部存活 mem_ 记忆(覆盖率→100%) + /// ③ 池内 created_at>10-07 条数从旧实现~2 显著上升 + #[test] + fn test_live_db_full_coverage() { + if std::env::var("LIVE_DB_WINDOW").as_deref() != Ok("1") { + eprintln!("[skip] LIVE_DB_WINDOW!=1"); + return; + } + let ldb = LanceDBOps::open("/var/lib/memoryweave").expect("open live db"); + let mut union = std::collections::HashSet::new(); + let mut cursor = String::new(); + let mut round = 0usize; + let mut live_total = 0usize; + let mut max_recent = 0usize; + let mut rounds_with_recent = 0usize; + loop { + let after = if cursor.is_empty() { None } else { Some(cursor.as_str()) }; + let w = ldb.scan_forgetting_window(2000, after).expect("window"); + if round == 0 { live_total = w.live_total; } + let recent = w.records.iter().filter(|r| r.created_at > "2026-10-07T00:00:00Z".to_string()).count(); + max_recent = max_recent.max(recent); + if recent > 0 { rounds_with_recent += 1; } + for r in &w.records { union.insert(r.id.clone()); } + round += 1; + println!("round{} n={} live_total={} wrapped={} recent>10-07={} union={}/{}", + round, w.records.len(), w.live_total, w.wrapped, recent, union.len(), live_total); + if w.wrapped { break; } + cursor = w.next_cursor; + if round > live_total.div_ceil(2000) + 5 { println!("guard break"); break; } + } + println!("RESULT: rounds={} union={} live_total={} coverage={:.4} max_recent_in_pool={} rounds_with_recent={}", + round, union.len(), live_total, union.len() as f64 / live_total as f64, max_recent, rounds_with_recent); + assert_eq!(union.len(), live_total, "全库存活 mem_ 记忆应被全覆盖"); + } +} \ No newline at end of file