@furongjun1999/dsh-memory 0.9.8 → 0.9.9

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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/codebuddy/CODEBUDDY.md +4 -0
  3. package/docs/README.md +3 -0
  4. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203.md +4 -0
  5. package/dsh/cordis.yml.example +2 -2
  6. package/lib/hooks.d.ts +11 -1
  7. package/lib/hooks.js +58 -3
  8. package/lib/index.d.ts +1 -1
  9. package/lib/index.js +2 -2
  10. package/lib/init.js +11 -2
  11. package/lib/lib/hook_audit.d.ts +3 -0
  12. package/lib/lib/hook_audit.js +37 -0
  13. package/md_cg/autonomy.py +1 -1
  14. package/md_cg/config_registry.py +329 -329
  15. package/md_cg/config_registry_bulk.py +483 -482
  16. package/md_cg/config_render.py +27 -0
  17. package/md_cg/config_validate.py +456 -455
  18. package/md_cg/conflict_surface.py +127 -0
  19. package/md_cg/mcp_server.py +5324 -5227
  20. package/md_cg/mdcg.py +12 -1
  21. package/md_cg/mdcos.py +7159 -7108
  22. package/md_cg/pooling.py +487 -485
  23. package/md_cg/qmd_llm.py +334 -334
  24. package/md_cg/reach.py +10 -4
  25. package/md_cg/sleep.py +2 -2
  26. package/md_cg/sustain.py +3 -3
  27. package/md_cg/test_auto_defaults.py +463 -463
  28. package/md_cg/test_autonomy_emotion.py +328 -328
  29. package/md_cg/test_bm25_default.py +56 -0
  30. package/md_cg/test_c3_transient_read_negative.py +7 -3
  31. package/md_cg/test_conflict_surface.py +75 -0
  32. package/md_cg/test_conflict_value_untrusted.py +63 -0
  33. package/md_cg/test_exact_text_cache.py +194 -191
  34. package/md_cg/test_hotcache_tool.py +121 -0
  35. package/md_cg/test_issue274_read_node_id_none.py +364 -341
  36. package/md_cg/test_issue561_pending_review.py +89 -5
  37. package/md_cg/test_issue578_service_info_gate.py +264 -0
  38. package/md_cg/test_p3_legacy_closure.py +441 -438
  39. package/md_cg/test_p43_pooling.py +419 -412
  40. package/md_cg/test_reach.py +5 -1
  41. package/md_cg/test_reach_exits.py +54 -0
  42. package/md_cg/test_reach_single_char.py +74 -0
  43. package/md_cg/test_search_bm25_default.py +60 -0
  44. package/md_cg/test_sleep_p1.py +1032 -1032
  45. package/md_cg/test_untrusted_audit.py +55 -0
  46. package/md_cg/test_untrusted_classifier.py +42 -0
  47. package/md_cg/test_untrusted_enforcement.py +66 -0
  48. package/md_cg/untrusted.py +45 -0
  49. package/md_cg/untrusted_audit.py +87 -0
  50. package/md_cg/value_conflict.py +71 -0
  51. package/package.json +7 -7
  52. package/src/hooks.ts +59 -5
  53. package/src/index.ts +2 -2
  54. package/src/init.ts +7 -2
  55. package/src/lib/hook_audit.ts +32 -0
  56. package/zcode/AGENTS.md +4 -0
