@furongjun1999/dsh-memory 0.9.6 → 0.9.7

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 (216) hide show
  1. package/data/policy.json +38 -38
  2. package/docs/discipline/templates/spec.txt.tmpl +1 -1
  3. package/dsh/cordis.yml.example +139 -139
  4. package/lib/hooks.d.ts +19 -0
  5. package/lib/hooks.js +29 -6
  6. package/lib/index.js +11 -2
  7. package/lib/lib/hook_audit.js +38 -2
  8. package/lib/lib/prompt_safety.js +14 -3
  9. package/lib/tools.d.ts +7 -0
  10. package/lib/tools.js +22 -1
  11. package/md_cg/_guard_kit.py +121 -121
  12. package/md_cg/anchor.py +114 -114
  13. package/md_cg/audit.py +15 -2
  14. package/md_cg/chain.py +3 -2
  15. package/md_cg/config_registry_guard.py +487 -487
  16. package/md_cg/conformance.py +747 -747
  17. package/md_cg/consolidate.py +1793 -1793
  18. package/md_cg/crypto.py +794 -794
  19. package/md_cg/hyperedge.py +262 -262
  20. package/md_cg/interface_schema.py +146 -146
  21. package/md_cg/lifecycle.py +426 -426
  22. package/md_cg/mdcos.py +12 -8
  23. package/md_cg/predict.py +1103 -1103
  24. package/md_cg/protect.py +654 -654
  25. package/md_cg/provenance.py +606 -606
  26. package/md_cg/queue_health.py +130 -130
  27. package/md_cg/refine.py +613 -613
  28. package/md_cg/retrieve.py +128 -128
  29. package/md_cg/revise.py +140 -140
  30. package/md_cg/rollback.py +657 -657
  31. package/md_cg/rollback_cli.py +124 -124
  32. package/md_cg/rotate.py +346 -346
  33. package/md_cg/routing.py +490 -490
  34. package/md_cg/self_surface.py +50 -50
  35. package/md_cg/semantic/canonical.py +144 -144
  36. package/md_cg/semantic/zh_en_atoms.py +141 -141
  37. package/md_cg/sources.py +1091 -1091
  38. package/md_cg/stg.py +3 -2
  39. package/md_cg/test_audit_rotate_parity.py +279 -279
  40. package/md_cg/test_autonomy_modes.py +2013 -2013
  41. package/md_cg/test_cn_recall_grams.py +206 -206
  42. package/md_cg/test_code_kind_forbidden.py +101 -0
  43. package/md_cg/test_condaccept.py +156 -156
  44. package/md_cg/test_condgate.py +141 -141
  45. package/md_cg/test_heartbeat_ledger.py +557 -557
  46. package/md_cg/test_i50e_readside_protection.py +658 -658
  47. package/md_cg/test_issue111_gate_order.py +76 -76
  48. package/md_cg/test_issue111_scoring_contract.py +86 -86
  49. package/md_cg/test_issue121_calibration_bounds.py +293 -293
  50. package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
  51. package/md_cg/test_issue147_pack_id_escape.py +378 -378
  52. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
  53. package/md_cg/test_issue149_accel_default_face.py +248 -248
  54. package/md_cg/test_issue150_empty_query_terms.py +328 -328
  55. package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
  56. package/md_cg/test_issue152_sealed_postings.py +309 -309
  57. package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
  58. package/md_cg/test_issue157b_index_remainder.py +344 -344
  59. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
  60. package/md_cg/test_issue191_import_trust.py +382 -382
  61. package/md_cg/test_issue193_write_scope.py +378 -378
  62. package/md_cg/test_issue212_writeface_gaps.py +349 -349
  63. package/md_cg/test_issue214_reject_sensitivity.py +266 -266
  64. package/md_cg/test_issue215_condition_source_gap.py +272 -272
  65. package/md_cg/test_issue216_clash_routes.py +214 -214
  66. package/md_cg/test_issue217_slot_routes.py +248 -248
  67. package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
  68. package/md_cg/test_issue258_pack_sensitivity.py +468 -468
  69. package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
  70. package/md_cg/test_issue274_read_node_id_none.py +341 -341
  71. package/md_cg/test_issue275_layer_param.py +250 -250
  72. package/md_cg/test_issue277_node_id_traversal.py +384 -384
  73. package/md_cg/test_issue278_neg_separated_tension.py +271 -271
  74. package/md_cg/test_issue278_neg_window.py +294 -294
  75. package/md_cg/test_issue278_negative_layering.py +83 -83
  76. package/md_cg/test_issue284_skip_not_pass.py +291 -291
  77. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
  78. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
  79. package/md_cg/test_issue303_design_boundaries.py +262 -262
  80. package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
  81. package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
  82. package/md_cg/test_issue321_mcp_deep_json.py +304 -304
  83. package/md_cg/test_issue322_node_write_lock.py +727 -727
  84. package/md_cg/test_issue324_write_size_fields.py +214 -214
  85. package/md_cg/test_issue325_audit_poison.py +229 -229
  86. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
  87. package/md_cg/test_issue326_key_perms.py +355 -355
  88. package/md_cg/test_issue326_twin_parser_parity.py +323 -323
  89. package/md_cg/test_issue326_vm_call_frame.py +569 -569
  90. package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
  91. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
  92. package/md_cg/test_issue348_insight_verify_op.py +199 -199
  93. package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
  94. package/md_cg/test_issue350_casefold_collision.py +235 -235
  95. package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
  96. package/md_cg/test_issue352_imgaudit.py +418 -418
  97. package/md_cg/test_issue352_pathsjson.py +537 -537
  98. package/md_cg/test_issue352_refindex.py +412 -412
  99. package/md_cg/test_issue352_rollback.py +604 -604
  100. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
  101. package/md_cg/test_issue354_rust_index_containment.py +571 -571
  102. package/md_cg/test_issue354_rust_wal_containment.py +606 -606
  103. package/md_cg/test_issue358_truncation_observable.py +247 -247
  104. package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
  105. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
  106. package/md_cg/test_issue362_neg_condition.py +468 -468
  107. package/md_cg/test_issue363_lexical_idf.py +275 -275
  108. package/md_cg/test_issue370_readcache_assembly.py +488 -488
  109. package/md_cg/test_issue376_heartbeat_failed.py +293 -293
  110. package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
  111. package/md_cg/test_issue378_protected_floor.py +310 -310
  112. package/md_cg/test_issue383_state_event_write_gate.py +462 -462
  113. package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
  114. package/md_cg/test_issue398_toolface_op_parity.py +511 -511
  115. package/md_cg/test_issue399_hive_json_shape.py +317 -317
  116. package/md_cg/test_issue401_wisdom_codegen.py +295 -295
  117. package/md_cg/test_issue404_heal_receipt.py +389 -389
  118. package/md_cg/test_issue409_compact_index_completeness.py +509 -509
  119. package/md_cg/test_issue410_verify_demote_write.py +366 -366
  120. package/md_cg/test_issue411_scrub_idempotence.py +575 -575
  121. package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
  122. package/md_cg/test_issue413_preimage_failclosed.py +239 -239
  123. package/md_cg/test_issue413_preimage_twin.py +339 -339
  124. package/md_cg/test_issue415_deps_gate_probe.py +357 -357
  125. package/md_cg/test_issue416_entry_key_subset.py +525 -525
  126. package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
  127. package/md_cg/test_issue425_ingest_library_path.py +331 -331
  128. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
  129. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
  130. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
  131. package/md_cg/test_issue427_serve_status_shape.py +191 -191
  132. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
  133. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
  134. package/md_cg/test_issue434_435_float_gate.py +90 -90
  135. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
  136. package/md_cg/test_issue43_default_policy.py +874 -874
  137. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
  138. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
  139. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
  140. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
  141. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
  142. package/md_cg/test_issue451_audit_actor.py +313 -313
  143. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
  144. package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
  145. package/md_cg/test_issue466_basis_registry.py +469 -469
  146. package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
  147. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
  148. package/md_cg/test_issue470_wal_event_durable.py +427 -427
  149. package/md_cg/test_issue471_identity_readable.py +136 -136
  150. package/md_cg/test_issue472_audit_chain.py +90 -90
  151. package/md_cg/test_issue472_prune_ledger.py +105 -105
  152. package/md_cg/test_issue472_rollback_degraded.py +81 -81
  153. package/md_cg/test_issue491_compose_sandbox.py +460 -460
  154. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
  155. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
  156. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
  157. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
  158. package/md_cg/test_issue525_read_null_semantics.py +52 -52
  159. package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
  160. package/md_cg/test_issue547_audit_durable.py +96 -96
  161. package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
  162. package/md_cg/test_issue559_refine_prefix.py +69 -69
  163. package/md_cg/test_issue562_retired_faces.py +150 -0
  164. package/md_cg/test_issue71_queue_backlog.py +376 -376
  165. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
  166. package/md_cg/test_issue82_credential_rules.py +271 -271
  167. package/md_cg/test_issue91_verifier_sandbox.py +314 -314
  168. package/md_cg/test_issue93_remember_redaction.py +282 -282
  169. package/md_cg/test_logref.py +1141 -1141
  170. package/md_cg/test_md_access_parity.py +330 -330
  171. package/md_cg/test_md_cg_no_hive_dep.py +139 -139
  172. package/md_cg/test_mutation_residue.py +119 -119
  173. package/md_cg/test_mutation_rollback.py +835 -835
  174. package/md_cg/test_n123_derive_expiry_chain.py +210 -210
  175. package/md_cg/test_n209_verify_write_face_gates.py +466 -466
  176. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  177. package/md_cg/test_neg_tail_honesty.py +733 -733
  178. package/md_cg/test_p21_tokens.py +294 -294
  179. package/md_cg/test_p27_docindex.py +792 -792
  180. package/md_cg/test_p28_refcheck.py +1053 -1053
  181. package/md_cg/test_p2_six_elements.py +476 -476
  182. package/md_cg/test_p33_ccg_wiring.py +300 -300
  183. package/md_cg/test_p3_legacy_closure.py +438 -438
  184. package/md_cg/test_p40_refine_worklist.py +244 -244
  185. package/md_cg/test_p4_freshness.py +781 -781
  186. package/md_cg/test_p9c_dedup_hints.py +288 -288
  187. package/md_cg/test_policy_required_ccg.py +444 -444
  188. package/md_cg/test_retr_s5.py +312 -312
  189. package/md_cg/test_s1_ast_judge.py +109 -109
  190. package/md_cg/test_state_event_op.py +521 -521
  191. package/md_cg/test_stgidx_index_parity.py +1024 -1024
  192. package/md_cg/test_sustain_bounded.py +652 -652
  193. package/md_cg/test_trust_edge_reachability.py +405 -405
  194. package/md_cg/test_w7_redlines.py +659 -659
  195. package/md_cg/test_write_return_shape.py +919 -919
  196. package/md_cg/test_writepipe.py +228 -228
  197. package/md_cg/trust.py +1114 -1114
  198. package/md_cg/twophase.py +303 -303
  199. package/md_cg/whitebox.py +536 -536
  200. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
  201. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
  202. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
  203. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
  204. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
  205. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
  206. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
  207. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
  208. package/md_cg/writepipe.py +1337 -1337
  209. package/package.json +3 -2
  210. package/scripts/workspace_index.py +328 -0
  211. package/src/hooks.ts +30 -6
  212. package/src/index.ts +14 -5
  213. package/src/lib/hook_audit.ts +282 -256
  214. package/src/lib/mdcg_client.ts +469 -469
  215. package/src/lib/prompt_safety.ts +17 -3
  216. package/src/tools.ts +23 -1
