@furongjun1999/dsh-memory 0.9.18 → 0.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ # -*- coding: utf-8 -*-
2
+ """宪章第十五条(复读污染)的实现:注入过滤 + history 去重 + 污染清除。
3
+
4
+ ## 为什么需要它
5
+
6
+ `docs/mdcg/guardrail-charter.md` 第十五条写:「幻觉锚点/失败复读自我强化——
7
+ 注入过滤 + history 去重 + 污染清除。」但**此前只有条文、没有实现**
8
+ (`src/` 与 `md_cg/` 搜「复读/degenerat/repetition」零命中)。
9
+
10
+ ## 关键取舍:**检测不等于删除**
11
+
12
+ 用户可能真的把同一句话说了两遍(实测库里就有一条 `role=user` 的消息重复 7 次,
13
+ 那是真发的,不是模型复读)。所以本模块**只做三件事,不做静默删除**:
14
+
15
+ 1. **检测**(`scan`):按 `(role, sha1(text))` 在**同一会话窗口内**计数;
16
+ 2. **标注**(`annotate`):给命中项打上 `repeat={count,suffix,first_t}`,供注入面渲染;
17
+ 3. **清理**(`dedupe`):**只保留最新一条 + 其余折叠为计数**,且**仅当调用方显式要求**
18
+ ——库内原文一个字都不动(与 `thinking-guard` 的「改注入副本、不改日志」同原则)。
19
+
20
+ ## 判据(阈值来源)
21
+
22
+ 仿 `dsh-degeneration-kit` 的 `rotationHit` 双阈值思路,但用于**事件窗口**而非思考块:
23
+
24
+ | 配置 | 默认 | 含义 |
25
+ |---|---|---|
26
+ | `minCount` | 3 | 同一 `(role, hash)` 至少出现这么多次才算「复读」 |
27
+ | `minChars` | 12 | 文本短于此长度不判(太短的话重复是正常的,如「好」「继续」) |
28
+ | `window` | 200 | 只看窗口内(与 `DEFAULT_RECENT_WINDOW` 同口径) |
29
+
30
+ ⚠️ `minChars=12` 这条是**从实测反推**的:实测库里 `x7` 那条长文本是真重复,
31
+ 而「好」「继续」这类短指令重复属正常对话,不该被判成污染。
32
+
33
+ ## 与智能论《扮演崩溃治理》的关系
34
+
35
+ 智能论 3.4 附录22.1:**「状态丢失(数不出搜索次数)= 扮演崩溃 → 状态外部化治之」**。
36
+ 本节做的是**事后**(`history 去重`),扮演崩溃的**事前**防线是「状态外置」
37
+ (把步骤清单/计数器写进任务消息,模型零判断)——两者互补,不是替代。
38
+ """
39
+
40
+ import hashlib
41
+
42
+ # 生效条件:恒返回 8 位十六进制(sha1(text) 前 8 位)——**纯确定性**,同一 text 恒得同一串;
43
+ # 用作「同一条事件」的判据,不参与任何权限判定。
44
+ def text_suffix(text) -> str:
45
+ return hashlib.sha1((text or "").encode("utf-8", "replace")).hexdigest()[:8]
46
+
47
+
48
+ # 生效条件:events 为可迭代的事件 dict 列表、min_count>=1、min_chars>=0 时,
49
+ # 按 (role, text_suffix(text)) 计数并返回命中项列表(按 count 降序);
50
+ # 文本长度 < min_chars 的条目不参与;非 dict 条目跳过(与 recent_record_ok 同款容错)。
51
+ def scan(events, min_count: int = 3, min_chars: int = 12):
52
+ """检测事件窗口内的重复(复读候选)。**只读,不修改入参**。"""
53
+ try:
54
+ lo = max(1, int(min_count))
55
+ lc = max(0, int(min_chars))
56
+ except (TypeError, ValueError):
57
+ lo, lc = 3, 12
58
+ buckets = {}
59
+ for ev in (events or ()):
60
+ if not isinstance(ev, dict):
61
+ continue
62
+ text = ev.get("text") or ""
63
+ if not isinstance(text, str) or len(text) < lc:
64
+ continue
65
+ key = (ev.get("role") or "user", text_suffix(text))
66
+ b = buckets.setdefault(key, {"count": 0, "suffix": key[1], "role": key[0],
67
+ "text": text[:200], "first_t": ev.get("t"),
68
+ "seqs": []})
69
+ b["count"] += 1
70
+ b["first_t"] = ev.get("t")
71
+ hits = [b for b in buckets.values() if b["count"] >= lo]
72
+ hits.sort(key=lambda b: -b["count"])
73
+ return hits
74
+
75
+
76
+ # 生效条件:scan 返回的命中列表非空时,为 events 中命中项**加** repeat 标注(返回新列表,
77
+ # 原 dict 不被修改——与「只改注入副本、库内正文保真」一致);未命中项原样透传。
78
+ def annotate(events, min_count: int = 3, min_chars: int = 12):
79
+ """给命中项加 `repeat={count, suffix}`。**返回新列表,不改原 dict**。"""
80
+ hits = scan(events, min_count=min_count, min_chars=min_chars)
81
+ if not hits:
82
+ return list(events or ())
83
+ by_key = {(b["role"], b["suffix"]): b for b in hits}
84
+ out = []
85
+ for ev in (events or ()):
86
+ if not isinstance(ev, dict):
87
+ out.append(ev)
88
+ continue
89
+ text = ev.get("text") or ""
90
+ h = by_key.get((ev.get("role") or "user", text_suffix(text))) if isinstance(text, str) else None
91
+ out.append(dict(ev, repeat={"count": h["count"], "suffix": h["suffix"]}) if h else ev)
92
+ return out
93
+
94
+
95
+ # 生效条件:events 非空且 dense=True 时,同一 (role, suffix) 只保留**最新一条**、
96
+ # 其余折叠为 `repeat:{count}` 标注(条目数减少,但每条都还在);dense=False 时等价于 annotate。
97
+ # **只作用于返回副本**:盘面 `_recent.jsonl` 不被读写。
98
+ def dedupe(events, min_count: int = 3, min_chars: int = 12):
99
+ """history 去重(注入面用):同一复读只留最新一条,其余合并为计数。**不写盘**。"""
100
+ rows = list(events or ())
101
+ hits = scan(rows, min_count=min_count, min_chars=min_chars)
102
+ if not hits:
103
+ return rows
104
+ by_key = {(b["role"], b["suffix"]): b for b in hits}
105
+ seen = set()
106
+ out = []
107
+ for ev in reversed(rows):
108
+ if not isinstance(ev, dict):
109
+ out.append(ev)
110
+ continue
111
+ text = ev.get("text") or ""
112
+ key = (ev.get("role") or "user", text_suffix(text)) if isinstance(text, str) else None
113
+ h = by_key.get(key) if key else None
114
+ if not h:
115
+ out.append(ev)
116
+ continue
117
+ if key in seen:
118
+ continue
119
+ seen.add(key)
120
+ out.append(dict(ev, repeat={"count": h["count"], "suffix": h["suffix"], "collapsed": True}))
121
+ out.reverse()
122
+ return out
@@ -0,0 +1,85 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:写入别名(aliases)是否是「薄别名」的守卫(issue #722 / 规范 v0.6)
3
+ # 生效条件:python -X utf8 -m md_cg.test_722_aliases_thin;被测面=md_cg/writegate.py 的 aliases_is_thin
4
+ # 子功能:
5
+ # A. 无 aliases(缺失/空 list/非 list)⇒ 判为薄
6
+ # B. 别名全在正文里(只重复已有词)⇒ 判为薄
7
+ # C. 只要有一个别名在正文里找不到(有扩召回首)⇒ 判为不薄
8
+ # D. 不判数量(3 个精准别名不因"少"被判薄)
9
+ # E. 任何输入不抛
10
+ # 执行:纯函数级断言,不建库、不写盘
11
+ # 验证方式:全部 PASS exit 0;每条注明「怎么让它红」
12
+ # 不适用条件:不判"别名写得好不好"(判不了语义);不覆盖写入接线(尚未接 add)
13
+ """为什么要它:
14
+
15
+ issue #722 的决定性案例——条件 `聊交接、换会话、压缩、或他流露舍不得时`,
16
+ 查询 `我不想你被换掉`:整词 / 二元组 / 查询扩展 / 现有同义词表**四条路全废**,
17
+ 只有 `aliases=[换掉, 被换, 别消失, 舍不得, …]` 能让 `_like` 从不命中变命中。
18
+
19
+ 而库内 aliases 覆盖率为 **0/120 = 0%**(2026-10-31 实测)⇒ 需要一道写入把关,
20
+ 提示"本条无扩展别名,自然问法可能召不回"。本守卫只锁判据本身。
21
+ """
22
+ import os
23
+ import sys
24
+
25
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.insert(0, ROOT)
27
+
28
+ from md_cg.writegate import aliases_is_thin # noqa: E402
29
+
30
+ _PASS, _FAIL = [], []
31
+
32
+
33
+ def ok(cond, msg, detail=""):
34
+ (_PASS if cond else _FAIL).append(msg)
35
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
36
+
37
+
38
+ BODY = "聊交接、换会话、压缩、或他流露舍不得时。正文里提到 换会话 和 压缩。"
39
+
40
+
41
+ def main():
42
+ print("== A 无 aliases(怎么让它红:把首个 return 改成 False)")
43
+ ok(aliases_is_thin({}, BODY) is True, "A1 缺 aliases ⇒ 薄")
44
+ ok(aliases_is_thin({"aliases": []}, BODY) is True, "A2 空 list ⇒ 薄")
45
+ ok(aliases_is_thin({"aliases": "换掉"}, BODY) is True, "A3 非 list ⇒ 薄(按缺处理)")
46
+ ok(aliases_is_thin(None, BODY) is True, "A4 fm 为 None ⇒ 薄")
47
+
48
+ print("== B 只重复正文(怎么让它红:把 s not in body 改成 s in body)")
49
+ ok(aliases_is_thin({"aliases": ["换会话", "压缩"]}, BODY) is True,
50
+ "B1 别名全在正文里 ⇒ 薄(没扩召回首)")
51
+
52
+ print("== C 有扩召回词(怎么让它红:把 C1 的 return 改成 True)")
53
+ ok(aliases_is_thin({"aliases": ["换会话", "换掉"]}, BODY) is False,
54
+ "C1 只要一个别名不在正文(换掉)⇒ 不薄")
55
+ ok(aliases_is_thin({"aliases": ["别消失"]}, BODY) is False,
56
+ "C2 单个扩展词也判不薄(不判数量)")
57
+
58
+ print("== D 不判数量(怎么让它红:加数量下限判断)")
59
+ ok(aliases_is_thin({"aliases": ["换掉"]}, BODY) is False,
60
+ "D1 1 个精准扩展词就够,不因\"少\"被判薄")
61
+
62
+ print("== E 不抛(怎么让它红:去掉 try/except 后传异常对象)")
63
+ ok(aliases_is_thin({"aliases": [None, ""]}, BODY) is True,
64
+ "E1 别名里含 None/空串 ⇒ 跳过,仍判薄")
65
+ try:
66
+ aliases_is_thin({"aliases": [{"a": 1}]}, BODY)
67
+ ok(True, "E2 别名含 dict 不抛")
68
+ except Exception as e: # noqa: BLE001
69
+ ok(False, "E2 别名含 dict 不抛", "%s: %s" % (type(e).__name__, e))
70
+ try:
71
+ aliases_is_thin({"aliases": ["换掉"]}, None)
72
+ ok(True, "E3 content 为 None 不抛")
73
+ except Exception as e: # noqa: BLE001
74
+ ok(False, "E3 content 为 None 不抛", "%s: %s" % (type(e).__name__, e))
75
+
76
+ print()
77
+ print("别名薄判据守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
78
+ if _FAIL:
79
+ for f in _FAIL:
80
+ print(" -", f)
81
+ return 0 if not _FAIL else 1
82
+
83
+
84
+ if __name__ == "__main__":
85
+ raise SystemExit(main())
@@ -0,0 +1,83 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:生效条件质量判据守卫(issue #722 / 规范 v0.5)
3
+ # 生效条件:python -X utf8 -m md_cg.test_722_condition_quality;被测面=md_cg/writegate.py 的 cond_is_metadata / check_condition_quality
4
+ # 子功能:
5
+ # A. `cond_is_metadata`:四槽合成形态(载体/位置+约束/方法)判为元数据;
6
+ # 真实的触发场景(「当他说…时」)**不**误判;混合条件也不误判
7
+ # B. `check_condition_quality`:把 A 包装成写入把关结果(ok/is_metadata/hint),**任何情况下不抛**
8
+ # C. 两处反例:无生效条件行、空内容 → ok=True(无条件是另一类问题)
9
+ # 执行:纯函数级断言,不建库、不写盘
10
+ # 验证方式:全部 PASS exit 0;每条注明「怎么让它红」
11
+ # 不适用条件:不测「库内元数据占比」(那需要读真实库,属实测脚本而非守卫);不测接线(`add` 尚未接)
12
+ """为什么要这个守卫:
13
+
14
+ 实测(2026-10-31,全库 32842 抽样 120)发现 **76.5% 的生效条件是元数据**——
15
+ 形如 `载体/位置:本地文档仓(大域=xxx);时间:全时窗;方法:md…;约束:源文档 a/b.md`,
16
+ 而**0 条**是「用户会怎么说」。这类条件在检索时几乎不可能被自然问法命中(#722 现象)。
17
+
18
+ 判据经**四次修正**才定稿(详见规范 v0.5 第八节):
19
+ ① 正向「所有词项都含元数据特征」→ 路径片段(knowledge / x.md)使 all() 恒 False;
20
+ ② 加短词表 → 仍 0 条;
21
+ ③ 反向「不含场景标志词」→ 单字「时」被「全时窗」误触发;
22
+ ④ **结构化槽标签**(本守卫固化)→ 5/5 用例 + 实测 76.5%。
23
+ """
24
+ import os
25
+ import sys
26
+
27
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28
+ sys.path.insert(0, ROOT)
29
+
30
+ from md_cg.writegate import check_condition_quality, cond_is_metadata # noqa: E402
31
+
32
+ _PASS, _FAIL = [], []
33
+
34
+
35
+ def ok(cond, msg, detail=""):
36
+ (_PASS if cond else _FAIL).append(msg)
37
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
38
+
39
+
40
+ META = ("载体/位置:本地文档仓(大域=whitebox_kb);时间:全时窗(任意时刻成立);"
41
+ "方法:md(md 章节切分,level≤3;只存标题+摘要,正文留在源文件);"
42
+ "约束:源文档 whitebox_kb/knowledge/x.md")
43
+ SCENE = '当他说"不想你被换掉""别消失""舍不得"时'
44
+ MIXED = '载体/位置:本地文档仓;当用户说"继续"时'
45
+
46
+
47
+ def main():
48
+ print("== A cond_is_metadata(怎么让它红:删掉槽标签判据 → A1 红;改成含场景词判 → A3 红)")
49
+ ok(cond_is_metadata(META) is True,
50
+ "A1 四槽合成形态(载体/位置 + 约束)判为元数据", cond_is_metadata(META))
51
+ ok(cond_is_metadata(SCENE) is False,
52
+ "A2 #722 报告人改写的触发场景**不**误判为元数据", cond_is_metadata(SCENE))
53
+ ok(cond_is_metadata(MIXED) is False,
54
+ "A3 混合条件(有载体标签 + 有真实场景)**不**误判(不误伤)", cond_is_metadata(MIXED))
55
+ ok(cond_is_metadata("") is False, "A4 空条件不算元数据(无条件是另一类问题)")
56
+
57
+ print("== B check_condition_quality(怎么让它红:把 ok 写成恒 True → B1 红)")
58
+ r = check_condition_quality("# 功能名:x\n# 生效条件:" + META)
59
+ ok(r["ok"] is False and r["is_metadata"] is True and r["hint"],
60
+ "B1 元数据条件 → ok=False 且带提示", r)
61
+ r2 = check_condition_quality("# 功能名:x\n# 生效条件:" + SCENE)
62
+ ok(r2["ok"] is True and r2["is_metadata"] is False,
63
+ "B2 真实场景条件 → ok=True", r2)
64
+
65
+ print("== C 不阻断(怎么让它红:去掉 try/except 后传非字符串 → C2 红)")
66
+ r3 = check_condition_quality("# 功能名:x")
67
+ ok(r3["ok"] is True, "C1 无生效条件行 → ok=True(不阻断)", r3)
68
+ try:
69
+ r4 = check_condition_quality(None)
70
+ ok(r4["ok"] is True, "C2 传 None 不抛、且 ok=True", r4)
71
+ except Exception as e: # noqa: BLE001
72
+ ok(False, "C2 传 None 不抛、且 ok=True", "%s: %s" % (type(e).__name__, e))
73
+
74
+ print()
75
+ print("生效条件质量守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
76
+ if _FAIL:
77
+ for f in _FAIL:
78
+ print(" -", f)
79
+ return 0 if not _FAIL else 1
80
+
81
+
82
+ if __name__ == "__main__":
83
+ raise SystemExit(main())
@@ -0,0 +1,80 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:前端 permissionNote 与服务端 _in_scope 的通配符判据一致性守卫(issue #723)
3
+ # 生效条件:python -X utf8 -m md_cg.test_723_permission_wildcard;被测面=ui/minimal/payload/web/app.js 与 md_cg/security.py
4
+ # 子功能:
5
+ # A. 服务端 `_in_scope` 认通配符 `*`(`"*" in allow or name in allow`)——这是**权威口径**
6
+ # B. 前端 `permissionNote` 必须同样认 `*`(否则全权令牌 12/12 全部误报「未声明权限」)
7
+ # C. 跨侧一致:两侧都必须处理 `*`,缺任一侧即红
8
+ # 执行:纯文本/源码断言,不建库、不写盘
9
+ # 验证方式:全部 PASS exit 0;每条注明「怎么让它红」
10
+ # 不适用条件:**不做浏览器端运行验证**(只断言源码口径);不覆盖 `web/app.js`(那是构建产物,gitignore 排除,由源生成)
11
+ """issue #723 的守卫。
12
+
13
+ 用户报告:全权令牌(`ops_allow: ["*"]`)下,前端 12/12 预设全部误报「未声明 xx 权限」,
14
+ 而服务端裁定照常放行——**同一份数据两侧判据不同口径**。
15
+
16
+ 根因:服务端 `_in_scope` 写的是 `"*" in allow or name in allow`(认通配符),
17
+ 前端 `permissionNote` 写的是 `allowed.includes(op)`(不认通配符)。
18
+
19
+ 本守卫防的是「一侧改了、另一侧没跟上」——**跨侧口径一致性**,与 `test_rust_fold_parity` 同族。
20
+ """
21
+ import os
22
+ import re
23
+ import sys
24
+
25
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+
27
+ _PASS, _FAIL = [], []
28
+
29
+
30
+ def ok(cond, msg, detail=""):
31
+ (_PASS if cond else _FAIL).append(msg)
32
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
33
+
34
+
35
+ def _read(rel):
36
+ p = os.path.join(ROOT, rel.replace("/", os.sep))
37
+ with open(p, encoding="utf-8") as f:
38
+ return f.read()
39
+
40
+
41
+ def main():
42
+ print("== A 服务端:_in_scope 认通配符(权威口径)")
43
+ sec = _read("md_cg/security.py")
44
+ ok('"*" in allow' in sec,
45
+ "A1 security.py 的 _in_scope 含 `\"*\" in allow`(权威口径认通配符)",
46
+ "未找到该判据")
47
+
48
+ print("== B 前端:permissionNote 必须同样认通配符")
49
+ js = _read("ui/minimal/payload/web/app.js")
50
+ m = re.search(r"function\s+permissionNote\s*\(op\)\s*\{(.*?)\n\s*\}", js, re.S)
51
+ ok(m is not None, "B1 能在 app.js 里定位到 permissionNote 函数体")
52
+ body = m.group(1) if m else ""
53
+ ok("'*'" in body or '"*"' in body,
54
+ "B2 permissionNote 函数体里出现通配符 `*` 的判断(怎么让它红:删掉 `includes('*')` 这一支)",
55
+ body[:160])
56
+ ok("includes(" in body and "op" in body,
57
+ "B3 仍保留 `includes(op)` 的具体操作判定(通配符不是替代,是补充)",
58
+ body[:160])
59
+
60
+ print("== C 跨侧一致:两侧都必须处理 *")
61
+ ok(("*" in sec) and (("*" in body) if body else False),
62
+ "C1 服务端与前端**同时**认通配符(任一侧缺失即红)",
63
+ {"server": '"*" in allow' in sec, "frontend": "'*'" in body if body else False})
64
+
65
+ print("== D 反例:不认通配符的旧写法必须被判红")
66
+ legacy = "return allowed && !allowed.includes(op) ?"
67
+ ok(legacy not in js,
68
+ "D1 app.js 里已不存在旧写法 `!allowed.includes(op)`(怎么让它红:改回旧写法)",
69
+ "仍存在旧写法")
70
+
71
+ print()
72
+ print("issue #723 守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
73
+ if _FAIL:
74
+ for f in _FAIL:
75
+ print(" -", f)
76
+ return 0 if not _FAIL else 1
77
+
78
+
79
+ if __name__ == "__main__":
80
+ raise SystemExit(main())
@@ -0,0 +1,92 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:命名别名(aliases)守卫——别名可召回、且不污染身份/锚点判据
3
+ # 生效条件:python -X utf8 -m md_cg.test_aliases_r2r3;被测面=md_cg/mdcg.py 的 _like/_canonical_state 与 tasks/predict 的 tags 判据
4
+ # 子功能:
5
+ # A. 别名参与词法召回(R2 的「检索能命中」)——只改 aliases、不改正文,用别名查询应命中
6
+ # B. aliases 不在 anchor 的 STATE_FIELDS 里 ⇒ 加别名不改变锚定状态摘要(R3 的 anchor 面)
7
+ # C. tasks 的「是不是任务卡」只读 tags ⇒ 加别名不翻转(R3 的 tasks 面)
8
+ # D. predict 的 ANCHOR_SKIP_TAGS 只读 tags ⇒ 加别名不触发跳过(R3 的 predict 面)
9
+ # 执行:纯函数级断言,不建库、不写盘
10
+ # 验证方式:全部 PASS exit 0;每条都注明「怎么让它红」
11
+ # 不适用条件:不覆盖语义检索(本守卫只测词法面);不覆盖 aliases 的写入/索引面(那是工程文档的活)
12
+ """为什么需要它(issue:命名与检索规范 R2/R3 的可验证载体)
13
+
14
+ 规范此前写「别名落 aliases、只参与召回不参与判据」,但 aliases 字段根本不存在 ⇒
15
+ 那条「加别名后三个判据结果不变」的验证是**恒真空断言**(没有可加的东西)。
16
+ 本守卫的三组 B/C/D 就是为了让那句话**能红**:只要有人把 aliases 塞进 tags、
17
+ 或把 aliases 加进 STATE_FIELDS / ANCHOR_SKIP_TAGS,本守卫立刻红。
18
+ """
19
+ import os
20
+ import sys
21
+
22
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
+ sys.path.insert(0, ROOT)
24
+
25
+ from md_cg.mdcg import MdCG # noqa: E402
26
+
27
+ _PASS, _FAIL = [], []
28
+
29
+
30
+ def ok(cond, msg, detail=""):
31
+ (_PASS if cond else _FAIL).append(msg)
32
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
33
+
34
+
35
+ def main():
36
+ like = MdCG._like
37
+
38
+ print("== A 别名参与词法召回(怎么让它红:从 _like 里去掉 aliases 拼接)")
39
+ fm_base = {"tags": ["记忆"], "layer": "knowledge"}
40
+ body = "这是一段完全无关的正文内容"
41
+ ok(not like(body, fm_base, ["旁白"]), "A0 基线:无 aliases 时别名查不到(证明下面 A1 不是恒真)")
42
+ fm_alias = {"tags": ["记忆"], "layer": "knowledge", "aliases": ["旁白"]}
43
+ ok(like(body, fm_alias, ["旁白"]), "A1 加了 aliases 后,用别名「旁白」能命中", "未命中")
44
+ ok(like(body, fm_alias, ["记忆"]), "A2 原 tags 仍然命中(别名不挤掉原标签)")
45
+ ok(not like(body, {"tags": [], "aliases": ["旁白"]}, ["无关词"]),
46
+ "A3 别名不等于万能命中(不相关词仍不命中)")
47
+
48
+ print("== A4 脏数据容错(怎么让它红:去掉 isinstance 判断后传字符串)")
49
+ try:
50
+ like(body, {"tags": [], "aliases": "旁白"}, ["旁白"])
51
+ ok(True, "A4 aliases 为字符串时不抛异常(按空处理,不误命中)")
52
+ except Exception as e: # noqa: BLE001
53
+ ok(False, "A4 aliases 为字符串时不抛异常", "%s: %s" % (type(e).__name__, e))
54
+
55
+ print("== B aliases 不进锚定状态摘要(怎么让它红:把 aliases 加进 STATE_FIELDS)")
56
+ from md_cg import anchor as _anchor
57
+ ok("aliases" not in _anchor.STATE_FIELDS,
58
+ "B1 STATE_FIELDS 不含 aliases(含了 → 每次改别名都会让全部在册回执失效)",
59
+ _anchor.STATE_FIELDS)
60
+ fm1 = {"layer": "knowledge", "tags": ["a"], "condition_space": {}}
61
+ fm2 = dict(fm1, aliases=["别名甲", "别名乙"])
62
+ ok(_anchor._canonical_state(fm1) == _anchor._canonical_state(fm2),
63
+ "B2 加 aliases 后 state_digest 的原料完全相同(锚定不受影响)")
64
+
65
+ print("== C 任务卡判据只读 tags(怎么让它红:把 aliases 并进 tags 或并进判据)")
66
+ from md_cg import tasks as _tasks
67
+ ok("aliases" not in getattr(_tasks, "TASK_TAG", ""),
68
+ "C1 TASK_TAG 仍是\"task\",没被改名成别名机制", getattr(_tasks, "TASK_TAG", None))
69
+ src = open(os.path.join(ROOT, "md_cg", "tasks.py"), encoding="utf-8").read()
70
+ ok("aliases" not in src,
71
+ "C2 tasks.py 全文不出现 aliases(任务卡判据不看别名)",
72
+ [l for l in src.splitlines() if "aliases" in l][:2])
73
+
74
+ print("== D 预测锚点判据只读 tags(怎么让它红:把 aliases 并进 ANCHOR_SKIP_TAGS 的读取处)")
75
+ from md_cg import predict as _predict
76
+ ok(tuple(_predict.ANCHOR_SKIP_TAGS) == ("gap_hint", "scene"),
77
+ "D1 ANCHOR_SKIP_TAGS 未被扩成含别名机制", _predict.ANCHOR_SKIP_TAGS)
78
+ psrc = open(os.path.join(ROOT, "md_cg", "predict.py"), encoding="utf-8").read()
79
+ ok("aliases" not in psrc,
80
+ "D2 predict.py 全文不出现 aliases(能不能当锚点不看别名)",
81
+ [l for l in psrc.splitlines() if "aliases" in l][:2])
82
+
83
+ print()
84
+ print("别名守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
85
+ if _FAIL:
86
+ for f in _FAIL:
87
+ print(" -", f)
88
+ return 0 if not _FAIL else 1
89
+
90
+
91
+ if __name__ == "__main__":
92
+ raise SystemExit(main())
@@ -572,11 +572,11 @@ def guard_dangling(tmp: str, sroot: str) -> None:
572
572
  ck("4f[删转写] 指路离线再生(服务态不写临时目录)",
573
573
  "repair" in (rd.get("rematerialize") or ""), rd.get("rematerialize"))
574
574
  # regenerable 免清退:dry_run 里不出现,且实做后节点仍在
575
- pl = refindex.prune_dangling(cg, dry_run=True, max_nodes=5000)
575
+ pl = refindex.prune_dangling(cg, dry_run=True, max_nodes=20000)
576
576
  ck("4g[regenerable 免清退] dry_run 候选为空且计数透出",
577
577
  pl.get("candidates") == 0 and pl.get("regenerable_skipped", 0) >= len(ns),
578
578
  (pl.get("candidates"), pl.get("regenerable_skipped"), len(ns)))
579
- refindex.prune_dangling(cg, max_nodes=5000)
579
+ refindex.prune_dangling(cg, max_nodes=20000)
580
580
  ck("4h[regenerable 免清退] 实做后节点仍在库",
581
581
  cg.get(nid) is not None and cg.get(nid) is not None)
582
582
  # 反向对照:非 regenerable 的悬空 doc 节点**必须**被列入
@@ -587,7 +587,7 @@ def guard_dangling(tmp: str, sroot: str) -> None:
587
587
  refindex.add_items(cg, [fake], kind="doc_ref",
588
588
  root=os.path.join(tmp, "g4", "nope"))
589
589
  fid = docindex.node_id(fake)
590
- pl2 = refindex.prune_dangling(cg, dry_run=True, max_nodes=5000)
590
+ pl2 = refindex.prune_dangling(cg, dry_run=True, max_nodes=20000)
591
591
  ck("4i[反向对照] 非 regenerable 的悬空节点被列入(判据有判别力)",
592
592
  fid in (pl2.get("pruned") or []) or pl2.get("candidates", 0) >= 1,
593
593
  (pl2.get("candidates"), (pl2.get("pruned") or [])[:3]))
@@ -625,7 +625,7 @@ def guard_regenerable_after_rebuild(tmp: str, sroot: str) -> None:
625
625
  for e in after.values()), sorted(after))
626
626
  # 删转写 → 全部 dangling:但「可再生」必须仍生效(第二判据靠 doc_ref.src)
627
627
  os.remove(tr_path(tr, "ws-a", "sess-1"))
628
- pl = refindex.prune_dangling(cg, dry_run=True, max_nodes=5000)
628
+ pl = refindex.prune_dangling(cg, dry_run=True, max_nodes=20000)
629
629
  ck("4s[heal 后] 无 regenerable 标签仍免清退(判据不依赖标签存活)",
630
630
  pl.get("candidates") == 0 and pl.get("regenerable_skipped", 0) >= len(after),
631
631
  (pl.get("candidates"), pl.get("regenerable_skipped"), len(after)))
@@ -408,6 +408,17 @@ from md_cg import mcp_server # noqa
408
408
  from md_cg.mdcos import MdCGOS # noqa: E402
409
409
 
410
410
  ENV = am.AUTONOMY_ENV_KEYS["mode"]
411
+
412
+ # fix(full_D 跨分钟时间泄漏,2026-10-31):`aggregate_line` 默认把**墙钟分钟**写进
413
+ # 聚合行(`- 【聚合 MM-DD HH:MM】…`)。`full_B` 比正文 ⇒ `_AGG_RE.sub("【聚合 <ts>】")`
414
+ # 掩码生效;但 `full_D` 比的是 `tombstone = _sig(content, 16)`——**哈希在掩码之前算好**,
415
+ # 掩码对它无能为力。两个子进程(cur/head)只要跨过分钟边界,就必然 14 SAME / 1 DIFF,
416
+ # 且只有 `full_D` 红。这里注入固定 stamp 消除泄漏;先例:`test_b3_merge_keeps_content.py`
417
+ # 同用 `setattr(forgetting, aggregate_line, ...)`。
418
+ _agg_orig = forgetting.aggregate_line
419
+ def _agg_fixed(body, content, stamp=None):
420
+ return _agg_orig(body, content, stamp="01-01 00:00")
421
+ forgetting.aggregate_line = _agg_fixed
411
422
  VOL = ("t", "created_at", "last_access", "time_window", "last_merge_at",
412
423
  "batch", "note", "elapsed_ms", "updated_at")
413
424
  AGG = re.compile(r"【聚合 [^】]*】")
@@ -579,22 +579,27 @@ def main():
579
579
  check("截断时不清退(没扫完 ≠ 剩下都过期)",
580
580
  r6.get("pruned") is None, f"truncated={r6.get('truncated')}")
581
581
 
582
+ # issue #718(2026-10-30):max_nodes 原写死 5000,而索引节点数会随仓库文件数增长——
583
+ # 加两个文件就可能从 5000 涨到 5001,触发 truncated: True,于是 prune 只处理了
584
+ # 扫到的那一段、悬空清不干净(实测读数:scanned=5001, truncated=True, candidates=1)。
585
+ # 这不是产品 bug,是测试在给「足够预算」时把数字写死了。改 20000(远大于当前规模),
586
+ # 让本段测的是**清退语义**,而不是「节点数恰好没超 5000」。
582
587
  print("\n【10b】悬空清退:源文件删除 → op=ref action=prune 处置")
583
- ck1 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 5000})
588
+ ck1 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 20000})
584
589
  pre = len(ck1.get("dangling") or [])
585
590
  os.remove(rn)
586
- ck2 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 5000})
591
+ ck2 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 20000})
587
592
  check("删源后 check 报悬空", len(ck2.get("dangling") or []) > pre,
588
593
  f"{pre}→{len(ck2.get('dangling') or [])}")
