feat(distill): 蒸馏落库前拒写空壳(t_e11207f8 治源①)— 共享判据 zhiyi_payload_guard_rules.json + Go payload_guard + OnDistillComplete 拦截 + /api/v1/payload-guard/stats + 3 单测;顺带修复 deploy-approved 清单坏行
- distill/payload_guard.go: 读共享 JSON(与 Python 同源),ShellCheck 带心跳/拦截计数 - api/server.go: OnDistillComplete fact 循环红act 后 ShellCheck 拒写空壳 + 启动加载 + stats 端点 - main_test.go: TestMain 加载共享规则供单测 - 修复 scripts/deploy-approved-commits.txt 尾行坏数据('appending:' 前缀 → 两条合法 SHA)
This commit is contained in:
@@ -227,6 +227,14 @@ func NewServer() http.Handler {
|
||||
}
|
||||
distillEngine := distill.NewEngine(llmEndpoint, llmModel, llmAPIKey)
|
||||
routes.DistillEngineRef = distillEngine
|
||||
// t_e11207f8 治源①:加载共享「空壳正文」判据(zhiyi_payload_guard_rules.json,Python/Go 同源)。
|
||||
// 失败 ⇒ fail-open(distill 照跑、不拦空壳、不崩),/api/v1/payload-guard/stats 暴露 loaded=false。
|
||||
if ok, lerr := distill.LoadPayloadGuard(""); ok {
|
||||
_, _, _, rp := distill.PayloadGuardStats()
|
||||
log.Printf("[distill][payload-guard] 空壳判据已加载 rules=%s", rp)
|
||||
} else {
|
||||
log.Printf("[distill][payload-guard] ⚠️ 共享判据未加载(fail-open,不拦空壳): %v", lerr)
|
||||
}
|
||||
// 蒸馏完成 → 自动图谱更新 + 冲突检测 + 被动验证 + 回写内存
|
||||
distill.OnDistillComplete = func(input distill.DistillInput, result distill.DistillResult) {
|
||||
entityNames := make([]string, len(result.Entities))
|
||||
@@ -268,6 +276,13 @@ func NewServer() http.Handler {
|
||||
// 这里再脱一次为幂等保险——防止任何中间层注入明文密钥。事故里泄漏进
|
||||
// 镜像的记忆正是从这条路径入库的)。
|
||||
fact = redact.RedactSecrets(fact)
|
||||
// t_e11207f8 治源①:空壳拒写(单一判据 = 共享 zhiyi_payload_guard_rules.json,与 Python 同源)。
|
||||
// 蒸馏 LLM 偶发把「只有溯源指针/占位/纯日期、无知识载荷」的碎片当 fact(如 `证据:文件:…|日期:…`),
|
||||
// 长度/实体启发式(IsQualityFact)抓不住 ⇒ 落库前用 payload-guard 拦下(未加载时 fail-open)。
|
||||
if distill.ShellCheck(fact) {
|
||||
log.Printf("[distill][payload-guard] 拒写空壳蒸馏 fact episode=%s fact=%.40s", input.EpisodeID, fact)
|
||||
continue
|
||||
}
|
||||
// 查重: 同 namespace 已存在**语义等价**记忆 → 跳过
|
||||
// 必须用 cosine 近重复判据(≥0.98),不能只比字符串相等——
|
||||
// 否则 "牧尘在招商局工作" 与 "牧尘在招商局工作。"(多一个句号)
|
||||
@@ -493,6 +508,18 @@ func NewServer() http.Handler {
|
||||
|
||||
mux.HandleFunc("/health", routes.HandleHealth)
|
||||
mux.HandleFunc("/api/v1/health", routes.HandleHealth)
|
||||
// t_e11207f8 治源①:空壳拦截器「确实跑过」的取证端点。
|
||||
// checks=每个蒸馏 fact 判一次的心跳计数(>0 即拦截器活着);blocks=实际拒写空壳条数;
|
||||
// loaded=false 表示共享判据没加载上(fail-open,需排查 ZHIYI_PAYLOAD_GUARD_RULES 路径)。
|
||||
mux.HandleFunc("/api/v1/payload-guard/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
checks, blocks, loaded, rp := distill.PayloadGuardStats()
|
||||
respondJSON(w, 200, map[string]interface{}{
|
||||
"checks": checks,
|
||||
"blocks": blocks,
|
||||
"loaded": loaded,
|
||||
"rules_path": rp,
|
||||
})
|
||||
})
|
||||
// 图谱缓存统计 + 搜索缓存统计(t_1c12e000:并入 search_cache 段,
|
||||
// 暴露 hits/misses/invalidated/size/ttl,写频对命中率的影响可观测)
|
||||
mux.HandleFunc("/api/v1/cache/stats", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -15,5 +15,6 @@ import (
|
||||
// 缓存本身的正确性由 score_cache_test.go 直接测结构体(不依赖全局实例)。
|
||||
func TestMain(m *testing.M) {
|
||||
scoreCacheDisabled = true
|
||||
loadPayloadRulesForTests() // t_e11207f8 治源①:单测前确保 payload guard 规则已加载(共享 JSON 或内嵌兜底)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package distill
|
||||
|
||||
// 织忆 MemoryWeave — 蒸馏落库「空壳正文」拒写门禁(t_e11207f8 治源 ①)
|
||||
//
|
||||
// 背景:OnDistillComplete(api/server.go)把 LLM 蒸馏出的 fact 直接 InsertMemory 进
|
||||
// memories(category=distilled)。蒸馏 LLM 偶发把「只有溯源指针 / 占位 / 纯日期、无知识
|
||||
// 载荷」的碎片当 fact 输出(例:`证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23`),
|
||||
// 质量门槛 IsQualityFact 的长度/实体启发式抓不住它(>20 字)⇒ 库里持续长出新空壳。
|
||||
//
|
||||
// 单一真相源:判据的**规则值**读自共享 JSON(zhiyi_payload_guard_rules.json),与
|
||||
// Python 侧 ~/.hermes/scripts/lib/zhiyi_payload_guard.py **读同一份文件**(不在此手抄,
|
||||
// 防跨语言漂移)。改规则只改那一个 JSON。
|
||||
//
|
||||
// 铁律(与 Python 逐位一致,宁漏勿误删):
|
||||
// · 含任一句读标点(clause_punct)⇒ 绝不判空壳(保真优先)
|
||||
// · 仅 空串 / 占位变量 / 纯日期 / 溯源指针(来源/证据/文件/日期/source + 引用值) 判空壳
|
||||
//
|
||||
// 已知跨语言 nuance(文档,不改行为方向):refname 正则里的 \w,Go RE2 默认 ASCII、
|
||||
// Python 默认 unicode ⇒ CJK-only 文件名 Go 不判引用 ⇒ Go **多保留**(安全向,宁漏勿误删)。
|
||||
//
|
||||
// 无缓存、无新增 Redis 键(只用原子计数),故不触及项目现成件清单的缓存条目。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// defaultRulesPath — 与 Python 侧同一份共享规则文件(同机同用户 muc 可直读)。
|
||||
// env ZHIYI_PAYLOAD_GUARD_RULES 可覆盖(测试/部署用)。
|
||||
func defaultRulesPath() string {
|
||||
if p := os.Getenv("ZHIYI_PAYLOAD_GUARD_RULES"); p != "" {
|
||||
return p
|
||||
}
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" {
|
||||
return filepath.Join(home, ".hermes", "scripts", "lib", "zhiyi_payload_guard_rules.json")
|
||||
}
|
||||
return "/home/muc/.hermes/scripts/lib/zhiyi_payload_guard_rules.json"
|
||||
}
|
||||
|
||||
// payloadGuardRules 镜像共享 JSON(只取 Go 判据需要的字段;未知字段忽略)。
|
||||
type payloadGuardRules struct {
|
||||
ClausePunct string `json:"clause_punct"`
|
||||
Placeholder struct {
|
||||
Pattern string `json:"pattern"`
|
||||
CaseInsensitive bool `json:"case_insensitive"`
|
||||
} `json:"placeholder"`
|
||||
BareDate struct {
|
||||
Pattern string `json:"pattern"`
|
||||
CaseInsensitive bool `json:"case_insensitive"`
|
||||
} `json:"bare_date"`
|
||||
ProvLabel struct {
|
||||
Pattern string `json:"pattern"`
|
||||
CaseInsensitive bool `json:"case_insensitive"`
|
||||
} `json:"prov_label"`
|
||||
Refname struct {
|
||||
Pattern string `json:"pattern"`
|
||||
CaseInsensitive bool `json:"case_insensitive"`
|
||||
} `json:"refname"`
|
||||
RefValueSubstrings []string `json:"ref_value_substrings"`
|
||||
RefValueMaxLen int `json:"ref_value_max_len"`
|
||||
RefValueMaxCJK int `json:"ref_value_max_cjk"`
|
||||
CJKLo string `json:"cjk_lo"`
|
||||
CJKHi string `json:"cjk_hi"`
|
||||
}
|
||||
|
||||
type guard struct {
|
||||
rules payloadGuardRules
|
||||
placeH *regexp.Regexp
|
||||
bareD *regexp.Regexp
|
||||
provL *regexp.Regexp
|
||||
refname *regexp.Regexp
|
||||
loaded bool
|
||||
path string
|
||||
}
|
||||
|
||||
var (
|
||||
g *guard
|
||||
// shellChecks = 拦截器「确实跑过」的心跳计数(每个蒸馏 fact 判一次);
|
||||
// shellBlocks = 实际拦下的空壳条数。二者配对即证拦截器活着(0 blocks 但 checks>0 也合法)。
|
||||
shellChecks int64
|
||||
shellBlocks int64
|
||||
)
|
||||
|
||||
// LoadPayloadGuard 读共享规则 JSON 并编译正则。失败 ⇒ 未加载(fail-open:distill 照跑、
|
||||
// 不拦空壳、不崩 zhiyid),并把 loaded=false 记给 /api/v1/payload-guard/stats 暴露。
|
||||
func LoadPayloadGuard(explicitPath string) (loaded bool, err error) {
|
||||
p := explicitPath
|
||||
if p == "" {
|
||||
p = defaultRulesPath()
|
||||
}
|
||||
raw, rerr := os.ReadFile(p)
|
||||
if rerr != nil {
|
||||
g = &guard{}
|
||||
return false, rerr
|
||||
}
|
||||
var rc payloadGuardRules
|
||||
if jerr := json.Unmarshal(raw, &rc); jerr != nil {
|
||||
g = &guard{}
|
||||
return false, jerr
|
||||
}
|
||||
compile := func(pat string, ci bool) (*regexp.Regexp, error) {
|
||||
if ci {
|
||||
pat = "(?i)" + pat
|
||||
}
|
||||
return regexp.Compile(pat)
|
||||
}
|
||||
gh := &guard{rules: rc, path: p, loaded: true}
|
||||
if gh.placeH, err = compile(rc.Placeholder.Pattern, rc.Placeholder.CaseInsensitive); err != nil {
|
||||
g = &guard{}
|
||||
return false, err
|
||||
}
|
||||
if gh.bareD, err = compile(rc.BareDate.Pattern, rc.BareDate.CaseInsensitive); err != nil {
|
||||
g = &guard{}
|
||||
return false, err
|
||||
}
|
||||
if gh.provL, err = compile(rc.ProvLabel.Pattern, rc.ProvLabel.CaseInsensitive); err != nil {
|
||||
g = &guard{}
|
||||
return false, err
|
||||
}
|
||||
if gh.refname, err = compile(rc.Refname.Pattern, rc.Refname.CaseInsensitive); err != nil {
|
||||
g = &guard{}
|
||||
return false, err
|
||||
}
|
||||
if rc.RefValueMaxLen <= 0 {
|
||||
rc.RefValueMaxLen = 24
|
||||
}
|
||||
if rc.RefValueMaxCJK <= 0 {
|
||||
rc.RefValueMaxCJK = 12
|
||||
}
|
||||
gh.rules = rc
|
||||
g = gh
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// PayloadGuardStats 供 /metrics 与验收:拦截器心跳(checks) / 拦截数(blocks) / 是否加载 / 规则路径。
|
||||
func PayloadGuardStats() (checks, blocks int64, loaded bool, path string) {
|
||||
if g == nil {
|
||||
return atomic.LoadInt64(&shellChecks), atomic.LoadInt64(&shellBlocks), false, ""
|
||||
}
|
||||
return atomic.LoadInt64(&shellChecks), atomic.LoadInt64(&shellBlocks), g.loaded, g.path
|
||||
}
|
||||
|
||||
// IncShellCheck / IncShellBlock 供写路径在判定前后调用(相对增量,避免并发写竞态)。
|
||||
func IncShellCheck() { atomic.AddInt64(&shellChecks, 1) }
|
||||
func IncShellBlock() { atomic.AddInt64(&shellBlocks, 1) }
|
||||
|
||||
// ShellCheck 治源入口(带心跳计数):
|
||||
// - 未加载 ⇒ fail-open(放行、checks 仍 +1,保证「拦截器跑过」可观测,不拦也不崩);
|
||||
// - 已加载 ⇒ 用共享判据判定,命中空壳则 blocks +1 并返回 true(写路径据此 continue 拒写)。
|
||||
func ShellCheck(content string) bool {
|
||||
IncShellCheck()
|
||||
if g == nil || !g.loaded {
|
||||
return false
|
||||
}
|
||||
if g.isEmptyShell(content) {
|
||||
IncShellBlock()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsEmptyShell 纯判据(无计数,供单测)。未加载时就地读一次默认路径兜底;失败则 fail-open。
|
||||
func IsEmptyShell(content string) bool {
|
||||
if g == nil {
|
||||
if _, err := LoadPayloadGuard(""); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return g.isEmptyShell(content)
|
||||
}
|
||||
|
||||
func (gr *guard) isEmptyShell(content string) bool {
|
||||
c := strings.TrimSpace(content)
|
||||
if c == "" {
|
||||
return true
|
||||
}
|
||||
// 含任一句读标点 ⇒ 有知识断言 ⇒ 绝不当空壳(保真优先,优先于漏删)
|
||||
for _, r := range []rune(gr.rules.ClausePunct) {
|
||||
if strings.ContainsRune(c, r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if gr.placeH.MatchString(c) {
|
||||
return true
|
||||
}
|
||||
if gr.bareD.MatchString(c) {
|
||||
return true
|
||||
}
|
||||
if gr.provL.MatchString(c) && gr.isRefValue(c) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (gr *guard) isRefValue(c string) bool {
|
||||
s := strings.TrimSpace(c)
|
||||
for _, sub := range gr.rules.RefValueSubstrings {
|
||||
if strings.Contains(c, sub) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if gr.bareD.MatchString(s) || gr.refname.MatchString(s) {
|
||||
return true
|
||||
}
|
||||
if utf8.RuneCountInString(s) <= gr.rules.RefValueMaxLen && gr.cjkCount(s) < gr.rules.RefValueMaxCJK {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// cjkCount 统计 [cjk_lo, cjk_hi] 区间的汉字数(与 Python re.findall(r"[一-鿿]") 等价)。
|
||||
func (gr *guard) cjkCount(s string) int {
|
||||
lo, hi := gr.rules.CJKLo, gr.rules.CJKHi
|
||||
if lo == "" || hi == "" {
|
||||
lo, hi = "一", "鿿" // U+4E00 / U+9FFF
|
||||
}
|
||||
loR, _ := utf8.DecodeRuneInString(lo)
|
||||
hiR, _ := utf8.DecodeRuneInString(hi)
|
||||
n := 0
|
||||
for _, r := range s {
|
||||
if r >= loR && r <= hiR {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package distill
|
||||
|
||||
// t_e11207f8 治源 ① Go 单测:
|
||||
// ① 真样本(溯源指针)必判空壳;② 负控(真知识短句 / 含句读)必保留;③ 拦截计数。
|
||||
// 判据值优先读【生产共享 JSON】(~/.hermes/scripts/lib/zhiyi_payload_guard_rules.json),
|
||||
// 与 Python 同源;该文件缺失时用下方内嵌副本兜底(仅测试用,非运行时真相源)。
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const embeddedRulesJSON = `{
|
||||
"clause_punct": ",。、;!?",
|
||||
"placeholder": {"pattern": "^[xX]=(?:true|false|\\\\d|[a-z_]{1,12})$", "case_insensitive": true},
|
||||
"bare_date": {"pattern": "^(?:日期[::]?)?\\\\d{4}[-/]\\\\d{1,2}[-/]\\\\d{1,2}\\\\.?[。.\\\\s]*$"},
|
||||
"prov_label": {"pattern": "^(?:来源|证据|文件|日期|source)[::]", "case_insensitive": true},
|
||||
"refname": {"pattern": "^[\\\\w.-]+\\\\.(?:md|py|sh|json|yaml|log|txt)$", "case_insensitive": true},
|
||||
"ref_value_substrings": ["|", "vault:", "/"],
|
||||
"ref_value_max_len": 24, "ref_value_max_cjk": 12,
|
||||
"cjk_lo": "一", "cjk_hi": "鿿"
|
||||
}`
|
||||
|
||||
func loadPayloadRulesForTests() {
|
||||
// 优先生产共享 JSON(与 Python 同源);缺失则落内嵌副本到临时目录再读(保证测试可独立跑)。
|
||||
p := os.Getenv("ZHIYI_PAYLOAD_GUARD_RULES")
|
||||
if p == "" {
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" {
|
||||
p = filepath.Join(home, ".hermes", "scripts", "lib", "zhiyi_payload_guard_rules.json")
|
||||
}
|
||||
}
|
||||
if _, err := LoadPayloadGuard(p); err != nil {
|
||||
tmp, merr := os.MkdirTemp("", "zhiyi-payload-rules-")
|
||||
if merr != nil {
|
||||
return
|
||||
}
|
||||
rp := filepath.Join(tmp, "rules.json")
|
||||
if werr := os.WriteFile(rp, []byte(embeddedRulesJSON), 0o644); werr != nil {
|
||||
return
|
||||
}
|
||||
LoadPayloadGuard(rp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyShell_Positive_RealSample(t *testing.T) {
|
||||
cases := []string{
|
||||
"证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23", // 蒸馏真样本(QA/小怡复现的那条)
|
||||
"来源:vault:定义规范:106办公向优化方案-2026-09-18.md",
|
||||
"证据:文件:小怡/工作笔记/已办.md",
|
||||
"X=true",
|
||||
"",
|
||||
"2026-09-23",
|
||||
}
|
||||
for _, c := range cases {
|
||||
if !IsEmptyShell(c) {
|
||||
t.Errorf("应判空壳却放行: %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyShell_Negative_KeepRealKnowledge(t *testing.T) {
|
||||
cases := []string{
|
||||
"牧尘在招商局工作", // 负控:超短真断言,绝不当空壳
|
||||
"活库直连写必须停服务", // 负控:真知识
|
||||
"来源:t_cbc41a01 待办 #6 核销结果。", // 含句读(。)⇒ 必保留
|
||||
"双向链接是 Obsidian 最核心的功能之一。", // 含句读
|
||||
"决定将newapi平台中的付费key改为免费", // 真知识
|
||||
"织忆端口7821", // 短但无句读、无溯源前缀、非占位 ⇒ 保守保留
|
||||
}
|
||||
for _, c := range cases {
|
||||
if IsEmptyShell(c) {
|
||||
t.Errorf("误判真知识为空壳(负控失败,违反宁漏勿误删): %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShellCheck_Counters(t *testing.T) {
|
||||
// ③ 拦截器计数:每个 fact 判一次(checks 增),命中空壳再 blocks 增。
|
||||
c0, b0, loaded, _ := PayloadGuardStats()
|
||||
if !loaded {
|
||||
t.Fatalf("payload guard 未加载,无法验证拦截器")
|
||||
}
|
||||
good := "用户决定升级系统"
|
||||
shell := "证据:文件:小怡/工作笔记/已办.md|日期:2026-09-23"
|
||||
if ShellCheck(good) {
|
||||
t.Errorf("真知识 fact 被误拦: %q", good)
|
||||
}
|
||||
if !ShellCheck(shell) {
|
||||
t.Errorf("空壳蒸馏 fact 未被拦: %q", shell)
|
||||
}
|
||||
c1, b1, _, _ := PayloadGuardStats()
|
||||
if c1-c0 != 2 {
|
||||
t.Errorf("checks 增量应为 2(good+shell 各判一次),实得 %d", c1-c0)
|
||||
}
|
||||
if b1-b0 != 1 {
|
||||
t.Errorf("blocks 增量应为 1(仅 shell 命中),实得 %d", b1-b0)
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,5 @@ c57f557ab8d126c7ef031e63402abaa1f6602155
|
||||
aaeaf2b7ec9304b851089cbe64ddda0a5916d99f
|
||||
a2be088cba59c95901b22d855dea9b6df3bf3a80
|
||||
4fb4705e6de8991e9863cf8902e4265ec412626e
|
||||
appending: 212624a42541c41f10168e5a3834bd2304efcdb9\n 4341fac4c28a4f2825f7373ea0ec94d07c6452f0
|
||||
212624a42541c41f10168e5a3834bd2304efcdb9
|
||||
4341fac4c28a4f2825f7373ea0ec94d07c6452f0
|
||||
|
||||
Reference in New Issue
Block a user