@@ -1,557 +1,557 @@
1
- # -*- coding: utf-8 -*-
2
- """心跳台账(append-only · 有界分片轮转)守卫 —— 让「连续 N 周期无断」可严格测得。
3
-
4
- 背景(答卷 `docs/plans/灵枢1.0_最小智能系统实存答卷_v1.1.md` §八 分诊第 4 项,
5
- **甲类能力缺口**;取证 `docs/eval/W7v11_结构面局限取证_v0.1.md` §丁):
6
- `_sustain.jsonl` 是 heal **动作**台账(有动作才写,平静期与停摆期不可区分),心跳戳
7
- 是**覆盖式单点**(无历史序列)——「连续 N 周期无断」在现数据结构下**不可严格测得**。
8
- 补法=给心跳加 **append-only 台账**(`<root>/_heartbeat.jsonl`),配合**分片轮转+
9
- 保留片数上限**(有界)与**只读统计**。
10
-
11
- 断言面(每条=一个可定点变异的判据):
12
- L1 **零判定变更**(硬门):台账**开/关**下,`beat()` 返回、心跳戳字段、
13
- `_sustain.jsonl` 既有记录、`judge()`/`heal()`/`diagnose()` 的返回**逐位一致**
14
- (依 `root`/时间戳等天然差异字段外)。
15
- L2 **append-only**:台账只追加——旧字节是新内容的**前缀**,行数==写入次数,
16
- 历史行不被改写。
17
- L3 **断点可检出**:注入一个人为断档(周期缺失 > 阈值)后,`heartbeat_ledger_stats`
18
- **报出断点**且最长连续区间**缩短**。
19
- L4 **有界**(硬门):超轮转阈值后分片产生、保留片数受上限约束(淘汰有痕,
20
- 不静默丢);`HEARTBEAT_ROTATE_BYTES=0` 为显式退回无上界开关。
21
-
22
- 运行:python -X utf8 -m md_cg.test_heartbeat_ledger
23
- python -X utf8 -m md_cg.test_heartbeat_ledger --mutate # 定点变异自证
24
- python -X utf8 -m md_cg.test_heartbeat_ledger --mutate --list # 只列变异表
25
-
26
- 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
27
- 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,不得静默跳过)。
28
-
29
- **基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
30
- **定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
31
- **沙箱纪律**:库根/辅助根/状态根/心跳目录全落守卫临时目录,绝不碰在役库与 `~/.mdcg`。
32
- """
33
- from __future__ import annotations
34
-
35
- import contextlib
36
- import io
37
- import json
38
- import os
39
- import shutil
40
- import sys
41
- import tempfile
42
- import types
43
-
44
- from . import sustain
45
- from .fsutil import read_jsonl
46
-
47
- _PASS = []
48
- _FAIL = []
49
- _SRC = {} # 变异模式下的源码文本(rel → text)
50
- _REAL = sustain
51
- _ORIG = {n: getattr(sustain, n) for n in (
52
- "HEARTBEAT_ROTATE_BYTES", "HEARTBEAT_KEEP_SHARDS", "HEARTBEAT_PROBE_EVERY",
53
- "HEARTBEAT_GAP_THRESHOLD")}
54
-
55
-
56
- def ok(cond, msg, extra=""):
57
- (_PASS if cond else _FAIL).append(msg)
58
- print((" PASS " if cond else " FAIL ") + msg
59
- + ((" ← " + str(extra)) if (extra and not cond) else ""))
60
-
61
-
62
- def _repo_root() -> str:
63
- return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
64
-
65
-
66
- def _rel_text(rel: str) -> str:
67
- if rel in _SRC:
68
- return _SRC[rel]
69
- with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
70
- return f.read()
71
-
72
-
73
- # ---------------------------------------------------------------- 沙箱
74
- _TMP = tempfile.mkdtemp(prefix="mdcg_hbledger_")
75
- _SAVED = {}
76
- _GEN = [0]
77
- _ENV_KEYS = ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
78
- "MDCG_HEARTBEAT_LEDGER")
79
-
80
-
81
- def _sandbox_env():
82
- for k in _ENV_KEYS:
83
- _SAVED[k] = os.environ.get(k)
84
- os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
85
- os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
86
- os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
87
- os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
88
- os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
89
-
90
-
91
- def _restore_env():
92
- for k, v in _SAVED.items():
93
- if v is None:
94
- os.environ.pop(k, None)
95
- else:
96
- os.environ[k] = v
97
-
98
-
99
- def _fresh_root(tag):
100
- """每轮用**全新根**(同一根跨轮复用会读到上一轮残留而假绿)。"""
101
- _GEN[0] += 1
102
- root = os.path.join(_TMP, "gen%d" % _GEN[0], tag)
103
- os.makedirs(root, exist_ok=True)
104
- return root
105
-
106
-
107
- def _netdir(tag):
108
- d = os.path.join(_TMP, "net", tag)
109
- os.makedirs(d, exist_ok=True)
110
- return d
111
-
112
-
113
- # ---------------------------------------------------------------- 投影
114
- #: 天然随运行变化的字段(路径/时间戳)——零判定变更比对应**排除**它们,其余逐位比。
115
- _VOLATILE = ("ts", "iso", "uptime", "t", "age", "mtime", "updated_at",
116
- "last_t", "root", "path", "started_at")
117
-
118
-
119
- def _strip(v):
120
- if isinstance(v, dict):
121
- return {k: _strip(x) for k, x in v.items() if k not in _VOLATILE}
122
- if isinstance(v, list):
123
- return [_strip(x) for x in v]
124
- return v
125
-
126
-
127
- def _canon(v, root):
128
- """把该跑的库根路径归一为 <ROOT>——两跑库根不同,路径差异不算判定差异。"""
129
- s = json.dumps(_strip(v), ensure_ascii=False, sort_keys=True)
130
- for form in (root, root.replace(os.sep, "/")):
131
- s = s.replace(json.dumps(form)[1:-1], "<ROOT>")
132
- return s
133
-
134
-
135
- # ---------------------------------------------------------------- G0 基线
136
- def g0():
137
- print("== G0 隔离与基线自证 ==")
138
- S = globals()["sustain"]
139
- ok(S.heartbeat_ledger_enabled() is True,
140
- "G0a 缺省开:未设 MDCG_HEARTBEAT_LEDGER 时台账启用")
141
- ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": off}) is False
142
- for off in ("0", "false", "False")),
143
- "G0b 关断字面量 0/false/False 均关(沿用 AUTO_OFF_VALUES 口径)")
144
- ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": on}) is True
145
- for on in ("1", "true", "", "yes")),
146
- "G0c 其余值(含空串)为开——只有三个关断字面量算关")
147
- ok(S.HEARTBEAT_ROTATE_BYTES > 0 and S.HEARTBEAT_KEEP_SHARDS > 0
148
- and S.HEARTBEAT_PROBE_EVERY >= 1,
149
- "G0d 有界参数缺省 >0(轮转开、保留片数有上限、节流步长≥1)",
150
- (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY))
151
- ok(S.heartbeat_path("/x") == os.path.join("/x", S.HEARTBEAT_LOG)
152
- and S.HEARTBEAT_LOG == "_heartbeat.jsonl",
153
- "G0e 台账落点=<root>/_heartbeat.jsonl(与 _sustain.jsonl 同域)",
154
- S.heartbeat_path("/x"))
155
- ok(os.environ["MDCG_ROOT"].startswith(_TMP),
156
- "G0f 沙箱:库根在守卫临时目录内(绝不碰在役库)", os.environ["MDCG_ROOT"])
157
-
158
-
159
- # ---------------------------------------------------------------- L1 零判定变更
160
- def _l1_scenario(root, netdir):
161
- """跑一段固定序列,返回「既有读面」的投影(台账开/关两跑须逐位一致)。"""
162
- from .mdcos import MdCGOS
163
- S = globals()["sustain"]
164
- cg = MdCGOS(root)
165
- # 造一个孤儿索引条目 → heal 必有动作 → `_sustain.jsonl` 必落一行(读面非空)。
166
- cg.index["nodes"]["ghost_hb"] = {"path": "knowledge/nope/ghost_hb.md"}
167
- lp = S.SustainLoop(cg, name="h1", d=netdir, beat_interval=3600.0,
168
- heal_interval=3600.0, scrub_interval=3600.0,
169
- evolve_interval=3600.0, tidy_interval=3600.0,
170
- auto_heal=True, auto_scrub=False, auto_evolve=False,
171
- auto_tidy=False)
172
- recs = [lp.beat(), lp.beat(True), lp.beat(False)]
173
- with open(S.stamp_path("h1", netdir), encoding="utf-8") as f:
174
- stamp = json.load(f)
175
- judges = [S.judge(a, interval=600.0, task_running=tr)
176
- for a in (None, 0.0, 1500.0, 2100.0, 2600.0, 99999.0)
177
- for tr in (False, True)]
178
- hr = S.heal(cg)
179
- dg = S.diagnose(cg)
180
- sust = list(read_jsonl(os.path.join(root, S.SUSTAIN_LOG)))
181
- return {"recs": recs, "stamp": stamp, "judges": judges, "heal": hr,
182
- "diag": dg, "sustain": sust,
183
- "sustain_exists": os.path.exists(os.path.join(root, S.SUSTAIN_LOG)),
184
- "ledger_exists": os.path.exists(S.heartbeat_path(root)),
185
- "ledger_n": len(list(read_jsonl(S.heartbeat_path(root))))}
186
-
187
-
188
- def l1():
189
- print("== L1 零判定变更(硬门)——台账开/关读面逐位一致 ==")
190
- S = globals()["sustain"]
191
- r_off = _fresh_root("l1_off")
192
- os.environ["MDCG_HEARTBEAT_LEDGER"] = "0"
193
- off = _l1_scenario(r_off, _netdir("l1_off"))
194
- r_on = _fresh_root("l1_on")
195
- os.environ.pop("MDCG_HEARTBEAT_LEDGER", None) # 缺省=开
196
- on = _l1_scenario(r_on, _netdir("l1_on"))
197
-
198
- ok(off["ledger_exists"] is False and off["ledger_n"] == 0,
199
- "L1 前置:台账关时不写盘(无 _heartbeat.jsonl)")
200
- ok(on["ledger_exists"] is True and on["ledger_n"] == 3,
201
- "L1a 台账开时恰 3 条周期行(三次 beat)",
202
- (on["ledger_exists"], on["ledger_n"]))
203
-
204
- ok(_canon(off["recs"], r_off) == _canon(on["recs"], r_on)
205
- and [set(r) for r in off["recs"]] == [set(r) for r in on["recs"]],
206
- "L1b beat() 返回逐位一致(键集 + 值)——台账不改返回")
207
- ok(_canon(off["stamp"], r_off) == _canon(on["stamp"], r_on)
208
- and set(off["stamp"]) == set(on["stamp"]),
209
- "L1c 心跳戳字段逐位一致(含进度三字段)")
210
- ok(off["judges"] == on["judges"] and off["judges"],
211
- "L1d judge() 返回逐位一致(12 组年龄×任务态)", off["judges"][:2])
212
- ok(_canon(off["heal"], r_off) == _canon(on["heal"], r_on),
213
- "L1e heal() 返回逐位一致(含 before/after 统计)")
214
- ok(bool(off["heal"]["actions"]) and bool(on["heal"]["actions"]),
215
- "L1e' 前置:heal 确有动作(读面非空,比对有意义)",
216
- [a.get("code") for a in off["heal"]["actions"]])
217
- ok(_canon(off["diag"], r_off) == _canon(on["diag"], r_on),
218
- "L1f diagnose() 返回逐位一致(含 issues/stats)")
219
- ok(off["sustain_exists"] and on["sustain_exists"]
220
- and _canon(off["sustain"], r_off) == _canon(on["sustain"], r_on)
221
- and off["sustain"],
222
- "L1g _sustain.jsonl 既有记录逐位一致(台账不污染既有台账)",
223
- len(off["sustain"]))
224
-
225
-
226
- # ---------------------------------------------------------------- L2 append-only
227
- def l2():
228
- print("== L2 append-only —— 只追加,历史行不被改写 ==")
229
- S = globals()["sustain"]
230
- root = _fresh_root("l2")
231
- os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
232
- saved = S.HEARTBEAT_ROTATE_BYTES
233
- S.HEARTBEAT_ROTATE_BYTES = 1 << 30 # 本轮不轮转,纯 append
234
- try:
235
- for i in range(5):
236
- S.record_heartbeat(root, "hb2", t=100.0 + i)
237
- raw1 = open(S.heartbeat_path(root), "rb").read()
238
- for i in range(5):
239
- S.record_heartbeat(root, "hb2", t=200.0 + i)
240
- raw2 = open(S.heartbeat_path(root), "rb").read()
241
-
242
- ok(raw1 and raw2.startswith(raw1),
243
- "L2 旧字节是新内容的前缀(历史行未被改写/截断)")
244
- lines = [l for l in raw2.split(b"\n") if l.strip()]
245
- ok(len(lines) == 10, "L2a 行数==写入次数(10)", len(lines))
246
- recs = [json.loads(l) for l in lines]
247
- ok([r["t"] for r in recs]
248
- == [100.0 + i for i in range(5)] + [200.0 + i for i in range(5)],
249
- "L2b 记录顺序==写入顺序(追加不重排)")
250
- ok(all(r.get("kind") == "beat" and "pid" in r and "name" in r
251
- and r.get("ok") is True for r in recs),
252
- "L2c 字段齐备(t/name/pid/ok/kind)")
253
- finally:
254
- S.HEARTBEAT_ROTATE_BYTES = saved
255
-
256
-
257
- # ---------------------------------------------------------------- L3 断点可检出
258
- def l3():
259
- print("== L3 断点可检出 —— 人为断档 → 报断点且最长区间缩短 ==")
260
- S = globals()["sustain"]
261
- os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
262
- saved = S.HEARTBEAT_ROTATE_BYTES
263
- S.HEARTBEAT_ROTATE_BYTES = 1 << 30
264
- try:
265
- r_move = _fresh_root("l3_move")
266
- for t in (0.0, 10.0, 20.0, 30.0, 40.0): # 全连续
267
- S.record_heartbeat(r_move, "hb3", t=t)
268
- r_break = _fresh_root("l3_break")
269
- for t in (0.0, 10.0, 20.0, 30.0, 1000.0, 1010.0, 1020.0): # 30→1000 断档
270
- S.record_heartbeat(r_break, "hb3", t=t)
271
-
272
- a = S.heartbeat_ledger_stats(r_move, name="hb3", threshold_s=15.0)
273
- b = S.heartbeat_ledger_stats(r_break, name="hb3", threshold_s=15.0)
274
- ok(a["breaks"] == 0 and a["longest_s"] == 40.0,
275
- "L3 连续序列:零断点、最长 40s", (a["breaks"], a["longest_s"]))
276
- ok(b["breaks"] == 1 and b["segments"] == 2,
277
- "L3a 注入断档后**报出断点**(breaks=1、segments=2)",
278
- (b["breaks"], b["segments"]))
279
- ok(b["longest_s"] == 30.0 and b["longest_s"] < a["longest_s"],
280
- "L3b 最长连续区间**缩短**(40s → 30s)",
281
- (a["longest_s"], b["longest_s"]))
282
- ok(b["breaks_top"] and b["breaks_top"][0]["gap_s"] == 970.0,
283
- "L3c 断点间隔可读数(30→1000=970s)", b["breaks_top"])
284
- ok(b["last_iso"] is not None and b["last_age_s"] is not None,
285
- "L3d 最近一次周期时刻可读(last_iso / last_age_s)")
286
-
287
- r_one = _fresh_root("l3_one")
288
- S.record_heartbeat(r_one, "hb3", t=5.0)
289
- c = S.heartbeat_ledger_stats(r_one, name="hb3", threshold_s=15.0)
290
- ok(c["n"] == 1 and c["breaks"] == 0 and c["longest_s"] == 0.0
291
- and c["segments"] == 1,
292
- "L3e 单条记录:零断点、最长 0s、一段")
293
- d = S.heartbeat_ledger_stats(_fresh_root("l3_none"), name="hb3")
294
- ok(d["absent"] is True and d["n"] == 0 and d["longest_s"] is None,
295
- "L3f 无记录:absent=True(诚实不编数)")
296
- finally:
297
- S.HEARTBEAT_ROTATE_BYTES = saved
298
-
299
-
300
- # ---------------------------------------------------------------- L4 有界
301
- def l4():
302
- print("== L4 有界(硬门)——分片轮转 + 保留片数上限 ==")
303
- S = globals()["sustain"]
304
- os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
305
- rot, keep, probe = (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS,
306
- S.HEARTBEAT_PROBE_EVERY)
307
- S.HEARTBEAT_ROTATE_BYTES = 256
308
- S.HEARTBEAT_KEEP_SHARDS = 2
309
- S.HEARTBEAT_PROBE_EVERY = 1
310
- try:
311
- root = _fresh_root("l4")
312
- pad = {"pad": "z" * 80}
313
- for i in range(120):
314
- S.record_heartbeat(root, "hb4", t=float(i), extra=pad)
315
- shards = S._hb_shards(root)
316
- ok(len(shards) == 2, "L4 分片数受 KEEP=2 约束(实际 %d)" % len(shards),
317
- shards)
318
- ok(len(shards) <= S.HEARTBEAT_KEEP_SHARDS,
319
- "L4a 保留片数不超上限(淘汰在跑)")
320
- act = os.path.getsize(S.heartbeat_path(root))
321
- arc = S.heartbeat_archive_dir(root)
322
- sh_bytes = sum(os.path.getsize(os.path.join(arc, n)) for n in shards)
323
- slack = 512
324
- ok(act <= 256 + slack,
325
- "L4b 活动台账有界:%.0f ≤ 阈值 256 + 单条余量" % act, act)
326
- ok(all(os.path.getsize(os.path.join(arc, n)) <= 256 + slack
327
- for n in shards),
328
- "L4c 每个分片有界(≤ 阈值 + 单条余量)")
329
- ok(act + sh_bytes <= (2 + 1) * 256 + slack,
330
- "L4d 总字节有界:%d ≤ (keep+1)×阈值 + 余量" % (act + sh_bytes),
331
- act + sh_bytes)
332
-
333
- rows = [json.loads(l) for l in
334
- open(S.heartbeat_path(root), encoding="utf-8") if l.strip()]
335
- marks = [r for r in rows
336
- if r.get("kind") == "rotate" and r.get("pruned")]
337
- ok(bool(marks) and len(marks[0]["pruned"]) >= 1,
338
- "L4e 淘汰**非静默**:pruned 名单写进轮转自述行(%s)"
339
- % (marks[0]["pruned"] if marks else "无"))
340
- idx = S._hb_load_index(root)
341
- ok(all(n in idx for n in shards) and all(n in shards for n in idx),
342
- "L4f 索引与磁盘分片对齐(淘汰即摘索引,不留悬空项)")
343
-
344
- # 显式退回无上界开关:阈值 0 → 不切分(应急/对照)
345
- r0 = _fresh_root("l4_off")
346
- S.HEARTBEAT_ROTATE_BYTES = 0
347
- for i in range(40):
348
- S.record_heartbeat(r0, "hb4", t=float(i), extra=pad)
349
- ok(not S._hb_shards(r0)
350
- and os.path.getsize(S.heartbeat_path(r0)) > 0,
351
- "L4g HEARTBEAT_ROTATE_BYTES=0 → 不切分(显式退回无上界形态)")
352
-
353
- # 归档目录不在 LAYERS(检索面零污染)
354
- from .mdcg import LAYERS
355
- ok(S.HEARTBEAT_ARCHIVE not in LAYERS,
356
- "L4h 归档目录不在 LAYERS → 分片不参与节点索引")
357
- finally:
358
- S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY \
359
- = rot, keep, probe
360
-
361
-
362
-
363
-
364
- def l5():
365
- """L5 心跳的**调度源唯一**(issue #207 T1)。
366
-
367
- 开启独立心跳线程(MDCG_SUSTAIN_BEAT_THREAD)后,beat 的调度源应当**转移**
368
- 到该线程,而不是在 _run 与线程上**各调度一次**——叠加会让心跳与台账行数
369
- 按倍率翻倍,并使 status()["beats"] 这一对外读数失真。
370
-
371
- 判据是**行为**的(真跑循环数台账行),不是源码文本:同一窗口下开关开/关的
372
- 台账 beat 行数必须同量级;若开关开时近乎翻倍,即叠加。
373
- """
374
- print("== L5 心跳调度源唯一(开关开 => 转移,不叠加)==")
375
- S = globals()["sustain"]
376
- import time as _t
377
-
378
- def _count(on, interval=0.25, window=2.5):
379
- os.environ["MDCG_SUSTAIN_BEAT_THREAD"] = "1" if on else "0"
380
- root, netdir = _fresh_root("l5"), _netdir("l5")
381
- from .mdcos import MdCGOS
382
- cg = MdCGOS(root)
383
- lp = S.SustainLoop(cg, name="h5", d=netdir, beat_interval=interval,
384
- heal_interval=1e9, scrub_interval=1e9,
385
- evolve_interval=1e9, tidy_interval=1e9,
386
- sleep_interval=1e9, auto_heal=False,
387
- auto_scrub=False, auto_evolve=False,
388
- auto_tidy=False)
389
- lp.start()
390
- _t.sleep(window)
391
- lp.stop(1.0)
392
- hp = S.heartbeat_path(root)
393
- n = 0
394
- if os.path.exists(hp):
395
- for line in open(hp, encoding="utf-8", errors="replace"):
396
- if chr(34) + "beat" + chr(34) in line:
397
- n += 1
398
- return n
399
-
400
- try:
401
- off = _count(False)
402
- on = _count(True)
403
- finally:
404
- os.environ.pop("MDCG_SUSTAIN_BEAT_THREAD", None)
405
- ok(off >= 4,
406
- "L5a 前置:关态窗口内确有 beat 行(否则比较空转)实际 %d" % off, off)
407
- ok(on <= off * 1.6,
408
- "L5b 开态**不叠加**:开=%d 关=%d(倍率 %.2fx,>1.6x 即两路各调度一次)"
409
- % (on, off, (on / off) if off else 0), (on, off))
410
- ok(on >= off * 0.6,
411
- "L5c 开态心跳**仍在推进**(未被误关掉):开=%d 关=%d" % (on, off),
412
- (on, off))
413
-
414
- _GROUPS = (g0, l1, l2, l3, l4, l5)
415
-
416
-
417
- # ---------------------------------------------------------------- 变异表
418
- # 锚点 = (名字, kind, rel, old, new, 预期红项数下限, 预期命中的红项子串)。
419
- # kind="mod":改**可执行实现**(exec 成模块并换进 sys.modules,供 `from .` 面读到)
420
- _MUTATIONS = (
421
- ("M1 台账写入退化为覆盖式(非 append)", "mod", "md_cg/sustain.py",
422
- " append_jsonl(heartbeat_path(root), row)\n",
423
- ' open(heartbeat_path(root), "w", encoding="utf-8").write('
424
- 'json.dumps(row, ensure_ascii=False) + "\\n")\n',
425
- 1, "L2"),
426
- ("M2 断点不可检出(阈值设为不可达)", "mod", "md_cg/sustain.py",
427
- " if t - prev > threshold_s:",
428
- " if t - prev > 1e300:",
429
- 1, "L3"),
430
- ("M3 关闭轮转(有界性消失)", "mod", "md_cg/sustain.py",
431
- " limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0:\n return",
432
- " limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0 or True:\n return",
433
- 1, "L4"),
434
- ("M4 关闭淘汰(分片无上界增长)", "mod", "md_cg/sustain.py",
435
- " keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0:\n return []",
436
- " keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0 or True:\n return []",
437
- 1, "L4"),
438
- ("M5 台账污染既有 _sustain.jsonl(判定变更)", "mod", "md_cg/sustain.py",
439
- " append_jsonl(heartbeat_path(root), row)\n",
440
- " append_jsonl(heartbeat_path(root), row)\n"
441
- " append_jsonl(os.path.join(root, SUSTAIN_LOG),"
442
- ' {"t": row["t"], "op": "hb_probe"})\n',
443
- 1, "L1"),
444
- ("M6 beat 调度源叠加(开关开时 _run 仍自行调度)", "mod",
445
- "md_cg/sustain.py",
446
- " if own_beat and now >= next_beat:",
447
- " if now >= next_beat:",
448
- 1, "L5"),
449
- )
450
-
451
-
452
- def _run_groups() -> int:
453
- _PASS.clear()
454
- _FAIL.clear()
455
- for g in _GROUPS:
456
- try:
457
- g()
458
- except Exception as exc: # noqa: BLE001
459
- ok(False, "断言组 %s 抛异常:%s" % (g.__name__, exc))
460
- import traceback
461
- print(traceback.format_exc()[-800:])
462
- for mod in (globals().get("sustain"), _REAL):
463
- try:
464
- mod.stop_all()
465
- except Exception: # noqa: BLE001
466
- pass
467
- return len(_FAIL)
468
-
469
-
470
- def _exec_module(name, rel, text):
471
- """把变异源码 exec 进**模块自身的 __dict__**——使函数的 __globals__ 就是
472
- 该模块 dict,从而 l2/l3/l4 的常量补丁(如 HEARTBEAT_ROTATE_BYTES)对变异
473
- 模块同样生效(否则补丁落到副本、函数仍读旧值,会假红 L4)。"""
474
- m = types.ModuleType(name)
475
- m.__file__ = os.path.join(_repo_root(), rel)
476
- m.__package__ = "md_cg"
477
- exec(compile(text, rel, "exec"), m.__dict__) # noqa: S102 —— 基线自证
478
- return m
479
-
480
-
481
- def _mutate_mode(list_only: bool = False) -> int:
482
- print("!! 定点变异自证:逐条注入退化,套件必须转红且打中预期判据\n")
483
- if list_only:
484
- for name, kind, rel, _o, _n, exp, label in _MUTATIONS:
485
- print(" %-44s [%s] expect_red>=%d hit~%s (%s)"
486
- % (name, kind, exp, label, rel))
487
- return 0
488
- anchor_miss, bad = [], []
489
- with contextlib.redirect_stdout(io.StringIO()):
490
- clean = _run_groups()
491
- print(" 未变异基线:失败=%d(必须为 0)" % clean)
492
- if clean:
493
- bad.append("未变异基线即失败")
494
-
495
- for name, kind, rel, old, new, expect, label in _MUTATIONS:
496
- src = _rel_text(rel)
497
- if old not in src:
498
- print(" ANCHOR-MISS %s —— 锚点在 %s 找不到(实现改了却没同步本表)"
499
- % (name, rel))
500
- anchor_miss.append(name)
501
- continue
502
- _SRC[rel] = src.replace(old, new, 1)
503
- live = None
504
- try:
505
- if kind == "mod":
506
- live = sys.modules["md_cg.sustain"]
507
- mut = _exec_module("md_cg._hb_mut", rel, _SRC[rel])
508
- sys.modules["md_cg.sustain"] = mut
509
- globals()["sustain"] = mut
510
- with contextlib.redirect_stdout(buf := io.StringIO()):
511
- reds = _run_groups()
512
- detail = buf.getvalue()
513
- finally:
514
- if live is not None:
515
- sys.modules["md_cg.sustain"] = live
516
- globals()["sustain"] = _REAL
517
- _SRC.pop(rel, None)
518
- red_lines = [l.strip() for l in detail.splitlines()
519
- if l.strip().startswith("FAIL ")]
520
- hit = any(label in l for l in red_lines)
521
- mark = "OK " if (reds >= expect and hit) else "MISMATCH"
522
- print(" %s %-44s 红项=%d 预期>=%d 命中%s=%s"
523
- % (mark, name, reds, expect, label, "是" if hit else "**否**"))
524
- for l in red_lines[:4]:
525
- print(" " + l[5:])
526
- if reds < expect or not hit:
527
- bad.append("%s(红=%d 预期>=%d,命中%s=%s)"
528
- % (name, reds, expect, label, hit))
529
-
530
- if anchor_miss:
531
- print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
532
- print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
533
- return 2
534
- print("\n定点变异自证:%s"
535
- % ("PASS(每处判据都被打红)" if not bad else "FAIL —— " + "、".join(bad)))
536
- return 0 if not bad else 1
537
-
538
-
539
- def main() -> int:
540
- _sandbox_env()
541
- try:
542
- if "--mutate" in sys.argv:
543
- return _mutate_mode("--list" in sys.argv)
544
- n = _run_groups()
545
- print("\n心跳台账守卫:%d 通过,%d 失败" % (len(_PASS), n))
546
- return 0 if not n else 1
547
- finally:
548
- try:
549
- _REAL.stop_all()
550
- except Exception: # noqa: BLE001
551
- pass
552
- _restore_env()
553
- shutil.rmtree(_TMP, ignore_errors=True)
554
-
555
-
556
- if __name__ == "__main__":
557
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """心跳台账(append-only · 有界分片轮转)守卫 —— 让「连续 N 周期无断」可严格测得。
3
+
4
+ 背景(答卷 `docs/plans/灵枢1.0_最小智能系统实存答卷_v1.1.md` §八 分诊第 4 项,
5
+ **甲类能力缺口**;取证 `docs/eval/W7v11_结构面局限取证_v0.1.md` §丁):
6
+ `_sustain.jsonl` 是 heal **动作**台账(有动作才写,平静期与停摆期不可区分),心跳戳
7
+ 是**覆盖式单点**(无历史序列)——「连续 N 周期无断」在现数据结构下**不可严格测得**。
8
+ 补法=给心跳加 **append-only 台账**(`<root>/_heartbeat.jsonl`),配合**分片轮转+
9
+ 保留片数上限**(有界)与**只读统计**。
10
+
11
+ 断言面(每条=一个可定点变异的判据):
12
+ L1 **零判定变更**(硬门):台账**开/关**下,`beat()` 返回、心跳戳字段、
13
+ `_sustain.jsonl` 既有记录、`judge()`/`heal()`/`diagnose()` 的返回**逐位一致**
14
+ (依 `root`/时间戳等天然差异字段外)。
15
+ L2 **append-only**:台账只追加——旧字节是新内容的**前缀**,行数==写入次数,
16
+ 历史行不被改写。
17
+ L3 **断点可检出**:注入一个人为断档(周期缺失 > 阈值)后,`heartbeat_ledger_stats`
18
+ **报出断点**且最长连续区间**缩短**。
19
+ L4 **有界**(硬门):超轮转阈值后分片产生、保留片数受上限约束(淘汰有痕,
20
+ 不静默丢);`HEARTBEAT_ROTATE_BYTES=0` 为显式退回无上界开关。
21
+
22
+ 运行:python -X utf8 -m md_cg.test_heartbeat_ledger
23
+ python -X utf8 -m md_cg.test_heartbeat_ledger --mutate # 定点变异自证
24
+ python -X utf8 -m md_cg.test_heartbeat_ledger --mutate --list # 只列变异表
25
+
26
+ 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
27
+ 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表,不得静默跳过)。
28
+
29
+ **基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
30
+ **定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
31
+ **沙箱纪律**:库根/辅助根/状态根/心跳目录全落守卫临时目录,绝不碰在役库与 `~/.mdcg`。
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import contextlib
36
+ import io
37
+ import json
38
+ import os
39
+ import shutil
40
+ import sys
41
+ import tempfile
42
+ import types
43
+
44
+ from . import sustain
45
+ from .fsutil import read_jsonl
46
+
47
+ _PASS = []
48
+ _FAIL = []
49
+ _SRC = {} # 变异模式下的源码文本(rel → text)
50
+ _REAL = sustain
51
+ _ORIG = {n: getattr(sustain, n) for n in (
52
+ "HEARTBEAT_ROTATE_BYTES", "HEARTBEAT_KEEP_SHARDS", "HEARTBEAT_PROBE_EVERY",
53
+ "HEARTBEAT_GAP_THRESHOLD")}
54
+
55
+
56
+ def ok(cond, msg, extra=""):
57
+ (_PASS if cond else _FAIL).append(msg)
58
+ print((" PASS " if cond else " FAIL ") + msg
59
+ + ((" ← " + str(extra)) if (extra and not cond) else ""))
60
+
61
+
62
+ def _repo_root() -> str:
63
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
64
+
65
+
66
+ def _rel_text(rel: str) -> str:
67
+ if rel in _SRC:
68
+ return _SRC[rel]
69
+ with open(os.path.join(_repo_root(), rel), encoding="utf-8") as f:
70
+ return f.read()
71
+
72
+
73
+ # ---------------------------------------------------------------- 沙箱
74
+ _TMP = tempfile.mkdtemp(prefix="mdcg_hbledger_")
75
+ _SAVED = {}
76
+ _GEN = [0]
77
+ _ENV_KEYS = ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT", "MDCG_SUSTAIN_DIR",
78
+ "MDCG_HEARTBEAT_LEDGER")
79
+
80
+
81
+ def _sandbox_env():
82
+ for k in _ENV_KEYS:
83
+ _SAVED[k] = os.environ.get(k)
84
+ os.environ["MDCG_ROOT"] = os.path.join(_TMP, "cg")
85
+ os.environ["MDCG_AUX_ROOT"] = os.path.join(_TMP, "aux")
86
+ os.environ["MDCG_STATE_ROOT"] = os.path.join(_TMP, "state")
87
+ os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
88
+ os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
89
+
90
+
91
+ def _restore_env():
92
+ for k, v in _SAVED.items():
93
+ if v is None:
94
+ os.environ.pop(k, None)
95
+ else:
96
+ os.environ[k] = v
97
+
98
+
99
+ def _fresh_root(tag):
100
+ """每轮用**全新根**(同一根跨轮复用会读到上一轮残留而假绿)。"""
101
+ _GEN[0] += 1
102
+ root = os.path.join(_TMP, "gen%d" % _GEN[0], tag)
103
+ os.makedirs(root, exist_ok=True)
104
+ return root
105
+
106
+
107
+ def _netdir(tag):
108
+ d = os.path.join(_TMP, "net", tag)
109
+ os.makedirs(d, exist_ok=True)
110
+ return d
111
+
112
+
113
+ # ---------------------------------------------------------------- 投影
114
+ #: 天然随运行变化的字段(路径/时间戳)——零判定变更比对应**排除**它们,其余逐位比。
115
+ _VOLATILE = ("ts", "iso", "uptime", "t", "age", "mtime", "updated_at",
116
+ "last_t", "root", "path", "started_at")
117
+
118
+
119
+ def _strip(v):
120
+ if isinstance(v, dict):
121
+ return {k: _strip(x) for k, x in v.items() if k not in _VOLATILE}
122
+ if isinstance(v, list):
123
+ return [_strip(x) for x in v]
124
+ return v
125
+
126
+
127
+ def _canon(v, root):
128
+ """把该跑的库根路径归一为 <ROOT>——两跑库根不同,路径差异不算判定差异。"""
129
+ s = json.dumps(_strip(v), ensure_ascii=False, sort_keys=True)
130
+ for form in (root, root.replace(os.sep, "/")):
131
+ s = s.replace(json.dumps(form)[1:-1], "<ROOT>")
132
+ return s
133
+
134
+
135
+ # ---------------------------------------------------------------- G0 基线
136
+ def g0():
137
+ print("== G0 隔离与基线自证 ==")
138
+ S = globals()["sustain"]
139
+ ok(S.heartbeat_ledger_enabled() is True,
140
+ "G0a 缺省开:未设 MDCG_HEARTBEAT_LEDGER 时台账启用")
141
+ ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": off}) is False
142
+ for off in ("0", "false", "False")),
143
+ "G0b 关断字面量 0/false/False 均关(沿用 AUTO_OFF_VALUES 口径)")
144
+ ok(all(S.heartbeat_ledger_enabled({"MDCG_HEARTBEAT_LEDGER": on}) is True
145
+ for on in ("1", "true", "", "yes")),
146
+ "G0c 其余值(含空串)为开——只有三个关断字面量算关")
147
+ ok(S.HEARTBEAT_ROTATE_BYTES > 0 and S.HEARTBEAT_KEEP_SHARDS > 0
148
+ and S.HEARTBEAT_PROBE_EVERY >= 1,
149
+ "G0d 有界参数缺省 >0(轮转开、保留片数有上限、节流步长≥1)",
150
+ (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY))
151
+ ok(S.heartbeat_path("/x") == os.path.join("/x", S.HEARTBEAT_LOG)
152
+ and S.HEARTBEAT_LOG == "_heartbeat.jsonl",
153
+ "G0e 台账落点=<root>/_heartbeat.jsonl(与 _sustain.jsonl 同域)",
154
+ S.heartbeat_path("/x"))
155
+ ok(os.environ["MDCG_ROOT"].startswith(_TMP),
156
+ "G0f 沙箱:库根在守卫临时目录内(绝不碰在役库)", os.environ["MDCG_ROOT"])
157
+
158
+
159
+ # ---------------------------------------------------------------- L1 零判定变更
160
+ def _l1_scenario(root, netdir):
161
+ """跑一段固定序列,返回「既有读面」的投影(台账开/关两跑须逐位一致)。"""
162
+ from .mdcos import MdCGOS
163
+ S = globals()["sustain"]
164
+ cg = MdCGOS(root)
165
+ # 造一个孤儿索引条目 → heal 必有动作 → `_sustain.jsonl` 必落一行(读面非空)。
166
+ cg.index["nodes"]["ghost_hb"] = {"path": "knowledge/nope/ghost_hb.md"}
167
+ lp = S.SustainLoop(cg, name="h1", d=netdir, beat_interval=3600.0,
168
+ heal_interval=3600.0, scrub_interval=3600.0,
169
+ evolve_interval=3600.0, tidy_interval=3600.0,
170
+ auto_heal=True, auto_scrub=False, auto_evolve=False,
171
+ auto_tidy=False)
172
+ recs = [lp.beat(), lp.beat(True), lp.beat(False)]
173
+ with open(S.stamp_path("h1", netdir), encoding="utf-8") as f:
174
+ stamp = json.load(f)
175
+ judges = [S.judge(a, interval=600.0, task_running=tr)
176
+ for a in (None, 0.0, 1500.0, 2100.0, 2600.0, 99999.0)
177
+ for tr in (False, True)]
178
+ hr = S.heal(cg)
179
+ dg = S.diagnose(cg)
180
+ sust = list(read_jsonl(os.path.join(root, S.SUSTAIN_LOG)))
181
+ return {"recs": recs, "stamp": stamp, "judges": judges, "heal": hr,
182
+ "diag": dg, "sustain": sust,
183
+ "sustain_exists": os.path.exists(os.path.join(root, S.SUSTAIN_LOG)),
184
+ "ledger_exists": os.path.exists(S.heartbeat_path(root)),
185
+ "ledger_n": len(list(read_jsonl(S.heartbeat_path(root))))}
186
+
187
+
188
+ def l1():
189
+ print("== L1 零判定变更(硬门)——台账开/关读面逐位一致 ==")
190
+ S = globals()["sustain"]
191
+ r_off = _fresh_root("l1_off")
192
+ os.environ["MDCG_HEARTBEAT_LEDGER"] = "0"
193
+ off = _l1_scenario(r_off, _netdir("l1_off"))
194
+ r_on = _fresh_root("l1_on")
195
+ os.environ.pop("MDCG_HEARTBEAT_LEDGER", None) # 缺省=开
196
+ on = _l1_scenario(r_on, _netdir("l1_on"))
197
+
198
+ ok(off["ledger_exists"] is False and off["ledger_n"] == 0,
199
+ "L1 前置:台账关时不写盘(无 _heartbeat.jsonl)")
200
+ ok(on["ledger_exists"] is True and on["ledger_n"] == 3,
201
+ "L1a 台账开时恰 3 条周期行(三次 beat)",
202
+ (on["ledger_exists"], on["ledger_n"]))
203
+
204
+ ok(_canon(off["recs"], r_off) == _canon(on["recs"], r_on)
205
+ and [set(r) for r in off["recs"]] == [set(r) for r in on["recs"]],
206
+ "L1b beat() 返回逐位一致(键集 + 值)——台账不改返回")
207
+ ok(_canon(off["stamp"], r_off) == _canon(on["stamp"], r_on)
208
+ and set(off["stamp"]) == set(on["stamp"]),
209
+ "L1c 心跳戳字段逐位一致(含进度三字段)")
210
+ ok(off["judges"] == on["judges"] and off["judges"],
211
+ "L1d judge() 返回逐位一致(12 组年龄×任务态)", off["judges"][:2])
212
+ ok(_canon(off["heal"], r_off) == _canon(on["heal"], r_on),
213
+ "L1e heal() 返回逐位一致(含 before/after 统计)")
214
+ ok(bool(off["heal"]["actions"]) and bool(on["heal"]["actions"]),
215
+ "L1e' 前置:heal 确有动作(读面非空,比对有意义)",
216
+ [a.get("code") for a in off["heal"]["actions"]])
217
+ ok(_canon(off["diag"], r_off) == _canon(on["diag"], r_on),
218
+ "L1f diagnose() 返回逐位一致(含 issues/stats)")
219
+ ok(off["sustain_exists"] and on["sustain_exists"]
220
+ and _canon(off["sustain"], r_off) == _canon(on["sustain"], r_on)
221
+ and off["sustain"],
222
+ "L1g _sustain.jsonl 既有记录逐位一致(台账不污染既有台账)",
223
+ len(off["sustain"]))
224
+
225
+
226
+ # ---------------------------------------------------------------- L2 append-only
227
+ def l2():
228
+ print("== L2 append-only —— 只追加,历史行不被改写 ==")
229
+ S = globals()["sustain"]
230
+ root = _fresh_root("l2")
231
+ os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
232
+ saved = S.HEARTBEAT_ROTATE_BYTES
233
+ S.HEARTBEAT_ROTATE_BYTES = 1 << 30 # 本轮不轮转,纯 append
234
+ try:
235
+ for i in range(5):
236
+ S.record_heartbeat(root, "hb2", t=100.0 + i)
237
+ raw1 = open(S.heartbeat_path(root), "rb").read()
238
+ for i in range(5):
239
+ S.record_heartbeat(root, "hb2", t=200.0 + i)
240
+ raw2 = open(S.heartbeat_path(root), "rb").read()
241
+
242
+ ok(raw1 and raw2.startswith(raw1),
243
+ "L2 旧字节是新内容的前缀(历史行未被改写/截断)")
244
+ lines = [l for l in raw2.split(b"\n") if l.strip()]
245
+ ok(len(lines) == 10, "L2a 行数==写入次数(10)", len(lines))
246
+ recs = [json.loads(l) for l in lines]
247
+ ok([r["t"] for r in recs]
248
+ == [100.0 + i for i in range(5)] + [200.0 + i for i in range(5)],
249
+ "L2b 记录顺序==写入顺序(追加不重排)")
250
+ ok(all(r.get("kind") == "beat" and "pid" in r and "name" in r
251
+ and r.get("ok") is True for r in recs),
252
+ "L2c 字段齐备(t/name/pid/ok/kind)")
253
+ finally:
254
+ S.HEARTBEAT_ROTATE_BYTES = saved
255
+
256
+
257
+ # ---------------------------------------------------------------- L3 断点可检出
258
+ def l3():
259
+ print("== L3 断点可检出 —— 人为断档 → 报断点且最长区间缩短 ==")
260
+ S = globals()["sustain"]
261
+ os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
262
+ saved = S.HEARTBEAT_ROTATE_BYTES
263
+ S.HEARTBEAT_ROTATE_BYTES = 1 << 30
264
+ try:
265
+ r_move = _fresh_root("l3_move")
266
+ for t in (0.0, 10.0, 20.0, 30.0, 40.0): # 全连续
267
+ S.record_heartbeat(r_move, "hb3", t=t)
268
+ r_break = _fresh_root("l3_break")
269
+ for t in (0.0, 10.0, 20.0, 30.0, 1000.0, 1010.0, 1020.0): # 30→1000 断档
270
+ S.record_heartbeat(r_break, "hb3", t=t)
271
+
272
+ a = S.heartbeat_ledger_stats(r_move, name="hb3", threshold_s=15.0)
273
+ b = S.heartbeat_ledger_stats(r_break, name="hb3", threshold_s=15.0)
274
+ ok(a["breaks"] == 0 and a["longest_s"] == 40.0,
275
+ "L3 连续序列:零断点、最长 40s", (a["breaks"], a["longest_s"]))
276
+ ok(b["breaks"] == 1 and b["segments"] == 2,
277
+ "L3a 注入断档后**报出断点**(breaks=1、segments=2)",
278
+ (b["breaks"], b["segments"]))
279
+ ok(b["longest_s"] == 30.0 and b["longest_s"] < a["longest_s"],
280
+ "L3b 最长连续区间**缩短**(40s → 30s)",
281
+ (a["longest_s"], b["longest_s"]))
282
+ ok(b["breaks_top"] and b["breaks_top"][0]["gap_s"] == 970.0,
283
+ "L3c 断点间隔可读数(30→1000=970s)", b["breaks_top"])
284
+ ok(b["last_iso"] is not None and b["last_age_s"] is not None,
285
+ "L3d 最近一次周期时刻可读(last_iso / last_age_s)")
286
+
287
+ r_one = _fresh_root("l3_one")
288
+ S.record_heartbeat(r_one, "hb3", t=5.0)
289
+ c = S.heartbeat_ledger_stats(r_one, name="hb3", threshold_s=15.0)
290
+ ok(c["n"] == 1 and c["breaks"] == 0 and c["longest_s"] == 0.0
291
+ and c["segments"] == 1,
292
+ "L3e 单条记录:零断点、最长 0s、一段")
293
+ d = S.heartbeat_ledger_stats(_fresh_root("l3_none"), name="hb3")
294
+ ok(d["absent"] is True and d["n"] == 0 and d["longest_s"] is None,
295
+ "L3f 无记录:absent=True(诚实不编数)")
296
+ finally:
297
+ S.HEARTBEAT_ROTATE_BYTES = saved
298
+
299
+
300
+ # ---------------------------------------------------------------- L4 有界
301
+ def l4():
302
+ print("== L4 有界(硬门)——分片轮转 + 保留片数上限 ==")
303
+ S = globals()["sustain"]
304
+ os.environ.pop("MDCG_HEARTBEAT_LEDGER", None)
305
+ rot, keep, probe = (S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS,
306
+ S.HEARTBEAT_PROBE_EVERY)
307
+ S.HEARTBEAT_ROTATE_BYTES = 256
308
+ S.HEARTBEAT_KEEP_SHARDS = 2
309
+ S.HEARTBEAT_PROBE_EVERY = 1
310
+ try:
311
+ root = _fresh_root("l4")
312
+ pad = {"pad": "z" * 80}
313
+ for i in range(120):
314
+ S.record_heartbeat(root, "hb4", t=float(i), extra=pad)
315
+ shards = S._hb_shards(root)
316
+ ok(len(shards) == 2, "L4 分片数受 KEEP=2 约束(实际 %d)" % len(shards),
317
+ shards)
318
+ ok(len(shards) <= S.HEARTBEAT_KEEP_SHARDS,
319
+ "L4a 保留片数不超上限(淘汰在跑)")
320
+ act = os.path.getsize(S.heartbeat_path(root))
321
+ arc = S.heartbeat_archive_dir(root)
322
+ sh_bytes = sum(os.path.getsize(os.path.join(arc, n)) for n in shards)
323
+ slack = 512
324
+ ok(act <= 256 + slack,
325
+ "L4b 活动台账有界:%.0f ≤ 阈值 256 + 单条余量" % act, act)
326
+ ok(all(os.path.getsize(os.path.join(arc, n)) <= 256 + slack
327
+ for n in shards),
328
+ "L4c 每个分片有界(≤ 阈值 + 单条余量)")
329
+ ok(act + sh_bytes <= (2 + 1) * 256 + slack,
330
+ "L4d 总字节有界:%d ≤ (keep+1)×阈值 + 余量" % (act + sh_bytes),
331
+ act + sh_bytes)
332
+
333
+ rows = [json.loads(l) for l in
334
+ open(S.heartbeat_path(root), encoding="utf-8") if l.strip()]
335
+ marks = [r for r in rows
336
+ if r.get("kind") == "rotate" and r.get("pruned")]
337
+ ok(bool(marks) and len(marks[0]["pruned"]) >= 1,
338
+ "L4e 淘汰**非静默**:pruned 名单写进轮转自述行(%s)"
339
+ % (marks[0]["pruned"] if marks else "无"))
340
+ idx = S._hb_load_index(root)
341
+ ok(all(n in idx for n in shards) and all(n in shards for n in idx),
342
+ "L4f 索引与磁盘分片对齐(淘汰即摘索引,不留悬空项)")
343
+
344
+ # 显式退回无上界开关:阈值 0 → 不切分(应急/对照)
345
+ r0 = _fresh_root("l4_off")
346
+ S.HEARTBEAT_ROTATE_BYTES = 0
347
+ for i in range(40):
348
+ S.record_heartbeat(r0, "hb4", t=float(i), extra=pad)
349
+ ok(not S._hb_shards(r0)
350
+ and os.path.getsize(S.heartbeat_path(r0)) > 0,
351
+ "L4g HEARTBEAT_ROTATE_BYTES=0 → 不切分(显式退回无上界形态)")
352
+
353
+ # 归档目录不在 LAYERS(检索面零污染)
354
+ from .mdcg import LAYERS
355
+ ok(S.HEARTBEAT_ARCHIVE not in LAYERS,
356
+ "L4h 归档目录不在 LAYERS → 分片不参与节点索引")
357
+ finally:
358
+ S.HEARTBEAT_ROTATE_BYTES, S.HEARTBEAT_KEEP_SHARDS, S.HEARTBEAT_PROBE_EVERY \
359
+ = rot, keep, probe
360
+
361
+
362
+
363
+
364
+ def l5():
365
+ """L5 心跳的**调度源唯一**(issue #207 T1)。
366
+
367
+ 开启独立心跳线程(MDCG_SUSTAIN_BEAT_THREAD)后,beat 的调度源应当**转移**
368
+ 到该线程,而不是在 _run 与线程上**各调度一次**——叠加会让心跳与台账行数
369
+ 按倍率翻倍,并使 status()["beats"] 这一对外读数失真。
370
+
371
+ 判据是**行为**的(真跑循环数台账行),不是源码文本:同一窗口下开关开/关的
372
+ 台账 beat 行数必须同量级;若开关开时近乎翻倍,即叠加。
373
+ """
374
+ print("== L5 心跳调度源唯一(开关开 => 转移,不叠加)==")
375
+ S = globals()["sustain"]
376
+ import time as _t
377
+
378
+ def _count(on, interval=0.25, window=2.5):
379
+ os.environ["MDCG_SUSTAIN_BEAT_THREAD"] = "1" if on else "0"
380
+ root, netdir = _fresh_root("l5"), _netdir("l5")
381
+ from .mdcos import MdCGOS
382
+ cg = MdCGOS(root)
383
+ lp = S.SustainLoop(cg, name="h5", d=netdir, beat_interval=interval,
384
+ heal_interval=1e9, scrub_interval=1e9,
385
+ evolve_interval=1e9, tidy_interval=1e9,
386
+ sleep_interval=1e9, auto_heal=False,
387
+ auto_scrub=False, auto_evolve=False,
388
+ auto_tidy=False)
389
+ lp.start()
390
+ _t.sleep(window)
391
+ lp.stop(1.0)
392
+ hp = S.heartbeat_path(root)
393
+ n = 0
394
+ if os.path.exists(hp):
395
+ for line in open(hp, encoding="utf-8", errors="replace"):
396
+ if chr(34) + "beat" + chr(34) in line:
397
+ n += 1
398
+ return n
399
+
400
+ try:
401
+ off = _count(False)
402
+ on = _count(True)
403
+ finally:
404
+ os.environ.pop("MDCG_SUSTAIN_BEAT_THREAD", None)
405
+ ok(off >= 4,
406
+ "L5a 前置:关态窗口内确有 beat 行(否则比较空转)实际 %d" % off, off)
407
+ ok(on <= off * 1.6,
408
+ "L5b 开态**不叠加**:开=%d 关=%d(倍率 %.2fx,>1.6x 即两路各调度一次)"
409
+ % (on, off, (on / off) if off else 0), (on, off))
410
+ ok(on >= off * 0.6,
411
+ "L5c 开态心跳**仍在推进**(未被误关掉):开=%d 关=%d" % (on, off),
412
+ (on, off))
413
+
414
+ _GROUPS = (g0, l1, l2, l3, l4, l5)
415
+
416
+
417
+ # ---------------------------------------------------------------- 变异表
418
+ # 锚点 = (名字, kind, rel, old, new, 预期红项数下限, 预期命中的红项子串)。
419
+ # kind="mod":改**可执行实现**(exec 成模块并换进 sys.modules,供 `from .` 面读到)
420
+ _MUTATIONS = (
421
+ ("M1 台账写入退化为覆盖式(非 append)", "mod", "md_cg/sustain.py",
422
+ " append_jsonl(heartbeat_path(root), row)\n",
423
+ ' open(heartbeat_path(root), "w", encoding="utf-8").write('
424
+ 'json.dumps(row, ensure_ascii=False) + "\\n")\n',
425
+ 1, "L2"),
426
+ ("M2 断点不可检出(阈值设为不可达)", "mod", "md_cg/sustain.py",
427
+ " if t - prev > threshold_s:",
428
+ " if t - prev > 1e300:",
429
+ 1, "L3"),
430
+ ("M3 关闭轮转(有界性消失)", "mod", "md_cg/sustain.py",
431
+ " limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0:\n return",
432
+ " limit = HEARTBEAT_ROTATE_BYTES\n if limit <= 0 or True:\n return",
433
+ 1, "L4"),
434
+ ("M4 关闭淘汰(分片无上界增长)", "mod", "md_cg/sustain.py",
435
+ " keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0:\n return []",
436
+ " keep = HEARTBEAT_KEEP_SHARDS\n if keep <= 0 or True:\n return []",
437
+ 1, "L4"),
438
+ ("M5 台账污染既有 _sustain.jsonl(判定变更)", "mod", "md_cg/sustain.py",
439
+ " append_jsonl(heartbeat_path(root), row)\n",
440
+ " append_jsonl(heartbeat_path(root), row)\n"
441
+ " append_jsonl(os.path.join(root, SUSTAIN_LOG),"
442
+ ' {"t": row["t"], "op": "hb_probe"})\n',
443
+ 1, "L1"),
444
+ ("M6 beat 调度源叠加(开关开时 _run 仍自行调度)", "mod",
445
+ "md_cg/sustain.py",
446
+ " if own_beat and now >= next_beat:",
447
+ " if now >= next_beat:",
448
+ 1, "L5"),
449
+ )
450
+
451
+
452
+ def _run_groups() -> int:
453
+ _PASS.clear()
454
+ _FAIL.clear()
455
+ for g in _GROUPS:
456
+ try:
457
+ g()
458
+ except Exception as exc: # noqa: BLE001
459
+ ok(False, "断言组 %s 抛异常:%s" % (g.__name__, exc))
460
+ import traceback
461
+ print(traceback.format_exc()[-800:])
462
+ for mod in (globals().get("sustain"), _REAL):
463
+ try:
464
+ mod.stop_all()
465
+ except Exception: # noqa: BLE001
466
+ pass
467
+ return len(_FAIL)
468
+
469
+
470
+ def _exec_module(name, rel, text):
471
+ """把变异源码 exec 进**模块自身的 __dict__**——使函数的 __globals__ 就是
472
+ 该模块 dict,从而 l2/l3/l4 的常量补丁(如 HEARTBEAT_ROTATE_BYTES)对变异
473
+ 模块同样生效(否则补丁落到副本、函数仍读旧值,会假红 L4)。"""
474
+ m = types.ModuleType(name)
475
+ m.__file__ = os.path.join(_repo_root(), rel)
476
+ m.__package__ = "md_cg"
477
+ exec(compile(text, rel, "exec"), m.__dict__) # noqa: S102 —— 基线自证
478
+ return m
479
+
480
+
481
+ def _mutate_mode(list_only: bool = False) -> int:
482
+ print("!! 定点变异自证:逐条注入退化,套件必须转红且打中预期判据\n")
483
+ if list_only:
484
+ for name, kind, rel, _o, _n, exp, label in _MUTATIONS:
485
+ print(" %-44s [%s] expect_red>=%d hit~%s (%s)"
486
+ % (name, kind, exp, label, rel))
487
+ return 0
488
+ anchor_miss, bad = [], []
489
+ with contextlib.redirect_stdout(io.StringIO()):
490
+ clean = _run_groups()
491
+ print(" 未变异基线:失败=%d(必须为 0)" % clean)
492
+ if clean:
493
+ bad.append("未变异基线即失败")
494
+
495
+ for name, kind, rel, old, new, expect, label in _MUTATIONS:
496
+ src = _rel_text(rel)
497
+ if old not in src:
498
+ print(" ANCHOR-MISS %s —— 锚点在 %s 找不到(实现改了却没同步本表)"
499
+ % (name, rel))
500
+ anchor_miss.append(name)
501
+ continue
502
+ _SRC[rel] = src.replace(old, new, 1)
503
+ live = None
504
+ try:
505
+ if kind == "mod":
506
+ live = sys.modules["md_cg.sustain"]
507
+ mut = _exec_module("md_cg._hb_mut", rel, _SRC[rel])
508
+ sys.modules["md_cg.sustain"] = mut
509
+ globals()["sustain"] = mut
510
+ with contextlib.redirect_stdout(buf := io.StringIO()):
511
+ reds = _run_groups()
512
+ detail = buf.getvalue()
513
+ finally:
514
+ if live is not None:
515
+ sys.modules["md_cg.sustain"] = live
516
+ globals()["sustain"] = _REAL
517
+ _SRC.pop(rel, None)
518
+ red_lines = [l.strip() for l in detail.splitlines()
519
+ if l.strip().startswith("FAIL ")]
520
+ hit = any(label in l for l in red_lines)
521
+ mark = "OK " if (reds >= expect and hit) else "MISMATCH"
522
+ print(" %s %-44s 红项=%d 预期>=%d 命中%s=%s"
523
+ % (mark, name, reds, expect, label, "是" if hit else "**否**"))
524
+ for l in red_lines[:4]:
525
+ print(" " + l[5:])
526
+ if reds < expect or not hit:
527
+ bad.append("%s(红=%d 预期>=%d,命中%s=%s)"
528
+ % (name, reds, expect, label, hit))
529
+
530
+ if anchor_miss:
531
+ print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
532
+ print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
533
+ return 2
534
+ print("\n定点变异自证:%s"
535
+ % ("PASS(每处判据都被打红)" if not bad else "FAIL —— " + "、".join(bad)))
536
+ return 0 if not bad else 1
537
+
538
+
539
+ def main() -> int:
540
+ _sandbox_env()
541
+ try:
542
+ if "--mutate" in sys.argv:
543
+ return _mutate_mode("--list" in sys.argv)
544
+ n = _run_groups()
545
+ print("\n心跳台账守卫:%d 通过,%d 失败" % (len(_PASS), n))
546
+ return 0 if not n else 1
547
+ finally:
548
+ try:
549
+ _REAL.stop_all()
550
+ except Exception: # noqa: BLE001
551
+ pass
552
+ _restore_env()
553
+ shutil.rmtree(_TMP, ignore_errors=True)
554
+
555
+
556
+ if __name__ == "__main__":
557
+ sys.exit(main())