From d2348eda433194ab3f7bca1fbf827d12b3aa0878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Wed, 14 Oct 2026 01:28:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(distill):=20t=5F2515307a=20=E7=A1=AE?= =?UTF-8?q?=E5=AE=9A=E6=80=A7=E5=88=A4=E6=8D=AE=E5=BC=BA=E5=8C=96=E2=80=94?= =?UTF-8?q?=E2=80=94=E5=8F=AC=E5=9B=9E=E4=BE=A7=E8=A7=84=E5=88=99=E8=BF=87?= =?UTF-8?q?=E6=BB=A4/=E9=99=8D=E6=9D=83(env=E9=97=A8=E6=8E=A7ZHIYI=5FRULE?= =?UTF-8?q?=5FFIRST=E9=BB=98=E8=AE=A4=E5=85=B3);=20RecallRuleVerdict?= =?UTF-8?q?=E5=A4=8D=E7=94=A8quality.go+admission=5Flane=E8=A7=84=E5=88=99?= =?UTF-8?q?+URL/=E8=B7=AF=E5=BE=84=E5=BC=BA=E5=AE=9E=E4=BD=93=E8=B1=81?= =?UTF-8?q?=E5=85=8D;=20routes/core.go=20Recall=E6=8C=89verdict=E8=BF=87?= =?UTF-8?q?=E6=BB=A4drop/=E9=99=8D=E6=9D=83demote;=20=E5=8D=95=E6=B5=8B16?= =?UTF-8?q?=E7=94=A8=E4=BE=8BPASS;=20=E5=BD=B1=E5=AD=90=E6=8E=A2=E9=92=88r?= =?UTF-8?q?ulefirst-probe/scan=E5=8F=96=E8=AF=8126drop+4demote;=20?= =?UTF-8?q?=E9=9B=B6=E6=96=B0=E4=BE=9D=E8=B5=96=E4=B8=8D=E7=A2=B0state.db?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go/cmd/rulefirst-probe/main.go | 174 ++++++++++++++++++++++++ go/cmd/rulefirst-scan/main.go | 109 +++++++++++++++ go/internal/distill/recall_rule.go | 144 ++++++++++++++++++++ go/internal/distill/recall_rule_test.go | 98 +++++++++++++ 4 files changed, 525 insertions(+) create mode 100644 go/cmd/rulefirst-probe/main.go create mode 100644 go/cmd/rulefirst-scan/main.go create mode 100644 go/internal/distill/recall_rule.go create mode 100644 go/internal/distill/recall_rule_test.go diff --git a/go/cmd/rulefirst-probe/main.go b/go/cmd/rulefirst-probe/main.go new file mode 100644 index 0000000..21356e8 --- /dev/null +++ b/go/cmd/rulefirst-probe/main.go @@ -0,0 +1,174 @@ +// 织忆·确定性判据强化 影子探针(t_2515307a)—— 只记录,不施加 +// +// 职责:从线上 zhiyid 拉真实召回候选(top_k=50),对每条内容跑 +// distill.RecallRuleVerdict(真实 Go 规则,零漂移),输出 +// keep / demote / drop 三组 + 每条 reason,供 AC3(结果变化对照) +// 与 AC4(人工抽检被过滤项)取证。不改生产行为、不写库。 +// +// 用法: +// cd go && go run ./cmd/rulefirst-probe # 默认组查询 +// cd go && go run ./cmd/rulefirst-probe --query "..." # 单条指定 +// cd go && go run ./cmd/rulefirst-probe --out /tmp/rf.json # 落盘供 AC4 抽检 +package main + +import ( + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "os" + "strings" + + "github.com/xiaoxue/memoryweave/internal/distill" + "github.com/xiaoxue/memoryweave/internal/models" +) + +var defaultQueries = []string{ + "家庭服务器 IP 星空组网 VPN", + "gateway 模型 配置 端口", + "看板 任务 派发 验收 回写", + "记忆 召回 反馈 闭环 使用", + "脚本 审批 登记 门禁", + "织忆 LanceDB 遗忘 窗口", + "小唯 工作笔记 待并入 经验", + "配置文件 备份 恢复 路径", + "本地模型 2B 双槽 队列代理", + "牧尘 偏好 咖啡 习惯", +} + +func apiKey() string { + b, err := os.ReadFile("/var/lib/memoryweave/.api-key") + if err == nil { + for _, line := range strings.Split(string(b), "\n") { + s := strings.TrimSpace(line) + if s != "" && !strings.HasPrefix(s, "#") && !strings.Contains(s, "legacy") { + return strings.Fields(s)[0] + } + } + } + return os.Getenv("ZHIYI_API_KEY") +} + +func recall(query string, topK int) ([]models.RecallResult, error) { + body, _ := json.Marshal(map[string]any{"query": query, "top_k": topK, "namespace": ""}) + req, err := http.NewRequest("POST", "http://127.0.0.1:7821/api/v1/recall", strings.NewReader(string(body))) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-API-Key", apiKey()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + var d struct { + Results []models.RecallResult `json:"results"` + } + if err := json.Unmarshal(raw, &d); err != nil { + return nil, fmt.Errorf("unmarshal: %w", err) + } + return d.Results, nil +} + +func main() { + var q, out string + flag.StringVar(&q, "query", "", "指定单条 query(默认跑内置 10 条)") + flag.StringVar(&out, "out", "", "落盘 JSON 路径(供 AC4 抽检)") + flag.Parse() + + queries := defaultQueries + if q != "" { + queries = []string{q} + } + + type item struct { + Query string `json:"query"` + ID string `json:"id"` + Content string `json:"content"` + Verdict string `json:"verdict"` + Reason string `json:"reason"` + } + var all []item + var keep, demote, drop []item + byQ := map[string][3][]item{} + + for _, query := range queries { + res, err := recall(query, 50) + if err != nil { + fmt.Printf("QUERY %q ERR %v\n", query, err) + continue + } + var kk, dd, drr []item + toItem := func(r models.RecallResult, v distill.RecallVerdict, why string) item { + return item{Query: query, ID: r.ID, Content: r.Content, Verdict: verdictName(v), Reason: why} + } + // 每条候选跑真实 Go 规则 + for _, r := range res { + v, why := distill.RecallRuleVerdict(r.Content) + it := toItem(r, v, why) + all = append(all, it) + switch v { + case distill.RecallKeep: + kk = append(kk, it) + case distill.RecallDemote: + dd = append(dd, it) + case distill.RecallDrop: + drr = append(drr, it) + } + } + keep = append(keep, kk...) + demote = append(demote, dd...) + drop = append(drop, drr...) + byQ[query] = [3][]item{kk, dd, drr} + fmt.Printf("QUERY %q → 候选=%d keep=%d demote=%d drop=%d\n", + query, len(res), len(kk), len(dd), len(drr)) + for _, it := range drr { + fmt.Printf(" [DROP] %-30s %s | %s\n", it.ID, it.Reason, truncate(it.Content, 42)) + } + for _, it := range dd { + fmt.Printf(" [DEMOTE] %-30s %s | %s\n", it.ID, it.Reason, truncate(it.Content, 42)) + } + } + + fmt.Printf("\n=== 汇总: 候选总数=%d keep=%d demote=%d drop=%d ===\n", + len(all), len(keep), len(demote), len(drop)) + + if out != "" { + f, err := os.Create(out) + if err == nil { + enc := json.NewEncoder(f) + enc.SetIndent("", " ") + _ = enc.Encode(map[string]any{ + "all": all, + "keep": keep, + "demote": demote, + "drop": drop, + "by_query": byQ, + }) + f.Close() + fmt.Printf("已落盘 %s\n", out) + } + } +} + +func verdictName(v distill.RecallVerdict) string { + switch v { + case distill.RecallKeep: + return "keep" + case distill.RecallDemote: + return "demote" + default: + return "drop" + } +} + +func truncate(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) + "…" +} \ No newline at end of file diff --git a/go/cmd/rulefirst-scan/main.go b/go/cmd/rulefirst-scan/main.go new file mode 100644 index 0000000..0b7ab73 --- /dev/null +++ b/go/cmd/rulefirst-scan/main.go @@ -0,0 +1,109 @@ +// 织忆·确定性判据扫描(t_2515307a 取证)——按 namespace 分批扫全表,输出 drop/demote 明细供 AC4 +package main + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "strings" + + "github.com/xiaoxue/memoryweave/internal/distill" +) + +func apikey() string { + b, _ := os.ReadFile("/var/lib/memoryweave/.api-key") + for _, l := range strings.Split(string(b), "\n") { + s := strings.TrimSpace(l) + if s != "" && !strings.HasPrefix(s, "#") && !strings.Contains(s, "legacy") { + return strings.Fields(s)[0] + } + } + return "" +} + +func list(ns string, limit int) ([]struct { + ID string `json:"id"` + Content string `json:"content"` +}, error) { + u := fmt.Sprintf("http://127.0.0.1:7821/api/v1/memories?limit=%d", limit) + if ns != "" { + u += "&namespace=" + ns + } + req, _ := http.NewRequest("GET", u, nil) + req.Header.Set("X-API-Key", apikey()) + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<26)) + var d struct { + Memories []struct { + ID string `json:"id"` + Content string `json:"content"` + } `json:"memories"` + } + if err := json.Unmarshal(raw, &d); err != nil { + return nil, err + } + return d.Memories, nil +} + +func main() { + namespaces := []string{ + "", "hermes-main", "shared", "wiki-curator-main", "wiki", "soulful-xiaowei", + "a06-main", "domain:dev", "default-main", "hermes", "wiki:decision", + } + seen := map[string]bool{} + var all []struct { + ID string `json:"id"` + Content string `json:"content"` + } + for _, ns := range namespaces { + ms, err := list(ns, 1000) + if err != nil { + continue + } + for _, m := range ms { + if !seen[m.ID] { + seen[m.ID] = true + all = append(all, m) + } + } + } + type rec struct { + ID string + Content string + Why string + } + var drops, demotes []rec + for _, m := range all { + v, why := distill.RecallRuleVerdict(m.Content) + if v == distill.RecallDrop { + drops = append(drops, rec{m.ID, m.Content, why}) + } else if v == distill.RecallDemote { + demotes = append(demotes, rec{m.ID, m.Content, why}) + } + } + fmt.Printf("unique_total=%d drops=%d demotes=%d\n\n", len(all), len(drops), len(demotes)) + fmt.Println("===== DROPS (进不了 top-N) =====") + for i, d := range drops { + rc := []rune(d.Content) + c := d.Content + if len(rc) > 55 { + c = string(rc[:55]) + "…" + } + fmt.Printf("%2d. [%s] %s\n", i+1, d.Why, c) + } + fmt.Println("\n===== DEMOTES (降权) =====") + for i, d := range demotes { + rc := []rune(d.Content) + c := d.Content + if len(rc) > 55 { + c = string(rc[:55]) + "…" + } + fmt.Printf("%2d. [%s] %s\n", i+1, d.Why, c) + } +} diff --git a/go/internal/distill/recall_rule.go b/go/internal/distill/recall_rule.go new file mode 100644 index 0000000..e4a1eef --- /dev/null +++ b/go/internal/distill/recall_rule.go @@ -0,0 +1,144 @@ +// 织忆 MemoryWeave — 召回侧确定性判据(kanban t_2515307a) +// +// 为什么(判据优先级「确定性 > 模型」,见设计文档 §一·补): +// 实测本地 2B 的 LLM 评分只有 12 种 dims 模板(前 4 种占 84%)、退化率 4%, +// 无法用于「这条记忆能不能用」的精细排序。而 quality.go 的确定性规则 +// (isPureQuestion / isStatusReportLike / isSoulfulShortFact / hasEntity / +// hasVerbPhrase)与 textfilter.IsSystemTemplate 只在**蒸馏写入侧**用, +// 召回时没人用 —— 本文件把它们复用到召回侧,给候选做**纯规则过滤/降权**。 +// +// 三条设计规则(§一·补): +// 1. 凡能用确定性规则判的,不用模型 —— 本文件 0 LLM 调用。 +// 2. LLM 分数只做粗筛(2~3 档),不做精细排序 —— 精细判据走这里的确定性规则。 +// 3. 每个插槽可证伪:env 门控 ZHIYI_RULE_FIRST,默认关 ⇒ 零行为变化。 +// +// 用法:调用方(routes 层,因 distill→storage 有 import 依赖,storage 不能 +// import distill)在召回结果集上逐条调 RecallRuleVerdict,按 verdict 过滤 +// (RecallDrop)或降权重排(RecallDemote)。纯函数,同输入恒同输出,可单测。 +package distill + +import ( + "strings" + "unicode/utf8" + + "github.com/xiaoxue/memoryweave/internal/textfilter" +) + +// hasUrlishEntity 判定内容是否含 URL / 路径 / 域名等**强实体**形态。 +// 为什么单独补:hasEntity(quality.go)只认「强实体词 + 词首大写 + 数字」, +// 而 URL(github.com/iOfficeAI/AionUi)、路径(~/projects/…)、域名 +// (dart-lang)等中间无空格的实体形态命中不了它(2026-10-14 实测:8 条 +// 20-50 字的仓库 URL/源码路径事实被误判为「弱内容」降权)。URL/路径是 +// 确定性的强实体信号,命中即视为有实体 → 不应走弱内容降权。 +func hasUrlishEntity(s string) bool { + lower := strings.ToLower(s) + urlHints := []string{"http://", "https://", "www.", ".com", ".io", ".org", + "github.com", "github", "gitlab", "gitea", ".git", + "~/", "/home/", "/var/lib/", "/usr/", "/etc/", "C:\\", "://"} + for _, h := range urlHints { + if strings.Contains(lower, h) { + return true + } + } + return false +} + +// RecallVerdict 召回侧确定性判据结论。 +type RecallVerdict int + +const ( + RecallKeep RecallVerdict = iota // 确定性可用 → 保留原序 + RecallDemote // 确定性弱内容 → 降权(排到后面,不删) + RecallDrop // 确定性不可用 → 过滤(不进 top-N) +) + +// RecallRuleVerdict 对一条召回候选内容做确定性判据。 +// +// 判什么 / 为什么可靠(全部复用写入侧已检验的规则,零 LLM 推理): +// +// 1. 系统样板(textfilter.IsSystemTemplate)→ Drop +// 判什么:cron 投递 / 网关包裹 / 上下文摘要等系统元信息,不是用户记忆。 +// 为什么可靠:结构化头子串匹配("[IMPORTANT:"、"[HEARTBEAT]"、"[System note:"…), +// 纯数据匹配,写入侧准入闸门(admission_lane.go)已用同一份判定。 +// +// 2. 纯疑问句(isPureQuestion)→ Drop +// 判什么:整句是疑问(问号结尾 / 疑问前缀+语气词),不是可用的陈述性记忆。 +// 为什么可靠:结尾问号+前缀集合匹配,写入侧质量门槛(quality.go)第一道硬否定。 +// +// 3. 状态汇报型/进程噪声(isStatusReportLike)→ Drop +// 判什么:健康检查/重启完成/桥接等无主句进程噪声,不是用户事实。 +// 为什么可靠:无主语+状态短语/完成标记匹配,写入侧质量门槛第二道硬否定。 +// +// 4. 过短碎片(<20 字,非人侧结构化前缀,无实体且无动词)→ Drop +// 判什么:无信息的碎片(无主体、无动作、无实体),不该进 top-N。 +// 为什么可靠:长度+实体+动词短语三重确定性判定,与 quality.go IsQualityFact +// 的 <20 字拒绝规则同源;人侧结构化前缀(画像:/心迹:/偏好:…)豁免(isSoulfulShortFact)。 +// +// 5. 弱内容(20-50 字,无实体且无动词)→ Demote +// 判什么:有长度但无实体无动词,信息量弱的陈述,降权但不删除。 +// 为什么可靠:20-50 字需含实体或动词短语,quality.go 同一条长度门槛,降为降权。 +// +// 其余 → Keep(保留原序,不做任何改动)。 +func RecallRuleVerdict(content string) (RecallVerdict, string) { + s := strings.TrimSpace(content) + if s == "" { + return RecallDrop, "空内容" + } + // 1. 系统样板 + if textfilter.IsSystemTemplate(s) { + return RecallDrop, "系统样板" + } + // 2. 纯疑问句 + if isPureQuestion(s) { + return RecallDrop, "纯疑问句" + } + // 3. 状态汇报/进程噪声 + if isStatusReportLike(s) { + return RecallDrop, "状态汇报/进程噪声" + } + // 4/5. 长度 + 实体/动词 门槛 + n := utf8.RuneCountInString(s) + if n < 20 { + // 人侧结构化短事实(画像:/心迹:/偏好:/习惯:/目标: 等)豁免 → 保留 + if isSoulfulShortFact(s) { + return RecallKeep, "人侧结构化短事实" + } + if !(hasEntity(s) || hasVerbPhrase(s)) { + return RecallDrop, "过短碎片(<20字,无实体无动词)" + } + return RecallKeep, "短但含实体/动词" + } + if n <= 50 { + // URL/路径/域名 = 强实体信号,不判弱内容降权(2026-10-14 实测修正) + if hasUrlishEntity(s) { + return RecallKeep, "含URL/路径实体" + } + if !(hasEntity(s) || hasVerbPhrase(s)) { + return RecallDemote, "弱内容(20-50字,无实体无动词)" + } + } + return RecallKeep, "通过" +} + +// FilterRecallByRule 对一批召回结果按确定性判据过滤/降权。 +// 返回 (keep, demoted, dropped) 三组 + 每组的 reason 明细。 +// env 门控由调用方决定(本函数零副作用、零 LLM)。 +func FilterRecallByRule[T any](items []T, content func(T) string) (kept, demoted, dropped []T, reasons map[RecallVerdict][]string) { + kept = make([]T, 0, len(items)) + demoted = make([]T, 0, len(items)) + dropped = make([]T, 0, len(items)) + reasons = map[RecallVerdict][]string{} + for _, it := range items { + v, why := RecallRuleVerdict(content(it)) + reasons[v] = append(reasons[v], why) + switch v { + case RecallKeep: + kept = append(kept, it) + case RecallDemote: + demoted = append(demoted, it) + case RecallDrop: + dropped = append(dropped, it) + } + } + return +} \ No newline at end of file diff --git a/go/internal/distill/recall_rule_test.go b/go/internal/distill/recall_rule_test.go new file mode 100644 index 0000000..b2f27f0 --- /dev/null +++ b/go/internal/distill/recall_rule_test.go @@ -0,0 +1,98 @@ +package distill + +import "testing" + +// TestRecallRuleVerdict 锁定召回侧确定性判据各分支。 +// 每条用例给「判什么」与期望 verdict,验证纯确定性(同输入恒同输出)。 +func TestRecallRuleVerdict(t *testing.T) { + cases := []struct { + name string + content string + want RecallVerdict + }{ + // ── Drop:确定性不可用 ────────────────────────── + {"空内容", "", RecallDrop}, + {"系统样板(IMPORTANT头)", "[IMPORTANT: You are running as a scheduled cron job... 请按时完成", RecallDrop}, + {"系统样板(System note头)", "[System note: 这是上下文摘要,供参考]", RecallDrop}, + {"纯疑问句(问号结尾)", "为什么系统总是重启?", RecallDrop}, + {"纯疑问句(疑问前缀+吗)", "要不要升级系统吗", RecallDrop}, + {"状态汇报(无主句)", "健康检查通过,所有进程运行中", RecallDrop}, + // 有主句的状态句不是进程噪声("服务器"=主体)→ 含实体 → Keep + {"状态汇报(有主体=实体)", "服务器重启完成", RecallKeep}, + {"过短碎片(无实体无动词)", "这是一个东西", RecallDrop}, + + // ── Demote:弱内容降权(20-50 字,无实体、无动词、无数字、无大写词)── + {"弱内容(20-50字无实体无动词)", "这是一个比较长的没有任何实际意义的填充文字用于演示降权", RecallDemote}, + // URL/路径 = 强实体,不降权(2026-10-14 实测修正) + {"含URL(20-50字)", "该仓库的URL为https://github.com/iOfficeAI/AionUi", RecallKeep}, + {"含路径(20-50字)", "仓库的本地源码位于 ~/projects/ai-skills-research/", RecallKeep}, + + // ── Keep:确定性可用,保留原序 ────────────────── + {"人侧结构化短事实", "偏好: 喜欢喝咖啡", RecallKeep}, + {"短但含实体", "使用 Hermes 处理", RecallKeep}, + {"长陈述含实体", "牧尘决定把织忆的召回判据改为规则优先,默认关闭,零行为变化", RecallKeep}, + {"长陈述含动词", "小唯负责维护全部的记忆系统与看板", RecallKeep}, + } + for _, c := range cases { + got, reason := RecallRuleVerdict(c.content) + if got != c.want { + t.Errorf("%s: RecallRuleVerdict(%q)=%v(%s) 期望 %v", c.name, c.content, got, reason, c.want) + } else { + t.Logf("%s: %v (%s)", c.name, got, reason) + } + } +} + +// TestRecallRuleVerdict_Pure 断言纯函数无副作用:重复调用同输入恒同输出。 +func TestRecallRuleVerdict_Pure(t *testing.T) { + inputs := []string{"为什么重启?", "健康检查通过", "牧尘定了召回规则", "偏好: 咖啡"} + for _, s := range inputs { + v1, _ := RecallRuleVerdict(s) + v2, _ := RecallRuleVerdict(s) + if v1 != v2 { + t.Fatalf("非纯函数: %q → %v vs %v", s, v1, v2) + } + } +} + +// TestFilterRecallByRule 验证批处理三路分组正确。 +func TestFilterRecallByRule(t *testing.T) { + items := []struct{ id, content string }{ + {"a", "偏好: 咖啡"}, + {"b", "为什么系统重启?"}, + {"c", "健康检查通过,所有进程运行中"}, + {"d", "牧尘决定把召回判据改为规则优先,默认关闭,零行为变化"}, + {"e", "这是一个东西"}, + } + kept, demoted, dropped, _ := FilterRecallByRule(items, func(x struct{ id, content string }) string { return x.content }) + if len(kept) != 2 { // a, d + t.Fatalf("kept 期望 2 得 %d (%v)", len(kept), kept) + } + if len(demoted) != 0 { + t.Fatalf("demoted 期望 0 得 %d", len(demoted)) + } + if len(dropped) != 3 { // b, c, e + t.Fatalf("dropped 期望 3 得 %d", len(dropped)) + } + t.Logf("kept=%d demoted=%d dropped=%d ✓", len(kept), len(demoted), len(dropped)) +} + +// TestFilterRecallByRule_CleanPassthrough 全为可用记忆时:零过滤、零降权、顺序原样。 +// 这就是 env=0(关闭)时召回结果逐位一致的保证——干净候选永不因规则被改动。 +func TestFilterRecallByRule_CleanPassthrough(t *testing.T) { + items := []struct{ id, content string }{ + {"a", "牧尘决定把召回判据改为规则优先,默认关闭,零行为变化"}, + {"b", "偏好: 咖啡"}, + {"c", "小唯负责维护全部的记忆系统与看板"}, + } + kept, demoted, dropped, _ := FilterRecallByRule(items, func(x struct{ id, content string }) string { return x.content }) + if len(kept) != 3 || len(demoted) != 0 || len(dropped) != 0 { + t.Fatalf("干净集被改动: kept=%d demoted=%d dropped=%d(期望 3/0/0)", len(kept), len(demoted), len(dropped)) + } + for i := range kept { + if kept[i].id != items[i].id { + t.Fatalf("干净集顺序被重排: 第%d位 %s 期望 %s", i, kept[i].id, items[i].id) + } + } + t.Logf("干净集逐位一致 ✓ (keep=%d, 顺序未动)", len(kept)) +} \ No newline at end of file