589
- dry = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 5000, "dry_run": True})
594
+ dry = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 20000, "dry_run": True})
590
595
  check("prune_dry_run 列出待清退但不删",
591
596
  dry.get("dry_run") is True and dry.get("count", 0) >= 1
592
597
  and any(cg.get(n) for n in ids4), str(dry)[:130])
593
- gone = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 5000})
598
+ gone = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 20000})
594
599
  check("prune 清退悬空节点",
595
600
  gone.get("count", 0) >= 1 and not any(cg.get(n) for n in ids4),
596
601
  str(gone)[:130])
597
- ck3 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 5000})
602
+ ck3 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 20000})
598
603
  check("清退后悬空归零", not (ck3.get("dangling") or []),
599
604
  str(ck3.get("dangling"))[:130])
600
605
 
@@ -610,11 +615,11 @@ def main():
610
615
  cg.index["nodes"][gid] = {"path": "knowledge/ghost_probe.md",
611
616
  "layer": "knowledge", "tags": ["doc"],
612
617
  "bucket": None, "importance": 0.5}
613
- g1 = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 5000})
618
+ g1 = call_tool(cg, "cg", {"op": "ref", "action": "prune", "max_nodes": 20000})
614
619
  check("幽灵条目被清退(索引有、文件无)",
615
620
  len(g1.get("ghost_pruned") or []) >= 1
616
621
  and gid not in (cg.index.get("nodes") or {}), str(g1)[:130])
