@furongjun1999/dsh-memory 0.9.8 → 0.9.10

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 (57) 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 +2 -0
  16. package/md_cg/config_render.py +27 -0
  17. package/md_cg/config_validate.py +10 -8
  18. package/md_cg/conflict_surface.py +127 -0
  19. package/md_cg/mcp_server.py +105 -8
  20. package/md_cg/mdcg.py +60 -2
  21. package/md_cg/mdcos.py +61 -6
  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 +797 -793
  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 +3 -0
  34. package/md_cg/test_hotcache_tool.py +121 -0
  35. package/md_cg/test_index_snapshot_fastpath.py +72 -0
  36. package/md_cg/test_issue274_read_node_id_none.py +29 -6
  37. package/md_cg/test_issue561_pending_review.py +89 -5
  38. package/md_cg/test_issue578_service_info_gate.py +264 -0
  39. package/md_cg/test_p3_legacy_closure.py +5 -2
  40. package/md_cg/test_p43_pooling.py +419 -412
  41. package/md_cg/test_reach.py +5 -1
  42. package/md_cg/test_reach_exits.py +54 -0
  43. package/md_cg/test_reach_single_char.py +74 -0
  44. package/md_cg/test_search_bm25_default.py +60 -0
  45. package/md_cg/test_sleep_p1.py +1032 -1032
  46. package/md_cg/test_untrusted_audit.py +55 -0
  47. package/md_cg/test_untrusted_classifier.py +42 -0
  48. package/md_cg/test_untrusted_enforcement.py +66 -0
  49. package/md_cg/untrusted.py +45 -0
  50. package/md_cg/untrusted_audit.py +87 -0
  51. package/md_cg/value_conflict.py +71 -0
  52. package/package.json +7 -7
  53. package/src/hooks.ts +986 -932
  54. package/src/index.ts +2 -2
  55. package/src/init.ts +7 -2
  56. package/src/lib/hook_audit.ts +32 -0
  57. package/zcode/AGENTS.md +4 -0
