@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,328 +1,328 @@
1
- # -*- coding: utf-8 -*-
2
- """W4 情绪→决策通路守卫:`autonomy.proposals` 的**情绪排序加分** `emotion_bonus`。
3
-
4
- 背景(`docs/eval/W4_情绪决策通路_设计_v0.1.md` + 其末尾「设计者定稿(5 点)」;
5
- `docs/eval/设计者首批裁定_v0.1.md` 第 4 条:只做排序/建议、一处、默认关):
6
- 情绪读数(信息差二阶 `d2`)此前止于读数/卡字段/建议,无命名消费位。本改动在
7
- `proposals()` 的排序键 `sort_score` 上加一个由 `d2_mean=d2_sum/samples` 派生的
8
- `emotion_bonus`(默认 `0.0`),**只加排序分**、不改 `score`(资格定价器)、不改
9
- `gain_gate`(σ(Gain) 筛选)、不改 `explore()` 终态。
10
-
11
- 覆盖(正向):
12
- P1 默认关反向腿:未设 / "0" / "false" ⇒ 与「恒 bonus=0.0 基线」**逐位一致**
13
- P2 开启腿:approaching ⇒ +ε;avoiding ⇒ −ε;stable ⇒ 0.0;|bonus| ≤ ε;
14
- 判别力(异号 ⇒ 排序翻转);确定性;观测面(reason/返回体);台账可回读
15
- P3 资格面不变量:`score` 纯 ΔD、`score<=0` 资格集合开/关逐位同、`gain_gate`
16
- 判据开/关逐位同、`sort_score=score+d_meta+emotion`
17
-
18
- 定点变异自证(`--self-proof`,fail-closed):就地变异**运行中的实现源码**
19
- (`inspect.getsource`,**不读 git**——把基线绑到某提交会在下次改动即失效),
20
- 逐条要求**恰好**命中期望红项;锚点漂移 ⇒ ANCHOR-MISS + 退出码 2。
21
-
22
- 运行:
23
- python -X utf8 -m md_cg.test_autonomy_emotion # 正向
24
- python -X utf8 -m md_cg.test_autonomy_emotion --self-proof # 变异自证
25
- """
26
- from __future__ import annotations
27
-
28
- import contextlib
29
- import inspect
30
- import io
31
- import json
32
- import os
33
- import shutil
34
- import sys
35
- import tempfile
36
- import textwrap
37
-
38
- from . import autonomy, metacognition
39
- from .fsutil import append_jsonl
40
- from .mdcos import MdCGOS
41
-
42
- PASS = FAIL = 0
43
- FAILS = []
44
-
45
-
46
- def ok(label, cond):
47
- global PASS, FAIL
48
- if cond:
49
- PASS += 1
50
- else:
51
- FAIL += 1
52
- FAILS.append(label)
53
- print(f" FAIL {label}")
54
-
55
-
56
- def _sig(cg, t, query, d2, states):
57
- append_jsonl(cg.reflection_log,
58
- {"t": t, "query": query, "d_prev": 1.0, "d_curr": 1.0,
59
- "d_delta": 0.0, "d2": d2, "states": states,
60
- "n_results": 3, "feedback": None})
61
-
62
-
63
- def _root():
64
- return tempfile.mkdtemp(prefix="mdcg_emo_")
65
-
66
-
67
- def _sortface(pl):
68
- """排序面:只取本次改动**不该改变**的既有排序键(反向腿对拍口径)。"""
69
- return [(p["query"], p["score"], p["d_meta_bonus"], p["sort_score"])
70
- for p in pl]
71
-
72
-
73
- def _efaces(pl):
74
- """情绪读数面:跨两次运行须逐位同(确定性)。"""
75
- return [(p["query"], p["emotion_bonus"], p["emotion"]["bias"],
76
- p["emotion"]["d2_mean"]) for p in pl]
77
-
78
-
79
- # ===================== 定点变异基础设施(就地变异运行中的实现源码) =====================
80
- # 锚点定位在**去缩进后的实现源码**上;每条变异声明**期望转红的断言项前缀集**,
81
- # 实跑红项必须与期望**恰好相等**(多红=断言语义纠缠,少红=该判据空转)。
82
- _STRIP = ("emotion_bonus = (round(W_EMO * eps * sign, 4) if emotion_on else 0.0)",
83
- "emotion_bonus = 0.0")
84
- _A_SWITCH = 'emotion_on = os.environ.get(EMOTION_ENV) == "1"'
85
- _A_BONUS = ("emotion_bonus = (round(W_EMO * eps * sign, 4) "
86
- "if emotion_on else 0.0)")
87
- _A_SCORE = 'a["score"] = round(score, 4)'
88
- _ANCHORS = (_A_SWITCH, _A_BONUS, _A_SCORE)
89
-
90
- #: (名, old, new, 期望红项前缀集合)
91
- _MUTATIONS = (
92
- ("①开关忽略环境变量(恒开)", _A_SWITCH, "emotion_on = True",
93
- {"P1.1", "P1.2", "P1.3", "P1.4", "P1.5", "P2.5"}),
94
- ("②去掉 ε 上限(bonus 放大×10)", _A_BONUS,
95
- "emotion_bonus = (round(W_EMO * eps * sign * 10.0, 4) "
96
- "if emotion_on else 0.0)",
97
- {"P2.1", "P2.2", "P2.4"}),
98
- ("③把 emotion_bonus 误加到 score(资格泄漏)", _A_SCORE,
99
- 'a["score"] = round(score + emotion_bonus, 4)',
100
- {"P3.1", "P3.3"}),
101
- )
102
-
103
-
104
- def _source():
105
- return textwrap.dedent(inspect.getsource(autonomy.proposals))
106
-
107
-
108
- def _load_variant(*pairs):
109
- """按 (old,new) 替换对就地生成 proposals 变体(锚点须恰好命中 1 次)。"""
110
- src = _source()
111
- for old, new in pairs:
112
- n = src.count(old)
113
- if n != 1:
114
- raise RuntimeError("ANCHOR 命中 %d 次(期望 1):%r" % (n, old[:60]))
115
- src = src.replace(old, new)
116
- ns = dict(vars(autonomy))
117
- exec(compile(src, "<w4emo-variant>", "exec"), ns) # noqa: S102
118
- return ns["proposals"]
119
-
120
-
121
- def _anchor_preflight():
122
- src = _source()
123
- bad = [(a, src.count(a)) for a in _ANCHORS if src.count(a) != 1]
124
- if not bad:
125
- return 0
126
- for a, n in bad:
127
- print(" ANCHOR-MISS 锚点漂移(命中 %d 次,期望恰好 1):%r" % (n, a[:70]))
128
- print(" => 实现已漂移,变异表失效:退出码 2(fail-closed;请同步 _MUTATIONS 锚点)")
129
- return 2
130
-
131
-
132
- # ===================== 断言组(正向 / 变异体复用同一组) =====================
133
-
134
-
135
- def _group(root, baseline_fn):
136
- """在隔离临时库上跑 P1–P3。`autonomy.proposals` 为实际被测(可被变异重绑),
137
- `baseline_fn` 为「恒 bonus=0.0 基线」(反向腿对拍源,不随变异改变)。"""
138
- cg = MdCGOS(root)
139
- _sig(cg, 1.0, "甲", -0.06, {}) # d2_mean=-0.06 < -0.05 → approaching
140
- _sig(cg, 2.0, "乙", 0.06, {}) # d2_mean=+0.06 > +0.05 → avoiding
141
- _sig(cg, 3.0, "丙", 0.04, {}) # |0.04| < 0.05 → stable
142
- _sig(cg, 4.0, "丁", 0.0, {}) # 零信号 → 不提案(资格面)
143
- eps = metacognition.D2_EMOTION
144
- env_name = autonomy.EMOTION_ENV
145
- saved = os.environ.get(env_name)
146
-
147
- def _set(v):
148
- if v is None:
149
- os.environ.pop(env_name, None)
150
- else:
151
- os.environ[env_name] = v
152
-
153
- try:
154
- # ---------- P1 反向腿:默认关 ⇒ 与「恒 bonus=0.0 基线」逐位一致 ----------
155
- _set(None)
156
- pr_off = autonomy.proposals(cg, limit=10)
157
- base = baseline_fn(cg, limit=10)
158
- off = pr_off["proposals"]
159
- ok("P1.1 默认关(env 未设)每条 emotion_bonus==0.0",
160
- all(p["emotion_bonus"] == 0.0 for p in off))
161
- ok("P1.2 默认关 sort_score == round(score + d_meta_bonus, 4)(逐位退化)",
162
- all(p["sort_score"] == round(p["score"] + p["d_meta_bonus"], 4)
163
- for p in off))
164
- ok("P1.3 默认关:排序面与『恒 bonus=0.0 基线』逐位一致",
165
- _sortface(off) == _sortface(base["proposals"]))
166
- ok("P1.5 默认关:返回体 emotion.enabled is False、cap==ε",
167
- pr_off["emotion"]["enabled"] is False
168
- and pr_off["emotion"]["cap"] == eps)
169
-
170
- _set("0")
171
- pr_off0 = autonomy.proposals(cg, limit=10)
172
- _set("false")
173
- pr_offf = autonomy.proposals(cg, limit=10)
174
- ok("P1.4 非 \"1\"(\"0\"/\"false\")同样恒 0.0 且 sort_score 退化",
175
- all(p["emotion_bonus"] == 0.0
176
- and p["sort_score"] == round(p["score"] + p["d_meta_bonus"], 4)
177
- for p in pr_off0["proposals"] + pr_offf["proposals"])
178
- and pr_off0["emotion"]["enabled"] is False
179
- and pr_offf["emotion"]["enabled"] is False)
180
-
181
- # ---------- P2 开启腿 ----------
182
- _set("1")
183
- pr_on = autonomy.proposals(cg, limit=10)
184
- pr_on2 = autonomy.proposals(cg, limit=10)
185
- on = {p["query"]: p for p in pr_on["proposals"]}
186
- ok("P2.1 approaching(d2_mean<-阈值)→ +ε",
187
- on.get("甲", {}).get("emotion", {}).get("bias") == "approaching"
188
- and on.get("甲", {}).get("emotion_bonus") == round(1.0 * eps, 4)
189
- and on.get("甲", {}).get("emotion", {}).get("d2_mean") == -0.06)
190
- ok("P2.2 avoiding(d2_mean>+阈值)→ −ε",
191
- on.get("乙", {}).get("emotion", {}).get("bias") == "avoiding"
192
- and on.get("乙", {}).get("emotion_bonus") == round(-1.0 * eps, 4))
193
- ok("P2.3 stable(|d2_mean|<=阈值)→ 0.0",
194
- on.get("丙", {}).get("emotion", {}).get("bias") == "stable"
195
- and on.get("丙", {}).get("emotion_bonus") == 0.0)
196
- ok("P2.4 硬上限恒成立 |emotion_bonus| <= ε",
197
- all(abs(p["emotion_bonus"]) <= eps for p in pr_on["proposals"]))
198
- off_order = [p["query"] for p in off]
199
- on_order = [p["query"] for p in pr_on["proposals"]]
200
- ok("P2.5 判别力:异号 d2_mean ⇒ 排序翻转且 approaching 前置",
201
- off_order != on_order and on_order[0] == "甲")
202
- ok("P2.6 确定性:同窗口两次开启跑同值",
203
- _efaces(pr_on["proposals"]) == _efaces(pr_on2["proposals"]))
204
- ok("P2.7 观测面:reason 含情绪读数、返回体含 emotion 块",
205
- all("情绪" in p["reason"] and "d2_mean" in p["reason"]
206
- for p in pr_on["proposals"])
207
- and pr_on["emotion"]["enabled"] is True
208
- and pr_on["emotion"]["w_emo"] == autonomy.W_EMO
209
- and pr_on["emotion"]["cap"] == eps)
210
- need = {"query", "d2_sum", "d2_abs", "blindspot", "defer", "samples",
211
- "last_t", "score", "d_meta_bonus", "sort_score", "reason",
212
- "emotion", "emotion_bonus", "gain_gate"}
213
- ok("P2.8 只增不改:既有键全在,新增 emotion/emotion_bonus",
214
- all(need <= set(p) for p in pr_on["proposals"]))
215
-
216
- # ---------- P3 资格面不变量(开/关对照) ----------
217
- ok("P3.1 score 仍是纯 ΔD 定价(开/关两态逐位不变)",
218
- all(p["score"] == round(autonomy.W_D2 * p["d2_abs"]
219
- + autonomy.W_BLINDSPOT * p["blindspot"]
220
- + autonomy.W_DEFER * p["defer"], 4)
221
- for p in off + pr_on["proposals"]))
222
- ok("P3.2 资格集合不变(score>0 者一致;零信号查询两态均不提案)",
223
- {p["query"] for p in off} == {p["query"] for p in pr_on["proposals"]}
224
- == {"甲", "乙", "丙"}
225
- and pr_off["n_signals"] == pr_on["n_signals"] == 4
226
- and all(p["query"] != "丁" for p in pr_on["proposals"]))
227
- ok("P3.3 sort_score == score + d_meta_bonus + emotion_bonus",
228
- all(p["sort_score"] == round(p["score"] + p["d_meta_bonus"]
229
- + p["emotion_bonus"], 4)
230
- for p in pr_on["proposals"]))
231
- ok("P3.4 gain_gate 判据开/关两态逐位相同(未泄漏进 σ(Gain))",
232
- {p["query"]: p.get("gain_gate") for p in off}
233
- == {p["query"]: p.get("gain_gate") for p in pr_on["proposals"]})
234
-
235
- # ---------- 台账可回读(explore 已把 proposals 原样并入 _explore.jsonl) ----------
236
- autonomy.explore(cg, actor="test")
237
- led = []
238
- with open(autonomy._explore_log_path(cg), encoding="utf-8") as fh:
239
- recs = [json.loads(x) for x in fh if x.strip()]
240
- led = recs[-1]["proposals"] if recs else []
241
- ok("P2.9 台账 _explore.jsonl 回读含 emotion_bonus 与 bias",
242
- bool(led) and all("emotion_bonus" in p and "emotion" in p
243
- for p in led)
244
- and any(p["emotion"]["bias"] == "approaching" for p in led))
245
- finally:
246
- _set(saved)
247
-
248
-
249
- def _run_group(root, baseline_fn):
250
- global PASS, FAIL
251
- PASS = FAIL = 0
252
- del FAILS[:]
253
- _group(root, baseline_fn)
254
- return {n.split(" ", 1)[0] for n in FAILS}
255
-
256
-
257
- # ===================== 定点变异自证(--self-proof) =====================
258
-
259
-
260
- def _self_proof():
261
- rc = _anchor_preflight()
262
- if rc:
263
- return rc
264
- print("!! 定点变异自证:就地变异运行中的实现源码(不读 git),"
265
- "逐条要求恰好命中期望红项\n")
266
- base_fn = _load_variant(_STRIP) # 恒 bonus=0.0 基线(反向腿对拍源)
267
- orig = autonomy.proposals
268
- root = _root()
269
- bad = []
270
- try:
271
- with contextlib.redirect_stdout(io.StringIO()):
272
- base_red = _run_group(root, base_fn)
273
- print(" 未变异基线:红项 %d %s"
274
- % (len(base_red), "(应为 0)" if base_red else ""))
275
- if base_red:
276
- bad.append("未变异基线即转红:%s" % sorted(base_red))
277
- marks = "①②③"
278
- for i, (name, old, new, expect) in enumerate(_MUTATIONS):
279
- mroot = _root() # 每变异体独立库(隔离 explore 台账串味)
280
- try:
281
- autonomy.proposals = _load_variant((old, new))
282
- try:
283
- with contextlib.redirect_stdout(io.StringIO()):
284
- red = _run_group(mroot, base_fn)
285
- except Exception as exc: # noqa: BLE001
286
- red = {"<变异体运行异常:%s>" % type(exc).__name__}
287
- finally:
288
- autonomy.proposals = orig
289
- shutil.rmtree(mroot, ignore_errors=True)
290
- hit = red == expect
291
- if not hit:
292
- bad.append("变异%s %s:红项 %s ≠ 期望 %s"
293
- % (marks[i], name, sorted(red), sorted(expect)))
294
- print(" 变异%s %-40s 红项 %d(期望 %d)%s"
295
- % (marks[i], name, len(red), len(expect),
296
- "PASS" if hit else "**FAIL** 实=%s 期=%s"
297
- % (sorted(red), sorted(expect))))
298
- finally:
299
- autonomy.proposals = orig
300
- shutil.rmtree(root, ignore_errors=True)
301
- print("\n变异自证:%s"
302
- % ("PASS(三处接线逐条恰好命中期望红项)" if not bad
303
- else "FAIL —— " + ";".join(bad)))
304
- return 0 if not bad else 1
305
-
306
-
307
- def main():
308
- print("W4 情绪→决策通路 · proposals 情绪排序加分守卫"
309
- "(默认关逐位一致 + 资格不变量 + 变异自证)")
310
- print("=" * 70)
311
- root = _root()
312
- base_fn = _load_variant(_STRIP)
313
- try:
314
- red = _run_group(root, base_fn)
315
- finally:
316
- shutil.rmtree(root, ignore_errors=True)
317
- print()
318
- if red:
319
- print("FAILED: %d 项 → %s" % (len(FAILS), ", ".join(FAILS)))
320
- return 1
321
- print("ALL OK: %d 项(情绪排序加分守卫全绿)" % PASS)
322
- return 0
323
-
324
-
325
- if __name__ == "__main__":
326
- if "--self-proof" in sys.argv:
327
- sys.exit(_self_proof())
328
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """W4 情绪→决策通路守卫:`autonomy.proposals` 的**情绪排序加分** `emotion_bonus`。
3
+
4
+ 背景(`docs/eval/W4_情绪决策通路_设计_v0.1.md` + 其末尾「设计者定稿(5 点)」;
5
+ `docs/eval/设计者首批裁定_v0.1.md` 第 4 条:只做排序/建议、一处、默认关):
6
+ 情绪读数(信息差二阶 `d2`)此前止于读数/卡字段/建议,无命名消费位。本改动在
7
+ `proposals()` 的排序键 `sort_score` 上加一个由 `d2_mean=d2_sum/samples` 派生的
8
+ `emotion_bonus`(默认 `0.0`),**只加排序分**、不改 `score`(资格定价器)、不改
9
+ `gain_gate`(σ(Gain) 筛选)、不改 `explore()` 终态。
10
+
11
+ 覆盖(正向):
12
+ P1 默认关反向腿:未设 / "0" / "false" ⇒ 与「恒 bonus=0.0 基线」**逐位一致**
13
+ P2 开启腿:approaching ⇒ +ε;avoiding ⇒ −ε;stable ⇒ 0.0;|bonus| ≤ ε;
14
+ 判别力(异号 ⇒ 排序翻转);确定性;观测面(reason/返回体);台账可回读
15
+ P3 资格面不变量:`score` 纯 ΔD、`score<=0` 资格集合开/关逐位同、`gain_gate`
16
+ 判据开/关逐位同、`sort_score=score+d_meta+emotion`
17
+
18
+ 定点变异自证(`--self-proof`,fail-closed):就地变异**运行中的实现源码**
19
+ (`inspect.getsource`,**不读 git**——把基线绑到某提交会在下次改动即失效),
20
+ 逐条要求**恰好**命中期望红项;锚点漂移 ⇒ ANCHOR-MISS + 退出码 2。
21
+
22
+ 运行:
23
+ python -X utf8 -m md_cg.test_autonomy_emotion # 正向
24
+ python -X utf8 -m md_cg.test_autonomy_emotion --self-proof # 变异自证
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import contextlib
29
+ import inspect
30
+ import io
31
+ import json
32
+ import os
33
+ import shutil
34
+ import sys
35
+ import tempfile
36
+ import textwrap
37
+
38
+ from . import autonomy, metacognition
39
+ from .fsutil import append_jsonl
40
+ from .mdcos import MdCGOS
41
+
42
+ PASS = FAIL = 0
43
+ FAILS = []
44
+
45
+
46
+ def ok(label, cond):
47
+ global PASS, FAIL
48
+ if cond:
49
+ PASS += 1
50
+ else:
51
+ FAIL += 1
52
+ FAILS.append(label)
53
+ print(f" FAIL {label}")
54
+
55
+
56
+ def _sig(cg, t, query, d2, states):
57
+ append_jsonl(cg.reflection_log,
58
+ {"t": t, "query": query, "d_prev": 1.0, "d_curr": 1.0,
59
+ "d_delta": 0.0, "d2": d2, "states": states,
60
+ "n_results": 3, "feedback": None})
61
+
62
+
63
+ def _root():
64
+ return tempfile.mkdtemp(prefix="mdcg_emo_")
65
+
66
+
67
+ def _sortface(pl):
68
+ """排序面:只取本次改动**不该改变**的既有排序键(反向腿对拍口径)。"""
69
+ return [(p["query"], p["score"], p["d_meta_bonus"], p["sort_score"])
70
+ for p in pl]
71
+
72
+
73
+ def _efaces(pl):
74
+ """情绪读数面:跨两次运行须逐位同(确定性)。"""
75
+ return [(p["query"], p["emotion_bonus"], p["emotion"]["bias"],
76
+ p["emotion"]["d2_mean"]) for p in pl]
77
+
78
+
79
+ # ===================== 定点变异基础设施(就地变异运行中的实现源码) =====================
80
+ # 锚点定位在**去缩进后的实现源码**上;每条变异声明**期望转红的断言项前缀集**,
81
+ # 实跑红项必须与期望**恰好相等**(多红=断言语义纠缠,少红=该判据空转)。
82
+ _STRIP = ("emotion_bonus = (round(W_EMO * eps * sign, 4) if emotion_on else 0.0)",
83
+ "emotion_bonus = 0.0")
84
+ _A_SWITCH = 'emotion_on = os.environ.get(EMOTION_ENV) == "1"'
85
+ _A_BONUS = ("emotion_bonus = (round(W_EMO * eps * sign, 4) "
86
+ "if emotion_on else 0.0)")
87
+ _A_SCORE = 'a["score"] = round(score, 4)'
88
+ _ANCHORS = (_A_SWITCH, _A_BONUS, _A_SCORE)
89
+
90
+ #: (名, old, new, 期望红项前缀集合)
91
+ _MUTATIONS = (
92
+ ("①开关忽略环境变量(恒开)", _A_SWITCH, "emotion_on = True",
93
+ {"P1.1", "P1.2", "P1.3", "P1.4", "P1.5", "P2.5"}),
94
+ ("②去掉 ε 上限(bonus 放大×10)", _A_BONUS,
95
+ "emotion_bonus = (round(W_EMO * eps * sign * 10.0, 4) "
96
+ "if emotion_on else 0.0)",
97
+ {"P2.1", "P2.2", "P2.4"}),
98
+ ("③把 emotion_bonus 误加到 score(资格泄漏)", _A_SCORE,
99
+ 'a["score"] = round(score + emotion_bonus, 4)',
100
+ {"P3.1", "P3.3"}),
101
+ )
102
+
103
+
104
+ def _source():
105
+ return textwrap.dedent(inspect.getsource(autonomy.proposals))
106
+
107
+
108
+ def _load_variant(*pairs):
109
+ """按 (old,new) 替换对就地生成 proposals 变体(锚点须恰好命中 1 次)。"""
110
+ src = _source()
111
+ for old, new in pairs:
112
+ n = src.count(old)
113
+ if n != 1:
114
+ raise RuntimeError("ANCHOR 命中 %d 次(期望 1):%r" % (n, old[:60]))
115
+ src = src.replace(old, new)
116
+ ns = dict(vars(autonomy))
117
+ exec(compile(src, "<w4emo-variant>", "exec"), ns) # noqa: S102
118
+ return ns["proposals"]
119
+
120
+
121
+ def _anchor_preflight():
122
+ src = _source()
123
+ bad = [(a, src.count(a)) for a in _ANCHORS if src.count(a) != 1]
124
+ if not bad:
125
+ return 0
126
+ for a, n in bad:
127
+ print(" ANCHOR-MISS 锚点漂移(命中 %d 次,期望恰好 1):%r" % (n, a[:70]))
128
+ print(" => 实现已漂移,变异表失效:退出码 2(fail-closed;请同步 _MUTATIONS 锚点)")
129
+ return 2
130
+
131
+
132
+ # ===================== 断言组(正向 / 变异体复用同一组) =====================
133
+
134
+
135
+ def _group(root, baseline_fn):
136
+ """在隔离临时库上跑 P1–P3。`autonomy.proposals` 为实际被测(可被变异重绑),
137
+ `baseline_fn` 为「恒 bonus=0.0 基线」(反向腿对拍源,不随变异改变)。"""
138
+ cg = MdCGOS(root)
139
+ _sig(cg, 1.0, "甲", -0.06, {}) # d2_mean=-0.06 < -0.05 → approaching
140
+ _sig(cg, 2.0, "乙", 0.06, {}) # d2_mean=+0.06 > +0.05 → avoiding
141
+ _sig(cg, 3.0, "丙", 0.04, {}) # |0.04| < 0.05 → stable
142
+ _sig(cg, 4.0, "丁", 0.0, {}) # 零信号 → 不提案(资格面)
143
+ eps = metacognition.D2_EMOTION
144
+ env_name = autonomy.EMOTION_ENV
145
+ saved = os.environ.get(env_name)
146
+
147
+ def _set(v):
148
+ if v is None:
149
+ os.environ.pop(env_name, None)
150
+ else:
151
+ os.environ[env_name] = v
152
+
153
+ try:
154
+ # ---------- P1 反向腿:默认关 ⇒ 与「恒 bonus=0.0 基线」逐位一致 ----------
155
+ _set(None)
156
+ pr_off = autonomy.proposals(cg, limit=10)
157
+ base = baseline_fn(cg, limit=10)
158
+ off = pr_off["proposals"]
159
+ ok("P1.1 默认关(env 未设)每条 emotion_bonus==0.0",
160
+ all(p["emotion_bonus"] == 0.0 for p in off))
161
+ ok("P1.2 默认关 sort_score == round(score + d_meta_bonus, 4)(逐位退化)",
162
+ all(p["sort_score"] == round(p["score"] + p["d_meta_bonus"], 4)
163
+ for p in off))
164
+ ok("P1.3 默认关:排序面与『恒 bonus=0.0 基线』逐位一致",
165
+ _sortface(off) == _sortface(base["proposals"]))
166
+ ok("P1.5 默认关:返回体 emotion.enabled is False、cap==ε",
167
+ pr_off["emotion"]["enabled"] is False
168
+ and pr_off["emotion"]["cap"] == eps)
169
+
170
+ _set("0")
171
+ pr_off0 = autonomy.proposals(cg, limit=10)
172
+ _set("false")
173
+ pr_offf = autonomy.proposals(cg, limit=10)
174
+ ok("P1.4 非 \"1\"(\"0\"/\"false\")同样恒 0.0 且 sort_score 退化",
175
+ all(p["emotion_bonus"] == 0.0
176
+ and p["sort_score"] == round(p["score"] + p["d_meta_bonus"], 4)
177
+ for p in pr_off0["proposals"] + pr_offf["proposals"])
178
+ and pr_off0["emotion"]["enabled"] is False
179
+ and pr_offf["emotion"]["enabled"] is False)
180
+
181
+ # ---------- P2 开启腿 ----------
182
+ _set("1")
183
+ pr_on = autonomy.proposals(cg, limit=10)
184
+ pr_on2 = autonomy.proposals(cg, limit=10)
185
+ on = {p["query"]: p for p in pr_on["proposals"]}
186
+ ok("P2.1 approaching(d2_mean<-阈值)→ +ε",
187
+ on.get("甲", {}).get("emotion", {}).get("bias") == "approaching"
188
+ and on.get("甲", {}).get("emotion_bonus") == round(1.0 * eps, 4)
189
+ and on.get("甲", {}).get("emotion", {}).get("d2_mean") == -0.06)
190
+ ok("P2.2 avoiding(d2_mean>+阈值)→ −ε",
191
+ on.get("乙", {}).get("emotion", {}).get("bias") == "avoiding"
192
+ and on.get("乙", {}).get("emotion_bonus") == round(-1.0 * eps, 4))
193
+ ok("P2.3 stable(|d2_mean|<=阈值)→ 0.0",
194
+ on.get("丙", {}).get("emotion", {}).get("bias") == "stable"
195
+ and on.get("丙", {}).get("emotion_bonus") == 0.0)
196
+ ok("P2.4 硬上限恒成立 |emotion_bonus| <= ε",
197
+ all(abs(p["emotion_bonus"]) <= eps for p in pr_on["proposals"]))
198
+ off_order = [p["query"] for p in off]
199
+ on_order = [p["query"] for p in pr_on["proposals"]]
200
+ ok("P2.5 判别力:异号 d2_mean ⇒ 排序翻转且 approaching 前置",
201
+ off_order != on_order and on_order[0] == "甲")
202
+ ok("P2.6 确定性:同窗口两次开启跑同值",
203
+ _efaces(pr_on["proposals"]) == _efaces(pr_on2["proposals"]))
204
+ ok("P2.7 观测面:reason 含情绪读数、返回体含 emotion 块",
205
+ all("情绪" in p["reason"] and "d2_mean" in p["reason"]
206
+ for p in pr_on["proposals"])
207
+ and pr_on["emotion"]["enabled"] is True
208
+ and pr_on["emotion"]["w_emo"] == autonomy.W_EMO
209
+ and pr_on["emotion"]["cap"] == eps)
210
+ need = {"query", "d2_sum", "d2_abs", "blindspot", "defer", "samples",
211
+ "last_t", "score", "d_meta_bonus", "sort_score", "reason",
212
+ "emotion", "emotion_bonus", "gain_gate"}
213
+ ok("P2.8 只增不改:既有键全在,新增 emotion/emotion_bonus",
214
+ all(need <= set(p) for p in pr_on["proposals"]))
215
+
216
+ # ---------- P3 资格面不变量(开/关对照) ----------
217
+ ok("P3.1 score 仍是纯 ΔD 定价(开/关两态逐位不变)",
218
+ all(p["score"] == round(autonomy.W_D2 * p["d2_abs"]
219
+ + autonomy.W_BLINDSPOT * p["blindspot"]
220
+ + autonomy.W_DEFER * p["defer"], 4)
221
+ for p in off + pr_on["proposals"]))
222
+ ok("P3.2 资格集合不变(score>0 者一致;零信号查询两态均不提案)",
223
+ {p["query"] for p in off} == {p["query"] for p in pr_on["proposals"]}
224
+ == {"甲", "乙", "丙"}
225
+ and pr_off["n_signals"] == pr_on["n_signals"] == 4
226
+ and all(p["query"] != "丁" for p in pr_on["proposals"]))
227
+ ok("P3.3 sort_score == score + d_meta_bonus + emotion_bonus",
228
+ all(p["sort_score"] == round(p["score"] + p["d_meta_bonus"]
229
+ + p["emotion_bonus"], 4)
230
+ for p in pr_on["proposals"]))
231
+ ok("P3.4 gain_gate 判据开/关两态逐位相同(未泄漏进 σ(Gain))",
232
+ {p["query"]: p.get("gain_gate") for p in off}
233
+ == {p["query"]: p.get("gain_gate") for p in pr_on["proposals"]})
234
+
235
+ # ---------- 台账可回读(explore 已把 proposals 原样并入 _explore.jsonl) ----------
236
+ autonomy.explore(cg, actor="test")
237
+ led = []
238
+ with open(autonomy._explore_log_path(cg), encoding="utf-8") as fh:
239
+ recs = [json.loads(x) for x in fh if x.strip()]
240
+ led = recs[-1]["proposals"] if recs else []
241
+ ok("P2.9 台账 _explore.jsonl 回读含 emotion_bonus 与 bias",
242
+ bool(led) and all("emotion_bonus" in p and "emotion" in p
243
+ for p in led)
244
+ and any(p["emotion"]["bias"] == "approaching" for p in led))
245
+ finally:
246
+ _set(saved)
247
+
248
+
249
+ def _run_group(root, baseline_fn):
250
+ global PASS, FAIL
251
+ PASS = FAIL = 0
252
+ del FAILS[:]
253
+ _group(root, baseline_fn)
254
+ return {n.split(" ", 1)[0] for n in FAILS}
255
+
256
+
257
+ # ===================== 定点变异自证(--self-proof) =====================
258
+
259
+
260
+ def _self_proof():
261
+ rc = _anchor_preflight()
262
+ if rc:
263
+ return rc
264
+ print("!! 定点变异自证:就地变异运行中的实现源码(不读 git),"
265
+ "逐条要求恰好命中期望红项\n")
266
+ base_fn = _load_variant(_STRIP) # 恒 bonus=0.0 基线(反向腿对拍源)
267
+ orig = autonomy.proposals
268
+ root = _root()
269
+ bad = []
270
+ try:
271
+ with contextlib.redirect_stdout(io.StringIO()):
272
+ base_red = _run_group(root, base_fn)
273
+ print(" 未变异基线:红项 %d %s"
274
+ % (len(base_red), "(应为 0)" if base_red else ""))
275
+ if base_red:
276
+ bad.append("未变异基线即转红:%s" % sorted(base_red))
277
+ marks = "①②③"
278
+ for i, (name, old, new, expect) in enumerate(_MUTATIONS):
279
+ mroot = _root() # 每变异体独立库(隔离 explore 台账串味)
280
+ try:
281
+ autonomy.proposals = _load_variant((old, new))
282
+ try:
283
+ with contextlib.redirect_stdout(io.StringIO()):
284
+ red = _run_group(mroot, base_fn)
285
+ except Exception as exc: # noqa: BLE001
286
+ red = {"<变异体运行异常:%s>" % type(exc).__name__}
287
+ finally:
288
+ autonomy.proposals = orig
289
+ shutil.rmtree(mroot, ignore_errors=True)
290
+ hit = red == expect
291
+ if not hit:
292
+ bad.append("变异%s %s:红项 %s ≠ 期望 %s"
293
+ % (marks[i], name, sorted(red), sorted(expect)))
294
+ print(" 变异%s %-40s 红项 %d(期望 %d)%s"
295
+ % (marks[i], name, len(red), len(expect),
296
+ "PASS" if hit else "**FAIL** 实=%s 期=%s"
297
+ % (sorted(red), sorted(expect))))
298
+ finally:
299
+ autonomy.proposals = orig
300
+ shutil.rmtree(root, ignore_errors=True)
301
+ print("\n变异自证:%s"
302
+ % ("PASS(三处接线逐条恰好命中期望红项)" if not bad
303
+ else "FAIL —— " + ";".join(bad)))
304
+ return 0 if not bad else 1
305
+
306
+
307
+ def main():
308
+ print("W4 情绪→决策通路 · proposals 情绪排序加分守卫"
309
+ "(默认关逐位一致 + 资格不变量 + 变异自证)")
310
+ print("=" * 70)
311
+ root = _root()
312
+ base_fn = _load_variant(_STRIP)
313
+ try:
314
+ red = _run_group(root, base_fn)
315
+ finally:
316
+ shutil.rmtree(root, ignore_errors=True)
317
+ print()
318
+ if red:
319
+ print("FAILED: %d 项 → %s" % (len(FAILS), ", ".join(FAILS)))
320
+ return 1
321
+ print("ALL OK: %d 项(情绪排序加分守卫全绿)" % PASS)
322
+ return 0
323
+
324
+
325
+ if __name__ == "__main__":
326
+ if "--self-proof" in sys.argv:
327
+ sys.exit(_self_proof())
328
+ sys.exit(main())