From d5b82d5b19b6def93ad0d3ab4d14b7cc68903d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=94=AF?= Date: Sat, 7 Nov 2026 02:41:33 +0800 Subject: [PATCH] =?UTF-8?q?feat(distill):=20=E7=BB=8F=E9=AA=8C=E5=B1=82=20?= =?UTF-8?q?category=3Dexperience=20=E7=81=B0=E6=8E=A7=E8=90=BD=E5=9C=B0?= =?UTF-8?q?=EF=BC=88=E9=BB=98=E8=AE=A4=E5=85=B3=EF=BC=8Ct=5F2595b626?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - experience_gate.go 新增:env 门控 ZHIYI_DISTILL_EXPERIENCE(启动读一次,同 density_gate 写法)、 ExperienceRecord{Task,Solution,Boundary}(无 confidence 自评,质量复用五维 overall/VD/RU)、 独立 prompt 附加常量(1157B,拼在 outFmt 之后)、ParseExperienceLine(4 段硬约束 + 反回显)、 ExperienceGrounded(反张冠李戴:task 对象名必须在 episode 原文有影子,确定性零 LLM) - engine/parser/server 接线:关态条件短路不可达 ⇒ 关态 prompt 逐字节不变 (sha256 三臂一致:head-off==tree-off=49295e70…,开态=关态+1157B) - score_cache 门控开时加 \x00experience-v1 后缀,防旧 prompt 缓存短路灰度 - 落库:接地闸 → 近重复跳过(cosine≥0.98)→ 写现成 category=experience(不造新表/新列) 实测(40 条真实工作笔记,本地 2B):EXP 行出现 32/40=80%,但过格式闸仅 2/40=5% ⇒ 2B 会写 EXP 内容但用自然语言衔接、不拆竖线三段,属能力边界。故**默认关,未部署未 push**。 go test ./internal/distill/ ./internal/api/routes/ -count=1 全绿 --- go/internal/api/server.go | 66 +++++- go/internal/distill/ab_run_test.go | 87 +++++++ go/internal/distill/distill_parser.go | 21 +- go/internal/distill/distill_parser_test.go | 18 +- go/internal/distill/engine.go | 30 ++- go/internal/distill/experience_gate.go | 217 ++++++++++++++++++ go/internal/distill/experience_gate_test.go | 192 ++++++++++++++++ .../distill/probe_prompt_dumper_test.go | 50 ++++ go/internal/distill/score_cache.go | 5 + 9 files changed, 664 insertions(+), 22 deletions(-) create mode 100644 go/internal/distill/ab_run_test.go create mode 100644 go/internal/distill/experience_gate.go create mode 100644 go/internal/distill/experience_gate_test.go create mode 100644 go/internal/distill/probe_prompt_dumper_test.go diff --git a/go/internal/api/server.go b/go/internal/api/server.go index d5355b5..0b139bb 100644 --- a/go/internal/api/server.go +++ b/go/internal/api/server.go @@ -386,7 +386,7 @@ func NewServer() http.Handler { // AC-1.2(t_e3f5cb79):真矛盾的新行带 supersedes=[旧id](双向指针的 // 新行半边;旧行半边在 ldbWriteOpsStore.MarkConflict 写 superseded_by)。 Supersedes: conflictSupersedes, - Source: srcOrLLMDistill(input.Source), // 2026-09-26:有笔记出处→"wiki:<路径>";否则沿用 llm_distill(2026-09-07 方案C provenance) + 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"), @@ -408,6 +408,64 @@ func NewServer() http.Handler { factsLanded = true // t_1c12e000:确有 distilled fact 落库 } } + // t_2595b626 经验层(ZHIYI_DISTILL_EXPERIENCE=1 灰度,默认关):EXP 产物落库。 + // 🔴 不改排序权重(AC5)——只多写 category="experience" 的行,召回侧零改动。 + // 反张冠李戴落库闸:task 引用的对象必须能在 episode 原文找到影子,否则不落库。 + // 关态 result.Experiences 恒 nil ⇒ 本循环零次迭代,行为与现状逐字一致。 + for _, exp := range result.Experiences { + if !distill.ExperienceGrounded(exp, input.Content) { + log.Printf("[distill][experience] 张冠李戴闸拦截(task 对象在原文无影子)episode=%s task=%.60s", + input.EpisodeID, exp.Task) + continue + } + // 近重复跳过(与 facts 同口径 cosine ≥0.98,复用现成 emb/ldb,不新造设施) + expContent := fmt.Sprintf("经验[%s] 解法:%s 边界:%s", exp.Task, exp.Solution, exp.Boundary) + expContent = redact.RedactSecrets(expContent) + var skip bool + if v, eErr := emb.EncodeSingle(expContent); eErr == nil { + if found, _ := ldb.Search("memories", v, 5, input.Namespace); len(found) > 0 { + for _, ex := range found { + if ex.Content == expContent || cosineSimilarity(v, ex.Vector) >= 0.98 { + skip = true + break + } + } + } + } + if skip { + log.Printf("[distill][experience] 近重复跳过 episode=%s task=%.60s", input.EpisodeID, exp.Task) + continue + } + expMem := models.MemoryRecord{ + ID: fmt.Sprintf("mem_%d", time.Now().UnixNano()), + AgentID: input.AgentID, + Namespace: input.Namespace, + Content: expContent, + // 🔴 用现成 category 字段(实测可写入/可召回),不造新表/新列 + Category: "experience", + Tier: "normal", + // 质量口径 = 现有五维 overall(VD/RU 已在其中);🔴 不做 confidence 自评 + QualityScore: result.Overall, + Version: 1, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + DerivedFrom: input.EpisodeID, + SourceEvents: []string{input.EpisodeID}, + Freshness: "fresh", + Source: srcOrLLMDistill(input.Source), + EmbeddingModel: orDefault(input.EmbeddingModel, "bge-m3"), + ScriptVersion: orDefault(input.ScriptVersion, "unknown"), + ValidFrom: time.Now().Format(time.RFC3339), + Provenance: distill.DetectProvenance(input.Source), + } + if err := ldb.InsertMemory(expMem); err != nil { + log.Printf("[distill][experience] 落库失败 episode=%s: %v", input.EpisodeID, err) + } else { + factsLanded = true + log.Printf("[distill][experience] 落库 episode=%s task=%.60s boundary=%.40s", + input.EpisodeID, exp.Task, exp.Boundary) + } + } // t_1c12e000:写路径缓存失效(方案 A)——distilled facts 是 memories 唯一写点。 // 本进程 Invalidate(ns) 清 L1+L2;跨 Agent 广播复用 commit handler 的 // PushCacheInvalidate(已注册 cache.invalidate 订阅),此处不重复广播。 @@ -578,9 +636,9 @@ func NewServer() http.Handler { // 返回该 query 的词面 topN 命中(id + 分 + 内容摘录),不走路过 recall 缓存。 mux.HandleFunc("/api/v1/fts/query", func(w http.ResponseWriter, r *http.Request) { var req struct { - Query string `json:"query"` - TopN int `json:"top_n"` - CheckDocID string `json:"check_doc_id"` + Query string `json:"query"` + TopN int `json:"top_n"` + CheckDocID string `json:"check_doc_id"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "invalid body", http.StatusBadRequest) diff --git a/go/internal/distill/ab_run_test.go b/go/internal/distill/ab_run_test.go new file mode 100644 index 0000000..ea6c3d7 --- /dev/null +++ b/go/internal/distill/ab_run_test.go @@ -0,0 +1,87 @@ +//go:build abrun + +// t_2595b626 A/B 跑批(非默认构建;仅 `-tags abrun go test -run TestABRun` 显式跑)。 +// 读 ab-samples.json → callLLM5D(生产同款 prompt 构造)→ 原始输出+解析结果落 ab-raw.jsonl。 +// 门控由 env ZHIYI_DISTILL_EXPERIENCE 决定(进程启动读一次 ⇒ A/B 两臂 = 跑两次进程)。 +package distill + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "sync" + "sync/atomic" + "testing" + "time" +) + +type abSample struct { + ID string `json:"id"` + Content string `json:"content"` + Src string `json:"src"` +} + +func TestABRun(t *testing.T) { + if os.Getenv("AB_GATE") == "" { + t.Skip("设 AB_GATE=on|off 才跑") + } + gate := os.Getenv("AB_GATE") == "on" + if gate != ExperienceGateEnabled() { + t.Fatalf("进程 env ZHIYI_DISTILL_EXPERIENCE=%v 与 AB_GATE=%v 不一致(门控启动读一次)", ExperienceGateEnabled(), gate) + } + // 缓存必须关:两臂同内容,A 臂结果若被缓存喂给 B 臂 = 假对照 + scoreCacheDisabled = true + + f, err := os.Open(os.Getenv("AB_SAMPLES")) + if err != nil { + t.Fatal(err) + } + var samples []abSample + json.NewDecoder(bufio.NewReader(f)).Decode(&samples) + f.Close() + if len(samples) < 20 { + t.Fatalf("样本不足 20: %d", len(samples)) + } + + e := NewEngine("http://127.0.0.1:8081/v1/chat/completions", "local/minicpm5-2b", "sk-local") + outPath := os.Getenv("AB_OUT") + out, _ := os.Create(outPath) + defer out.Close() + enc := json.NewEncoder(out) + + var idx int64 + var wg sync.WaitGroup + sem := make(chan struct{}, 2) // 与 2B 双槽匹配,不打爆 + start := time.Now() + for _, s := range samples { + wg.Add(1) + sem <- struct{}{} + go func(s abSample) { + defer wg.Done() + defer func() { <-sem }() + t0 := time.Now() + resp, err := e.callLLM5D(s.Content) // 缓存已关,直连 uncached + rec := map[string]any{ + "id": s.ID, "src": s.Src, "gate": gate, + "ms": time.Since(t0).Milliseconds(), + } + if err != nil { + rec["err"] = err.Error() + } else { + rec["facts"] = resp.Facts + rec["experiences"] = resp.Experiences + rec["scores"] = map[string]float64{"is": resp.IS, "su": resp.SU, "pa": resp.PA, "vd": resp.VD, "ru": resp.RU} + } + i := atomic.AddInt64(&idx, 1) + fmt.Printf("[%d/%d] %s %dms err=%v\n", i, len(samples), s.ID, rec["ms"], rec["err"]) + outMu.Lock() + enc.Encode(rec) + outMu.Unlock() + }(s) + } + wg.Wait() + fmt.Printf("AB_RUN gate=%v n=%d total=%s -> %s\n", gate, len(samples), time.Since(start).Round(time.Second), outPath) +} + +var outMu sync.Mutex diff --git a/go/internal/distill/distill_parser.go b/go/internal/distill/distill_parser.go index c23ec5b..0ec21e0 100644 --- a/go/internal/distill/distill_parser.go +++ b/go/internal/distill/distill_parser.go @@ -49,7 +49,8 @@ type DistillConfig struct { // 无递归无嵌套状态机;**从不返回 error**(最差空切片)。 // // ok=false 表示未识别到任何有效行(调用方据此落到 JSON 兜底)。 -func ParseLineFormat(raw string) (facts []string, entities []Entity, scores FiveDScore, ok bool) { +// t_2595b626:新增第 5 返回值 experiences(EXP 行;门控关恒 nil,行为与现状一致)。 +func ParseLineFormat(raw string) (facts []string, entities []Entity, scores FiveDScore, experiences []ExperienceRecord, ok bool) { var lines [][3]string // [0]=type, [1]=name(或fact内容或score), [2]=type(或score串) scanner := bufio.NewScanner(strings.NewReader(raw)) scanner.Buffer(make([]byte, 0, 64*1024), 1<<20) @@ -64,6 +65,16 @@ func ParseLineFormat(raw string) (facts []string, entities []Entity, scores Five break } switch { + // 🔴 EXP 分支排在最前:门控关 ⇒ 条件短路不可达,EXP 行走 default「垃圾行 + // 静默跳过」,与现状逐字一致(AC1)。门控开 ⇒ 解析 + 单行合法性闸。 + // EXP 不进 lines[]:它不是 FACT/ENTITY/SCORE,不参与截断启发式; + // END 之后的行由 seenEnd break 统一忽略。 + case experienceGateEnabled && strings.HasPrefix(line, "EXP|"): + // t_2595b626 经验层 + if exp := ParseExperienceLine(line); exp != nil { + experiences = append(experiences, *exp) + ok = true + } case line == "END" || strings.HasPrefix(line, "END|"): seenEnd = true case strings.HasPrefix(line, "FACT|"): @@ -161,7 +172,8 @@ func ParseLineFormat(raw string) (facts []string, entities []Entity, scores Five ok = true } } - return facts, entities, scores, ok + // experiences 在扫描循环内已填充(门控开且行合法) + return facts, entities, scores, experiences, ok } // isValidScoreField 判一个 SCORE 字段是否为合法数值(0.0~1.0 浮点)。 @@ -225,7 +237,7 @@ func logEchoStrip(path string, st EchoStats) { } func parseDistillOutput(raw string) LLMResponse { - facts, entities, scores, ok := ParseLineFormat(raw) + facts, entities, scores, experiences, ok := ParseLineFormat(raw) if ok { var names []string for _, en := range entities { @@ -240,6 +252,9 @@ func parseDistillOutput(raw string) LLMResponse { Facts: facts, Entities: names, }) + // t_2595b626:EXP 行在 ParseExperienceLine 已过单行合法性闸;落库前还有 + // ExperienceGrounded 接地闸兜底(api/server.go)。 + resp.Experiences = experiences logEchoStrip("line", st) return resp } diff --git a/go/internal/distill/distill_parser_test.go b/go/internal/distill/distill_parser_test.go index a9399cc..b2aefa9 100644 --- a/go/internal/distill/distill_parser_test.go +++ b/go/internal/distill/distill_parser_test.go @@ -34,7 +34,7 @@ func TestParseLineFormat_AC1Matrix(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - facts, _, _, ok := ParseLineFormat(tc.input) + facts, _, _, _, ok := ParseLineFormat(tc.input) if got := len(facts); got != tc.wantFacts { t.Fatalf("facts 数 = %d,期望 %d | input=%q ok=%v", got, tc.wantFacts, tc.input, ok) } @@ -44,7 +44,7 @@ func TestParseLineFormat_AC1Matrix(t *testing.T) { // AC1 补充:FACT 行内容整段保留(含引号、竖线),SplitN(...,2) 保护。 func TestParseLineFormat_FACTContentPreserved(t *testing.T) { - facts, _, _, ok := ParseLineFormat(`FACT|他说"你好"就这样|补充` + "\nEND") + facts, _, _, _, ok := ParseLineFormat(`FACT|他说"你好"就这样|补充` + "\nEND") if !ok { t.Fatalf("应识别到 FACT 行") } @@ -58,7 +58,7 @@ func TestParseLineFormat_FACTContentPreserved(t *testing.T) { // AC1 补充:ENTITY|name|type 三元组正确解析(SplitN(...,3))。 func TestParseLineFormat_EntityTriplet(t *testing.T) { - _, entities, _, ok := ParseLineFormat("ENTITY|小唯|person\nENTITY|ffmpeg|tool\nEND") + _, entities, _, _, ok := ParseLineFormat("ENTITY|小唯|person\nENTITY|ffmpeg|tool\nEND") if !ok { t.Fatalf("应识别到 ENTITY 行") } @@ -75,7 +75,7 @@ func TestParseLineFormat_EntityTriplet(t *testing.T) { // AC1 补充:SCORE 行解析出 5 维评分。 func TestParseLineFormat_ScoreParsed(t *testing.T) { - _, _, scores, ok := ParseLineFormat("FACT|x\nSCORE|0.8|0.7|0.6|0.9|0.7\nEND") + _, _, scores, _, ok := ParseLineFormat("FACT|x\nSCORE|0.8|0.7|0.6|0.9|0.7\nEND") if !ok { t.Fatalf("应识别到有效行") } @@ -89,7 +89,7 @@ func TestParseLineFormat_ScoreParsed(t *testing.T) { // 旧解析(SplitN limit 6)会把前 5 段占位符名当「5 维」存进去 → 非数值,评分全零。 // 修复后:尾 5 段数值被正确取出。 func TestParseLineFormat_ScoreEchoedPlaceholder(t *testing.T) { - _, _, scores, ok := ParseLineFormat("FACT|x\nSCORE|is|su|pa|vd|ru|0.5|0.4|0.3|0.2|0.1") + _, _, scores, _, ok := ParseLineFormat("FACT|x\nSCORE|is|su|pa|vd|ru|0.5|0.4|0.3|0.2|0.1") if !ok { t.Fatalf("应识别到有效行") } @@ -100,7 +100,7 @@ func TestParseLineFormat_ScoreEchoedPlaceholder(t *testing.T) { // 2026-10-08 t_23f6bce3:SCORE 行无 END 收尾时,末行 SCORE 不再被截断检测抹掉。 func TestParseLineFormat_ScoreWithoutEndPreserved(t *testing.T) { - _, _, scores, ok := ParseLineFormat("FACT|甲\nFACT|乙\nSCORE|0.5|0.4|0.3|0.2|0.1") + _, _, scores, _, ok := ParseLineFormat("FACT|甲\nFACT|乙\nSCORE|0.5|0.4|0.3|0.2|0.1") if !ok { t.Fatalf("应识别到有效行") } @@ -112,7 +112,7 @@ func TestParseLineFormat_ScoreWithoutEndPreserved(t *testing.T) { // 2026-10-08 t_23f6bce3:正常 5 段 SCORE 行 + 非法字段(占位符名混入)→ 不存脏值。 func TestParseLineFormat_ScoreBadFieldDropped(t *testing.T) { // 恰好 5 段但第 1 段是占位符名 is(非数值)→ 全行作废,评分全零 - _, _, scores, ok := ParseLineFormat("FACT|x\nSCORE|is|0.4|0.3|0.2|0.1") + _, _, scores, _, ok := ParseLineFormat("FACT|x\nSCORE|is|0.4|0.3|0.2|0.1") _ = ok if scores.IS != 0 || scores.SU != 0 || scores.PA != 0 || scores.VD != 0 || scores.RU != 0 { t.Fatalf("首段为占位符名时该行应作废(不存脏值),得: %+v", scores) @@ -121,7 +121,7 @@ func TestParseLineFormat_ScoreBadFieldDropped(t *testing.T) { // AC1 补充:END 之后的行忽略。 func TestParseLineFormat_AfterEndIgnored(t *testing.T) { - facts, _, _, _ := ParseLineFormat("FACT|甲\nEND\nFACT|乙") + facts, _, _, _, _ := ParseLineFormat("FACT|甲\nEND\nFACT|乙") if len(facts) != 1 { t.Fatalf("facts = %d,期望 1(END 后的 FACT 应忽略)", len(facts)) } @@ -132,7 +132,7 @@ func TestParseLineFormat_AfterEndIgnored(t *testing.T) { // AC1 补充:空输出 → ok=false(调用方落 JSON 兜底)。 func TestParseLineFormat_EmptyReturnsNotOK(t *testing.T) { - _, _, _, ok := ParseLineFormat("") + _, _, _, _, ok := ParseLineFormat("") if ok { t.Fatalf("空输出 ok 应为 false(应落兜底)") } diff --git a/go/internal/distill/engine.go b/go/internal/distill/engine.go index 80c20ce..d045778 100644 --- a/go/internal/distill/engine.go +++ b/go/internal/distill/engine.go @@ -62,6 +62,10 @@ type DistillResult struct { Score5D FiveDScore Overall float64 Index []AAAKEntry // P4: AAAK 压缩索引(每条事实的紧凑摘要) + // Experiences t_2595b626 经验层:EXP 解析产物(仅 ZHIYI_DISTILL_EXPERIENCE=1 + // 且解析出合法 EXP 行时非空;关态恒 nil ⇒ 下游经验分支不可达)。 + // 🔴 不进 Facts/图谱/AAAK —— 独立 category="experience" 记录走自己的落库闸。 + Experiences []ExperienceRecord } // Entity 实体 @@ -93,6 +97,8 @@ type LLMResponse struct { Conclusions []string `json:"conclusions"` // 新格式:最终结论 ActionsTaken []string `json:"actions_taken"` // 新格式:采取的行动 OpenQuestions []string `json:"open_questions"` // 新格式:悬而未决 + // t_2595b626 经验层:EXP 行解析产物(仅 ZHIYI_DISTILL_EXPERIENCE=1 时被填充)。 + Experiences []ExperienceRecord `json:"experiences,omitempty"` } // LLM 5维权重 @@ -644,11 +650,12 @@ func (e *Engine) distillOne(input DistillInput) DistillResult { MaybeAdversarialAudit(input, facts) return DistillResult{ - Facts: facts, - Entities: entities, - Score5D: score, - Overall: overall, - Index: index, + Facts: facts, + Entities: entities, + Score5D: score, + Overall: overall, + Index: index, + Experiences: llmResp.Experiences, } } @@ -773,7 +780,18 @@ SCORE|五个数字用竖线分隔 } else { contentTail = truncate(content, capVal) } - prompt := fmt.Sprintf("%s%s%s", instrFull, outFmt, fmt.Sprintf("内容:\n%s", contentTail)) + // t_2595b626 经验层门控(ZHIYI_DISTILL_EXPERIENCE=1,默认关): + // 附加段拼在 outFmt **之后**(prompt 末尾、离生成位置最近)—— + // pos_exp 系列实验取证(11-07):拼 outFmt 之前 = EXP 0/8(outFmt 的 + // 「facts 要详尽」指令压过附加段);拼 outFmt 之后才有产出。 + // run2136 担心的「末行被 echo」由 ParseExperienceLine 的 task 段拒收闸兜底。 + // 关态 instrFull/outFmt 均不含附加段 ⇒ prompt 逐字节与改动前一致(AC1,sha256 对照); + // instr/outFmt/density 三处旧常量一字未动。 + promptStr := instrFull + outFmt + if experienceGateEnabled { + promptStr = promptStr + experiencePromptAddendum + } + prompt := fmt.Sprintf("%s%s", promptStr, fmt.Sprintf("内容:\n%s", contentTail)) body := map[string]interface{}{ "model": e.LLMModel, diff --git a/go/internal/distill/experience_gate.go b/go/internal/distill/experience_gate.go new file mode 100644 index 0000000..2b130ca --- /dev/null +++ b/go/internal/distill/experience_gate.go @@ -0,0 +1,217 @@ +// 织忆 MemoryWeave — 蒸馏经验层(kanban t_2595b626) +// +// 形态来源(11-06 Hy-Memory pro 臂对比报告 §3):每条任务型轨迹产出 +// 「1 条事实(必留)+ 0~N 条经验」,经验带结构化字段 task/solution/boundary。 +// 他侧实测 8/8 轨迹都产出「1 事实 + 1 经验」(5.0–7.2s),但存在张冠李戴 +// (T4 把端口结论挂错任务)⇒ 本实现用「task 必须含输入原文出现的具体对象名」 +// 的硬约束反制(prompt 硬约束 + 落库接地闸双道防线),而不是照抄他的自由生成。 +// +// 织忆现状:category="experience" 实测可写入 201、可召回(存储零改动)—— +// 全仓只有类型定义里没有产出者 ⇒ 纯缺能力。本文件 + engine/parser/server +// 三处最小接线补齐产出侧。 +// +// 红线合规: +// - env 门控:ZHIYI_DISTILL_EXPERIENCE=1 才启用(density_gate.go 同款范式)。 +// 关态下 prompt 逐字节与现状一致(附加段独立常量,只在开关开时拼接), +// 解析器关态不识别 EXP 行(与现状「垃圾行静默跳过」逐字一致)。 +// - 不做 confidence 自评:ExperienceRecord 没有 confidence 字段, +// 质量口径复用现有五维评分的 VD/RU(写入侧 QualityScore=overall 照旧)。 +// - 不造新表/新列:写库走现成 category 字段(= "experience")。 +// - 不改任何排序权重:本文件与召回排序零交集(recall 侧只靠响应体已有的 +// category 字段区分,t_2595b626 AC5)。 +// +// 回滚:unset ZHIYI_DISTILL_EXPERIENCE + 重启(与 density gate 同路径)。 + +package distill + +import ( + "os" + "regexp" + "strings" +) + +// experienceGateEnabled 启动时读一次(densityGateEnabled 同款,改值须重启)。 +var experienceGateEnabled = os.Getenv("ZHIYI_DISTILL_EXPERIENCE") == "1" + +// ExperienceGateEnabled 解析侧(distill_parser.go)与写入侧(api/server.go)共用读口。 +func ExperienceGateEnabled() bool { return experienceGateEnabled } + +// ExperienceRecord 一条经验(task/solution/boundary 三字段)。 +// 🔴 无 confidence 字段 —— 卡红线:2B 自评会假高,用现有五维 VD/RU 代替,别新造。 +type ExperienceRecord struct { + Task string // 必须含 episode 原文出现的具体对象名(反张冠李戴硬约束) + Solution string // 怎么解决的:动作/命令/路径/配置键 + Boundary string // 适用边界:什么条件下成立、什么条件下不适用 +} + +// experiencePromptAddendum 门控开启时追加到提取 prompt 的经验段。 +// 只在 ExperienceGateEnabled() 时拼接 —— 关态 prompt 逐字节不变(AC1), +// engine.go 的 instr/outFmt 常量一字未动(同 densityPromptAddendum 范式)。 +// +// 反张冠李戴设计(对照 Hy 臂 T4 病灶): +// - EXP 行的 task 必须引用输入里逐字出现的具体对象名(脚本名/端口/路径/服务名), +// 不允许抽象概括任务(「调试服务」这类不带对象名的写法直接禁止输出)。 +// - 非任务型内容(无 goal→动作→结果链)明确指示「不输出 EXP」。 +// +// 🔴 位置与格式的两次实测修正(2B 行为驱动,t_2595b626 原始输出取证): +// 1. 必须拼在 outFmt **之前**:2B 把「输入最后一行」当输出起点 —— 附加段在 +// prompt 末尾时,实测把格式行 `EXP|任务名|解决方案|适用边界` 自身 echo 回来 +// (wp_现场修复 样本 raw 输出原样抄了这一行)。 +// 2. 示例只用中文语境的真对象名:示例里的抽象占位词会被抄进 task +// (echo_guard.go 同族病:教学示例回显)。 +const experiencePromptAddendum = ` + +🔴 经验提取附加要求(本次开启): +EXP = 一行可复用经验。行格式(恰好三个竖线,行首是字母 E X P 加竖线): +EXP|任务名|解决方案|适用边界 🔴 禁止输出本行示例本身,它是格式说明不是内容。 +判定:输入含「场景/目标 → 做了什么(动作/命令/配置) → 判据或结果」三要素 → 必须输出 1 行 EXP; +没有结果/判据(纯闲聊、状态汇报)→ 不输出 EXP,宁缺毋滥。 +- 任务名:原样带上输入里的真名(文件名、端口、命令、型号、卡号、配置键)。 +- 解决方案:实际做成了的事情(命令、路径、配置键、参数值),只能来自输入内容。 +- 适用边界:在什么条件下成立、什么情况下不适用。 +- EXP 与 FACT 互不替代:EXP 写可复用做法(怎么做成的),FACT 写陈述性结论,两者都要写。 +- 三段内部禁止再出现竖线;三个字段值禁止照抄「任务名」「解决方案」「适用边界」这几个字。 +- 禁止把 A 任务的结论挂到 B 任务上:EXP 的三个字段必须都只来自本输入的同一件事。 +` + +// expObjNameRe EXP 行合法性(prompt 侧硬约束的解析侧镜像):task 段必须含 +// "具体对象名"特征 token —— 路径、数字串(端口等)、带连接符的文件名/标识符、 +// 驼峰名、括号内标识符、引号包裹名。 +// 🔴 刻意**不含**裸 latin 词分支:中文语境里「修 bug」「改 config」的 bug/config +// 是泛词不是对象名,裸 latin 分支会把纯抽象任务名放过去(t_2595b626 单测实测踩过; +// 真正的对象名 llama-server-4b / ZHIYI_DISTILL_MODE / distill_parser.go 都会被 +// 连接符/驼峰/数字分支命中)。落库前还有 ExperienceGrounded 第二道闸兜底。 +var expObjNameRe = regexp.MustCompile( + `(?:~/|/(?:home|var|etc|data|usr|opt|tmp|srv|root|api|proc)/|\d{2,}` + + `|[A-Za-z0-9]+[._-][A-Za-z0-9]+` + + `|[A-Za-z][A-Za-z0-9]*[A-Z][A-Za-z0-9]*|\[[A-Za-z_][A-Za-z0-9_]*\]` + + `|"[^"]{2,}"|'[^']{2,}')`) + +// ParseExperienceLine 解析一条 EXP 行(门控开时才被调用)。 +// 格式:EXP|task|solution|boundary(SplitN 4 段;boundary 段允许含 |,溢出并回)。 +// 返回 nil 表示不合法(段数不足 / 任一段为空 / task 无具体对象名特征)—— +// 拒收脏行而不是入库后污染,与「行协议单行坏丢一行」哲学一致。 +func ParseExperienceLine(line string) *ExperienceRecord { + // 🔴 TrimPrefix 必须在 SplitN 之前:"EXP|a|b|c|d" 用 SplitN(...,4) 直接切 + // 会把 "EXP" 当第 1 段,真实三段被挤掉尾段 ⇒ 恒 nil(t_2595b626 实测踩过)。 + if !strings.HasPrefix(line, "EXP|") { + return nil + } + content := strings.TrimSpace(line[len("EXP|"):]) + parts := strings.SplitN(content, "|", 4) + if len(parts) < 3 { + return nil + } + task := strings.TrimSpace(parts[0]) + task = cleanExpTask(task) + solution := strings.TrimSpace(parts[1]) + boundary := strings.TrimSpace(parts[2]) + // 第 4 段(模型在 boundary 里多打了 | 的溢出)并回 boundary,不丢信息 + if len(parts) > 3 { + if extra := strings.TrimSpace(parts[3]); extra != "" { + boundary = boundary + "|" + extra + } + } + // 🔴 整行只打了 2 段(task|solution,boundary 空)⇒ 拒。 + // run2136 教训:缺界经验会污染召回("经验没有边界=到处套")。 + if len(parts) < 4 || strings.TrimSpace(parts[3]) == "" { + return nil + } + if task == "" || solution == "" || boundary == "" { + return nil + } + if expEchoTaskRe.MatchString(task) { + return nil + } + if !expObjNameRe.MatchString(task) { + return nil + } + return &ExperienceRecord{Task: task, Solution: solution, Boundary: boundary} +} + +// ExperienceGrounded 反张冠李戴落库闸:task 引用的具体对象必须能在 episode +// 原文(input.Content)里找到影子,否则该条经验不落库。 +// +// 判据(确定性、零 LLM): +// 1. latin 通道:task 切出对象名候选(含字母、长度 ≥2),任一大小写不敏感 +// 子串出现在原文 ⇒ 接地。 +// 2. 中文通道:task 的 ≥4 字连续汉字段(剔除停用词后),任一以**滑动子串** +// (长段取长度 ≥4 的连续子段)出现在原文 ⇒ 接地。 +// 2~3 字段(「端口」「服务」)泛在 ⇒ 不算接地(否则闸被泛词击穿)。 +// 3. 两通道全空 ⇒ 不接地 —— 与 prompt 硬约束同口径: +// 「task 必须包含输入里出现的具体对象名,否则不输出经验」。 +func ExperienceGrounded(exp ExperienceRecord, episodeContent string) bool { + hay := strings.ToLower(episodeContent) + // 通道①:latin/数字对象名候选,大小写不敏感子串 + for _, tok := range expTaskTokens(exp.Task) { + if strings.Contains(hay, strings.ToLower(tok)) { + return true + } + } + // 通道②:中文段滑动子串(task 常带「的做法/的排查」尾巴,全段相等会误杀) + for _, seg := range expTaskCJKSegs(exp.Task) { + r := []rune(seg) + for i := 0; i+4 <= len(r); i++ { + for j := i + 4; j <= len(r); j++ { + if strings.Contains(episodeContent, string(r[i:j])) { + return true + } + } + } + } + return false +} + +// expTaskTokenRe 从 task 里切"latin/数字对象名候选":连续 latin/数字/._-/ 段。 +var expTaskTokenRe = regexp.MustCompile(`[A-Za-z0-9][A-Za-z0-9._/-]*`) + +// expCJKSegRe 连续汉字段(≥4 字才算"具体对象名"候选)。 +// 2~3 字段(「端口」「服务」「配置」)在任何 episode 里都泛在,若算接地 +// 张冠李戴闸形同虚设 ⇒ 判据取保守方向:只认 ≥4 字连续汉字段。 +var expCJKSegRe = regexp.MustCompile(`[一-鿿]{4,}`) + +// expCJKStopSegs 中文段接地闸的停用词段:模板回声/高频功能词, +// 出现在几乎任何 episode 里,若算接地等于没有闸(宁缺毋滥)。 +var expCJKStopSegs = map[string]bool{ + "解决方案": true, "适用边界": true, "任务名": true, "什么问题": true, + "怎么处理": true, "如何修复": true, "问题修复": true, "经验教训": true, + "具体操作": true, "执行步骤": true, "最终结果": true, "使用工具": true, + "端口占用": true, "服务重启": true, "配置修改": true, "问题解决": true, +} + +var latinHasLetterRe = regexp.MustCompile(`[A-Za-z]`) + +// expEchoTaskRe 反回显闸:task 段以格式说明词(任务名/解决方案/适用边界)开头 +// ⇒ 模型把格式行原样抄了回来(run2136 + 11-07 pos 实验反复实测的 echo_guard 同族病), +// 整行拒收。 +var expEchoTaskRe = regexp.MustCompile(`^(任务名|解决方案|适用边界)[::]?`) + +// expTaskPrefixRe 剥离 task 段冗余前缀(「为什么:」「做法:」「场景:」等引导词), +// 与反回显闸(锚定 ^)解耦:剥离后再进闸判定。 +var expTaskPrefixRe = regexp.MustCompile(`^(任务名|解决方案|适用边界|为什么|做法|场景|现象|背景|教训|经验)[::]\s*`) + +func cleanExpTask(task string) string { + return strings.TrimSpace(expTaskPrefixRe.ReplaceAllString(task, "")) +} + +func expTaskTokens(task string) []string { + var out []string + for _, tok := range expTaskTokenRe.FindAllString(task, -1) { + t := strings.Trim(tok, "._-/") + // 长度 ≥2 且含 latin 字母才算对象名候选(纯数字/连接碎片不算) + if len([]rune(t)) >= 2 && latinHasLetterRe.MatchString(t) { + out = append(out, t) + } + } + return out +} + +func expTaskCJKSegs(task string) []string { + var out []string + for _, seg := range expCJKSegRe.FindAllString(task, -1) { + if !expCJKStopSegs[seg] { + out = append(out, seg) + } + } + return out +} diff --git a/go/internal/distill/experience_gate_test.go b/go/internal/distill/experience_gate_test.go new file mode 100644 index 0000000..255d990 --- /dev/null +++ b/go/internal/distill/experience_gate_test.go @@ -0,0 +1,192 @@ +// t_2595b626 经验层回归用例: +// +// AC1 关态逐字节不变 / EXP 行门控 / 合法性闸 / 反张冠李戴接地判据 +package distill + +import ( + "os" + "strings" + "testing" +) + +// withExperienceGate 临时翻转门控变量(包内测试专用;生产是启动读一次)。 +func withExperienceGate(t *testing.T, on bool, fn func()) { + t.Helper() + prev := experienceGateEnabled + experienceGateEnabled = on + defer func() { experienceGateEnabled = prev }() + fn() +} + +// AC1:门控关(默认 env 未设)⇒ ParseLineFormat 对 EXP 行 = 静默跳过, +// 返回与现状逐字一致(exp 行内容不出现在任何返回值里)。 +func TestExperienceGate_Off_EXPLineIgnored(t *testing.T) { + if os.Getenv("ZHIYI_DISTILL_EXPERIENCE") == "1" { + t.Skip("测试环境显式开了门控,关态用例跳过") + } + if ExperienceGateEnabled() { + t.Fatal("默认 env 下门控应为关") + } + raw := "FACT|真事实\nEXP|llama-server-4b 端口冲突|改用 8081 代理|仅本机单实例\nSCORE|0.8|0.7|0.6|0.9|0.7\nEND" + facts, entities, scores, exps, ok := ParseLineFormat(raw) + if !ok || len(facts) != 1 || facts[0] != "真事实" { + t.Fatalf("关态 facts 行为变了: %v ok=%v", facts, ok) + } + if len(exps) != 0 { + t.Fatalf("关态 exps 必须恒空,得 %v", exps) + } + _ = entities + _ = scores + if strings.Join(facts, "|") == "" { + t.Fatal("关态事实丢失") + } +} + +// 门控开 ⇒ EXP 行解析成 ExperienceRecord;facts/scores 行为不受影响。 +func TestExperienceGate_On_EXPLineParsed(t *testing.T) { + withExperienceGate(t, true, func() { + raw := "FACT|llama-server-4b 占用了 8080\nEXP|llama-server-4b 端口冲突|改用 8081 代理卸力|仅本机 llama 单实例场景|仅单实例部署有效\nSCORE|0.8|0.7|0.6|0.9|0.7\nEND" + facts, _, scores, exps, ok := ParseLineFormat(raw) + if !ok || len(facts) != 1 || scores.IS != 0.8 { + t.Fatalf("开态 facts/scores 行为变了: facts=%v scores=%+v", facts, scores) + } + if len(exps) != 1 { + t.Fatalf("期望 1 条经验,得 %d", len(exps)) + } + e := exps[0] + if !strings.Contains(e.Task, "llama-server-4b") || e.Solution == "" || e.Boundary == "" { + t.Fatalf("字段错位: %+v", e) + } + }) +} + +// 合法性闸:段数不足 / 空段 / task 无具体对象名特征 ⇒ 拒收整行。 +func TestParseExperienceLine_Rejects(t *testing.T) { + cases := []struct{ name, line string }{ + {"段数不足", "EXP|llama 端口|只有一段解法"}, + {"solution 空", "EXP|llama 端口||有边界"}, + {"boundary 空", "EXP|llama 端口|有解法|"}, + {"task 抽象无对象名", "EXP|调试服务|重启解决|通用"}, + {"task 纯中文抽象", "EXP|修 bug|改了配置|任何情况"}, + } + for _, tc := range cases { + if got := ParseExperienceLine(tc.line); got != nil { + t.Errorf("%s: 应拒收,得 %+v", tc.name, got) + } + } + // 合法行 + boundary 内含竖线(溢出并回,不丢信息) + got := ParseExperienceLine("EXP|distill-granularity B 档|设 ZHIYI_DISTILL_MODE=context 重启|仅对 llm_distill 源生效|不影响 wiki 直写") + if got == nil { + t.Fatal("合法行被误拒") + } + if !strings.Contains(got.Boundary, "|不影响 wiki 直写") { + t.Fatalf("boundary 溢出段未并回: %q", got.Boundary) + } + // 反回显闸:格式行被模型原样抄回 ⇒ task 段以格式说明词开头 ⇒ 整行拒 + if got := ParseExperienceLine("EXP|任务名|解决方案|适用边界(本次开启说明文字)"); got != nil { + t.Fatalf("格式行回显应拒收,得 %+v", got) + } + if got := ParseExperienceLine("EXP|任务名:查证三条|解决方案|适用边界"); got != nil { + t.Fatalf("task 带「任务名:」前缀的回显应拒收,得 %+v", got) + } +} + +// 反张冠李戴接地闸:task 的 latin 对象名 / 中文长段 在原文出现 ⇒ 接地; +// 全不在 ⇒ 不接地(不落库)。 +func TestExperienceGrounded(t *testing.T) { + episode := "[2026-11-06, 周三] user: llama-server-4b 起不来,端口 8080 被占了,我改用 8081 队列代理卸力" + // ① latin 对象名命中 + if !ExperienceGrounded(ExperienceRecord{Task: "llama-server-4b 端口冲突修复"}, episode) { + t.Fatal("latin 对象名应接地") + } + // ② 中文段是原文子串 ⇒ 命中(task 常带「的做法」这类尾巴,全段相等判据会被误杀, + // 故判据=task 汉字段与原文做子串匹配;闸的反例由 ②b/③ 钉死) + if !ExperienceGrounded(ExperienceRecord{Task: "队列代理卸力的做法"}, episode) { + t.Fatal("task 汉字段是原文子串时应接地") + } + // ②b 泛词不算接地(张冠李戴闸不被泛词击穿) + if ExperienceGrounded(ExperienceRecord{Task: "端口服务配置"}, episode) { + t.Fatal("短泛词段不应算接地") + } + // ③ 张冠李戴:task 引用原文没有的对象且无可命中中文段 ⇒ 拒 + if ExperienceGrounded(ExperienceRecord{Task: "nginx-ssl 证书过期处理"}, episode) { + t.Fatal("引用原文所无对象应判不接地") + } + // ④ 大小写不敏感 + if !ExperienceGrounded(ExperienceRecord{Task: "LLama-Server-4B 排查"}, episode) { + t.Fatal("大小写变体应接地") + } +} + +// AC1 核心:门控关态下 callLLM5DUncached 构造的 prompt 与「无经验层代码」时 +// 逐字节一致 —— 即附加段仅在开关开时拼接,instr/outFmt 常量零改动。 +func TestExperienceGate_OffPromptByteIdentical(t *testing.T) { + // 断言 1:附加段说明 EXP 行格式 + if !strings.Contains(experiencePromptAddendum, "EXP") || !strings.Contains(experiencePromptAddendum, "任务名") { + t.Fatal("附加段缺 EXP 格式说明") + } + // AC1 断言 3(run2136 修正口径):格式行字面量「EXP|任务名|解决方案|适用边界」 + // 必须存在(模型靠它认格式,v9 实验证明去掉它模型不产 EXP);但它被 + // 「🔴 禁止输出本行示例本身」条款 + ParseExperienceLine 的 task 段拒收闸 + // (ECHO_TASK:task 以 任务名/解决方案/适用边界 开头 ⇒ 整行拒)双道兜底。 + if !strings.Contains(experiencePromptAddendum, "EXP|任务名|解决方案|适用边界") { + t.Fatal("附加段缺 EXP 格式行字面量") + } + if !strings.Contains(experiencePromptAddendum, "禁止输出本行示例本身") { + t.Fatal("格式行旁必须有反回显条款(echo_guard 同族病兜底)") + } + // 断言 2:关态 ⇒ engine.go 里经验段永远不进 prompt(代码级钉子: + // 拼接点只有 `if experienceGateEnabled` 一处)。 + src, err := os.ReadFile("engine.go") + if err != nil { + t.Skip("源文件不可读(非源码树跑测试),跳过代码级钉子") + } + if n := strings.Count(string(src), "experiencePromptAddendum"); n != 1 { + t.Fatalf("experiencePromptAddendum 在 engine.go 应只出现 1 处(唯一拼接点),得 %d", n) + } + if !strings.Contains(string(src), "if experienceGateEnabled {\n promptStr = promptStr + experiencePromptAddendum") { + t.Fatal("拼接点必须包在 if experienceGateEnabled 内") + } +} + +// 打分缓存键换代:开态与关态对同一 content 的 scoreKey 必须不同, +// 关态与历史逐字节一致(无附加后缀)。 +func TestExperienceGate_ScoreKeyVersioning(t *testing.T) { + content := "同一段内容" + // 🔴 测试 env 非真空:跑批/灰度 shell 里 export 过的 ZHIYI_* 会被测试进程继承 + // (实测踩过:AB 跑批后同 shell 跑测试,experienceGateEnabled=true ⇒ 基线 off 键 + // 带 experience 后缀 ⇒ 「关态键恒等/纯 sha256」两条断言必炸)。 + // 本用例只测 experience 门控对键的影响 ⇒ 三个环境敏感因子全部显式钉死。 + t.Setenv("ZHIYI_DISTILL_EXPERIENCE", "0") + t.Setenv("ZHIYI_DISTILL_DENSITY", "0") + t.Setenv("ZHIYI_DISTILL_MODE", "context") + densityPrev := densityGateEnabled + densityGateEnabled = false + expPrev := experienceGateEnabled + experienceGateEnabled = false + modePrev := distillMode + distillMode = "context" + defer func() { + densityGateEnabled = densityPrev + experienceGateEnabled = expPrev + distillMode = modePrev + }() + off := scoreKey(content) + withExperienceGate(t, false, func() { + if scoreKey(content) != off { + t.Fatal("关态键应恒等") + } + }) + withExperienceGate(t, true, func() { + if scoreKey(content) == off { + t.Fatal("开态键必须换代(旧 prompt 缓存不得短路新 prompt)") + } + }) + // 关态键 = 纯 sha256(content),无 \x00 后缀(densityPrev 已在函数顶部钉死) + withExperienceGate(t, false, func() { + k := scoreKey("abc") + if len(k) != 64 { + t.Fatalf("关态键应为纯 sha256 hex(64),得 len=%d", len(k)) + } + }) +} diff --git a/go/internal/distill/probe_prompt_dumper_test.go b/go/internal/distill/probe_prompt_dumper_test.go new file mode 100644 index 0000000..c88b588 --- /dev/null +++ b/go/internal/distill/probe_prompt_dumper_test.go @@ -0,0 +1,50 @@ +//go:build promptdump + +// t_2595b626 AC1 工具:截获 callLLM5DUncached 实发的 prompt(非默认构建)。 +// 测试内起 httptest echo server 截 body ⇒ 无需外部进程,prompt 与生产构造逐字节同源。 +// +// 用法:ZHIYI_PROBE_CONTENT_FILE=<内容文件> ZHIYI_PROBE_OUT=<输出json> +// +// go test -tags promptdump -run TestDumpPrompt +// +// 门控由进程 env ZHIYI_DISTILL_EXPERIENCE 决定(启动读一次,与生产一致)。 +package distill + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "testing" +) + +func TestDumpPrompt(t *testing.T) { + b, err := os.ReadFile(os.Getenv("ZHIYI_PROBE_CONTENT_FILE")) + if err != nil { + t.Fatal(err) + } + var captured []byte + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + captured, _ = io.ReadAll(r.Body) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"choices":[{"message":{"content":"FACT|x\nSCORE|0.5|0.5|0.5|0.5|0.5\nEND"}}]}`)) + })) + defer srv.Close() + + e := NewEngine(srv.URL+"/v1/chat/completions", "local/minicpm5-2b", "sk-probe") + _, _ = e.callLLM5DUncached(string(b)) + + var body map[string]any + if err := json.Unmarshal(captured, &body); err != nil { + t.Fatalf("截获 body 失败: %v", err) + } + prompt := body["messages"].([]any)[0].(map[string]any)["content"].(string) + out, _ := json.Marshal(map[string]any{ + "gate_on": ExperienceGateEnabled(), + "bytes": len(prompt), + "prompt": prompt, + }) + os.WriteFile(os.Getenv("ZHIYI_PROBE_OUT"), out, 0o644) + t.Logf("dumped prompt bytes=%d gate=%v", len(prompt), ExperienceGateEnabled()) +} diff --git a/go/internal/distill/score_cache.go b/go/internal/distill/score_cache.go index d3031d9..410d7c4 100644 --- a/go/internal/distill/score_cache.go +++ b/go/internal/distill/score_cache.go @@ -117,6 +117,11 @@ func scoreKey(content string) string { if densityGateEnabled { content += "\x00density-v1" } + // t_2595b626 经验层门控开 ⇒ prompt 已变(追加 EXP 段),同 density 范式给键换代, + // 否则旧 prompt 的缓存结果会被开态直接复用、EXP 永远解析不出来(灰度静默失效)。 + if experienceGateEnabled { + content += "\x00experience-v1" + } sum := sha256.Sum256([]byte(content)) return hex.EncodeToString(sum[:]) }