@@ -1,463 +1,463 @@
1
- # -*- coding: utf-8 -*-
2
- """`auto_*` 四档缺省「单一真源」守卫(P0-2,2026-10-01)。
3
-
4
- 契约(设计稿 `docs/plans/睡眠与自迭代_功能优化设计_v0.4.md` §八 P0-2 / §4.7):
5
-
6
- 同一 `(root, name)` 的两条入口必须得到**同一组** `auto_*` 取值;
7
- 缺省只许有**一份定义**(`sustain.AUTO_DEFAULTS` + 三个读取器),
8
- 两个调用点不得再写第二处字面量。
9
-
10
- 改动前实测(探针读数,逐条引 `path:line`):
11
-
12
- op 路径(工具面 `sustain action=start`) `auto_tidy=bool(a.get("auto_tidy", False))`
13
- → **False**(mcp_server.py:1639)
14
- env 路径(常驻 serve 自启 `_start_sustain`)`auto_tidy=os.environ.get("MDCG_AUTO_TIDY","1") not in (...)`
15
- → **True**(mcp_server.py:3595-3596)
16
- 另三项 auto_heal/auto_scrub/auto_evolve 两入口一致(True / False / False);
17
- `SustainLoop.__init__` 形参另有一份 `auto_tidy=False`(sustain.py:966)——
18
- 即「单一真源尚未成立,全仓 auto_tidy 缺省字面量至少两处」。
19
-
20
- **本轮对外可见的缺省变更(裁决值 = 开)**:`auto_tidy` 缺省由 False 收敛为
21
- **True**(取 env 路径既有值);opt-out = `MDCG_AUTO_TIDY=0`(env 路径)/
22
- 显式 `auto_tidy=false`(op 路径)。另三项**逐项未变**(G4 钉死,防「顺手改多了」)。
23
-
24
- 断言分组:
25
-
26
- G0 隔离与基线自证——库根/状态根/辅助根/心跳目录全落守卫临时目录(绝不碰在役
27
- 库与 `~/.mdcg`);断言真源表与三个读取器在位。
28
- G1 真源表与读取器——四项值、键集、env 键映射、关断字面量固定;`auto_default`
29
- 逐项一致;`auto_from_env` 的缺省字面量**由表推出**(真值→"1"、假值→"0",
30
- 与改动前两处字面量同义)。
31
- G2 三面同源读数(端到端,真起循环)——env 路径(`_start_sustain`)、op 路径
32
- (`_sustain_call` 的 start 分支)、构造面(`SustainLoop(cg)`)三面在同一档上
33
- 取值相同且**都等于真源表**;并验两侧 opt-out / 显式入参仍优先。
34
- G3 单一真源(静态)——带引号字面量 `"MDCG_AUTO_TIDY"` 在生产源码里恰 1 处
35
- (在 `AUTO_ENVS`);`mcp_server.py` 内 `a.get("auto_*"` /
36
- `os.environ.get("MDCG_AUTO_*"` / `os.environ.get("MDCG_SUSTAIN_AUTOHEAL"` 零命中;
37
- 两入口各恰好一处读取器调用。(`md_cg/test_*.py` 不在判据面内:本守卫自己的
38
- 变异表就含这些字面量,属红基线工具面。)
39
- G4 对外可见变更的披露面——`auto_tidy` 缺省为 True 且 op 路径无参即得 True;
40
- 另三项缺省与本轮前逐项相同;opt-out 名取自 `AUTO_ENVS` 而非硬编码。
41
-
42
- 运行:python -X utf8 -m md_cg.test_auto_defaults
43
- python -X utf8 -m md_cg.test_auto_defaults --mutate # 定点变异自证
44
- python -X utf8 -m md_cg.test_auto_defaults --mutate --list # 只列变异表
45
-
46
- 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
47
- 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,
48
- 锚点漂移必须硬失败,不得静默跳过)。
49
-
50
- **基线纪律**:本守卫**不以 git HEAD 为基线源**——「改动前形态」由在当前工作区
51
- 源码上做**定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
52
- """
53
- from __future__ import annotations
54
-
55
- import contextlib
56
- import io
57
- import os
58
- import shutil
59
- import subprocess
60
- import sys
61
- import tempfile
62
- import types
63
-
64
- from . import mcp_server as MCP
65
- from . import sustain
66
-
67
- _PASS = []
68
- _FAIL = []
69
- _SKIP = []
70
- #: 变异模式下供静态组读取的**源码文本**(rel → text);未变异时读盘。
71
- _SRC = {}
72
-
73
- _REAL_SUSTAIN = sustain
74
- _REAL_MCP = MCP
75
-
76
-
77
- def ok(cond, msg, extra=""):
78
- (_PASS if cond else _FAIL).append(msg)
79
- print((" PASS " if cond else " FAIL ") + msg
80
- + ((" ← " + str(extra)) if (extra and not cond) else ""))
81
-
82
-
83
- def skip(msg):
84
- _SKIP.append(msg)
85
- print(" SKIP " + msg)
86
-
87
-
88
- def _repo_root() -> str:
89
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
90
-
91
-
92
- def _rel_text(rel: str) -> str:
93
- """源码文本:变异模式下取变异后的文本,否则读盘。"""
94
- if rel in _SRC:
95
- return _SRC[rel]
96
- with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
97
- return f.read()
98
-
99
-
100
- def _tracked_rels():
101
- """git 追踪面(仓根相对 · posix 分隔)集合;git 不可用/非仓 ⇒ None(调用方降级)。
102
-
103
- G3 静态判据面须锚在**追踪面**而非文件系统面:本地工作树的 gitignore 产物
104
- (`.tmp/` 草稿、`md_cg/_md_cg_eval_*/` 评测灌库、`md_cg/knowledge/` 运行态)
105
- 不在 CI 干净克隆里,用文件系统面判定会让「本地红 / CI 绿」分裂。`.tmp` 只是
106
- 当前最大污染源,故按「是否被 git 追踪」这个**性质**判,不逐个硬编码排除目录。
107
- """
108
- try:
109
- proc = subprocess.run(["git", "-C", _repo_root(), "ls-files", "-z"],
110
- capture_output=True, check=True)
111
- except Exception: # noqa: BLE001 —— 兜底见下
112
- return None
113
- return {p.replace("\\", "/") for p in
114
- proc.stdout.decode("utf-8", "replace").split("\0") if p}
115
-
116
-
117
- def _md_cg_py_texts():
118
- """静态判据面 = `md_cg/` 下全部 `.py` ∩ **git 追踪面**(非追踪件不入面)。
119
-
120
- 降级(明示,非静默改语义):git 不可用或非仓环境 ⇒ 退化为原文件系统走查,
121
- 并打印 `[降级]` 一行——此时判据面可能与 CI 干净克隆不一致,读数须按降级看待。
122
- """
123
- tracked = _tracked_rels()
124
- if tracked is None:
125
- print(" [降级] git 不可用:G3 静态扫描面退化为文件系统走查"
126
- "(可能与 CI 干净克隆不一致)")
127
- d = os.path.join(_repo_root(), "md_cg")
128
- out = {}
129
- for fn in sorted(os.listdir(d)):
130
- if not fn.endswith(".py"):
131
- continue
132
- rel = "md_cg/" + fn
133
- if tracked is not None and rel not in tracked:
134
- continue # 非追踪件不入判据面(保留原 .py 语义)
135
- out[rel] = _rel_text(rel)
136
- return out
137
-
138
-
139
- # ---------------------------------------------------------------- 沙箱
140
- _TMP = tempfile.mkdtemp(prefix="mdcg_autodef_")
141
- _SAVED = {}
142
- _GEN = [0]
143
-
144
-
145
- def _sandbox_env():
146
- """把四条根全钉进守卫临时目录;原值留待还原(绝不碰在役库 / ~/.mdcg)。"""
147
- for k in ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
148
- "MDCG_SUBSTAIN", "MDCG_SUSTAIN", "MDCG_SUSTAIN_NAME",
149
- "MDCG_AUTO_TIDY", "MDCG_AUTO_SCRUB", "MDCG_AUTO_EVOLVE",
150
- "MDCG_SUSTAIN_AUTOHEAL"):
151
- _SAVED[k] = os.environ.get(k)
152
- os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
153
- os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
154
- os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
155
- os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
156
- os.environ["MDCG_SUBSTAIN"] = "0"
157
- os.environ.pop("MDCG_SUSTAIN", None)
158
- for k in ("MDCG_AUTO_TIDY", "MDCG_AUTO_SCRUB", "MDCG_AUTO_EVOLVE",
159
- "MDCG_SUSTAIN_AUTOHEAL"):
160
- os.environ.pop(k, None)
161
-
162
-
163
- def _restore_env():
164
- for k, v in _SAVED.items():
165
- if v is None:
166
- os.environ.pop(k, None)
167
- else:
168
- os.environ[k] = v
169
-
170
-
171
- def _cg(name="cg"):
172
- """每轮 `_run_groups` 用**全新根**:`sustain.ensure_loop` 按 (root,name) 复用
173
- 实例,同一根跨轮复用会让变异轮读到上一轮的循环(假绿)。"""
174
- from .mdcos import MdCGOS
175
- root = os.path.join(_TMP, "gen%d" % _GEN[0], name)
176
- os.makedirs(root, exist_ok=True)
177
- return MdCGOS(root)
178
-
179
-
180
- # ---------------------------------------------------------------- G0
181
- def g0():
182
- print("== G0 隔离与基线自证 ==")
183
- ok(hasattr(_REAL_SUSTAIN, "AUTO_DEFAULTS"),
184
- "G0a sustain.AUTO_DEFAULTS 存在(缺省真源表)")
185
- ok(all(hasattr(_REAL_SUSTAIN, n)
186
- for n in ("auto_default", "auto_from_env", "auto_from_args")),
187
- "G0b 三个读取器(auto_default / auto_from_env / auto_from_args)均在位")
188
- ok(os.environ["MDCG_ROOT"].startswith(_TMP)
189
- and os.environ["MDCG_AUX_ROOT"].startswith(_TMP),
190
- "G0c 沙箱:库根与辅助根都在守卫临时目录内", os.environ["MDCG_ROOT"])
191
-
192
-
193
- # ---------------------------------------------------------------- G1
194
- _EXPECT = {"auto_heal": True, "auto_scrub": False,
195
- "auto_evolve": False, "auto_tidy": True}
196
-
197
-
198
- def g1():
199
- print("== G1 真源表与读取器 ==")
200
- S = globals()["sustain"]
201
- ok(dict(S.AUTO_DEFAULTS) == _EXPECT,
202
- "G1 真源表四项与裁决值一致(含 auto_tidy=True——本轮唯一的对外可见变更)",
203
- S.AUTO_DEFAULTS)
204
- ok(set(S.AUTO_ENVS) == set(S.AUTO_DEFAULTS),
205
- "G1a env 键映射与真源表同键集", sorted(S.AUTO_ENVS))
206
- ok(S.AUTO_ENVS["auto_tidy"] == "MDCG_AUTO_TIDY",
207
- "G1b auto_tidy 的 env 键名 = MDCG_AUTO_TIDY(opt-out 名)")
208
- ok(tuple(S.AUTO_OFF_VALUES) == ("0", "false", "False"),
209
- "G1c 关断字面量与改动前两入口逐字一致(0 / false / False)",
210
- S.AUTO_OFF_VALUES)
211
- for k, v in _EXPECT.items():
212
- ok(S.auto_default(k) is v,
213
- "G1d auto_default(%s) 与表一致 = %r" % (k, v))
214
- for k, v in _EXPECT.items():
215
- ok(S.auto_from_env(k, {}) is v,
216
- "G1e auto_from_env(%s) 空环境下回落真源缺省 %r(默认字面量由表推出)"
217
- % (k, v))
218
- for k in _EXPECT:
219
- for off in ("0", "false", "False", "FALSE ", ""):
220
- got = S.auto_from_env(k, {S.AUTO_ENVS[k]: off})
221
- want = off not in S.AUTO_OFF_VALUES
222
- ok(got is want,
223
- "G1f auto_from_env(%s) 取 %r → %r(关断口径不变)" % (k, off, want),
224
- got)
225
- ok(S.auto_from_env("auto_tidy", {"MDCG_AUTO_TIDY": "1"}) is True,
226
- "G1g 显式 1 仍为开(开态仍可达)")
227
-
228
-
229
- # ---------------------------------------------------------------- G2
230
- def g2():
231
- print("== G2 三面同源读数(端到端,真起循环)==")
232
- S = globals()["sustain"]
233
- M = globals()["MCP"]
234
- cg = _cg("cg_g2")
235
- os.environ.pop("MDCG_AUTO_TIDY", None)
236
- os.environ["MDCG_SUSTAIN_NAME"] = "env_edge"
237
- lp = M._start_sustain(cg)
238
- ok(lp is not None, "G2 env 路径确已起循环(前置)")
239
- ok(lp.auto_tidy is True,
240
- "G2a env 路径(_start_sustain)无 env 覆盖时 auto_tidy=True(生产路径既有值)",
241
- lp.auto_tidy)
242
- os.environ["MDCG_AUTO_TIDY"] = "0"
243
- os.environ["MDCG_SUSTAIN_NAME"] = "env_off"
244
- lp2 = M._start_sustain(cg)
245
- ok(lp2 is not None and lp2.auto_tidy is False,
246
- "G2b env 路径 opt-out:MDCG_AUTO_TIDY=0 → auto_tidy=False",
247
- (lp2.auto_tidy if lp2 else None))
248
- os.environ.pop("MDCG_AUTO_TIDY", None)
249
- ti = {"beat_interval": 3600, "heal_interval": 3600, "scrub_interval": 3600,
250
- "evolve_interval": 3600, "tidy_interval": 3600}
251
- r = M._sustain_call(cg, dict({"action": "start", "name": "op_default"}, **ti))
252
- opl = S.get_loop(cg, "op_default")
253
- ok("loop" in r and opl is not None, "G2c op 路径确已起循环(前置)", r)
254
- ok(opl is not None and opl.auto_tidy is True,
255
- "G2d op 路径(sustain action=start)不传参时 auto_tidy=True——**本轮的缺省变更**",
256
- (opl.auto_tidy if opl else None))
257
- M._sustain_call(cg, dict({"action": "start", "name": "op_off",
258
- "auto_tidy": False}, **ti))
259
- opl2 = S.get_loop(cg, "op_off")
260
- ok(opl2 is not None and opl2.auto_tidy is False,
261
- "G2e op 路径显式 auto_tidy=false → False(显式入参优先于真源表)",
262
- (opl2.auto_tidy if opl2 else None))
263
- M._sustain_call(cg, dict({"action": "start", "name": "op_face"}, **ti))
264
- env_face = S.get_loop(cg, "env_edge")
265
- op_face = S.get_loop(cg, "op_face")
266
- ctor_face = S.SustainLoop(cg, name="ctor_face",
267
- d=os.environ["MDCG_SUSTAIN_DIR"])
268
- ok(env_face is not None and op_face is not None,
269
- "G2f 前置:env / op 两面循环都在册")
270
- for k in _EXPECT:
271
- trio = (getattr(env_face, k), getattr(op_face, k), getattr(ctor_face, k))
272
- ok(trio[0] == trio[1] == trio[2] == _EXPECT[k],
273
- "G2g 三面同值 %s:env/op/构造 = %r,真源 = %r" % (k, trio, _EXPECT[k]))
274
- S.stop_all()
275
-
276
-
277
- # ---------------------------------------------------------------- G3
278
- def g3():
279
- print("== G3 单一真源(静态)==")
280
- texts = _md_cg_py_texts()
281
- prod = {rel: t for rel, t in texts.items()
282
- if not os.path.basename(rel).startswith("test_")}
283
- quoted = sorted((rel, t.count('"MDCG_AUTO_TIDY"')) for rel, t in prod.items()
284
- if t.count('"MDCG_AUTO_TIDY"'))
285
- ok(quoted == [("md_cg/sustain.py", 1)],
286
- "G3 带引号字面量 \"MDCG_AUTO_TIDY\" 在生产源码里恰 1 处(在 AUTO_ENVS)",
287
- quoted)
288
- pats = ('os.environ.get("MDCG_AUTO_TIDY"', 'a.get("auto_tidy"',
289
- 'a.get("auto_heal"', 'a.get("auto_scrub"', 'a.get("auto_evolve"',
290
- 'os.environ.get("MDCG_AUTO_SCRUB"',
291
- 'os.environ.get("MDCG_AUTO_EVOLVE"',
292
- 'os.environ.get("MDCG_SUSTAIN_AUTOHEAL"')
293
- bad = [(rel, p, t.count(p)) for rel, t in prod.items()
294
- for p in pats if t.count(p)]
295
- ok(not bad, "G3a 生产源码里零命中「缺省字面量」形态(^ 见 detail)", bad)
296
- s = _rel_text("md_cg/sustain.py")
297
- ok("AUTO_DEFAULTS = {" in s, "G3b 真源表在 sustain.py 定义")
298
- ok(s.count("auto_tidy: bool = AUTO_DEFAULTS[") == 1,
299
- "G3c SustainLoop 形参默认值引用真源表(不写第二处字面量)")
300
- m = _rel_text("md_cg/mcp_server.py")
301
- ok(m.count('auto_tidy=sustain.auto_from_args("auto_tidy", a)') == 1,
302
- "G3d op 路径恰一处经 auto_from_args 读 auto_tidy")
303
- ok(m.count('auto_tidy=sustain.auto_from_env("auto_tidy")') == 1,
304
- "G3e env 路径恰一处经 auto_from_env 读 auto_tidy")
305
- ok('"auto_tidy", False' not in m and 'auto_tidy=False)' not in m,
306
- "G3f mcp_server.py 内不再有 auto_tidy 的 False 缺省字面量")
307
-
308
-
309
- # ---------------------------------------------------------------- G4
310
- def g4():
311
- print("== G4 变更披露面(防顺手改多了)==")
312
- S = globals()["sustain"]
313
- ok(S.AUTO_DEFAULTS["auto_tidy"] is True,
314
- "G4 裁决值 = 开:auto_tidy 真源缺省为 True")
315
- ok(S.AUTO_DEFAULTS["auto_heal"] is True
316
- and S.AUTO_DEFAULTS["auto_scrub"] is False
317
- and S.AUTO_DEFAULTS["auto_evolve"] is False,
318
- "G4a 另三项缺省与本轮前逐项相同(heal=True / scrub=False / evolve=False)",
319
- S.AUTO_DEFAULTS)
320
- ok(S.AUTO_ENVS["auto_tidy"] == "MDCG_AUTO_TIDY",
321
- "G4b opt-out env 名(自真源读)= MDCG_AUTO_TIDY")
322
- ok(S.auto_from_args("auto_tidy", {"auto_tidy": None}) is False,
323
- "G4c 显式传 None(键在)→ False,与改动前 bool(a.get(name, default)) 同义")
324
- ok(S.auto_from_args("auto_tidy", {"other": 1}) is True,
325
- "G4d 缺键才回落真源缺省(True)")
326
-
327
-
328
- _GROUPS = (g0, g1, g2, g3, g4)
329
-
330
-
331
- # ---------------------------------------------------------------- 变异表
332
- # 锚点 = (名字, 模式, rel, old, new, 预期红项数下限)。
333
- # "mod" = 改**可执行实现**(exec 成模块并换进 `sys.modules`,供 `from . import` 面读到)
334
- # "src" = 只改**源码文本**(静态组 G3 读 `_SRC`,不 exec)
335
- # 「改动前形态」的复现即在这里:
336
- # M1 把真源表里的 auto_tidy 改回 False(= 旧的 op 路径字面量)
337
- # M2 让 op 路径读取器不回落真源(= 旧的「另一处字面量」)
338
- # M3 把 env 路径改回旧的手写 env 读取(= 旧 env 路径形态 + 第二处字面量)
339
- _MUTATIONS = (
340
- ("真源表 auto_tidy 改回 False(旧 op 路径值)", "mod", "md_cg/sustain.py",
341
- '"auto_evolve": False, "auto_tidy": True}',
342
- '"auto_evolve": False, "auto_tidy": False}', 1),
343
- ("op 路径读取器不回落真源(旧「另一处字面量」)", "mod", "md_cg/sustain.py",
344
- " return bool(args[name])\n return auto_default(name)",
345
- " return bool(args[name])\n return False", 1),
346
- # 锚点 = **布局无关的唯一子串**:只取到 `("auto_tidy")` 为止,不带尾括号——
347
- # `ensure_loop(` 的收尾随「单行参数 / 多行关键字实参」而变(现役实现是多行、
348
- # 行尾 `,`),把 `))` 写进锚点即把变异项钉死在某一版行布局上(S4a 缺陷:
349
- # 实现改成多行后锚点漂移、`--mutate` 误判为 fail-closed 退出码 2)。
350
- # 该串在 mcp_server.py 恰 1 处(与 G3e 同一子串,唯一性由 G3e 守卫)。
351
- ("env 路径改回手写 env 读取(第二处 MDCG_AUTO_TIDY 字面量)", "src",
352
- "md_cg/mcp_server.py",
353
- 'auto_tidy=sustain.auto_from_env("auto_tidy")',
354
- 'auto_tidy=os.environ.get("MDCG_AUTO_TIDY", "1") not in ("0", "false", "False")',
355
- 1),
356
- )
357
-
358
-
359
- def _run_groups() -> int:
360
- _GEN[0] += 1
361
- _PASS.clear()
362
- _FAIL.clear()
363
- for g in _GROUPS:
364
- try:
365
- g()
366
- except Exception as exc: # noqa: BLE001
367
- ok(False, "断言组 %s 抛异常:%s" % (g.__name__, exc))
368
- import traceback
369
- print(traceback.format_exc()[-800:])
370
- for mod in (globals().get("sustain"), _REAL_SUSTAIN):
371
- try:
372
- mod.stop_all()
373
- except Exception: # noqa: BLE001
374
- pass
375
- return len(_FAIL)
376
-
377
-
378
- def _exec_module(name: str, rel: str, text: str):
379
- ns = {"__name__": name, "__package__": "md_cg",
380
- "__file__": os.path.join(_repo_root(), rel)}
381
- exec(compile(text, rel, "exec"), ns) # noqa: S102 —— 基线自证用
382
- m = types.ModuleType(name)
383
- m.__dict__.update(ns)
384
- return m
385
-
386
-
387
- def _mutate_mode(list_only: bool = False) -> int:
388
- print("!! 定点变异自证:逐条把「单一真源」改回改动前形态,套件必须转红\n")
389
- if list_only:
390
- for name, kind, rel, _o, _n, exp in _MUTATIONS:
391
- print(" %-46s [%s] expect_red>=%d (%s)" % (name, kind, exp, rel))
392
- return 0
393
- anchor_miss, bad = [], []
394
- with contextlib.redirect_stdout(io.StringIO()):
395
- clean = _run_groups()
396
- print(" 未变异基线:失败=%d(必须为 0)" % clean)
397
- if clean:
398
- bad.append("未变异基线即失败")
399
-
400
- for name, kind, rel, old, new, expect in _MUTATIONS:
401
- src = _rel_text(rel)
402
- if old not in src:
403
- print(" ANCHOR-MISS %s —— 锚点在 %s 源码里找不到(实现改了却没同步"
404
- "本表;锚点漂移不得静默)" % (name, rel))
405
- anchor_miss.append(name)
406
- continue
407
- mut_src = src.replace(old, new, 1)
408
- _SRC[rel] = mut_src
409
- live = None
410
- try:
411
- if kind == "mod":
412
- live = sys.modules["md_cg.sustain"]
413
- mut = _exec_module("md_cg._autodef_mut", rel, mut_src)
414
- sys.modules["md_cg.sustain"] = mut
415
- globals()["sustain"] = mut
416
- with contextlib.redirect_stdout(buf := io.StringIO()):
417
- reds = _run_groups()
418
- detail = buf.getvalue()
419
- finally:
420
- if live is not None:
421
- sys.modules["md_cg.sustain"] = live
422
- globals()["sustain"] = _REAL_SUSTAIN
423
- _SRC.pop(rel, None)
424
- red_lines = [l for l in detail.splitlines()
425
- if l.strip().startswith("FAIL ")]
426
- verdict = "红" if reds else "**仍全绿 = 该判据空转**"
427
- mark = "OK " if reds >= expect else "MISMATCH"
428
- print(" %s %-46s 红项=%d 预期>=%d %s"
429
- % (mark, name, reds, expect, verdict))
430
- for l in red_lines[:6]:
431
- print(" " + l.strip()[5:])
432
- if reds < expect:
433
- bad.append("%s(红=%d 预期>=%d)" % (name, reds, expect))
434
-
435
- if anchor_miss:
436
- print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
437
- print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
438
- return 2
439
- print("\n定点变异自证:%s"
440
- % ("PASS(每处判据都被打红)" if not bad else "FAIL —— " + "、".join(bad)))
441
- return 0 if not bad else 1
442
-
443
-
444
- def main() -> int:
445
- _sandbox_env()
446
- try:
447
- if "--mutate" in sys.argv:
448
- return _mutate_mode("--list" in sys.argv)
449
- n = _run_groups()
450
- print("\nauto_* 缺省单一真源守卫:%d 通过,%d 失败,%d 跳过"
451
- % (len(_PASS), n, len(_SKIP)))
452
- return 0 if not n else 1
453
- finally:
454
- try:
455
- _REAL_SUSTAIN.stop_all()
456
- except Exception: # noqa: BLE001
457
- pass
458
- _restore_env()
459
- shutil.rmtree(_TMP, ignore_errors=True)
460
-
461
-
462
- if __name__ == "__main__":
463
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """`auto_*` 四档缺省「单一真源」守卫(P0-2,2026-10-01)。
3
+
4
+ 契约(设计稿 `docs/plans/睡眠与自迭代_功能优化设计_v0.4.md` §八 P0-2 / §4.7):
5
+
6
+ 同一 `(root, name)` 的两条入口必须得到**同一组** `auto_*` 取值;
7
+ 缺省只许有**一份定义**(`sustain.AUTO_DEFAULTS` + 三个读取器),
8
+ 两个调用点不得再写第二处字面量。
9
+
10
+ 改动前实测(探针读数,逐条引 `path:line`):
11
+
12
+ op 路径(工具面 `sustain action=start`) `auto_tidy=bool(a.get("auto_tidy", False))`
13
+ → **False**(mcp_server.py:1639)
14
+ env 路径(常驻 serve 自启 `_start_sustain`)`auto_tidy=os.environ.get("MDCG_AUTO_TIDY","1") not in (...)`
15
+ → **True**(mcp_server.py:3595-3596)
16
+ 另三项 auto_heal/auto_scrub/auto_evolve 两入口一致(True / False / False);
17
+ `SustainLoop.__init__` 形参另有一份 `auto_tidy=False`(sustain.py:966)——
18
+ 即「单一真源尚未成立,全仓 auto_tidy 缺省字面量至少两处」。
19
+
20
+ **本轮对外可见的缺省变更(裁决值 = 开)**:`auto_tidy` 缺省由 False 收敛为
21
+ **True**(取 env 路径既有值);opt-out = `MDCG_AUTO_TIDY=0`(env 路径)/
22
+ 显式 `auto_tidy=false`(op 路径)。另三项**逐项未变**(G4 钉死,防「顺手改多了」)。
23
+
24
+ 断言分组:
25
+
26
+ G0 隔离与基线自证——库根/状态根/辅助根/心跳目录全落守卫临时目录(绝不碰在役
27
+ 库与 `~/.mdcg`);断言真源表与三个读取器在位。
28
+ G1 真源表与读取器——四项值、键集、env 键映射、关断字面量固定;`auto_default`
29
+ 逐项一致;`auto_from_env` 的缺省字面量**由表推出**(真值→"1"、假值→"0",
30
+ 与改动前两处字面量同义)。
31
+ G2 三面同源读数(端到端,真起循环)——env 路径(`_start_sustain`)、op 路径
32
+ (`_sustain_call` 的 start 分支)、构造面(`SustainLoop(cg)`)三面在同一档上
33
+ 取值相同且**都等于真源表**;并验两侧 opt-out / 显式入参仍优先。
34
+ G3 单一真源(静态)——带引号字面量 `"MDCG_AUTO_TIDY"` 在生产源码里恰 1 处
35
+ (在 `AUTO_ENVS`);`mcp_server.py` 内 `a.get("auto_*"` /
36
+ `os.environ.get("MDCG_AUTO_*"` / `os.environ.get("MDCG_SUSTAIN_AUTOHEAL"` 零命中;
37
+ 两入口各恰好一处读取器调用。(`md_cg/test_*.py` 不在判据面内:本守卫自己的
38
+ 变异表就含这些字面量,属红基线工具面。)
39
+ G4 对外可见变更的披露面——`auto_tidy` 缺省为 True 且 op 路径无参即得 True;
40
+ 另三项缺省与本轮前逐项相同;opt-out 名取自 `AUTO_ENVS` 而非硬编码。
41
+
42
+ 运行:python -X utf8 -m md_cg.test_auto_defaults
43
+ python -X utf8 -m md_cg.test_auto_defaults --mutate # 定点变异自证
44
+ python -X utf8 -m md_cg.test_auto_defaults --mutate --list # 只列变异表
45
+
46
+ 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
47
+ 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,
48
+ 锚点漂移必须硬失败,不得静默跳过)。
49
+
50
+ **基线纪律**:本守卫**不以 git HEAD 为基线源**——「改动前形态」由在当前工作区
51
+ 源码上做**定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
52
+ """
53
+ from __future__ import annotations
54
+
55
+ import contextlib
56
+ import io
57
+ import os
58
+ import shutil
59
+ import subprocess
60
+ import sys
61
+ import tempfile
62
+ import types
63
+
64
+ from . import mcp_server as MCP
65
+ from . import sustain
66
+
67
+ _PASS = []
68
+ _FAIL = []
69
+ _SKIP = []
70
+ #: 变异模式下供静态组读取的**源码文本**(rel → text);未变异时读盘。
71
+ _SRC = {}
72
+
73
+ _REAL_SUSTAIN = sustain
74
+ _REAL_MCP = MCP
75
+
76
+
77
+ def ok(cond, msg, extra=""):
78
+ (_PASS if cond else _FAIL).append(msg)
79
+ print((" PASS " if cond else " FAIL ") + msg
80
+ + ((" ← " + str(extra)) if (extra and not cond) else ""))
81
+
82
+
83
+ def skip(msg):
84
+ _SKIP.append(msg)
85
+ print(" SKIP " + msg)
86
+
87
+
88
+ def _repo_root() -> str:
89
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
90
+
91
+
92
+ def _rel_text(rel: str) -> str:
93
+ """源码文本:变异模式下取变异后的文本,否则读盘。"""
94
+ if rel in _SRC:
95
+ return _SRC[rel]
96
+ with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
97
+ return f.read()
98
+
99
+
100
+ def _tracked_rels():
101
+ """git 追踪面(仓根相对 · posix 分隔)集合;git 不可用/非仓 ⇒ None(调用方降级)。
102
+
103
+ G3 静态判据面须锚在**追踪面**而非文件系统面:本地工作树的 gitignore 产物
104
+ (`.tmp/` 草稿、`md_cg/_md_cg_eval_*/` 评测灌库、`md_cg/knowledge/` 运行态)
105
+ 不在 CI 干净克隆里,用文件系统面判定会让「本地红 / CI 绿」分裂。`.tmp` 只是
106
+ 当前最大污染源,故按「是否被 git 追踪」这个**性质**判,不逐个硬编码排除目录。
107
+ """
108
+ try:
109
+ proc = subprocess.run(["git", "-C", _repo_root(), "ls-files", "-z"],
110
+ capture_output=True, check=True)
111
+ except Exception: # noqa: BLE001 —— 兜底见下
112
+ return None
113
+ return {p.replace("\\", "/") for p in
114
+ proc.stdout.decode("utf-8", "replace").split("\0") if p}
115
+
116
+
117
+ def _md_cg_py_texts():
118
+ """静态判据面 = `md_cg/` 下全部 `.py` ∩ **git 追踪面**(非追踪件不入面)。
119
+
120
+ 降级(明示,非静默改语义):git 不可用或非仓环境 ⇒ 退化为原文件系统走查,
121
+ 并打印 `[降级]` 一行——此时判据面可能与 CI 干净克隆不一致,读数须按降级看待。
122
+ """
123
+ tracked = _tracked_rels()
124
+ if tracked is None:
125
+ print(" [降级] git 不可用:G3 静态扫描面退化为文件系统走查"
126
+ "(可能与 CI 干净克隆不一致)")
127
+ d = os.path.join(_repo_root(), "md_cg")
128
+ out = {}
129
+ for fn in sorted(os.listdir(d)):
130
+ if not fn.endswith(".py"):
131
+ continue
132
+ rel = "md_cg/" + fn
133
+ if tracked is not None and rel not in tracked:
134
+ continue # 非追踪件不入判据面(保留原 .py 语义)
135
+ out[rel] = _rel_text(rel)
136
+ return out
137
+
138
+
139
+ # ---------------------------------------------------------------- 沙箱
140
+ _TMP = tempfile.mkdtemp(prefix="mdcg_autodef_")
141
+ _SAVED = {}
142
+ _GEN = [0]
143
+
144
+
145
+ def _sandbox_env():
146
+ """把四条根全钉进守卫临时目录;原值留待还原(绝不碰在役库 / ~/.mdcg)。"""
147
+ for k in ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
148
+ "MDCG_SUBSTAIN", "MDCG_SUSTAIN", "MDCG_SUSTAIN_NAME",
149
+ "MDCG_AUTO_TIDY", "MDCG_AUTO_SCRUB", "MDCG_AUTO_EVOLVE",
150
+ "MDCG_SUSTAIN_AUTOHEAL"):
151
+ _SAVED[k] = os.environ.get(k)
152
+ os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
153
+ os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
154
+ os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
155
+ os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
156
+ os.environ["MDCG_SUBSTAIN"] = "0"
157
+ os.environ.pop("MDCG_SUSTAIN", None)
158
+ for k in ("MDCG_AUTO_TIDY", "MDCG_AUTO_SCRUB", "MDCG_AUTO_EVOLVE",
159
+ "MDCG_SUSTAIN_AUTOHEAL"):
160
+ os.environ.pop(k, None)
161
+
162
+
163
+ def _restore_env():
164
+ for k, v in _SAVED.items():
165
+ if v is None:
166
+ os.environ.pop(k, None)
167
+ else:
168
+ os.environ[k] = v
169
+
170
+
171
+ def _cg(name="cg"):
172
+ """每轮 `_run_groups` 用**全新根**:`sustain.ensure_loop` 按 (root,name) 复用
173
+ 实例,同一根跨轮复用会让变异轮读到上一轮的循环(假绿)。"""
174
+ from .mdcos import MdCGOS
175
+ root = os.path.join(_TMP, "gen%d" % _GEN[0], name)
176
+ os.makedirs(root, exist_ok=True)
177
+ return MdCGOS(root)
178
+
179
+
180
+ # ---------------------------------------------------------------- G0
181
+ def g0():
182
+ print("== G0 隔离与基线自证 ==")
183
+ ok(hasattr(_REAL_SUSTAIN, "AUTO_DEFAULTS"),
184
+ "G0a sustain.AUTO_DEFAULTS 存在(缺省真源表)")
185
+ ok(all(hasattr(_REAL_SUSTAIN, n)
186
+ for n in ("auto_default", "auto_from_env", "auto_from_args")),
187
+ "G0b 三个读取器(auto_default / auto_from_env / auto_from_args)均在位")
188
+ ok(os.environ["MDCG_ROOT"].startswith(_TMP)
189
+ and os.environ["MDCG_AUX_ROOT"].startswith(_TMP),
190
+ "G0c 沙箱:库根与辅助根都在守卫临时目录内", os.environ["MDCG_ROOT"])
191
+
192
+
193
+ # ---------------------------------------------------------------- G1
194
+ _EXPECT = {"auto_heal": True, "auto_scrub": True,
195
+ "auto_evolve": True, "auto_tidy": True}
196
+
197
+
198
+ def g1():
199
+ print("== G1 真源表与读取器 ==")
200
+ S = globals()["sustain"]
201
+ ok(dict(S.AUTO_DEFAULTS) == _EXPECT,
202
+ "G1 真源表四项与裁决值一致(scrub/evolve 默认已改 True——使用者裁定 2026-10-21)",
203
+ S.AUTO_DEFAULTS)
204
+ ok(set(S.AUTO_ENVS) == set(S.AUTO_DEFAULTS),
205
+ "G1a env 键映射与真源表同键集", sorted(S.AUTO_ENVS))
206
+ ok(S.AUTO_ENVS["auto_tidy"] == "MDCG_AUTO_TIDY",
207
+ "G1b auto_tidy 的 env 键名 = MDCG_AUTO_TIDY(opt-out 名)")
208
+ ok(tuple(S.AUTO_OFF_VALUES) == ("0", "false", "False"),
209
+ "G1c 关断字面量与改动前两入口逐字一致(0 / false / False)",
210
+ S.AUTO_OFF_VALUES)
211
+ for k, v in _EXPECT.items():
212
+ ok(S.auto_default(k) is v,
213
+ "G1d auto_default(%s) 与表一致 = %r" % (k, v))
214
+ for k, v in _EXPECT.items():
215
+ ok(S.auto_from_env(k, {}) is v,
216
+ "G1e auto_from_env(%s) 空环境下回落真源缺省 %r(默认字面量由表推出)"
217
+ % (k, v))
218
+ for k in _EXPECT:
219
+ for off in ("0", "false", "False", "FALSE ", ""):
220
+ got = S.auto_from_env(k, {S.AUTO_ENVS[k]: off})
221
+ want = off not in S.AUTO_OFF_VALUES
222
+ ok(got is want,
223
+ "G1f auto_from_env(%s) 取 %r → %r(关断口径不变)" % (k, off, want),
224
+ got)
225
+ ok(S.auto_from_env("auto_tidy", {"MDCG_AUTO_TIDY": "1"}) is True,
226
+ "G1g 显式 1 仍为开(开态仍可达)")
227
+
228
+
229
+ # ---------------------------------------------------------------- G2
230
+ def g2():
231
+ print("== G2 三面同源读数(端到端,真起循环)==")
232
+ S = globals()["sustain"]
233
+ M = globals()["MCP"]
234
+ cg = _cg("cg_g2")
235
+ os.environ.pop("MDCG_AUTO_TIDY", None)
236
+ os.environ["MDCG_SUSTAIN_NAME"] = "env_edge"
237
+ lp = M._start_sustain(cg)
238
+ ok(lp is not None, "G2 env 路径确已起循环(前置)")
239
+ ok(lp.auto_tidy is True,
240
+ "G2a env 路径(_start_sustain)无 env 覆盖时 auto_tidy=True(生产路径既有值)",
241
+ lp.auto_tidy)
242
+ os.environ["MDCG_AUTO_TIDY"] = "0"
243
+ os.environ["MDCG_SUSTAIN_NAME"] = "env_off"
244
+ lp2 = M._start_sustain(cg)
245
+ ok(lp2 is not None and lp2.auto_tidy is False,
246
+ "G2b env 路径 opt-out:MDCG_AUTO_TIDY=0 → auto_tidy=False",
247
+ (lp2.auto_tidy if lp2 else None))
248
+ os.environ.pop("MDCG_AUTO_TIDY", None)
249
+ ti = {"beat_interval": 3600, "heal_interval": 3600, "scrub_interval": 3600,
250
+ "evolve_interval": 3600, "tidy_interval": 3600}
251
+ r = M._sustain_call(cg, dict({"action": "start", "name": "op_default"}, **ti))
252
+ opl = S.get_loop(cg, "op_default")
253
+ ok("loop" in r and opl is not None, "G2c op 路径确已起循环(前置)", r)
254
+ ok(opl is not None and opl.auto_tidy is True,
255
+ "G2d op 路径(sustain action=start)不传参时 auto_tidy=True——**本轮的缺省变更**",
256
+ (opl.auto_tidy if opl else None))
257
+ M._sustain_call(cg, dict({"action": "start", "name": "op_off",
258
+ "auto_tidy": False}, **ti))
259
+ opl2 = S.get_loop(cg, "op_off")
260
+ ok(opl2 is not None and opl2.auto_tidy is False,
261
+ "G2e op 路径显式 auto_tidy=false → False(显式入参优先于真源表)",
262
+ (opl2.auto_tidy if opl2 else None))
263
+ M._sustain_call(cg, dict({"action": "start", "name": "op_face"}, **ti))
264
+ env_face = S.get_loop(cg, "env_edge")
265
+ op_face = S.get_loop(cg, "op_face")
266
+ ctor_face = S.SustainLoop(cg, name="ctor_face",
267
+ d=os.environ["MDCG_SUSTAIN_DIR"])
268
+ ok(env_face is not None and op_face is not None,
269
+ "G2f 前置:env / op 两面循环都在册")
270
+ for k in _EXPECT:
271
+ trio = (getattr(env_face, k), getattr(op_face, k), getattr(ctor_face, k))
272
+ ok(trio[0] == trio[1] == trio[2] == _EXPECT[k],
273
+ "G2g 三面同值 %s:env/op/构造 = %r,真源 = %r" % (k, trio, _EXPECT[k]))
274
+ S.stop_all()
275
+
276
+
277
+ # ---------------------------------------------------------------- G3
278
+ def g3():
279
+ print("== G3 单一真源(静态)==")
280
+ texts = _md_cg_py_texts()
281
+ prod = {rel: t for rel, t in texts.items()
282
+ if not os.path.basename(rel).startswith("test_")}
283
+ quoted = sorted((rel, t.count('"MDCG_AUTO_TIDY"')) for rel, t in prod.items()
284
+ if t.count('"MDCG_AUTO_TIDY"'))
285
+ ok(quoted == [("md_cg/sustain.py", 1)],
286
+ "G3 带引号字面量 \"MDCG_AUTO_TIDY\" 在生产源码里恰 1 处(在 AUTO_ENVS)",
287
+ quoted)
288
+ pats = ('os.environ.get("MDCG_AUTO_TIDY"', 'a.get("auto_tidy"',
289
+ 'a.get("auto_heal"', 'a.get("auto_scrub"', 'a.get("auto_evolve"',
290
+ 'os.environ.get("MDCG_AUTO_SCRUB"',
291
+ 'os.environ.get("MDCG_AUTO_EVOLVE"',
292
+ 'os.environ.get("MDCG_SUSTAIN_AUTOHEAL"')
293
+ bad = [(rel, p, t.count(p)) for rel, t in prod.items()
294
+ for p in pats if t.count(p)]
295
+ ok(not bad, "G3a 生产源码里零命中「缺省字面量」形态(^ 见 detail)", bad)
296
+ s = _rel_text("md_cg/sustain.py")
297
+ ok("AUTO_DEFAULTS = {" in s, "G3b 真源表在 sustain.py 定义")
298
+ ok(s.count("auto_tidy: bool = AUTO_DEFAULTS[") == 1,
299
+ "G3c SustainLoop 形参默认值引用真源表(不写第二处字面量)")
300
+ m = _rel_text("md_cg/mcp_server.py")
301
+ ok(m.count('auto_tidy=sustain.auto_from_args("auto_tidy", a)') == 1,
302
+ "G3d op 路径恰一处经 auto_from_args 读 auto_tidy")
303
+ ok(m.count('auto_tidy=sustain.auto_from_env("auto_tidy")') == 1,
304
+ "G3e env 路径恰一处经 auto_from_env 读 auto_tidy")
305
+ ok('"auto_tidy", False' not in m and 'auto_tidy=False)' not in m,
306
+ "G3f mcp_server.py 内不再有 auto_tidy 的 False 缺省字面量")
307
+
308
+
309
+ # ---------------------------------------------------------------- G4
310
+ def g4():
311
+ print("== G4 变更披露面(防顺手改多了)==")
312
+ S = globals()["sustain"]
313
+ ok(S.AUTO_DEFAULTS["auto_tidy"] is True,
314
+ "G4 裁决值 = 开:auto_tidy 真源缺省为 True")
315
+ ok(S.AUTO_DEFAULTS["auto_heal"] is True
316
+ and S.AUTO_DEFAULTS["auto_scrub"] is True
317
+ and S.AUTO_DEFAULTS["auto_evolve"] is True,
318
+ "G4a 三项缺省均为 True(heal/scrub/evolve——2026-10-21 裁定改为默认开)",
319
+ S.AUTO_DEFAULTS)
320
+ ok(S.AUTO_ENVS["auto_tidy"] == "MDCG_AUTO_TIDY",
321
+ "G4b opt-out env 名(自真源读)= MDCG_AUTO_TIDY")
322
+ ok(S.auto_from_args("auto_tidy", {"auto_tidy": None}) is False,
323
+ "G4c 显式传 None(键在)→ False,与改动前 bool(a.get(name, default)) 同义")
324
+ ok(S.auto_from_args("auto_tidy", {"other": 1}) is True,
325
+ "G4d 缺键才回落真源缺省(True)")
326
+
327
+
328
+ _GROUPS = (g0, g1, g2, g3, g4)
329
+
330
+
331
+ # ---------------------------------------------------------------- 变异表
332
+ # 锚点 = (名字, 模式, rel, old, new, 预期红项数下限)。
333
+ # "mod" = 改**可执行实现**(exec 成模块并换进 `sys.modules`,供 `from . import` 面读到)
334
+ # "src" = 只改**源码文本**(静态组 G3 读 `_SRC`,不 exec)
335
+ # 「改动前形态」的复现即在这里:
336
+ # M1 把真源表里的 auto_tidy 改回 False(= 旧的 op 路径字面量)
337
+ # M2 让 op 路径读取器不回落真源(= 旧的「另一处字面量」)
338
+ # M3 把 env 路径改回旧的手写 env 读取(= 旧 env 路径形态 + 第二处字面量)
339
+ _MUTATIONS = (
340
+ ("真源表 auto_tidy 改回 False(旧 op 路径值)", "mod", "md_cg/sustain.py",
341
+ '"auto_evolve": True, "auto_tidy": True}',
342
+ '"auto_evolve": False, "auto_tidy": False}', 1),
343
+ ("op 路径读取器不回落真源(旧「另一处字面量」)", "mod", "md_cg/sustain.py",
344
+ " return bool(args[name])\n return auto_default(name)",
345
+ " return bool(args[name])\n return False", 1),
346
+ # 锚点 = **布局无关的唯一子串**:只取到 `("auto_tidy")` 为止,不带尾括号——
347
+ # `ensure_loop(` 的收尾随「单行参数 / 多行关键字实参」而变(现役实现是多行、
348
+ # 行尾 `,`),把 `))` 写进锚点即把变异项钉死在某一版行布局上(S4a 缺陷:
349
+ # 实现改成多行后锚点漂移、`--mutate` 误判为 fail-closed 退出码 2)。
350
+ # 该串在 mcp_server.py 恰 1 处(与 G3e 同一子串,唯一性由 G3e 守卫)。
351
+ ("env 路径改回手写 env 读取(第二处 MDCG_AUTO_TIDY 字面量)", "src",
352
+ "md_cg/mcp_server.py",
353
+ 'auto_tidy=sustain.auto_from_env("auto_tidy")',
354
+ 'auto_tidy=os.environ.get("MDCG_AUTO_TIDY", "1") not in ("0", "false", "False")',
355
+ 1),
356
+ )
357
+
358
+
359
+ def _run_groups() -> int:
360
+ _GEN[0] += 1
361
+ _PASS.clear()
362
+ _FAIL.clear()
363
+ for g in _GROUPS:
364
+ try:
365
+ g()
366
+ except Exception as exc: # noqa: BLE001
367
+ ok(False, "断言组 %s 抛异常:%s" % (g.__name__, exc))
368
+ import traceback
369
+ print(traceback.format_exc()[-800:])
370
+ for mod in (globals().get("sustain"), _REAL_SUSTAIN):
371
+ try:
372
+ mod.stop_all()
373
+ except Exception: # noqa: BLE001
374
+ pass
375
+ return len(_FAIL)
376
+
377
+
378
+ def _exec_module(name: str, rel: str, text: str):
379
+ ns = {"__name__": name, "__package__": "md_cg",
380
+ "__file__": os.path.join(_repo_root(), rel)}
381
+ exec(compile(text, rel, "exec"), ns) # noqa: S102 —— 基线自证用
382
+ m = types.ModuleType(name)
383
+ m.__dict__.update(ns)
384
+ return m
385
+
386
+
387
+ def _mutate_mode(list_only: bool = False) -> int:
388
+ print("!! 定点变异自证:逐条把「单一真源」改回改动前形态,套件必须转红\n")
389
+ if list_only:
390
+ for name, kind, rel, _o, _n, exp in _MUTATIONS:
391
+ print(" %-46s [%s] expect_red>=%d (%s)" % (name, kind, exp, rel))
392
+ return 0
393
+ anchor_miss, bad = [], []
394
+ with contextlib.redirect_stdout(io.StringIO()):
395
+ clean = _run_groups()
396
+ print(" 未变异基线:失败=%d(必须为 0)" % clean)
397
+ if clean:
398
+ bad.append("未变异基线即失败")
399
+
400
+ for name, kind, rel, old, new, expect in _MUTATIONS:
401
+ src = _rel_text(rel)
402
+ if old not in src:
403
+ print(" ANCHOR-MISS %s —— 锚点在 %s 源码里找不到(实现改了却没同步"
404
+ "本表;锚点漂移不得静默)" % (name, rel))
405
+ anchor_miss.append(name)
406
+ continue
407
+ mut_src = src.replace(old, new, 1)
408
+ _SRC[rel] = mut_src
409
+ live = None
410
+ try:
411
+ if kind == "mod":
412
+ live = sys.modules["md_cg.sustain"]
413
+ mut = _exec_module("md_cg._autodef_mut", rel, mut_src)
414
+ sys.modules["md_cg.sustain"] = mut
415
+ globals()["sustain"] = mut
416
+ with contextlib.redirect_stdout(buf := io.StringIO()):
417
+ reds = _run_groups()
418
+ detail = buf.getvalue()
419
+ finally:
420
+ if live is not None:
421
+ sys.modules["md_cg.sustain"] = live
422
+ globals()["sustain"] = _REAL_SUSTAIN
423
+ _SRC.pop(rel, None)
424
+ red_lines = [l for l in detail.splitlines()
425
+ if l.strip().startswith("FAIL ")]
426
+ verdict = "红" if reds else "**仍全绿 = 该判据空转**"
427
+ mark = "OK " if reds >= expect else "MISMATCH"
428
+ print(" %s %-46s 红项=%d 预期>=%d %s"
429
+ % (mark, name, reds, expect, verdict))
430
+ for l in red_lines[:6]:
431
+ print(" " + l.strip()[5:])
432
+ if reds < expect:
433
+ bad.append("%s(红=%d 预期>=%d)" % (name, reds, expect))
434
+
435
+ if anchor_miss:
436
+ print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
437
+ print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
438
+ return 2
439
+ print("\n定点变异自证:%s"
440
+ % ("PASS(每处判据都被打红)" if not bad else "FAIL —— " + "、".join(bad)))
441
+ return 0 if not bad else 1
442
+
443
+
444
+ def main() -> int:
445
+ _sandbox_env()
446
+ try:
447
+ if "--mutate" in sys.argv:
448
+ return _mutate_mode("--list" in sys.argv)
449
+ n = _run_groups()
450
+ print("\nauto_* 缺省单一真源守卫:%d 通过,%d 失败,%d 跳过"
451
+ % (len(_PASS), n, len(_SKIP)))
452
+ return 0 if not n else 1
453
+ finally:
454
+ try:
455
+ _REAL_SUSTAIN.stop_all()
456
+ except Exception: # noqa: BLE001
457
+ pass
458
+ _restore_env()
459
+ shutil.rmtree(_TMP, ignore_errors=True)
460
+
461
+
462
+ if __name__ == "__main__":
463
+ sys.exit(main())