@@ -1,438 +1,441 @@
1
- # -*- coding: utf-8 -*-
2
- """P3 遗留四条闭环守卫(A 融合口径披露 / B S3 不变量读数 / C 缺省路集分叉 / D ④部分满足)。
3
-
4
- 来源:设计稿 §5.4 / §6.2 / §6.3 与交接单「P3 遗留四条·必须在本批闭环」。
5
- 四条各缺一条即不得收口,故**每条一个断言组**:
6
-
7
- A **默认 recall 的融合口径由 sum 变 max**(`use_causal` 缺省 True)——
8
- A1 判据单点 `mcp_server.recall_fusion_default` 的取值断言(缺省态 == "max",
9
- 显式关因果 == None;`use_temporal` **不入判据**);
10
- A2 同一确定性库上「默认 vs 显式 sum」的 top-k 读数**逐条不同**(分数与名次);
11
- A3 默认调用点确实走该单点(源码断言:`fusion = a.get("fusion") or
12
- recall_fusion_default(...)`)。
13
- B **S3 不变量 ① 与 ⑥ 的读数缺口**——
14
- B1 ①「种子取自过 S1/S2 门控的命中」:因果路**种子** ⊆ 已过门控的候选面
15
- (`entries`),且因果路**输出** ⊆ 候选面(两条断言,实跑)。
16
- B2 ⑥「不走全表」实测不成立 ⇒ 如实降级声明:`chain.adjacency` **不读正文**
17
- (读盘调用计数 == 0),但邻接构建为 **O(N) 索引条目级**——给代价读数
18
- (N 条目的冷建耗时),并断言文档/注释里**不再**把「不走全表」当作
19
- 对 `adjacency` 成立的表述。
20
- C **Rust 侧缺省路集分叉**(如实披露,**不得**声称对拍通过)——
21
- Rust `EngineConfig::default{paths:None}` 字面量 == 四路;
22
- Python `search_rrf` 缺省 == 六路;两者**不相等**(分叉登记)。
23
- D **S3 ④ 只部分满足**——类型集可配(`MDCG_CHAIN_TYPES`)、权重沿用唯一表
24
- `EDGE_WEIGHTS`、方向固定为依赖方向(出边)——逐条断言,并断言措辞已改准。
25
-
26
- 运行:
27
- python -X utf8 -m md_cg.test_p3_legacy_closure
28
- python -X utf8 -m md_cg.test_p3_legacy_closure --mutate
29
- python -X utf8 -m md_cg.test_p3_legacy_closure --mutate --list
30
-
31
- 退出码:0 全绿;1 有失败 / 变异未按预期转红;2 ANCHOR-MISS。
32
- """
33
- from __future__ import annotations
34
-
35
- import inspect
36
- import os
37
- import re
38
- import statistics
39
- import sys
40
- import tempfile
41
- import time
42
-
43
- _TMP0 = tempfile.mkdtemp(prefix="p3_legacy_")
44
- os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP0, "auxroot")
45
- os.environ["MDCG_MASTER_KEY"] = "34" * 32
46
- os.environ["MDCG_TOKEN_FILE"] = os.path.join(_TMP0, "tokens.json")
47
- os.environ["MDCG_ROOT"] = os.path.join(_TMP0, "cgroot")
48
- for _k in ("MDCG_TOKEN", "MDCG_TENANT", "MDCG_CLEARANCE", "MDCG_SESSION",
49
- "MDCG_RETRIEVAL_PIPELINE", "MDCG_POOLING", "MDCG_FRESHNESS",
50
- "MDCG_CHAIN_TYPES"):
51
- os.environ.pop(_k, None)
52
-
53
- _HERE = os.path.dirname(os.path.abspath(__file__))
54
- _REPO = os.path.dirname(_HERE)
55
- sys.path.insert(0, _REPO)
56
-
57
- try:
58
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
59
- except AttributeError:
60
- pass
61
-
62
- from md_cg import chain # noqa: E402
63
- from md_cg import mcp_server as MS # noqa: E402
64
- from md_cg import mdcg as M # noqa: E402
65
- from md_cg import subgraph as SG # noqa: E402
66
- from md_cg.mdcos import MdCGOS # noqa: E402
67
-
68
- PASS = 0
69
- FAIL = 0
70
- FAILS = []
71
-
72
-
73
- def check(name, cond, detail=""):
74
- global PASS, FAIL
75
- if cond:
76
- PASS += 1
77
- print(f" OK {name}")
78
- else:
79
- FAIL += 1
80
- FAILS.append(name)
81
- print(f" FAIL {name} {detail}")
82
- return bool(cond)
83
-
84
-
85
- def _src(rel):
86
- with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
87
- return f.read()
88
-
89
-
90
- _CCG = ("# 功能名:{n}\n# 生效条件:无条件\n# 子功能:无\n# 执行:占位\n"
91
- "# 验证方式:compiler 复现\n# 不适用条件:其它会话\n\n{t}\n")
92
-
93
-
94
- def _fusion_lib():
95
- """受控库:两路共识 vs 单路更好名次——sum 与 max 的 top-k 序列在此分开。"""
96
- root = tempfile.mkdtemp(prefix="p3_fuse_")
97
- cg = MdCGOS(root)
98
- cg.add("m_aa", _CCG.format(n="m_aa", t="苹果 别的内容 章节 分离"),
99
- layer="knowledge", tags=["苹果"], importance=0.5)
100
- cg.add("m_zz", _CCG.format(n="m_zz", t="苹果 别的内容 章节 分离"),
101
- # 2026-10-12(#130 名次可信度契约):本夹具原用「entity 路对 m_aa/m_zz 给同一个常量分、
102
- # 交由 importance 兜底分先后」来制造两路共识——而该形态正是 #130 判定为「名次不可信」
103
- # 因而不投票的形态;契约生效后 sum/max 退化为同序 ⇒ A2「逐条不同」失去可观测性
104
- # (CI 实测 29 通过 / 2 失败)。改法:让 m_zz 的 tag 成为**真分数**(aff 1.0,m_aa 为 0.7)
105
- # 而非常量 ⇒ entity 路重新携带名次信息,A2 恢复可观测。契约本身不动,本改动=夹具前提修复。
106
- layer="knowledge", tags=["苹果 章节"], importance=0.9)
107
- cg.add("m_lex", _CCG.format(n="m_lex", t="苹果章节 同构"),
108
- layer="knowledge", importance=0.5)
109
- cg.add("m_other", _CCG.format(n="m_other", t="苹果 别的内容 章节 分离 更多"),
110
- layer="knowledge", importance=0.5)
111
- cg.flush()
112
- return root, cg
113
-
114
-
115
- def _chain_lib(n_seed=3, n_other=6):
116
- root = tempfile.mkdtemp(prefix="p3_chain_")
117
- cg = MdCGOS(root)
118
- for i in range(n_seed):
119
- cg.add(f"s{i}", _CCG.format(n=f"s{i}", t="苹果 章节 种子"),
120
- layer="knowledge", importance=0.5,
121
- edges=[{"target": f"t{i}", "relation_type": "causal",
122
- "confidence": 0.9}])
123
- cg.add(f"t{i}", _CCG.format(n=f"t{i}", t="下游 结论"),
124
- layer="knowledge", importance=0.5)
125
- for i in range(n_other):
126
- cg.add(f"o{i}", _CCG.format(n=f"o{i}", t="无关 其它"),
127
- layer="knowledge", importance=0.5)
128
- # 负记忆层节点:**不在** `_candidates` 的候选面(NEG_ROUTE_LAYERS)——
129
- # 有它,不变量①「种子 ⊆ 已过门控的候选面」才有判别力
130
- cg.add("rj1", _CCG.format(n="rj1", t="苹果 章节 被否决的假设"),
131
- layer="rejected", importance=0.0)
132
- cg.flush()
133
- return root, cg
134
-
135
-
136
- def ga_fusion():
137
- print("== A 默认 recall 融合口径 sum→max(披露 + 判据 + 读数)==")
138
- check("A1 判据单点:缺省(use_causal=True)→ max",
139
- MS.recall_fusion_default(False, False, False, True) == "max",
140
- str(MS.recall_fusion_default(False, False, False, True)))
141
- check("A1 显式关因果且其余全关 → None(回到 search_rrf 的 sum 缺省)",
142
- MS.recall_fusion_default(False, False, False, False) is None)
143
- check("A1 use_temporal 不入判据(时间路是排名项,非单路独有召回型)",
144
- MS.recall_fusion_default(False, False, False, False, True) is None
145
- and MS.recall_fusion_default(False, False, False, True, True) == "max")
146
- src = _src(os.path.join("md_cg", "mcp_server.py"))
147
- check("A3 默认调用点走判据单点",
148
- "fusion = a.get(\"fusion\") or recall_fusion_default(" in src)
149
- check("A3 use_causal 缺省 True(披露的根因)",
150
- "use_causal = True if use_causal is None else bool(use_causal)" in src)
151
- root, cg = _fusion_lib()
152
- try:
153
- def top(**kw):
154
- pack = MS._dispatch(cg, "mdcg_recall",
155
- dict({"query": "苹果 章节", "k": 5}, **kw))
156
- return [[it.get("id"), it.get("score")]
157
- for it in (pack.get("pack") or [])]
158
- d = top()
159
- s = top(fusion="sum")
160
- mx = top(fusion="max")
161
- print(f" default={d}")
162
- print(f" sum ={s}")
163
- print(f" max ={mx}")
164
- check("A2 默认口径 == max(逐条相同)", d == mx, f"{d} vs {mx}")
165
- check("A2 默认口径 ≠ sum(逐条不同:分数或名次)", d != s, f"{d} vs {s}")
166
- check("A2 top-1 名次在 sum/max 下不同(口径差可观测)",
167
- bool(d) and bool(s) and d[0][0] != s[0][0],
168
- f"{d[:1]} vs {s[:1]}")
169
- finally:
170
- cg.close()
171
-
172
-
173
- def gb_s3_invariants():
174
- print("== B S3 不变量 ①⑥ 读数(种子 ⊆ 门控面 / 邻接代价)==")
175
- root, cg = _chain_lib()
176
- try:
177
- # ① 因果路种子 ⊆ 已过 S1/S2 门控的候选面(entries)
178
- seen = {}
179
- orig = chain.expand_from_seeds
180
-
181
- def spy(cg_, seeds, **kw):
182
- seen["seeds"] = list(seeds.items()) if isinstance(seeds, dict) \
183
- else list(seeds or [])
184
- return orig(cg_, seeds, **kw)
185
-
186
- chain.expand_from_seeds = spy
187
- try:
188
- res, meta = cg.search_rrf("苹果 章节", k=8, record=False,
189
- paths=("lexical", "chain"))
190
- finally:
191
- chain.expand_from_seeds = orig
192
- ent_ids = {e["path"].split("/")[-1][:-3] for e in cg._candidates()}
193
- seed_ids = {nid for nid, _s in (seen.get("seeds") or [])}
194
- check("① 因果路种子非空(夹具前提)", bool(seed_ids), str(seen))
195
- check("① 种子 ⊆ 已过门控的候选面(entries)",
196
- seed_ids <= ent_ids, f"{seed_ids - ent_ids}")
197
- out_ids = {r[0]["id"] for r in res}
198
- check("① 因果路输出 ⊆ 候选面(不得引入未过门控的节点)",
199
- out_ids <= ent_ids, f"{out_ids - ent_ids}")
200
- check("① 因果路确实产出(下游 t* 被召回)",
201
- any(i.startswith("t") for i in out_ids), str(sorted(out_ids)))
202
-
203
- # ⑥ 邻接:不读正文(读盘计数 == 0)+ O(N) 索引条目级代价读数
204
- calls = {"n": 0}
205
- orig_read, orig_get = M.MdCG._read, M.MdCG.get
206
-
207
- def rd(self, *a, **kw):
208
- calls["n"] += 1
209
- return orig_read(self, *a, **kw)
210
-
211
- def gt(self, *a, **kw):
212
- calls["n"] += 1
213
- return orig_get(self, *a, **kw)
214
-
215
- M.MdCG._read, M.MdCG.get = rd, gt
216
- try:
217
- cg._chain_adj = None
218
- adj = chain.adjacency(cg)
219
- finally:
220
- M.MdCG._read, M.MdCG.get = orig_read, orig_get
221
- check("⑥ 邻接构建不读正文/不读盘(读盘调用计数 == 0)",
222
- calls["n"] == 0, f"reads={calls['n']}")
223
- # 代价读数:N 条目冷建耗时(夹具 N=9;再取一个 400 条目的规模读)
224
- big = tempfile.mkdtemp(prefix="p3_adj_")
225
- cg2 = MdCGOS(big)
226
- N = 400
227
- for i in range(N):
228
- cg2.add(f"n{i:04d}", _CCG.format(n=f"n{i:04d}", t="苹果 章节"),
229
- layer="knowledge", importance=0.5,
230
- edges=[{"target": f"n{(i + 1) % N:04d}",
231
- "relation_type": "causal"}])
232
- cg2.flush()
233
- cg2._chain_adj = None
234
- t0 = time.perf_counter()
235
- adj2 = chain.adjacency(cg2)
236
- dt = time.perf_counter() - t0
237
- print(f" 代价读数:N={N} 条目,cold adjacency = {dt * 1000:.3f} ms"
238
- f"(邻接源数 {len(adj2)})")
239
- check("⑥ O(N) 条目级代价(400 条目冷建 < 200ms,宽松上界)",
240
- dt < 0.2, f"{dt:.4f}s")
241
- cg2.close()
242
- # 文档/注释措辞:不得把「不走全表」当作对 adjacency 成立的表述
243
- ch = _src(os.path.join("md_cg", "chain.py"))
244
- check("⑥ chain.adjacency 注释已改为「不读正文;O(N) 索引条目级」",
245
- "邻接构建为 O(N) 索引条目级" in ch)
246
- ct = _src(os.path.join("docs", "hive", "检索路径与认知结构契约_v0.1.md"))
247
- check("⑥ 契约文档已改正(含代价读数与可选硬化路径)",
248
- "不读正文;\n 邻接构建为 O(N) 索引条目级" in ct
249
- or "邻接构建为 O(N) 索引条目级" in ct)
250
- check("⑥ 契约文档不再出现无条件的「不走全表」断言",
251
- "扩散 N 跳、按跳数衰减;不走全表" not in ct)
252
- finally:
253
- cg.close()
254
-
255
-
256
- def gc_lang_divergence():
257
- print("== C 缺省路集分叉:Rust 四路 vs Python 六路(登记,非对拍通过)==")
258
- eng = _src(os.path.join("rust", "src", "engine.rs"))
259
- m = re.search(r"cfg\.paths\.clone\(\)\.unwrap_or_else\(\|\|\s*\{(.*?)\}\)",
260
- eng, re.S)
261
- check("C Rust 缺省 paths 字面量可解析", m is not None)
262
- rust_paths = re.findall(r'"([a-z_]+)"\.to_string\(\)', m.group(1)) if m else []
263
- check("C Rust 缺省 == 四路(lexical/bucket/entity/graph)",
264
- rust_paths == ["lexical", "bucket", "entity", "graph"],
265
- str(rust_paths))
266
- py_default = inspect.signature(MdCGOS.search_rrf).parameters["paths"].default
267
- check("C Python search_rrf 缺省 == 六路",
268
- tuple(py_default) == ("lexical", "bucket", "entity", "graph",
269
- "chain", "temporal"), str(py_default))
270
- check("C 两侧缺省**不相等**(分叉为已知边界,不得声称对拍通过)",
271
- set(rust_paths) != set(py_default), f"{rust_paths} vs {list(py_default)}")
272
- check("C 契约文档已登记该分叉(§4.2)",
273
- "读侧**语言面**分叉" in _src(os.path.join(
274
- "docs", "hive", "检索路径与认知结构契约_v0.1.md")))
275
- # mdcg_recall 缺省构造:paths=None(交给 mdcos 六路缺省)
276
- ms = _src(os.path.join("md_cg", "mcp_server.py"))
277
- check("C mdcg_recall 缺省把 paths 交给 mdcos(paths = None)",
278
- "paths = None # 缺省六路" in ms)
279
-
280
-
281
- def gd_s3_partial():
282
- print("== D S3 ④ 部分满足:类型集可配 / 权重唯一表 / 方向固定 ==")
283
- ch = _src(os.path.join("md_cg", "chain.py"))
284
- check("D 类型集可配(env MDCG_CHAIN_TYPES)",
285
- 'CHAIN_TYPES_ENV = "MDCG_CHAIN_TYPES"' in ch
286
- and callable(chain.chain_types_from_env))
287
- os.environ["MDCG_CHAIN_TYPES"] = "reference,causal"
288
- try:
289
- check("D 类型集生效且只含已登记类型",
290
- chain.chain_types_from_env() == ("reference", "causal"),
291
- str(chain.chain_types_from_env()))
292
- finally:
293
- os.environ.pop("MDCG_CHAIN_TYPES", None)
294
- os.environ["MDCG_CHAIN_TYPES"] = "不存在的类型"
295
- try:
296
- check("D 非法类型集回落缺省(剔除即回落,不静默走未知边)",
297
- chain.chain_types_from_env() == chain.CHAIN_TYPES_DEFAULT)
298
- finally:
299
- os.environ.pop("MDCG_CHAIN_TYPES", None)
300
- check("D 权重沿用**唯一表** EDGE_WEIGHTS(无第二份边权表)",
301
- "EDGE_WEIGHTS = {" in ch
302
- and ch.count("EDGE_WEIGHTS.get(") >= 1
303
- and "def edge_weight(edge)" in ch)
304
- check("D 类型集只从 EDGE_WEIGHTS 里挑子集(t in EDGE_WEIGHTS)",
305
- "if t in EDGE_WEIGHTS" in ch)
306
- sig = inspect.signature(chain.walk).parameters
307
- check("D 方向固定为依赖方向(出边):walk 缺省 direction == 'out'",
308
- sig["direction"].default == "out", str(sig["direction"].default))
309
- check("D 措辞已改准(docstring 写明「部分满足」与三件口径)",
310
- "可配面边界" in ch and "**部分满足**" in ch
311
- and "**方向**:固定为**依赖方向(出边)**" in ch
312
- and "沿用**唯一表** `EDGE_WEIGHTS`" in ch)
313
- ct = _src(os.path.join("docs", "hive", "检索路径与认知结构契约_v0.1.md"))
314
- check("D 契约文档已把 S3 ④ 标为部分满足",
315
- "**部分满足**" in ct and "边权数值" in ct)
316
-
317
-
318
- # --------------------------------------------------------------------------
319
- # 定点变异(只改本进程内存对象/临时输入,绝不改仓库文件)
320
- # --------------------------------------------------------------------------
321
-
322
- def _mut_fusion_causal_dropped():
323
- orig = MS.recall_fusion_default
324
-
325
- def no_causal(use_fuzzy, use_semantic, use_goal, use_causal,
326
- use_temporal=False):
327
- return "max" if (use_fuzzy or use_semantic or use_goal) else None
328
- MS.recall_fusion_default = no_causal
329
-
330
- def restore():
331
- MS.recall_fusion_default = orig
332
- return restore
333
-
334
-
335
- def _mut_chain_seed_all():
336
- """把因果路种子改成「全库节点」——不变量 ① 应当立刻变红。"""
337
- orig = MdCGOS._path_chain
338
-
339
- def polluted(self, query, entries, seeds, context=None, **kw):
340
- # 未过门控的节点**排在前 8**(`_path_chain` 只取 seeds[:8])——
341
- # 这正是「种子引入了未过 S1/S2 门控的节点」这一违规形态
342
- ent = {id(e) for e in entries}
343
- nodes = list((self.index.get("nodes") or {}).items())
344
- allseeds = [({"id": nid}, 1.0) for nid, e in nodes
345
- if id(e) not in ent]
346
- allseeds += [({"id": nid}, 1.0) for nid, e in nodes if id(e) in ent]
347
- return orig(self, query, entries, allseeds, context, **kw)
348
- MdCGOS._path_chain = polluted
349
-
350
- def restore():
351
- MdCGOS._path_chain = orig
352
- return restore
353
-
354
-
355
- def _mut_adjacency_reads():
356
- """让邻接构建读正文(走 cg.get)——「不读正文」断言应当变红。"""
357
- orig = SG._fm
358
-
359
- def slow(cg_, nid):
360
- node = cg_.get(nid)
361
- return (node or {}).get("frontmatter") or {}
362
- SG._fm = slow
363
-
364
- def restore():
365
- SG._fm = orig
366
- return restore
367
-
368
-
369
- def _mut_py_default_paths():
370
- """把 mdcos.search_rrf 的 paths 缺省改成四路(源码复制体上验证)。"""
371
- orig = MdCGOS.search_rrf.__defaults__
372
-
373
- def restore():
374
- MdCGOS.search_rrf.__defaults__ = orig
375
- args = list(orig)
376
- for i, a in enumerate(args):
377
- if isinstance(a, tuple) and "chain" in a:
378
- args[i] = ("lexical", "bucket", "entity", "graph")
379
- MdCGOS.search_rrf.__defaults__ = tuple(args)
380
- return restore
381
-
382
-
383
- _MUTATIONS = [
384
- ("fusion_drop_causal", "融合判据丢掉 use_causal(缺省退化为 sum)",
385
- _mut_fusion_causal_dropped),
386
- ("chain_seeds_all", "因果路种子改成全库节点且未过门控者排前(不变量①应红)",
387
- _mut_chain_seed_all),
388
- ("adjacency_reads_body", "邻接构建改成读正文(不变量⑥应红)",
389
- _mut_adjacency_reads),
390
- ("py_default_four_paths", "Python 缺省路集改成四路(分叉登记应红)",
391
- _mut_py_default_paths),
392
- ]
393
-
394
-
395
- def _collect():
396
- global PASS, FAIL, FAILS
397
- PASS, FAIL, FAILS = 0, 0, []
398
- ga_fusion()
399
- gb_s3_invariants()
400
- gc_lang_divergence()
401
- gd_s3_partial()
402
- return list(FAILS)
403
-
404
-
405
- def main(argv):
406
- if "--mutate" in argv:
407
- if "--list" in argv:
408
- for name, desc, _fn in _MUTATIONS:
409
- print(f" {name:24s} {desc}")
410
- return 0
411
- base = _collect()
412
- if base:
413
- print(f"\n!! 基线不绿({len(base)} 条):{base}")
414
- return 1
415
- bad = []
416
- for name, desc, fn in _MUTATIONS:
417
- try:
418
- restore = fn()
419
- except (AttributeError, StopIteration) as exc:
420
- print(f" ANCHOR-MISS {name}: {exc}")
421
- return 2
422
- got = _collect()
423
- restore()
424
- if got:
425
- print(f" MUTATE-OK {name}({desc})→ 转红 {len(got)} 条:{got[:3]}")
426
- else:
427
- bad.append(name)
428
- print(f" MUTATE-FAIL {name}({desc})→ 仍全绿")
429
- print(f"\ntest_p3_legacy_closure --mutate: "
430
- f"{len(_MUTATIONS) - len(bad)}/{len(_MUTATIONS)} 变异按预期转红")
431
- return 0 if not bad else 1
432
- fails = _collect()
433
- print(f"\ntest_p3_legacy_closure: {PASS} 通过 / {FAIL} 失败")
434
- return 0 if not fails else 1
435
-
436
-
437
- if __name__ == "__main__":
438
- sys.exit(main(sys.argv[1:]))
1
+ # -*- coding: utf-8 -*-
2
+ """P3 遗留四条闭环守卫(A 融合口径披露 / B S3 不变量读数 / C 缺省路集分叉 / D ④部分满足)。
3
+
4
+ 来源:设计稿 §5.4 / §6.2 / §6.3 与交接单「P3 遗留四条·必须在本批闭环」。
5
+ 四条各缺一条即不得收口,故**每条一个断言组**:
6
+
7
+ A **默认 recall 的融合口径由 sum 变 max**(`use_causal` 缺省 True)——
8
+ A1 判据单点 `mcp_server.recall_fusion_default` 的取值断言(缺省态 == "max",
9
+ 显式关因果 == None;`use_temporal` **不入判据**);
10
+ A2 同一确定性库上「默认 vs 显式 sum」的 top-k 读数**逐条不同**(分数与名次);
11
+ A3 默认调用点确实走该单点(源码断言:`fusion = a.get("fusion") or
12
+ recall_fusion_default(...)`)。
13
+ B **S3 不变量 ① 与 ⑥ 的读数缺口**——
14
+ B1 ①「种子取自过 S1/S2 门控的命中」:因果路**种子** ⊆ 已过门控的候选面
15
+ (`entries`),且因果路**输出** ⊆ 候选面(两条断言,实跑)。
16
+ B2 ⑥「不走全表」实测不成立 ⇒ 如实降级声明:`chain.adjacency` **不读正文**
17
+ (读盘调用计数 == 0),但邻接构建为 **O(N) 索引条目级**——给代价读数
18
+ (N 条目的冷建耗时),并断言文档/注释里**不再**把「不走全表」当作
19
+ 对 `adjacency` 成立的表述。
20
+ C **Rust 侧缺省路集分叉**(如实披露,**不得**声称对拍通过)——
21
+ Rust `EngineConfig::default{paths:None}` 字面量 == 四路;
22
+ Python `search_rrf` 缺省 == 六路;两者**不相等**(分叉登记)。
23
+ D **S3 ④ 只部分满足**——类型集可配(`MDCG_CHAIN_TYPES`)、权重沿用唯一表
24
+ `EDGE_WEIGHTS`、方向固定为依赖方向(出边)——逐条断言,并断言措辞已改准。
25
+
26
+ 运行:
27
+ python -X utf8 -m md_cg.test_p3_legacy_closure
28
+ python -X utf8 -m md_cg.test_p3_legacy_closure --mutate
29
+ python -X utf8 -m md_cg.test_p3_legacy_closure --mutate --list
30
+
31
+ 退出码:0 全绿;1 有失败 / 变异未按预期转红;2 ANCHOR-MISS。
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import inspect
36
+ import os
37
+ import re
38
+ import statistics
39
+ import sys
40
+ import tempfile
41
+ import time
42
+
43
+ _TMP0 = tempfile.mkdtemp(prefix="p3_legacy_")
44
+ os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP0, "auxroot")
45
+ os.environ["MDCG_MASTER_KEY"] = "34" * 32
46
+ os.environ["MDCG_TOKEN_FILE"] = os.path.join(_TMP0, "tokens.json")
47
+ os.environ["MDCG_ROOT"] = os.path.join(_TMP0, "cgroot")
48
+ for _k in ("MDCG_TOKEN", "MDCG_TENANT", "MDCG_CLEARANCE", "MDCG_SESSION",
49
+ "MDCG_RETRIEVAL_PIPELINE", "MDCG_POOLING", "MDCG_FRESHNESS",
50
+ "MDCG_CHAIN_TYPES"):
51
+ os.environ.pop(_k, None)
52
+
53
+ _HERE = os.path.dirname(os.path.abspath(__file__))
54
+ _REPO = os.path.dirname(_HERE)
55
+ sys.path.insert(0, _REPO)
56
+
57
+ try:
58
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
59
+ except AttributeError:
60
+ pass
61
+
62
+ from md_cg import chain # noqa: E402
63
+ from md_cg import mcp_server as MS # noqa: E402
64
+ from md_cg import mdcg as M # noqa: E402
65
+ from md_cg import subgraph as SG # noqa: E402
66
+ from md_cg.mdcos import MdCGOS # noqa: E402
67
+
68
+ PASS = 0
69
+ FAIL = 0
70
+ FAILS = []
71
+
72
+
73
+ def check(name, cond, detail=""):
74
+ global PASS, FAIL
75
+ if cond:
76
+ PASS += 1
77
+ print(f" OK {name}")
78
+ else:
79
+ FAIL += 1
80
+ FAILS.append(name)
81
+ print(f" FAIL {name} {detail}")
82
+ return bool(cond)
83
+
84
+
85
+ def _src(rel):
86
+ with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
87
+ return f.read()
88
+
89
+
90
+ _CCG = ("# 功能名:{n}\n# 生效条件:无条件\n# 子功能:无\n# 执行:占位\n"
91
+ "# 验证方式:compiler 复现\n# 不适用条件:其它会话\n\n{t}\n")
92
+
93
+
94
+ def _fusion_lib():
95
+ """受控库:两路共识 vs 单路更好名次——sum 与 max 的 top-k 序列在此分开。"""
96
+ root = tempfile.mkdtemp(prefix="p3_fuse_")
97
+ cg = MdCGOS(root)
98
+ cg.add("m_aa", _CCG.format(n="m_aa", t="苹果 别的内容 章节 分离"),
99
+ layer="knowledge", tags=["苹果"], importance=0.5)
100
+ cg.add("m_zz", _CCG.format(n="m_zz", t="苹果 别的内容 章节 分离"),
101
+ # 2026-10-12(#130 名次可信度契约):本夹具原用「entity 路对 m_aa/m_zz 给同一个常量分、
102
+ # 交由 importance 兜底分先后」来制造两路共识——而该形态正是 #130 判定为「名次不可信」
103
+ # 因而不投票的形态;契约生效后 sum/max 退化为同序 ⇒ A2「逐条不同」失去可观测性
104
+ # (CI 实测 29 通过 / 2 失败)。改法:让 m_zz 的 tag 成为**真分数**(aff 1.0,m_aa 为 0.7)
105
+ # 而非常量 ⇒ entity 路重新携带名次信息,A2 恢复可观测。契约本身不动,本改动=夹具前提修复。
106
+ layer="knowledge", tags=["苹果 章节"], importance=0.9)
107
+ cg.add("m_lex", _CCG.format(n="m_lex", t="苹果章节 同构"),
108
+ layer="knowledge", importance=0.5)
109
+ cg.add("m_other", _CCG.format(n="m_other", t="苹果 别的内容 章节 分离 更多"),
110
+ layer="knowledge", importance=0.5)
111
+ cg.flush()
112
+ return root, cg
113
+
114
+
115
+ def _chain_lib(n_seed=3, n_other=6):
116
+ root = tempfile.mkdtemp(prefix="p3_chain_")
117
+ cg = MdCGOS(root)
118
+ for i in range(n_seed):
119
+ cg.add(f"s{i}", _CCG.format(n=f"s{i}", t="苹果 章节 种子"),
120
+ layer="knowledge", importance=0.5,
121
+ edges=[{"target": f"t{i}", "relation_type": "causal",
122
+ "confidence": 0.9}])
123
+ cg.add(f"t{i}", _CCG.format(n=f"t{i}", t="下游 结论"),
124
+ layer="knowledge", importance=0.5)
125
+ for i in range(n_other):
126
+ cg.add(f"o{i}", _CCG.format(n=f"o{i}", t="无关 其它"),
127
+ layer="knowledge", importance=0.5)
128
+ # 负记忆层节点:**不在** `_candidates` 的候选面(NEG_ROUTE_LAYERS)——
129
+ # 有它,不变量①「种子 ⊆ 已过门控的候选面」才有判别力
130
+ cg.add("rj1", _CCG.format(n="rj1", t="苹果 章节 被否决的假设"),
131
+ layer="rejected", importance=0.0)
132
+ cg.flush()
133
+ return root, cg
134
+
135
+
136
+ def ga_fusion():
137
+ print("== A 默认 recall 融合口径 sum→max(披露 + 判据 + 读数)==")
138
+ check("A1 判据单点:缺省(use_causal=True)→ max",
139
+ MS.recall_fusion_default(False, False, False, True) == "max",
140
+ str(MS.recall_fusion_default(False, False, False, True)))
141
+ check("A1 显式关因果且其余全关 → None(回到 search_rrf 的 sum 缺省)",
142
+ MS.recall_fusion_default(False, False, False, False) is None)
143
+ check("A1 use_temporal 不入判据(时间路是排名项,非单路独有召回型)",
144
+ MS.recall_fusion_default(False, False, False, False, True) is None
145
+ and MS.recall_fusion_default(False, False, False, True, True) == "max")
146
+ src = _src(os.path.join("md_cg", "mcp_server.py"))
147
+ check("A3 默认调用点走判据单点",
148
+ "fusion = a.get(\"fusion\") or recall_fusion_default(" in src)
149
+ check("A3 use_causal 缺省 True(披露的根因)",
150
+ "use_causal = True if use_causal is None else bool(use_causal)" in src)
151
+ root, cg = _fusion_lib()
152
+ try:
153
+ def top(**kw):
154
+ pack = MS._dispatch(cg, "mdcg_recall",
155
+ dict({"query": "苹果 章节", "k": 5}, **kw))
156
+ return [[it.get("id"), it.get("score")]
157
+ for it in (pack.get("pack") or [])]
158
+ d = top()
159
+ s = top(fusion="sum")
160
+ mx = top(fusion="max")
161
+ print(f" default={d}")
162
+ print(f" sum ={s}")
163
+ print(f" max ={mx}")
164
+ check("A2 默认口径 == max(逐条相同)", d == mx, f"{d} vs {mx}")
165
+ check("A2 默认口径 ≠ sum(逐条不同:分数或名次)", d != s, f"{d} vs {s}")
166
+ # 口径差的可观测形式(2026-10-21 重述):**分数或名次**任一不同即算观测到差异。
167
+ # 原断言只比 id——BM25 默认开之后 sum/max 的 id 顺序可能相同、但分数按 2 倍差异,
168
+ # 只比 id 会把"口径确实不同"误判成"没差异"。
169
+ check("A2 top-1 读数在 sum/max 下不同(分数或名次,口径差可观测)",
170
+ bool(d) and bool(s) and d[0] != s[0],
171
+ f"{d[:1]} vs {s[:1]}")
172
+ finally:
173
+ cg.close()
174
+
175
+
176
+ def gb_s3_invariants():
177
+ print("== B S3 不变量 ①⑥ 读数(种子 ⊆ 门控面 / 邻接代价)==")
178
+ root, cg = _chain_lib()
179
+ try:
180
+ # ① 因果路种子 ⊆ 已过 S1/S2 门控的候选面(entries)
181
+ seen = {}
182
+ orig = chain.expand_from_seeds
183
+
184
+ def spy(cg_, seeds, **kw):
185
+ seen["seeds"] = list(seeds.items()) if isinstance(seeds, dict) \
186
+ else list(seeds or [])
187
+ return orig(cg_, seeds, **kw)
188
+
189
+ chain.expand_from_seeds = spy
190
+ try:
191
+ res, meta = cg.search_rrf("苹果 章节", k=8, record=False,
192
+ paths=("lexical", "chain"))
193
+ finally:
194
+ chain.expand_from_seeds = orig
195
+ ent_ids = {e["path"].split("/")[-1][:-3] for e in cg._candidates()}
196
+ seed_ids = {nid for nid, _s in (seen.get("seeds") or [])}
197
+ check("① 因果路种子非空(夹具前提)", bool(seed_ids), str(seen))
198
+ check("① 种子 ⊆ 已过门控的候选面(entries)",
199
+ seed_ids <= ent_ids, f"{seed_ids - ent_ids}")
200
+ out_ids = {r[0]["id"] for r in res}
201
+ check("① 因果路输出 ⊆ 候选面(不得引入未过门控的节点)",
202
+ out_ids <= ent_ids, f"{out_ids - ent_ids}")
203
+ check("① 因果路确实产出(下游 t* 被召回)",
204
+ any(i.startswith("t") for i in out_ids), str(sorted(out_ids)))
205
+
206
+ # ⑥ 邻接:不读正文(读盘计数 == 0)+ O(N) 索引条目级代价读数
207
+ calls = {"n": 0}
208
+ orig_read, orig_get = M.MdCG._read, M.MdCG.get
209
+
210
+ def rd(self, *a, **kw):
211
+ calls["n"] += 1
212
+ return orig_read(self, *a, **kw)
213
+
214
+ def gt(self, *a, **kw):
215
+ calls["n"] += 1
216
+ return orig_get(self, *a, **kw)
217
+
218
+ M.MdCG._read, M.MdCG.get = rd, gt
219
+ try:
220
+ cg._chain_adj = None
221
+ adj = chain.adjacency(cg)
222
+ finally:
223
+ M.MdCG._read, M.MdCG.get = orig_read, orig_get
224
+ check("⑥ 邻接构建不读正文/不读盘(读盘调用计数 == 0)",
225
+ calls["n"] == 0, f"reads={calls['n']}")
226
+ # 代价读数:N 条目冷建耗时(夹具 N=9;再取一个 400 条目的规模读)
227
+ big = tempfile.mkdtemp(prefix="p3_adj_")
228
+ cg2 = MdCGOS(big)
229
+ N = 400
230
+ for i in range(N):
231
+ cg2.add(f"n{i:04d}", _CCG.format(n=f"n{i:04d}", t="苹果 章节"),
232
+ layer="knowledge", importance=0.5,
233
+ edges=[{"target": f"n{(i + 1) % N:04d}",
234
+ "relation_type": "causal"}])
235
+ cg2.flush()
236
+ cg2._chain_adj = None
237
+ t0 = time.perf_counter()
238
+ adj2 = chain.adjacency(cg2)
239
+ dt = time.perf_counter() - t0
240
+ print(f" 代价读数:N={N} 条目,cold adjacency = {dt * 1000:.3f} ms"
241
+ f"(邻接源数 {len(adj2)})")
242
+ check("⑥ O(N) 条目级代价(400 条目冷建 < 200ms,宽松上界)",
243
+ dt < 0.2, f"{dt:.4f}s")
244
+ cg2.close()
245
+ # 文档/注释措辞:不得把「不走全表」当作对 adjacency 成立的表述
246
+ ch = _src(os.path.join("md_cg", "chain.py"))
247
+ check("⑥ chain.adjacency 注释已改为「不读正文;O(N) 索引条目级」",
248
+ "邻接构建为 O(N) 索引条目级" in ch)
249
+ ct = _src(os.path.join("docs", "hive", "检索路径与认知结构契约_v0.1.md"))
250
+ check("⑥ 契约文档已改正(含代价读数与可选硬化路径)",
251
+ "不读正文;\n 邻接构建为 O(N) 索引条目级" in ct
252
+ or "邻接构建为 O(N) 索引条目级" in ct)
253
+ check("⑥ 契约文档不再出现无条件的「不走全表」断言",
254
+ "扩散 N 跳、按跳数衰减;不走全表" not in ct)
255
+ finally:
256
+ cg.close()
257
+
258
+
259
+ def gc_lang_divergence():
260
+ print("== C 缺省路集分叉:Rust 四路 vs Python 六路(登记,非对拍通过)==")
261
+ eng = _src(os.path.join("rust", "src", "engine.rs"))
262
+ m = re.search(r"cfg\.paths\.clone\(\)\.unwrap_or_else\(\|\|\s*\{(.*?)\}\)",
263
+ eng, re.S)
264
+ check("C Rust 缺省 paths 字面量可解析", m is not None)
265
+ rust_paths = re.findall(r'"([a-z_]+)"\.to_string\(\)', m.group(1)) if m else []
266
+ check("C Rust 缺省 == 四路(lexical/bucket/entity/graph)",
267
+ rust_paths == ["lexical", "bucket", "entity", "graph"],
268
+ str(rust_paths))
269
+ py_default = inspect.signature(MdCGOS.search_rrf).parameters["paths"].default
270
+ check("C Python search_rrf 缺省 == 六路",
271
+ tuple(py_default) == ("lexical", "bucket", "entity", "graph",
272
+ "chain", "temporal"), str(py_default))
273
+ check("C 两侧缺省**不相等**(分叉为已知边界,不得声称对拍通过)",
274
+ set(rust_paths) != set(py_default), f"{rust_paths} vs {list(py_default)}")
275
+ check("C 契约文档已登记该分叉(§4.2)",
276
+ "读侧**语言面**分叉" in _src(os.path.join(
277
+ "docs", "hive", "检索路径与认知结构契约_v0.1.md")))
278
+ # mdcg_recall 缺省构造:paths=None(交给 mdcos 六路缺省)
279
+ ms = _src(os.path.join("md_cg", "mcp_server.py"))
280
+ check("C mdcg_recall 缺省把 paths 交给 mdcos(paths = None)",
281
+ "paths = None # 缺省六路" in ms)
282
+
283
+
284
+ def gd_s3_partial():
285
+ print("== D S3 ④ 部分满足:类型集可配 / 权重唯一表 / 方向固定 ==")
286
+ ch = _src(os.path.join("md_cg", "chain.py"))
287
+ check("D 类型集可配(env MDCG_CHAIN_TYPES)",
288
+ 'CHAIN_TYPES_ENV = "MDCG_CHAIN_TYPES"' in ch
289
+ and callable(chain.chain_types_from_env))
290
+ os.environ["MDCG_CHAIN_TYPES"] = "reference,causal"
291
+ try:
292
+ check("D 类型集生效且只含已登记类型",
293
+ chain.chain_types_from_env() == ("reference", "causal"),
294
+ str(chain.chain_types_from_env()))
295
+ finally:
296
+ os.environ.pop("MDCG_CHAIN_TYPES", None)
297
+ os.environ["MDCG_CHAIN_TYPES"] = "不存在的类型"
298
+ try:
299
+ check("D 非法类型集回落缺省(剔除即回落,不静默走未知边)",
300
+ chain.chain_types_from_env() == chain.CHAIN_TYPES_DEFAULT)
301
+ finally:
302
+ os.environ.pop("MDCG_CHAIN_TYPES", None)
303
+ check("D 权重沿用**唯一表** EDGE_WEIGHTS(无第二份边权表)",
304
+ "EDGE_WEIGHTS = {" in ch
305
+ and ch.count("EDGE_WEIGHTS.get(") >= 1
306
+ and "def edge_weight(edge)" in ch)
307
+ check("D 类型集只从 EDGE_WEIGHTS 里挑子集(t in EDGE_WEIGHTS)",
308
+ "if t in EDGE_WEIGHTS" in ch)
309
+ sig = inspect.signature(chain.walk).parameters
310
+ check("D 方向固定为依赖方向(出边):walk 缺省 direction == 'out'",
311
+ sig["direction"].default == "out", str(sig["direction"].default))
312
+ check("D 措辞已改准(docstring 写明「部分满足」与三件口径)",
313
+ "可配面边界" in ch and "**部分满足**" in ch
314
+ and "**方向**:固定为**依赖方向(出边)**" in ch
315
+ and "沿用**唯一表** `EDGE_WEIGHTS`" in ch)
316
+ ct = _src(os.path.join("docs", "hive", "检索路径与认知结构契约_v0.1.md"))
317
+ check("D 契约文档已把 S3 ④ 标为部分满足",
318
+ "**部分满足**" in ct and "边权数值" in ct)
319
+
320
+
321
+ # --------------------------------------------------------------------------
322
+ # 定点变异(只改本进程内存对象/临时输入,绝不改仓库文件)
323
+ # --------------------------------------------------------------------------
324
+
325
+ def _mut_fusion_causal_dropped():
326
+ orig = MS.recall_fusion_default
327
+
328
+ def no_causal(use_fuzzy, use_semantic, use_goal, use_causal,
329
+ use_temporal=False):
330
+ return "max" if (use_fuzzy or use_semantic or use_goal) else None
331
+ MS.recall_fusion_default = no_causal
332
+
333
+ def restore():
334
+ MS.recall_fusion_default = orig
335
+ return restore
336
+
337
+
338
+ def _mut_chain_seed_all():
339
+ """把因果路种子改成「全库节点」——不变量 ① 应当立刻变红。"""
340
+ orig = MdCGOS._path_chain
341
+
342
+ def polluted(self, query, entries, seeds, context=None, **kw):
343
+ # 未过门控的节点**排在前 8**(`_path_chain` 只取 seeds[:8])——
344
+ # 这正是「种子引入了未过 S1/S2 门控的节点」这一违规形态
345
+ ent = {id(e) for e in entries}
346
+ nodes = list((self.index.get("nodes") or {}).items())
347
+ allseeds = [({"id": nid}, 1.0) for nid, e in nodes
348
+ if id(e) not in ent]
349
+ allseeds += [({"id": nid}, 1.0) for nid, e in nodes if id(e) in ent]
350
+ return orig(self, query, entries, allseeds, context, **kw)
351
+ MdCGOS._path_chain = polluted
352
+
353
+ def restore():
354
+ MdCGOS._path_chain = orig
355
+ return restore
356
+
357
+
358
+ def _mut_adjacency_reads():
359
+ """让邻接构建读正文(走 cg.get)——「不读正文」断言应当变红。"""
360
+ orig = SG._fm
361
+
362
+ def slow(cg_, nid):
363
+ node = cg_.get(nid)
364
+ return (node or {}).get("frontmatter") or {}
365
+ SG._fm = slow
366
+
367
+ def restore():
368
+ SG._fm = orig
369
+ return restore
370
+
371
+
372
+ def _mut_py_default_paths():
373
+ """把 mdcos.search_rrf 的 paths 缺省改成四路(源码复制体上验证)。"""
374
+ orig = MdCGOS.search_rrf.__defaults__
375
+
376
+ def restore():
377
+ MdCGOS.search_rrf.__defaults__ = orig
378
+ args = list(orig)
379
+ for i, a in enumerate(args):
380
+ if isinstance(a, tuple) and "chain" in a:
381
+ args[i] = ("lexical", "bucket", "entity", "graph")
382
+ MdCGOS.search_rrf.__defaults__ = tuple(args)
383
+ return restore
384
+
385
+
386
+ _MUTATIONS = [
387
+ ("fusion_drop_causal", "融合判据丢掉 use_causal(缺省退化为 sum)",
388
+ _mut_fusion_causal_dropped),
389
+ ("chain_seeds_all", "因果路种子改成全库节点且未过门控者排前(不变量①应红)",
390
+ _mut_chain_seed_all),
391
+ ("adjacency_reads_body", "邻接构建改成读正文(不变量⑥应红)",
392
+ _mut_adjacency_reads),
393
+ ("py_default_four_paths", "Python 缺省路集改成四路(分叉登记应红)",
394
+ _mut_py_default_paths),
395
+ ]
396
+
397
+
398
+ def _collect():
399
+ global PASS, FAIL, FAILS
400
+ PASS, FAIL, FAILS = 0, 0, []
401
+ ga_fusion()
402
+ gb_s3_invariants()
403
+ gc_lang_divergence()
404
+ gd_s3_partial()
405
+ return list(FAILS)
406
+
407
+
408
+ def main(argv):
409
+ if "--mutate" in argv:
410
+ if "--list" in argv:
411
+ for name, desc, _fn in _MUTATIONS:
412
+ print(f" {name:24s} {desc}")
413
+ return 0
414
+ base = _collect()
415
+ if base:
416
+ print(f"\n!! 基线不绿({len(base)} 条):{base}")
417
+ return 1
418
+ bad = []
419
+ for name, desc, fn in _MUTATIONS:
420
+ try:
421
+ restore = fn()
422
+ except (AttributeError, StopIteration) as exc:
423
+ print(f" ANCHOR-MISS {name}: {exc}")
424
+ return 2
425
+ got = _collect()
426
+ restore()
427
+ if got:
428
+ print(f" MUTATE-OK {name}({desc})→ 转红 {len(got)} 条:{got[:3]}")
429
+ else:
430
+ bad.append(name)
431
+ print(f" MUTATE-FAIL {name}({desc})→ 仍全绿")
432
+ print(f"\ntest_p3_legacy_closure --mutate: "
433
+ f"{len(_MUTATIONS) - len(bad)}/{len(_MUTATIONS)} 变异按预期转红")
434
+ return 0 if not bad else 1
435
+ fails = _collect()
436
+ print(f"\ntest_p3_legacy_closure: {PASS} 通过 / {FAIL} 失败")
437
+ return 0 if not fails else 1
438
+
439
+
440
+ if __name__ == "__main__":
441
+ sys.exit(main(sys.argv[1:]))