From 7562714819e8b4b7c2be8fc39634adf7f93d7b73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Fri, 30 Oct 2026 22:01:39 +0800 Subject: [PATCH] =?UTF-8?q?feat(distill):=20=E4=BF=A1=E6=81=AF=E5=AF=86?= =?UTF-8?q?=E5=BA=A6=E5=88=A4=E6=8D=AE=E2=80=94=E2=80=94=E4=B8=89=E9=A1=B9?= =?UTF-8?q?=E5=88=A4=E6=8D=AE=E2=89=A52=20=E6=89=8D=E4=BF=9D=E6=8C=81=20di?= =?UTF-8?q?stilled=EF=BC=8C=E4=B8=8D=E8=B6=B3=E9=99=8D=E7=BA=A7=20observe?= =?UTF-8?q?=EF=BC=88env=20ZHIYI=5FDISTILL=5FDENSITY=20=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E5=85=B3=EF=BC=89=20(t=5Fab5b2461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go/internal/api/server.go | 13 +++- go/internal/distill/density_gate.go | 88 ++++++++++++++++++++++++ go/internal/distill/density_gate_test.go | 53 ++++++++++++++ go/internal/distill/engine.go | 8 ++- go/internal/distill/score_cache.go | 6 ++ 5 files changed, 166 insertions(+), 2 deletions(-) create mode 100644 go/internal/distill/density_gate.go create mode 100644 go/internal/distill/density_gate_test.go diff --git a/go/internal/api/server.go b/go/internal/api/server.go index 14fc5bd..58639d1 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -349,12 +349,23 @@ func NewServer() http.Handler { // verdict==nil(off 未跑判定;理论死分支——off 不进 WriteOpsEnabled 块) // 或 shadow(标记零调用)⇒ 基础插入无条件执行。 } + // t_ab5b2461 信息密度判据(env ZHIYI_DISTILL_DENSITY=1 灰度,默认关): + // 三项判据(①可执行/命令/路径 ②判据/阈值 ③因果)满足 ≥2 项才保持 + // Category="distilled";<2 项降级 Category="observe" —— 行照写、量照计 + // (AC3 写入量不饿死),可召回可逆,只是不再冒充高质量知识形态。 + // env 关 ⇒ category 恒 "distilled",与现状逐位等价(AC5)。 + category := "distilled" + if distill.DensityGateEnabled() && !distill.DensityKeep(fact) { + category = "observe" + log.Printf("[distill][density] 信息量不足(需≥2项判据) → Category=observe episode=%s src=%q fact=%.48s", + input.EpisodeID, input.Source, fact) + } mem := models.MemoryRecord{ ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()), AgentID: input.AgentID, Namespace: input.Namespace, Content: fact, - Category: "distilled", + Category: category, Tier: "normal", QualityScore: result.Overall, Version: 1, diff --git a/go/internal/distill/density_gate.go b/go/internal/distill/density_gate.go new file mode 100644 index 0000000..3f0ac66 --- /dev/null +++ b/go/internal/distill/density_gate.go @@ -0,0 +1,88 @@ +// 织忆 MemoryWeave — 蒸馏产出信息密度判据(kanban t_ab5b2461) +// +// 病(2026-10-30 全面评估 + 本卡按 Source 分组定位):memories 表 content 中位数 35 字、 +// 83.3% <60 字、含可执行标记率低 —— 蒸馏产物太短,召回出来没法直接用。 +// 分组实测(groups_before.json,live 42,150):llm_distill p50=36、wiki:worklog-note p50=36、 +// wiki:domain-kb p50=38、wiki:session-compress p50=30 —— distill 全家族整体都碎, +// 不是某一条上游的病 ⇒ 收口在共用写入点(server.go OnDistillComplete 写库循环 + +// engine.go 提取 prompt),不逐脚本打补丁。 +// +// 设计(延续 procedural_gate.go 分诊哲学 + 卡红线「禁为长度而长度」): +// - 纯确定性判据,零 LLM 调用,三项各自独立判定(正则): +// ① 可执行动作/命令/路径(反引号命令、CLI 调用、绝对/家目录路径、脚本/配置文件扩展名) +// ② 明确判据或阈值(数字+单位、比较符、阈值/上限/下限/门槛类词) +// ③ 因果(「为什么」:因为/由于/导致/根因/否则/⇒ 等因果链词) +// - 满足 ≥2 项 ⇒ 保持 Category="distilled"(知识形态)。 +// - <2 项 ⇒ 降级 Category="observe":行照写、可召回、计入写入量(AC3 不饿死), +// 只是不再冒充高质量知识 —— 与 t_3636b872 同一理由:降级可逆,丢弃不可逆。 +// - 不做长度硬门槛:长度是三项判据的**结果**不是目标(卡红线)。 +// +// env 门控:ZHIYI_DISTILL_DENSITY=1 启用(灰度开在 systemd drop-in); +// 未设 ⇒ DensityGateEnabled()=false ⇒ 写入侧 Category 恒 "distilled"、 +// prompt 与打分缓存键逐字节回到现状(AC5 可回滚)。 +// 回滚:rm 42-density-gate.conf + daemon-reload + zhiyi-restart-with-lock.sh restart。 + +package distill + +import ( + "os" + "regexp" +) + +// densityGateEnabled 启动时读一次(与 proceduralShadowMode 同款,改值须重启)。 +var densityGateEnabled = os.Getenv("ZHIYI_DISTILL_DENSITY") == "1" + +// DensityGateEnabled 写入侧(server.go)与打分缓存(score_cache.go)共用的开关读口。 +func DensityGateEnabled() bool { return densityGateEnabled } + +// 三项判据正则(RE2;口径写进交付,判据即文档)。 +var ( + // densityCmdRe ① 可执行动作/命令/路径: + // 路径前缀(绝对/家目录)、脚本与配置文件扩展名、常见 CLI + 参数、反引号内联命令。 + densityCmdRe = regexp.MustCompile( + `(?:~/|/(?:home|var|etc|data|usr|opt|tmp|srv|root)/|\.(?:sh|py|go|rs|conf|json|jsonl|ya?ml|toml|db|service|sql)\b` + + `|\b(?:git|curl|wget|grep|rg|sed|awk|jq|yq|systemctl|journalctl|python3?|docker|uv|pip|npm|make|ssh|scp|rsync|chmod|chown|mv|cp|rm|mkdir|tar|sqlite3|psql|redis-cli|crontab|hermes|llama|ss|lsof|pgrep|kill|flock|ffmpeg)\s+\S` + + "|`[^`]{3,}`)") + + // densityThrRe ② 判据/阈值:比较符+数字、百分比、阈值词汇、数字+量词单位。 + densityThrRe = regexp.MustCompile( + `(?:[≥≤><]=?\s*\d|\d+(?:\.\d+)?\s*[%%]|阈值|上限|下限|门槛|限额|配额|\bcap\b|\blimit\b|\bcritical\b` + + `|\d+\s*(?:ms|毫秒|秒|分钟|小时|天|次|条|行|字|MB|GB|TB|端口|万|亿))`) + + // densityCauseRe ③ 因果/为什么:因果连接词与根因词汇、箭头推导。 + densityCauseRe = regexp.MustCompile( + `(?:因为|由于|导致|因此|所以|为了|从而|以致|以免|否则|根因|原因为|起因|源于|使得|⇒|->|=>)`) +) + +// DensitySatisfyCount 数一条事实满足三项判据中的几项(0~3)。 +// 纯函数:同一输入永远同一结果,可单测、零副作用。 +func DensitySatisfyCount(fact string) int { + n := 0 + if densityCmdRe.MatchString(fact) { + n++ + } + if densityThrRe.MatchString(fact) { + n++ + } + if densityCauseRe.MatchString(fact) { + n++ + } + return n +} + +// DensityKeep 事实是否够格保持 Category="distilled":满足 ≥2 项。 +// 注意:本函数只在 DensityGateEnabled() 时被调用;关态下调用方保持 "distilled" 不动。 +func DensityKeep(fact string) bool { + return DensitySatisfyCount(fact) >= 2 +} + +// densityPromptAddendum 灰度开启时追加到提取 prompt 的信息量要求。 +// 只在 DensityGateEnabled() 时拼接 —— 关态 prompt 逐字节不变(AC5), +// 旧 prompt 原文保留在 engine.go 的 instr/outFmt 常量里,一字未动。 +const densityPromptAddendum = ` +🔴 信息量要求(灰度生效中): +- 同一事件/操作的关联细节**合并成一条完整句子**,不要拆成多条各含一个要素的短句。 +- 每条 FACT 在原文支持的前提下尽量同时给出:做什么(命令/路径/动作)+ 条件或程度(阈值/判据)+ 为什么(因果背景)。 +- 纯元信息行(如「该条记录日期为…」「文件保存在…」这类只有溯源没有知识载荷的)不要输出为事实。 +- 禁止为凑长度堆修饰词:原文只有短句就照实提取,长是信息完整的结果,不是目标。 +` diff --git a/go/internal/distill/density_gate_test.go b/go/internal/distill/density_gate_test.go new file mode 100644 index 0000000..42db91d --- /dev/null +++ b/go/internal/distill/density_gate_test.go @@ -0,0 +1,53 @@ +// t_ab5b2461 信息密度判据单测(判据 = 交付里贴出的口径,测试即文档)。 +package distill + +import "testing" + +func TestDensitySatisfyCount(t *testing.T) { + cases := []struct { + name string + fact string + wantN int + keep bool + }{ + {"命令+阈值", "重启用 ~/.hermes/scripts/zhiyi-restart-with-lock.sh,健康检查 40 秒内必须返回 200,否则回滚", 3, true}, + {"路径+因果", "state.db 损坏时走 db-op-gate.sh,因为 gateway 运行期直接写活库会放大损坏面", 2, true}, + {"仅阈值", "该表写入量超过 500 条时告警", 1, false}, + {"仅因果", "因为昨晚断网所以任务没有跑完", 1, false}, + {"元信息行(全不中)", "该条经验记录的日期为 2026-10-25", 0, false}, + {"裸短句(全不中)", "用户授权助手自行决定", 0, false}, + {"阈值+因果", "磁盘余量 <5% 时触发清理,否则 backups 目录会把根分区写满", 2, true}, + {"路径单中", "配置文件在 /etc/ssh/sshd_config", 1, false}, + } + for _, c := range cases { + if n := DensitySatisfyCount(c.fact); n != c.wantN { + t.Errorf("%s: DensitySatisfyCount(%q)=%d, want %d", c.name, c.fact, n, c.wantN) + } + if got := DensityKeep(c.fact); got != c.keep { + t.Errorf("%s: DensityKeep(%q)=%v, want %v", c.name, c.fact, got, c.keep) + } + } +} + +// AC5 结构证据:灰度段是**追加**,不改动既有 prompt 常量 —— +// instr/outFmt 常量文本里不含「信息量要求」字样(关态 prompt 逐字节为旧文本)。 +func TestDensityAddendumOnlyAppended(t *testing.T) { + if len(densityPromptAddendum) == 0 { + t.Fatal("addendum 不能为空") + } + // 追加段自带独有锚点,供源内定位(防止误删)。 + if !contains(densityPromptAddendum, "禁止为凑长度堆修饰词") { + t.Error("addendum 缺「禁为长度而长度」红线锚点") + } +} + +func contains(s, sub string) bool { + return len(s) >= len(sub) && (func() bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false + })() +} diff --git a/go/internal/distill/engine.go b/go/internal/distill/engine.go index 2664d87..c3fb6c3 100644 --- a/go/internal/distill/engine.go +++ b/go/internal/distill/engine.go @@ -750,7 +750,13 @@ SCORE|五个数字用竖线分隔 // 注意:本行写法刻意让 vet 的 Sprintf(格式串) 检查不匹配(外层 %s%s%s 与 3 实参对齐, // 内层「内容:\n%s」是嵌套 Sprintf 的独立格式串,运行时各自 1 槽 1 参); // rawscore_liveprobe_test.go 的 extractPromptTemplate 锚点须与本行「fmt.Sprintf("内容:\n%s"」保持同步。 - prompt := fmt.Sprintf("%s%s%s", instr, outFmt, fmt.Sprintf("内容:\n%s", truncate(content, 1000))) + // t_ab5b2461 信息密度判据灰度(ZHIYI_DISTILL_DENSITY=1):只在开关开时追加信息量要求段。 + // 关态 instrFull == instr,prompt 逐字节与现状一致(AC5);上方旧 prompt 常量一字未动。 + instrFull := instr + if densityGateEnabled { + instrFull = instr + densityPromptAddendum + } + prompt := fmt.Sprintf("%s%s%s", instrFull, outFmt, fmt.Sprintf("内容:\n%s", truncate(content, 1000))) body := map[string]interface{}{ "model": e.LLMModel, diff --git a/go/internal/distill/score_cache.go b/go/internal/distill/score_cache.go index 5446f6a..d3031d9 100644 --- a/go/internal/distill/score_cache.go +++ b/go/internal/distill/score_cache.go @@ -111,6 +111,12 @@ func getScoreCache() *scoreCache { } func scoreKey(content string) string { + // t_ab5b2461:灰度开启(prompt 已变)时给键加版本后缀 —— 否则 Redis 里 + // 旧 prompt 产出的评分/抽取结果会被新 prompt 直接复用,判据灰度形同虚设。 + // 关态键与历史逐字节一致(AC5:不设 env ⇒ 缓存行为零变化)。 + if densityGateEnabled { + content += "\x00density-v1" + } sum := sha256.Sum256([]byte(content)) return hex.EncodeToString(sum[:]) }