feat(metanote): t_5ad3f843 meta-note 分类门禁(Go 侧,ZHIYI_META_FILTER=1 启用,默认零行为变化)
- internal/metanote:21 条正则 Go 等价式 + 判定逐步同序镜像 Python 口径真相源 (scripts/lib/meta_note_filter.py);\b/\w 映射显式化:\w→[[:word:]\pL\pN]、 \b 剥离改匹配值前缀边界校验(pre/post/both 三表,未被裸替代项覆盖才校验) - parity/差分三件套(同 memprotect 范式): * Go 等价式 == 变换函数(Py 源式) 逐字节锁死 * 实时 dump Python 常量逐字节比对(漂移即 FAIL) * /tmp 副本异变必须让 parity FAIL(负控) * 14 正+11 负+14 边界+SOT 用例表 全量差分 vs 真实 Python classify - 咽喉点接线 4 处:Commit/WriteMemory/BatchCommit(422 拒绝+skipped_meta) + AutoDistillTrigger(admin distill/force 经此函数一并覆盖) - handler 级验证:门禁开 meta⇒422 先于触碰 storage(零值 API 不 panic) - 只新增/改 go 侧与判定,未碰 7821/生产二进制/生产 unit/存量记忆,门未激活
This commit is contained in:
@@ -2,10 +2,12 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/distill"
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/metanote"
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
)
|
||||
|
||||
@@ -27,6 +29,14 @@ type CommitMeta struct {
|
||||
// 2026-10-08 (t_7e3577c5):新增 embedModel/scriptVer 血缘字段透传
|
||||
// 2026-10-08 (Gap#2):改为 CommitMeta 结构体,新增 confidence 透传
|
||||
func AutoDistillTrigger(episodeID string, content string, category string, namespace string, agentID string, meta CommitMeta) {
|
||||
// 2026-10-16 t_5ad3f843:meta-note 门禁(env ZHIYI_META_FILTER=1 启用;默认关闭=零行为变化)。
|
||||
// 蒸馏是事实写入的唯一咽喉:原文判 meta ⇒ 不进蒸馏(引擎路径与降级路径都挡),
|
||||
// 从源头杜绝 meta-note 生成 memories 事实(admin distill/force 也经此函数,一并覆盖)。
|
||||
if skip, reason := metanote.ShouldSkip(content); skip {
|
||||
log.Printf("[metanote] auto-distill skipped: ep=%s agent=%s reason=%s content=%.60s", episodeID, agentID, reason, content)
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 硬规则过滤
|
||||
if !distill.HardRulesPass(content) {
|
||||
return
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
"github.com/xiaoxue/memoryweave/internal/metrics"
|
||||
"github.com/xiaoxue/memoryweave/internal/models"
|
||||
"github.com/xiaoxue/memoryweave/internal/metanote"
|
||||
"github.com/xiaoxue/memoryweave/internal/selfoptimize"
|
||||
"github.com/xiaoxue/memoryweave/internal/storage"
|
||||
)
|
||||
@@ -101,6 +102,15 @@ func (a *API) Commit(w http.ResponseWriter, r *http.Request) {
|
||||
respondError(w, 400, "agent_id and content required")
|
||||
return
|
||||
}
|
||||
// 2026-10-16 t_5ad3f843:meta-note 门禁(env ZHIYI_META_FILTER=1 启用;默认关闭=零行为变化)。
|
||||
// 判定与 Python 口径真相源同源(internal/metanote,parity/差分测试锁死);
|
||||
// 判 meta ⇒ 422 拒绝,不写 episode、不进蒸馏(卡面:把 meta 挡在咽喉点)。
|
||||
if skip, reason := metanote.ShouldSkip(req.Content); skip {
|
||||
log.Printf("[metanote] commit rejected (gate ON, meta-note): agent=%s ns=%s reason=%s content=%.60s",
|
||||
req.AgentID, req.Namespace, reason, req.Content)
|
||||
respondError(w, 422, "meta-note rejected: "+reason)
|
||||
return
|
||||
}
|
||||
if req.Namespace == "" {
|
||||
req.Namespace = classifyNamespace(req.Category, req.AgentID, req.Content)
|
||||
}
|
||||
@@ -308,6 +318,12 @@ func (a *API) WriteMemory(w http.ResponseWriter, r *http.Request) {
|
||||
respondError(w, 400, "content too short (<8 chars)")
|
||||
return
|
||||
}
|
||||
// 2026-10-16 t_5ad3f843:meta-note 门禁(同 Commit;默认关闭=零行为变化)。
|
||||
if skip, reason := metanote.ShouldSkip(req.Content); skip {
|
||||
log.Printf("[metanote] write_memory rejected: agent=%s reason=%s content=%.60s", req.AgentID, reason, req.Content)
|
||||
respondError(w, 422, "meta-note rejected: "+reason)
|
||||
return
|
||||
}
|
||||
if req.AgentID == "" {
|
||||
req.AgentID = "hermes-a06"
|
||||
}
|
||||
@@ -1206,7 +1222,14 @@ func (a *API) BatchCommit(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var ids []string
|
||||
skippedMeta := 0
|
||||
for _, item := range req.Items {
|
||||
// 2026-10-16 t_5ad3f843:meta-note 门禁——逐条跳过 meta 条目(门禁默认关闭=零行为变化)。
|
||||
if skip, reason := metanote.ShouldSkip(item.Content); skip {
|
||||
log.Printf("[metanote] batch item skipped: agent=%s reason=%s content=%.60s", item.AgentID, reason, item.Content)
|
||||
skippedMeta++
|
||||
continue
|
||||
}
|
||||
ns := item.Namespace
|
||||
if ns == "" {
|
||||
cat := item.Category
|
||||
@@ -1226,7 +1249,7 @@ func (a *API) BatchCommit(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
respond(w, 201, map[string]interface{}{"ids": ids, "count": len(ids), "status": "ok"})
|
||||
respond(w, 201, map[string]interface{}{"ids": ids, "count": len(ids), "skipped_meta": skippedMeta, "status": "ok"})
|
||||
}
|
||||
|
||||
// ─── Namespace 分类规则(按 §1.3 设计)─────────────────────
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package routes
|
||||
|
||||
// t_5ad3f843 AC8:handler 级门禁验证。
|
||||
// 门禁开 ⇒ meta-note 在**触碰 storage 之前**被 422 拒绝:
|
||||
// 零值 API{}(LanceDB 接口为 nil)足证——若门禁按设计在写路径前生效,
|
||||
// 422 先行返回、不会 nil 解引用 panic;若门禁失效走到 InsertEpisode ⇒ panic。
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/metanote"
|
||||
)
|
||||
|
||||
func TestCommitGate_MetaRejectedBeforeStorage(t *testing.T) {
|
||||
old := os.Getenv("ZHIYI_META_FILTER")
|
||||
os.Setenv("ZHIYI_META_FILTER", "1")
|
||||
defer os.Setenv("ZHIYI_META_FILTER", old)
|
||||
|
||||
a := &API{} // 零值:LanceDB 为 nil —— 422 先于写路径 ⇒ 不 panic
|
||||
body := `{"agent_id":"hermes-a06","namespace":"hermes-main","content":"实测 淇县 ANN 731→15(都进池50)","category":"system_fact"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/commit", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
a.Commit(w, req)
|
||||
if w.Code != 422 {
|
||||
t.Fatalf("commit(meta, 门禁开) 期望 422,实际 %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "meta-note") {
|
||||
t.Errorf("拒绝体应说明 meta-note 原因: %s", w.Body.String())
|
||||
}
|
||||
|
||||
// 门禁关 ⇒ 同一内容 ShouldSkip 必须 false(AC6 零行为变化)
|
||||
os.Setenv("ZHIYI_META_FILTER", "")
|
||||
if skip, _ := metanote.ShouldSkip("实测 淇县 ANN 731→15(都进池50)"); skip {
|
||||
t.Fatal("门禁关闭时 ShouldSkip 必须为 false(零行为变化)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteMemoryGate_MetaRejectedBeforeStorage(t *testing.T) {
|
||||
old := os.Getenv("ZHIYI_META_FILTER")
|
||||
os.Setenv("ZHIYI_META_FILTER", "1")
|
||||
defer os.Setenv("ZHIYI_META_FILTER", old)
|
||||
|
||||
a := &API{}
|
||||
body := `{"agent_id":"hermes-a06","content":"织忆 golden 14/14 不退化,recall@5 = 0.4286"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/memory/write", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
a.WriteMemory(w, req)
|
||||
if w.Code != 422 {
|
||||
t.Fatalf("write_memory(meta, 门禁开) 期望 422,实际 %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package metanote
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Classify 返回 (isMeta, reason)。判定逐步同序镜像 Python classify();
|
||||
// reason 仅人读(命中规则拼接),与 Python 文案不逐字比。
|
||||
func Classify(text string) (bool, string) {
|
||||
if text == "" {
|
||||
return false, ""
|
||||
}
|
||||
t := strings.TrimSpace(text)
|
||||
if utf8.RuneCountInString(t) < 4 {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// STRONG 档:任一形状命中即 meta(顺序与 Python 一致,仅影响 reason 拼法)
|
||||
var strong []string
|
||||
add := func(nm string) {
|
||||
if anyMatch(nm, t) {
|
||||
strong = append(strong, nm)
|
||||
}
|
||||
}
|
||||
add("mem_id")
|
||||
add("data_inv")
|
||||
add("pool")
|
||||
add("pool_in")
|
||||
add("ci_log")
|
||||
add("repro")
|
||||
add("rank")
|
||||
add("rank_num")
|
||||
if anyMatch("num_arrow", t) && (anyMatch("pool", t) || anyMatch("pool_in", t)) {
|
||||
strong = append(strong, "num_arrow+pool")
|
||||
}
|
||||
add("db_task")
|
||||
add("recall_count")
|
||||
add("recall_act")
|
||||
add("write_bug")
|
||||
add("eval_metric")
|
||||
add("debug_mark")
|
||||
if len(strong) > 0 {
|
||||
return true, "strong:" + strings.Join(strong, "+")
|
||||
}
|
||||
|
||||
// CUE 档(distinct 计数;边界过滤后的组值)
|
||||
cues := distinctVals("sys_cue", t)
|
||||
if anyMatch("t_id", t) {
|
||||
cues["t_id"] = true
|
||||
}
|
||||
if anyMatch("svc_fam", t) {
|
||||
cues["svc_fam"] = true
|
||||
}
|
||||
for w := range distinctVals("svc_word", t) {
|
||||
cues[w] = true
|
||||
}
|
||||
diags := distinctVals("diag", t)
|
||||
nCue, nDiag := len(cues), len(diags)
|
||||
|
||||
// 「事实 vs 调查记录」区分判据(AC4):声明形系统事实 + 无调查信号 ⇒ 放行。
|
||||
// 调查信号 = 诊断词 ∨ 概念词(泛系词 svc_fam/召回/蒸馏 之外)∨ t_id。
|
||||
// 调查记录(带实测/复现/命名空间/限流/碎片化… 或 诊断词)不受事实形豁免。
|
||||
hasInv := nDiag > 0
|
||||
if !hasInv {
|
||||
for c := range cues {
|
||||
if c != "svc_fam" && c != "召回" && c != "蒸馏" {
|
||||
hasInv = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if anyMatch("fact_decl", t) && !hasInv {
|
||||
return false, "fact_decl"
|
||||
}
|
||||
if nCue >= 2 {
|
||||
return true, "cue×2"
|
||||
}
|
||||
if nCue >= 1 && nDiag >= 1 {
|
||||
return true, "cue+diag"
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// GateEnabled:env 门控(ZHIYI_META_FILTER=1 启用;默认关闭 = 零行为变化)。
|
||||
// 逐请求读取:测试/灰度可无需重启翻转(生产由 unit env 决定,默认无 = 关)。
|
||||
func GateEnabled() bool {
|
||||
return strings.TrimSpace(os.Getenv("ZHIYI_META_FILTER")) == "1"
|
||||
}
|
||||
|
||||
// ShouldSkip:门禁 ON 且判 meta ⇒ (true, reason)。调用点据此拒绝落库。
|
||||
func ShouldSkip(text string) (bool, string) {
|
||||
if !GateEnabled() {
|
||||
return false, ""
|
||||
}
|
||||
return Classify(text)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package metanote
|
||||
|
||||
// 差分测试:同一 fixture 表 → Go Classify vs 真实 Python classify,逐行断言
|
||||
// 布尔一致(与 go/internal/memprotect TestDifferential_PythonReference 同款)。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os/exec"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// diffFixturesStatic:QA 判据集(verify-meta-filter.py 的 14 正例 + 11 负例,
|
||||
// 逐字)+ 14 条边界边缘(专测 \b/\w 映射的 CJK 词边界语义)。
|
||||
var diffFixturesStatic = []string{
|
||||
// ── 14 正例(生产原文逐字,必须全判 meta)──
|
||||
"短问法 MISS 复现:牧尘工作所在的县是哪个",
|
||||
"实测 淇县 ANN 731→15、鹤壁 6536→18(都进池50)",
|
||||
"淇县库里 21 条、鹤壁 10 条、河南 15 条语料可用。",
|
||||
"实测(只读,未改任何库/代码):目标「用户在招商局工作」在 query「我工作所在的县是哪个」的 400 候选池内 cos 排名 17",
|
||||
"memory_write 落 episodes 表 + vector 全 0 —— 写入路径待修",
|
||||
"织忆 golden 14/14 不退化,recall@5 = 0.4286",
|
||||
"本次复核的探针脚本输出:命中 3 条,与分身自报 3 条一致",
|
||||
"复现步骤:query「我工作所在的县是哪个」返回 0 条相关",
|
||||
"DEBUG: recall returned empty, investigating index",
|
||||
"依据:全文搜索会命中任何提过该词的笔记,噪声淹没正解",
|
||||
"避免蒸馏碎片化后广泛问法召不到",
|
||||
"召回诊断三步法:①IPC 全表扫确认「在库」→ ②默认 recall top-5 看「是否命中」",
|
||||
"现在动召回等于照着一把会撒谎的尺子去改。",
|
||||
"实测 淇县 ANN 731→15(都进池50)",
|
||||
// ── 11 负例(系统事实,必须全放行)──
|
||||
"牧尘在河南省鹤壁市淇县工作。",
|
||||
"淇县招商项目台账(09-27阅读版).md 已发布。",
|
||||
"织忆服务的健康检查接口监听 7821 端口。",
|
||||
"织忆召回接口 POST /api/v1/recall 接受 top_k 参数。",
|
||||
"召回缓存 recall-cache 每 6 小时刷新一次。",
|
||||
"织忆主服务进程名是 zhiyi" + "d-new,合并服务是 zhiyi-consolidate。",
|
||||
"公文排版正文用仿宋_GB2312 字体,行距 28 磅。",
|
||||
"家庭服务器(跑 Gitea)在局域网里的地址是 192.168.123.11。",
|
||||
"本地 2B 模型服务监听 8080 端口。",
|
||||
"牧尘负责生物制造产业专班 + 卫都街道安全管理。",
|
||||
"小怡日常主链模型是 deepseek-v4-flash(官方直连)。",
|
||||
// ── 边界边缘(CJK 词边界语义,专测 \b→代码校验 的映射)──
|
||||
"淇县ANN 731→15", // 县 是 word ⇒ 前界不成立 ⇒ 非 meta
|
||||
"cosine 相似度 0.9 不算高", // cos 后接 i ⇒ 后界不成立 ⇒ 非 meta
|
||||
"启用兜底机制。", // 兜 前 用 / 后 机 皆 word ⇒ 非 meta
|
||||
"限流与退避都生效。", // 裸 cue×2 ⇒ meta
|
||||
"IPC 全表扫确认「在库」。", // cue IPC+全表扫 ⇒ meta
|
||||
"memory_write 落库测试", // 尾界(空格)成立 ⇒ meta
|
||||
"MEMORY 大写不判 meta。", // [a-z]+ 不匹配 ⇒ 非 meta
|
||||
"validate.js 契约通过", // 尾界成立 ⇒ meta
|
||||
"接受top_k参数", // 事实形无调查信号 ⇒ 放行
|
||||
"接受 召回 参数,每 6 小时一次", // 召回∈豁免系 + 事实形 ⇒ 放行
|
||||
"探针脚本命中 3 条", // strong debug_mark ⇒ meta
|
||||
"召回 诊断 三步", // cue+diag ⇒ meta
|
||||
"淇县招商项目台账已发布。", // 无信号 ⇒ 非 meta
|
||||
"每 6 小时刷新一次缓存。", // 事实形 ⇒ 放行
|
||||
}
|
||||
|
||||
// pyBoolBatch:把文本表喂给**真实 Python classify**(subprocess),返回逐行布尔。
|
||||
func pyBoolBatch(t *testing.T, sot string, texts []string) []bool {
|
||||
t.Helper()
|
||||
tb, _ := json.Marshal(texts)
|
||||
code := `
|
||||
import importlib.util, json, sys
|
||||
spec = importlib.util.spec_from_file_location("mnf_sot", sys.argv[1])
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
texts = json.loads(sys.argv[2])
|
||||
print(json.dumps([m.classify(x)[0] for x in texts]))
|
||||
`
|
||||
out, err := exec.Command("python3", "-c", code, sot, string(tb)).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("Python classify 执行失败: %v (out=%s)", err, out)
|
||||
}
|
||||
var res []bool
|
||||
if err := json.Unmarshal(out, &res); err != nil {
|
||||
t.Fatalf("Python 结果解析失败: %v (raw=%s)", err, out)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// pyListNames:实时 dump Python 侧既有用例表(_KNOWN_META/_REAL_KNOWLEDGE),
|
||||
// 让差分表随 SOT 演进(SOT 加新样本 ⇒ 本测试自动跟上,无需手改 Go)。
|
||||
func pyListNames(t *testing.T, sot, attr string) []string {
|
||||
t.Helper()
|
||||
code := `
|
||||
import importlib.util, json, sys
|
||||
spec = importlib.util.spec_from_file_location("mnf_sot", sys.argv[1])
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
print(json.dumps(list(getattr(m, sys.argv[2]))))
|
||||
`
|
||||
out, err := exec.Command("python3", "-c", code, sot, attr).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("Python 用例表 dump 失败: %v (out=%s)", err, out)
|
||||
}
|
||||
var res []string
|
||||
if err := json.Unmarshal(out, &res); err != nil {
|
||||
t.Fatalf("用例表解析失败: %v (raw=%s)", err, out)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// TestDifferential_PythonReference:Go vs 真实 Python 全量差分(14+11+14 静态
|
||||
// + _KNOWN_META + _REAL_KNOWLEDGE 实时)。任何一处口径漂移在此 FAIL。
|
||||
func TestDifferential_PythonReference(t *testing.T) {
|
||||
sot := pySOTPath()
|
||||
if sot == "" {
|
||||
t.Skip("无 HOME,无法定位 Python SOT")
|
||||
}
|
||||
texts := append([]string{}, diffFixturesStatic...)
|
||||
texts = append(texts, pyListNames(t, sot, "_KNOWN_META")...)
|
||||
texts = append(texts, pyListNames(t, sot, "_REAL_KNOWLEDGE")...)
|
||||
// 去重(_KNOWN_META 与静态表可能有逐字重叠;重叠不影响判定,仅省 subprocess 体积)
|
||||
seen := map[string]bool{}
|
||||
uniq := texts[:0]
|
||||
for _, x := range texts {
|
||||
if !seen[x] {
|
||||
seen[x] = true
|
||||
uniq = append(uniq, x)
|
||||
}
|
||||
}
|
||||
want := pyBoolBatch(t, sot, uniq)
|
||||
for i, x := range uniq {
|
||||
got, _ := Classify(x)
|
||||
if got != want[i] {
|
||||
t.Errorf("case %d: Go=%v ≠ Python=%v — 口径漂移: %q", i, got, want[i], x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDifferential_ExpectedSpotChecks:手写锚点(CI 安全、不依赖 Python),
|
||||
// 锁死当前规则行为最关键的几行(正例必须拦、3 条误拦负例必须放)。
|
||||
func TestDifferential_ExpectedSpotChecks(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"实测 淇县 ANN 731→15、鹤壁 6536→18(都进池50)": true, // 卡面点名 · 曾漏
|
||||
"织忆 golden 14/14 不退化,recall@5 = 0.4286": true, // 评测指标形
|
||||
"DEBUG: recall returned empty, investigating index": true,
|
||||
"织忆召回接口 POST /api/v1/recall 接受 top_k 参数。": false, // 曾误拦·事实
|
||||
"召回缓存 recall-cache 每 6 小时刷新一次。": false, // 曾误拦·事实
|
||||
"淇县ANN 731→15": false, // 边界边缘:非 meta
|
||||
}
|
||||
for x, want := range cases {
|
||||
got, reason := Classify(x)
|
||||
if got != want {
|
||||
t.Errorf("spot %q: Go=%v (reason=%s) 期望=%v", x, got, reason, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package metanote
|
||||
|
||||
// 实时 parity(同 go/internal/memprotect 范式:解析 Python 侧真实常量):
|
||||
// ① Go 等价式 == 变换函数(Py 源式);② 实时 dump Python 常量逐字节比对;
|
||||
// ③ 异变 /tmp 副本后 parity 必须 FAIL(负控)。
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// pySOTPath:Python 口径真相源位置(env 可覆盖 ⇒ 变异副本测试用它指 /tmp 副本)。
|
||||
func pySOTPath() string {
|
||||
if p := os.Getenv("METANOTE_PY_SOT"); p != "" {
|
||||
return p
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".hermes", "scripts", "lib", "meta_note_filter.py")
|
||||
}
|
||||
|
||||
const pyDumpCode = `
|
||||
import importlib.util, json, sys
|
||||
p = sys.argv[1]
|
||||
spec = importlib.util.spec_from_file_location("mnf_sot", p)
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
names = ["_MEM_ID","_T_ID","_DATA_INV","_POOL","_POOL_IN","_CI_LOG","_REPRO",
|
||||
"_RANK","_RANK_NUM","_NUM_ARROW","_DBTASK","_RECCOUNT","_RCALLACT",
|
||||
"_WRITE_BUG","_EVAL_METRIC","_DEBUG_MARK","_SVC_FAM","_SVC_WORD",
|
||||
"_SYS_CUE","_DIAG","_FACT_DECL"]
|
||||
km = {"_MEM_ID":"mem_id","_T_ID":"t_id","_DATA_INV":"data_inv","_POOL":"pool",
|
||||
"_POOL_IN":"pool_in","_CI_LOG":"ci_log","_REPRO":"repro","_RANK":"rank",
|
||||
"_RANK_NUM":"rank_num","_NUM_ARROW":"num_arrow","_DBTASK":"db_task",
|
||||
"_RECCOUNT":"recall_count","_RCALLACT":"recall_act","_WRITE_BUG":"write_bug",
|
||||
"_EVAL_METRIC":"eval_metric","_DEBUG_MARK":"debug_mark","_SVC_FAM":"svc_fam",
|
||||
"_SVC_WORD":"svc_word","_SYS_CUE":"sys_cue","_DIAG":"diag",
|
||||
"_FACT_DECL":"fact_decl"}
|
||||
out = {km[n]: getattr(m, n).pattern for n in names}
|
||||
print(json.dumps(out))
|
||||
`
|
||||
|
||||
// pyDumpPatterns:subprocess 实时 dump Python SOT 的 21 条正则常量(pattern 文本)。
|
||||
func pyDumpPatterns(t *testing.T, sot string) map[string]string {
|
||||
t.Helper()
|
||||
out, err := exec.Command("python3", "-c", pyDumpCode, sot).Output()
|
||||
if err != nil {
|
||||
t.Fatalf("Python 常量 dump 失败: %v (out=%s)", err, out)
|
||||
}
|
||||
var m map[string]string
|
||||
if err := json.Unmarshal(out, &m); err != nil {
|
||||
t.Fatalf("dump JSON 解析失败: %v (raw=%s)", err, out)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// TestGoEquivalentMatchesTransform:Go 等价式必须 == pyToGo(Python 源式)——
|
||||
// 6 条含 \w/\b 的映射式与 15 条逐字转写全部锁死。
|
||||
func TestGoEquivalentMatchesTransform(t *testing.T) {
|
||||
if len(goPats) != len(expectedPySrc) {
|
||||
t.Fatalf("表大小不等: Go=%d Python=%d", len(goPats), len(expectedPySrc))
|
||||
}
|
||||
for name, pySrc := range expectedPySrc {
|
||||
want := pyToGo(pySrc)
|
||||
got, ok := goPats[name]
|
||||
if !ok {
|
||||
t.Errorf("Go 表缺 %q(Python 有)", name)
|
||||
continue
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("等价式漂移 %q:\n Go = %q\n 变换后 = %q\n Py 源式 = %q", name, got, want, pySrc)
|
||||
}
|
||||
}
|
||||
for name := range goPats {
|
||||
if _, ok := expectedPySrc[name]; !ok {
|
||||
t.Errorf("Go 表有多余 %q(Python 无)", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParity_PythonLive:实时解析 Python 侧真实常量,逐字节比对(漂移即 FAIL)。
|
||||
func TestParity_PythonLive(t *testing.T) {
|
||||
sot := pySOTPath()
|
||||
if sot == "" {
|
||||
t.Skip("无 HOME,无法定位 Python SOT")
|
||||
}
|
||||
if _, err := os.Stat(sot); err != nil {
|
||||
t.Skipf("Python SOT 不存在: %s", sot)
|
||||
}
|
||||
dump := pyDumpPatterns(t, sot)
|
||||
for name, want := range expectedPySrc {
|
||||
got, ok := dump[name]
|
||||
if !ok {
|
||||
t.Errorf("Python dump 缺 %q", name)
|
||||
continue
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("parity 漂移 %q: Python 现行 = %q ≠ 期望 %q(改规则须双端同改并报 default 裁定)", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParity_MutatedCopyFails(负控):把 SOT 拷到 /tmp 副本并异变一条正则,
|
||||
// parity 检查必须**发现**漂移 —— 证明「异变 /tmp 副本后 parity 测试会 FAIL」
|
||||
// (memprotect 范式同款)。若此处检测不到漂移,本测试自己 FAIL。
|
||||
func TestParity_MutatedCopyFails(t *testing.T) {
|
||||
sot := pySOTPath()
|
||||
if sot == "" {
|
||||
t.Skip("无 HOME,无法定位 Python SOT")
|
||||
}
|
||||
src, err := os.ReadFile(sot)
|
||||
if err != nil {
|
||||
t.Skipf("Python SOT 读不到: %v", err)
|
||||
}
|
||||
mutated := strings.Replace(string(src),
|
||||
`_DEBUG_MARK = re.compile(r"(\bDEBUG\b|探针|自报|脚本输出)")`,
|
||||
`_DEBUG_MARK = re.compile(r"(\bDEBUG\b|自报|脚本输出)")`, 1)
|
||||
if mutated == string(src) {
|
||||
t.Fatalf("变异未生效(SOT 里 _DEBUG_MARK 行已变,本负控需同步)")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
cop := filepath.Join(dir, "meta_note_filter_mutated.py")
|
||||
if err := os.WriteFile(cop, []byte(mutated), 0o644); err != nil {
|
||||
t.Fatalf("写变异副本失败: %v", err)
|
||||
}
|
||||
dump := pyDumpPatterns(t, cop)
|
||||
problems := 0
|
||||
for name, want := range expectedPySrc {
|
||||
if got, ok := dump[name]; ok && got != want {
|
||||
problems++
|
||||
if name == "debug_mark" {
|
||||
t.Logf("负控命中:debug_mark 在变异副本 = %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
if problems == 0 {
|
||||
t.Fatalf("负控失效:变异 /tmp 副本后 parity 未检出任何漂移 ⇒ 变异必须让 parity FAIL,现在没 FAIL")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package metanote
|
||||
|
||||
import "strings"
|
||||
|
||||
// expectedPySrc:Python SOT(~/.hermes/scripts/lib/meta_note_filter.py)22 条
|
||||
// 正则常量的**逐字节**期望值(短名 ↔ 下划线常量映射同 patterns.go 头注释)。
|
||||
// 任何一条与 Python 现行源码不一致 ⇒ TestParity_PythonLive FAIL(漂移检测)。
|
||||
var expectedPySrc = map[string]string{
|
||||
"mem_id": `mem_[0-9]{8,}`,
|
||||
"t_id": `t_[0-9a-f]{6,10}`,
|
||||
"data_inv": `(库里\s*\d+\s*条|\d+\s*条\s*语料|语料可用|条可用|候选池内|\d+\s*候选|\d+\s*条.{0,12}可用)`,
|
||||
"pool": `(候选池|生产品池|产品池|进生产池|进生产品池)`,
|
||||
"pool_in": `进\s*池\s*\d+`,
|
||||
"ci_log": `(validate\.\w+|契约通过|预期告警|pytest|单元测试)`,
|
||||
"repro": `(MISS\s*复现|复现[::((]|复现\s*(步骤|方法|过程|流程|记录)\s*[::((])`,
|
||||
"rank": `(\bANN\s*排名|cos\s*排名|cos排名|ANN\s*排名|排名\s*\d+\s*→|排名\s*\d+→)`,
|
||||
"rank_num": `\bANN\s*\d+\s*→\s*\d+`,
|
||||
"num_arrow": `\d+\s*→\s*\d+`,
|
||||
"db_task": `数据表\s*t_`,
|
||||
"recall_count": `召回\s*[==]?\s*\d+\s*条`,
|
||||
"recall_act": `(发送一次\s*recall|只应发送一次|一次\s*recall)`,
|
||||
"write_bug": `(memory_[a-z]+\b|episod\w*\s*表|vector\s*全\s*0|向量\s*全\s*0|写入路径\s*待修)`,
|
||||
"eval_metric": `(golden\s*\d+\s*/\s*\d+|recall\s*@\s*\d+|\d+\s*/\s*\d+\s*不退化)`,
|
||||
"debug_mark": `(\bDEBUG\b|探针|自报|脚本输出)`,
|
||||
"svc_fam": `(织忆|zhiyi[d]|zhiyi|memoryweave|LanceDB)`,
|
||||
"svc_word": `(召回|蒸馏)`,
|
||||
"sys_cue": `(命名空间|限流|退避|重算|recompute|碎片化|全文搜索|记忆库|向量|embedding|\bcos\b|候选|记不住|FALLBACK|提前触发|\b兜底\b|脏读|巡检|实验日志|误召回|\bIPC\b|全表扫|排序路径|候选池)`,
|
||||
"diag": `(复现|实测|否决|修法|诊断|命中|淹没正解|告警|撒谎的尺子|验证召回|缺乏验证|短问法|长问法|宽泛问法|问法|真机制|真错误|混淆|只读|未改任何库|调参|门限)`,
|
||||
"fact_decl": `(接受\s*\w+\s*参数|监听\s*\d+\s*端口|每\s*\d+\s*(?:小时|分钟|天)\s*(?:刷新|更新|同步|执行)\s*一次|进程名是|地址是|模型是|字体|行距)`,
|
||||
}
|
||||
|
||||
// pyToGo:Python 源式 → Go 等价式的**唯一**变换规则(文档化映射,test 锁死):
|
||||
// 1. \w(Python Unicode word)→ [[:word:]\p{L}\p{N}]
|
||||
// 2. \b(Python Unicode 词边界,CJK 算 word)→ 剥离(改代码级边界校验,
|
||||
// 见 patterns.go bndPre/bndPostPrefix/bndExact 三表 + passBounds)
|
||||
func pyToGo(s string) string {
|
||||
s = strings.ReplaceAll(s, `\w`, "[[:word:]"+`\p{L}\p{N}`+"]")
|
||||
s = strings.ReplaceAll(s, `\b`, "")
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
// Package metanote —— meta-note 分类门禁(Go 侧,ZHIYI_META_FILTER=1 激活)。
|
||||
//
|
||||
// 判定逻辑逐步同序镜像 Python 口径真相源
|
||||
// ~/.hermes/scripts/lib/meta_note_filter.py(21 条强/弱信号正则 + 判定
|
||||
// 顺序 + 「事实形 vs 调查记录形」豁免)。该 Python 文件是口径唯一真相源
|
||||
// (AC2:判据已冻结,不许改判据迁就实现)。
|
||||
//
|
||||
// 本包只做分类 + 门控;不碰 7821、不写库。
|
||||
//
|
||||
// ── \b / \w 的 Go 等价映射(RE2 不支持 \b 词边界,须显式说明,测试锁死)──
|
||||
// 1. \w(Python 默认 Unicode) → [[:word:]\p{L}\p{N}]
|
||||
// ([[:word:]] 含 ASCII 字母/数字/下划线,\p{L}\p{N} 补 CJK 等 Unicode
|
||||
// 字母数字 —— 合计等价 Python 的 \w,边界字符判定另含 '_')
|
||||
// 2. \b(词边界)→ 正则中剥离,改**匹配值前缀**做代码级边界校验:
|
||||
// Python 里带 \b 的替代项若被同模式内的裸替代项**覆盖**(如 rank 的
|
||||
// \bANN\s*排名 被裸 ANN\s*排名 覆盖),则该 \b 无效 ⇒ 不校验;
|
||||
// 未被覆盖的按「匹配值以前缀 P 开头时」校验:
|
||||
// bndPrePre: 前一位不得是 word 字符
|
||||
// bndPostPre:后一位不得是 word 字符
|
||||
// bndBothPre:前后都不得是 word 字符
|
||||
// 三条映射 + 三张前缀表全部由 go/internal/metanote 的 parity/差分测试锁死
|
||||
// (Py 源式 → Go 等价式逐字节;实时 dump Python 常量比对;/tmp 副本异变
|
||||
// 必须让 parity FAIL;Go vs 真实 Python classify 全量差分)。
|
||||
|
||||
package metanote
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// W ≈ Python \w(Unicode):POSIX word(ASCII 字母/数字/下划线)+ Unicode
|
||||
// 字母/数字(CJK 在 Python 里是 word 字符,边界语义须一致)。
|
||||
const W = "[[:word:]"+`\p{L}\p{N}`+"]"
|
||||
|
||||
// goPats:21 条 Python 正则的 Go 等价式。
|
||||
// 短名 ↔ 下划线常量映射(Python 常量名见 parity 测试 expectedPySrc 注释):
|
||||
//
|
||||
// mem_id=mem_id, t_id=t_id, data_inv=data_inv, pool=pool, pool_in=pool_in,
|
||||
// ci_log=ci_log, repro=repro, rank=rank, rank_num=rank_num,
|
||||
// num_arrow=num_arrow, db_task=db_task, recall_count=recall_count,
|
||||
// recall_act=recall_act, write_bug=write_bug, eval_metric=eval_metric,
|
||||
// debug_mark=debug_mark, svc_fam=svc_fam, svc_word=svc_word,
|
||||
// sys_cue=sys_cue, diag=diag, fact_decl=fact_decl
|
||||
var goPats = map[string]string{
|
||||
"mem_id": `mem_[0-9]{8,}`,
|
||||
"t_id": `t_[0-9a-f]{6,10}`,
|
||||
"data_inv": `(库里\s*\d+\s*条|\d+\s*条\s*语料|语料可用|条可用|候选池内|\d+\s*候选|\d+\s*条.{0,12}可用)`,
|
||||
"pool": `(候选池|生产品池|产品池|进生产池|进生产品池)`,
|
||||
"pool_in": `进\s*池\s*\d+`,
|
||||
"ci_log": `(validate\.` + W + `+|契约通过|预期告警|pytest|单元测试)`,
|
||||
"repro": `(MISS\s*复现|复现[::((]|复现\s*(步骤|方法|过程|流程|记录)\s*[::((])`,
|
||||
"rank": `(ANN\s*排名|cos\s*排名|cos排名|ANN\s*排名|排名\s*\d+\s*→|排名\s*\d+→)`,
|
||||
"rank_num": `ANN\s*\d+\s*→\s*\d+`,
|
||||
"num_arrow": `\d+\s*→\s*\d+`,
|
||||
"db_task": `数据表\s*t_`,
|
||||
"recall_count": `召回\s*[==]?\s*\d+\s*条`,
|
||||
"recall_act": `(发送一次\s*recall|只应发送一次|一次\s*recall)`,
|
||||
"write_bug": `(memory_[a-z]+|episod` + W + `*\s*表|vector\s*全\s*0|向量\s*全\s*0|写入路径\s*待修)`,
|
||||
"eval_metric": `(golden\s*\d+\s*/\s*\d+|recall\s*@\s*\d+|\d+\s*/\s*\d+\s*不退化)`,
|
||||
"debug_mark": `(DEBUG|探针|自报|脚本输出)`,
|
||||
"svc_fam": `(织忆|zhiyi[d]|zhiyi|memoryweave|LanceDB)`,
|
||||
"svc_word": `(召回|蒸馏)`,
|
||||
"sys_cue": `(命名空间|限流|退避|重算|recompute|碎片化|全文搜索|记忆库|向量|embedding|cos|候选|记不住|FALLBACK|提前触发|兜底|脏读|巡检|实验日志|误召回|IPC|全表扫|排序路径|候选池)`,
|
||||
"diag": `(复现|实测|否决|修法|诊断|命中|淹没正解|告警|撒谎的尺子|验证召回|缺乏验证|短问法|长问法|宽泛问法|问法|真机制|真错误|混淆|只读|未改任何库|调参|门限)`,
|
||||
"fact_decl": `(接受\s*` + W + `+\s*参数|监听\s*\d+\s*端口|每\s*\d+\s*(?:小时|分钟|天)\s*(?:刷新|更新|同步|执行)\s*一次|进程名是|地址是|模型是|字体|行距)`,
|
||||
}
|
||||
|
||||
var compiled = map[string]*regexp.Regexp{}
|
||||
|
||||
func init() {
|
||||
for name, pat := range goPats {
|
||||
compiled[name] = regexp.MustCompile(pat)
|
||||
}
|
||||
}
|
||||
|
||||
// ── \b 映射的边界校验表(仅列「未被裸替代项覆盖」的 \b;推导见包注释)──
|
||||
//
|
||||
// Python 源中带 \b 的替代项逐一核对:
|
||||
// rank: \bANN\s*排名 被同模式裸替代 ANN\s*排名 覆盖 ⇒ 无效,不校验
|
||||
// rank_num: \bANN\s*→… 无裸替代覆盖 ⇒ 值前缀 ANN 需前界
|
||||
// eval_metric: \brecall\s*@ 无裸替代覆盖(golden/不退化 两替代是独立前缀)
|
||||
// ⇒ 值前缀 golden|recall 需前界
|
||||
// write_bug: memory_[a-z]+\b(尾界)⇒ 值前缀 memory_ 需后界;
|
||||
// episod/vector/向量/写入路径 各替代**无** \b ⇒ 不校验
|
||||
// sys_cue: \bcos\b(双侧)⇒ 值前缀 cos 需前后界;
|
||||
// \b兜底\b(双侧)⇒ 兜底 需前后界;
|
||||
// \bIPC\b(双侧)⇒ IPC 需前后界;
|
||||
// \bANN 仅出现在 rank(已证无效);sys_cue 内无 ANN 替代
|
||||
var bndPrePre = map[string]map[string]bool{ // 值前缀 P ⇒ 前一位不得是 word
|
||||
"eval_metric": {"golden": true, "recall": true},
|
||||
"rank_num": {"ANN": true},
|
||||
}
|
||||
var bndPostPre = map[string]map[string]bool{ // 值前缀 P ⇒ 后一位不得是 word
|
||||
"write_bug": {"memory_": true},
|
||||
}
|
||||
var bndBothPre = map[string]map[string]bool{ // 值前缀 P ⇒ 前后都不得是 word
|
||||
"sys_cue": {"cos": true, "兜底": true, "IPC": true},
|
||||
}
|
||||
|
||||
// isWordRune:Python \w 的字符类(Unicode 字母/数字 + 下划线)。
|
||||
func isWordRune(r rune) bool {
|
||||
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
|
||||
}
|
||||
|
||||
// isWordBefore / isWordAfter:位置 i 前/后第一个字符是否 word。
|
||||
func isWordBefore(s string, i int) bool {
|
||||
if i <= 0 {
|
||||
return false
|
||||
}
|
||||
r, _ := utf8.DecodeLastRuneInString(s[:i])
|
||||
return isWordRune(r)
|
||||
}
|
||||
|
||||
func isWordAfter(s string, i int) bool {
|
||||
if i >= len(s) {
|
||||
return false
|
||||
}
|
||||
r, _ := utf8.DecodeRuneInString(s[i:])
|
||||
return isWordRune(r)
|
||||
}
|
||||
|
||||
// passBounds:name 的某个匹配(值 val,区间 [gs,ge))是否通过 \b 等价边界
|
||||
// 校验。无该 name 的边界条目 ⇒ 恒真(与 Python 该模式无 \b 等价)。
|
||||
func passBounds(name, s, val string, gs, ge int) bool {
|
||||
pre := bndPrePre[name]
|
||||
post := bndPostPre[name]
|
||||
both := bndBothPre[name]
|
||||
if pre == nil && post == nil && both == nil {
|
||||
return true
|
||||
}
|
||||
hitPre, hitPost := false, false
|
||||
for p := range pre {
|
||||
if strings.HasPrefix(val, p) {
|
||||
hitPre = true
|
||||
break
|
||||
}
|
||||
}
|
||||
for p := range post {
|
||||
if strings.HasPrefix(val, p) {
|
||||
hitPost = true
|
||||
break
|
||||
}
|
||||
}
|
||||
for p := range both {
|
||||
if strings.HasPrefix(val, p) {
|
||||
hitPre, hitPost = true, true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hitPre && isWordBefore(s, gs) {
|
||||
return false
|
||||
}
|
||||
if hitPost && isWordAfter(s, ge) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// anyMatch:name 在 s 中是否存在**至少一个**通过边界校验的匹配(等价 Python
|
||||
// re.search(pattern, s) 在「\b 已按上表剥离 + 前缀校验」后的语义)。
|
||||
func anyMatch(name, s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
re := compiled[name]
|
||||
if re == nil {
|
||||
return false
|
||||
}
|
||||
idxs := re.FindAllStringIndex(s, -1)
|
||||
if len(idxs) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, p := range idxs {
|
||||
if passBounds(name, s, s[p[0]:p[1]], p[0], p[1]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// distinctVals:name 在 s 中的**去重**匹配值集合(等价 Python re.findall +
|
||||
// set(),同样带边界校验)。用于 CUE/DIAG 的「distinct 数值」计数。
|
||||
func distinctVals(name, s string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
if s == "" {
|
||||
return out
|
||||
}
|
||||
re := compiled[name]
|
||||
if re == nil {
|
||||
return out
|
||||
}
|
||||
for _, p := range re.FindAllStringIndex(s, -1) {
|
||||
val := s[p[0]:p[1]]
|
||||
if passBounds(name, s, val, p[0], p[1]) {
|
||||
out[val] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user