617
- ck4 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 5000})
622
+ ck4 = call_tool(cg, "cg", {"op": "ref", "action": "check", "max_nodes": 20000})
618
623
  check("清幽灵后悬空仍为零", not (ck4.get("dangling") or []),
619
624
  str(ck4.get("dangling"))[:130])
620
625
 
@@ -0,0 +1,89 @@
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:宪章第十五条(复读污染)守卫——注入过滤 / history 去重 / 污染清除
3
+ # 生效条件:python -X utf8 -m md_cg.test_repeat_guard_charter15;被测面=md_cg/repeat_guard.py 的 scan/annotate/dedupe
4
+ # 子功能:①长文本重复被判、短指令重复不判(minChars 保护非空转)②minCount 分界 ③dedupe 只留最新一条且幂等 ④annotate/dedupe 不改入参 dict(只改副本)⑤脏数据容错 ⑥text_suffix 确定性
5
+ # 执行:纯函数级断言,不依赖真实库与磁盘
6
+ # 验证方式:全部 PASS exit 0;每条都写明「怎么让它红」
7
+ # 不适用条件:不判模型侧是否真的复读(本模块只判事件窗口内的重复);不判注入面渲染(接入在 session_recall,另批)
8
+ """宪章第十五条此前**只有条文没有实现**(`src/` 与 `md_cg/` 搜「复读/degenerat」零命中)。
9
+
10
+ 本守卫盯的是实现里的三个易错点:
11
+ ① `minChars` 保护是否空转(短指令「好」「继续」重复属正常对话,不该判污染);
12
+ ② `dedupe` 是否真的「只留最新一条」且**幂等**;
13
+ ③ `annotate`/`dedupe` 是否**不改入参**(库内正文保真,只改注入副本)。
14
+ """
15
+ import os
16
+ import sys
17
+
18
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ sys.path.insert(0, ROOT)
20
+
21
+ from md_cg import repeat_guard as rg # noqa: E402
22
+
23
+ _PASS, _FAIL = [], []
24
+
25
+
26
+ def ok(cond, msg, detail=""):
27
+ (_PASS if cond else _FAIL).append(msg)
28
+ print((" PASS " if cond else " FAIL ") + msg + ((" <- " + str(detail)) if detail and not cond else ""))
29
+
30
+
31
+ def main():
32
+ LONG = "这是一条足够长的测试消息内容,用于验证重复检测"
33
+ print("== A minChars 保护(防短指令误判)")
34
+ short_evs = [{"role": "user", "text": "好", "t": i} for i in range(5)]
35
+ ok(len(rg.scan(short_evs, min_count=3, min_chars=0)) == 1,
36
+ "A1 minChars=0 时「好」×5 **会**被判(证明该参数真的在起作用)",
37
+ rg.scan(short_evs, min_count=3, min_chars=0))
38
+ ok(len(rg.scan(short_evs, min_count=3, min_chars=12)) == 0,
39
+ "A2 minChars=12 时「好」×5 **不**被判(正确:短指令重复属正常对话)",
40
+ rg.scan(short_evs, min_count=3, min_chars=12))
41
+
42
+ print("== B minCount 分界")
43
+ evs = [{"role": "assistant", "text": LONG, "t": i} for i in range(4)]
44
+ ok(len(rg.scan(evs, min_count=3)) == 1, "B1 ×4 且 minCount=3 → 命中")
45
+ ok(len(rg.scan(evs, min_count=5)) == 0,
46
+ "B2 ×4 且 minCount=5 → **不**命中(阈值真的生效,非恒真)")
47
+
48
+ print("== C dedupe:只留最新一条 + 幂等")
49
+ seq = [{"role": "assistant", "text": LONG, "t": i, "tag": "v%d" % i} for i in range(5)]
50
+ out = rg.dedupe(seq, min_count=3)
51
+ ok(len(out) == 1, "C1 5 条重复折叠成 1 条", len(out))
52
+ ok(out[0].get("tag") == "v4",
53
+ "C2 **保留的是最新一条**(v4,不是 v0)——去重方向不能搞反", out[0].get("tag"))
54
+ ok((out[0].get("repeat") or {}).get("count") == 5,
55
+ "C3 折叠后的条目带 repeat.count=5(信息不丢)", out[0].get("repeat"))
56
+ ok(len(rg.dedupe(out, min_count=3)) == 1,
57
+ "C4 幂等:对已折叠结果再跑一次,条数不变")
58
+
59
+ print("== D 不改入参(库内正文保真)")
60
+ lst = [{"role": "assistant", "text": LONG, "t": i} for i in range(4)]
61
+ ann = rg.annotate(lst, min_count=3)
62
+ ok(all("repeat" not in r for r in lst),
63
+ "D1 annotate **不改入参 dict**(只改返回副本)", [r for r in lst if "repeat" in r][:1])
64
+ ok(any("repeat" in r for r in ann), "D2 返回的副本带 repeat 标注")
65
+ ok(len(ann) == len(lst), "D3 annotate 不改变条数(只标不折)")
66
+
67
+ print("== E 容错")
68
+ dirty = [None, 1, "x", {"text": None}, {"role": None, "text": LONG}]
69
+ try:
70
+ h = rg.scan(dirty, min_count=1)
71
+ ok(True, "E1 脏数据(None/数字/字符串/text=None)不抛异常", len(h))
72
+ except Exception as e: # noqa: BLE001
73
+ ok(False, "E1 脏数据不抛异常", "%s: %s" % (type(e).__name__, e))
74
+
75
+ print("== F text_suffix 确定性")
76
+ ok(rg.text_suffix(LONG) == rg.text_suffix(LONG), "F1 同一 text 恒得同一串(可用作判据)")
77
+ ok(rg.text_suffix(LONG) != rg.text_suffix(LONG + "x"), "F2 不同 text 得不同串")
78
+ ok(len(rg.text_suffix("")) == 8, "F3 空串也返回 8 位(不抛)")
79
+
80
+ print()
81
+ print("宪章第十五条守卫:%d 通过 / %d 失败" % (len(_PASS), len(_FAIL)))
82
+ if _FAIL:
83
+ for f in _FAIL:
84
+ print(" -", f)
85
+ return 0 if not _FAIL else 1
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())