@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,652 +1,652 @@
1
- # -*- coding: utf-8 -*-
2
- """常驻循环卡死防护与观测守卫(issue #63)。
3
-
4
- 背景(外部 issue #63 三条根因,全部本文件钉死):
5
-
6
- ① `sleep._git()` **无 timeout=**——子进程无界等待(实测停 9.5 小时);
7
- ② 同处**未指定 stdin** ⇒ 子进程继承父进程 stdin(DSH 常驻宿主的
8
- JSON-RPC 活管道)——活管道下读 stdin 的子进程永不 EOF;
9
- ③ tick 台账在 `run_cycle` **返回后**才写 ⇒ 卡住期间外部无法知道卡在哪档
10
- (`phases` 空)。
11
-
12
- 修法的可判据面:
13
-
14
- T1 参数面——`sleep._git` 调 `subprocess.run` 必带
15
- `timeout=_GIT_TIMEOUT_S` 与 `stdin=subprocess.DEVNULL`(捕获 kwargs 判据);
16
- 旁证(机理复现,等价形态):活管道(PIPE 不写不关)下读 stdin 的子进程
17
- 悬挂;DEVNULL 下 0.02s 级立即 EOF 返回。旁证二:真挂起子进程 + 同形态
18
- timeout → 真 `TimeoutExpired` 且有界(本机 Python 超时机制在位)。
19
- T2 真超时——替身按 `subprocess.run(timeout=)` 契约行事(跑满一个 timeout
20
- 后抛 `TimeoutExpired`):`_git_ok` 抛 `SleepError`(`SleepGitTimeout`),
21
- 消息含「超时」「已被 kill」与命令名,耗时 **≈ timeout(有界)**;
22
- 并钉「可区分」:rc≠0 走「失败」文案、与超时文案分开。
23
- T3 循环续走回归——某档 tick 抛异常 → `_run` 不中断(该档下一轮照常,
24
- 其它档不受影响)——既有能力回归。
25
- T4 进度面——tick 入口写 `current_tick`(且**进入即刷既有心跳戳**)/ 出口清
26
- 并记 `last_tick_done`;失败档记 `last_tick_error`(容忍≠静默);`status`
27
- 展示三字段;构造过期 `current_tick` → `status` 报 `stale_tick`
28
- (含档名与已运行时长;负对照:未超不报)。
29
- T5 审计断言——interop / audit / units / bench×3 / sleep 的 `subprocess.run`
30
- 调用(AST 参数面)带 timeout 与 `stdin=DEVNULL`;whitebox 的 Popen
31
- 保持协议面原形态(stdin=PIPE,**不在加固面**)。
32
-
33
- 运行:python -X utf8 -m md_cg.test_sustain_bounded
34
- python -X utf8 -m md_cg.test_sustain_bounded --mutate # 变异自证
35
- python -X utf8 -m md_cg.test_sustain_bounded --mutate --list # 只列变异表
36
- python -X utf8 -m md_cg.test_sustain_bounded --mutate --null # 空转检出对照
37
-
38
- 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
39
- 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表)。
40
-
41
- **红项口径(复核打回修复,2026-10-06)**:每条变异的「自身红项」= 该条运行
42
- 前后 `_FAIL` 长度差——**不得**拿 `len(_FAIL)` 当本轮红项(累计值恒非空,
43
- 会让「判据空转」检测失效、空转变异被静默放行);红项行**全量**打印且与
44
- 自身红项数**账实相符**(不符按失败判)。该缺陷类别由 `--mutate --null`
45
- (new==old 的无害变异必须被判 MISS)钉住。
46
-
47
- **基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
48
- **定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
49
- """
50
- from __future__ import annotations
51
-
52
- import ast
53
- import contextlib
54
- import io
55
- import os
56
- import shutil
57
- import subprocess
58
- import sys
59
- import tempfile
60
- import time
61
- import types
62
-
63
- from . import sleep as SL
64
- from . import sustain as SUS
65
-
66
- _PASS = []
67
- _FAIL = []
68
- _SRC = {}
69
- _TMP = tempfile.mkdtemp(prefix="mdcg_bounded_")
70
- _SAVED = {}
71
- _REAL_SL = SL
72
- _REAL_SUS = SUS
73
-
74
- _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
75
-
76
- #: T5 的审计面:这些文件里的 `subprocess.run` 调用必须带 timeout 与
77
- #: stdin=DEVNULL(issue #63 同批加固);whitebox 的 Popen 单列(不在加固面)。
78
- _AUDIT_RUN_FILES = ("md_cg/sleep.py", "md_cg/interop.py", "md_cg/audit.py",
79
- "md_cg/units.py", "md_cg/bench_locomo_zh.py",
80
- "md_cg/bench_zh_mad.py", "md_cg/bench_governance.py")
81
- #: 不在加固面的既有正确形态(免误伤):whitebox 的 Popen 是**长驻对话协议面**
82
- #: (stdin=PIPE 与后端持续对话,给 DEVNULL 会改变协议语义)。
83
- _WHITEBOX_REL = "md_cg/whitebox.py"
84
-
85
-
86
- def ok(cond, msg, extra=""):
87
- (_PASS if cond else _FAIL).append(msg)
88
- print((" PASS " if cond else " FAIL ") + msg
89
- + ((" ← " + str(extra)) if (extra and not cond) else ""))
90
-
91
-
92
- def _rel_text(rel: str) -> str:
93
- if rel in _SRC:
94
- return _SRC[rel]
95
- with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
96
- return f.read()
97
-
98
-
99
- def _sandbox_env():
100
- for k in ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT",
101
- "MDCG_SUSTAIN_DIR", "MDCG_SUSTAIN", "MDCG_SLEEP_GITDIR",
102
- "MDCG_SLEEP_SHADOW"):
103
- _SAVED[k] = os.environ.get(k)
104
- os.environ.pop(k, None)
105
- os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
106
- os.environ["MDCG_ROOT"] = os.path.join(_TMP, "data")
107
-
108
-
109
- def _restore_env():
110
- for k, v in _SAVED.items():
111
- if v is None:
112
- os.environ.pop(k, None)
113
- else:
114
- os.environ[k] = v
115
-
116
-
117
- class _FakeCG:
118
- """最小 cg 替身:SustainLoop 只消费 .root(写戳 / 会话账本读点)。"""
119
-
120
- def __init__(self, root):
121
- self.root = root
122
-
123
-
124
- def _new_loop(**kw):
125
- root = os.path.join(_TMP, "data")
126
- os.makedirs(root, exist_ok=True)
127
- d = os.path.join(_TMP, "sustain")
128
- os.makedirs(d, exist_ok=True)
129
- kw.setdefault("name", "md_cg_bounded")
130
- kw.setdefault("auto_sleep", True)
131
- kw.setdefault("sleep_merge", "auto")
132
- kw.setdefault("sleep_window", "")
133
- kw.setdefault("sleep_scrub_apply", False)
134
- return SUS.SustainLoop(_FakeCG(root), d=d, **kw)
135
-
136
-
137
- # ---------------------------------------------------------------- T1
138
- def t1():
139
- print("== T1 参数面:_git 必带 timeout=_GIT_TIMEOUT_S 与 stdin=DEVNULL ==")
140
- S = globals()["SL"]
141
- real_run = subprocess.run
142
- calls = []
143
-
144
- def fake(argv, **kw):
145
- calls.append((list(argv), dict(kw)))
146
- return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
147
-
148
- subprocess.run = fake
149
- try:
150
- S._git("<G>", "<root>", "status", "--short")
151
- finally:
152
- subprocess.run = real_run
153
- ok(len(calls) == 1, "T1 前置:_git 恰调 subprocess.run 一次", calls)
154
- if calls:
155
- argv, kw = calls[0]
156
- # 回显面**剔除 env**(含本机敏感变量,纪律第 9 条:敏感信息隔离)
157
- safe = {k: v for k, v in kw.items() if k != "env"}
158
- ok(argv[:3] == ["git", "--git-dir=<G>", "--work-tree=<root>"],
159
- "T1a argv 显式 --git-dir / --work-tree(唯一出口形态不变)", argv)
160
- ok(kw.get("timeout") == S._GIT_TIMEOUT_S
161
- and isinstance(kw.get("timeout"), (int, float)),
162
- "T1b **_git 必带 timeout=_GIT_TIMEOUT_S**(%r)——无界等待被闸住"
163
- % (kw.get("timeout"),), safe)
164
- ok(kw.get("stdin") is subprocess.DEVNULL,
165
- "T1c **_git 必带 stdin=subprocess.DEVNULL**——不继承父进程 stdin"
166
- "(常驻宿主下是 JSON-RPC 活管道)", safe)
167
- ok(kw.get("shell") is False and kw.get("capture_output") is True,
168
- "T1d 既有形态保持(shell=False + capture_output=True)", safe)
169
- ok((kw.get("env") or {}).get("PYTHONUTF8") == "1",
170
- "T1e env 带 PYTHONUTF8=1(既有形态保持;不回显 env 内容)")
171
-
172
- # 机理旁证(等价形态):活管道 ⇒ 读 stdin 的子进程悬挂;DEVNULL ⇒ 立即 EOF
173
- code = "import sys\nsys.stdin.read()\nprint('EOF-OK')\n"
174
- p = subprocess.Popen([sys.executable, "-c", code], stdin=subprocess.PIPE,
175
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
176
- text=True, encoding="utf-8", errors="replace")
177
- try:
178
- time.sleep(0.6)
179
- hung = p.poll() is None
180
- finally:
181
- p.kill()
182
- with contextlib.suppress(Exception):
183
- p.communicate(timeout=5)
184
- ok(hung, "T1f 机理旁证:**活管道**(PIPE 不写不关)下读 stdin 的子进程"
185
- "悬挂(poll=None;DSH JSON-RPC 管道的等价形态)")
186
- t0 = time.time()
187
- r = subprocess.run([sys.executable, "-c", code], stdin=subprocess.DEVNULL,
188
- capture_output=True, text=True, encoding="utf-8",
189
- errors="replace", timeout=15)
190
- dt = time.time() - t0
191
- ok(r.returncode == 0 and "EOF-OK" in (r.stdout or ""),
192
- "T1g 机理旁证:**stdin=DEVNULL** 下同一子进程立即 EOF 返回"
193
- "(%.2fs)" % dt, (r.returncode, r.stdout, r.stderr))
194
- t0 = time.time()
195
- timed_out = False
196
- try:
197
- subprocess.run([sys.executable, "-c", "import time; time.sleep(30)"],
198
- stdin=subprocess.DEVNULL, capture_output=True,
199
- timeout=0.5)
200
- except subprocess.TimeoutExpired:
201
- timed_out = True
202
- dt = time.time() - t0
203
- ok(timed_out and dt < 5.0,
204
- "T1h 机理旁证:真子进程 + timeout → 真 TimeoutExpired 且有界"
205
- "(%.2fs)——本机 timeout 机制在位" % dt)
206
-
207
-
208
- # ---------------------------------------------------------------- T2
209
- def t2():
210
- print("== T2 真超时:SleepError + 耗时≈timeout(有界)+ 消息含「超时」 ==")
211
- S = globals()["SL"]
212
- g = S._git.__globals__
213
- real_run = subprocess.run
214
- real_tmo = g["_GIT_TIMEOUT_S"]
215
- calls = []
216
-
217
- def fake(argv, **kw):
218
- """按 `subprocess.run(timeout=)` 契约行事:跑满一个 timeout 后 kill 抛出。
219
-
220
- 无 timeout(旧形态)⇒ 跑满 2s 才返回(无界等待的等价模拟——T1b/T2a
221
- 会在该形态下转红)。
222
- """
223
- calls.append((list(argv), dict(kw)))
224
- tmo = kw.get("timeout")
225
- if tmo is None:
226
- time.sleep(2.0)
227
- return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
228
- time.sleep(float(tmo))
229
- raise subprocess.TimeoutExpired(cmd=argv, timeout=float(tmo))
230
-
231
- g["_GIT_TIMEOUT_S"] = 0.3 # 测试用短 timeout(模块单点可调)
232
- subprocess.run = fake
233
- t0 = time.time()
234
- raised = None
235
- try:
236
- try:
237
- S._git_ok("<G>", "<root>", "status")
238
- except S.SleepError as e:
239
- raised = e
240
- finally:
241
- subprocess.run = real_run
242
- g["_GIT_TIMEOUT_S"] = real_tmo
243
- dt = time.time() - t0
244
- ok(raised is not None and isinstance(raised, S.SleepGitTimeout),
245
- "T2a 超时**不吞**:_git/_git_ok 抛 SleepError(SleepGitTimeout)", raised)
246
- ok(raised is not None and "超时" in str(raised),
247
- "T2b 消息含「超时」", str(raised))
248
- ok(raised is not None and "已被 kill" in str(raised),
249
- "T2c 消息含「已被 kill」(kill 语义明示)", str(raised))
250
- ok(raised is not None and "status" in str(raised),
251
- "T2d 消息含命令名", str(raised))
252
- ok(raised is not None and "index.lock" in str(raised),
253
- "T2e 消息含残留锁人工核删指引(不自动删)", str(raised))
254
- ok(raised is not None and dt <= 0.3 * 3,
255
- "T2f **耗时有界**(≈timeout:%.2fs ≤ 3×0.3s)——不是无界等待" % dt, dt)
256
-
257
- # 可区分(issue #63):rc≠0 的失败走「失败」文案,与超时面分开
258
- def fake_fail(argv, **kw):
259
- return subprocess.CompletedProcess(argv, 1, stdout="",
260
- stderr="fatal: boom")
261
-
262
- subprocess.run = fake_fail
263
- raised2 = None
264
- try:
265
- try:
266
- S._git_ok("<G>", "<root>", "status")
267
- except S.SleepError as e2:
268
- raised2 = e2
269
- finally:
270
- subprocess.run = real_run
271
- ok(raised2 is not None and "失败" in str(raised2)
272
- and "超时" not in str(raised2),
273
- "T2g **可区分**:rc≠0 走「失败」文案、不含「超时」(两条失败面分开)",
274
- str(raised2))
275
-
276
-
277
- # ---------------------------------------------------------------- T3
278
- def t3():
279
- print("== T3 循环续走回归:某档抛异常 → _run 不中断(下一轮照常)==")
280
- lp = _new_loop(beat_interval=30.0, heal_interval=0.15, scrub_interval=0.3,
281
- evolve_interval=60.0, tidy_interval=60.0,
282
- sleep_interval=60.0)
283
- log = []
284
-
285
- def bad():
286
- log.append(("heal", time.time()))
287
- raise RuntimeError("t3-fail-once")
288
-
289
- def good():
290
- log.append(("scrub", time.time()))
291
-
292
- lp._tick_heal = bad
293
- lp._tick_scrub = good
294
- lp._tick_evolve = lambda: log.append(("evolve", time.time()))
295
- lp._tick_tidy = lambda: log.append(("tidy", time.time()))
296
- lp._tick_sleep = lambda: log.append(("sleep", time.time()))
297
- lp.start()
298
- try:
299
- time.sleep(1.1)
300
- finally:
301
- lp.stop()
302
- n_heal = sum(1 for t, _ in log if t == "heal")
303
- n_scrub = sum(1 for t, _ in log if t == "scrub")
304
- ok(n_heal >= 2,
305
- "T3a 某档 tick 抛异常后**不中断**:该档下一轮照常调度(heal×%d)"
306
- % n_heal, log)
307
- ok(n_scrub >= 1,
308
- "T3b 其它档不受影响(scrub×%d)" % n_scrub, log)
309
- ok(lp.last_tick_error is not None
310
- and lp.last_tick_error.get("name") == "heal"
311
- and "RuntimeError: t3-fail-once" in lp.last_tick_error.get("error", ""),
312
- "T3c 异常**不再全静默**:last_tick_error 记 {档名, 类名+摘要}",
313
- lp.last_tick_error)
314
- # issue #213 Q9(2026-10-13 DSH 端):原 T3d 断言「最近一档 == 失败档」,
315
- # 即 last_tick_done.get("ok") is False——该断言**结构性竞态**,不是负载敏感。
316
- # 机理:_run 是**单线程顺序**执行(beat→heal→scrub→evolve→tidy→sleep,
317
- # 固定次序,同一轮内逐个判到期)。heal(0.15s) 与 scrub(0.3s) 同轮到期时,
318
- # **scrub 必然在 heal 之后写 last_tick_done**,把 heal 的 ok=False 覆盖成
319
- # ok=True。故最后一档是 heal 还是 scrub,只取决于 stop() 落在哪——
320
- # 实测扫 14 个 stop 时刻,**6 个失败**(0.5/0.6/0.9/1.0/1.3/1.4s)。
321
- # 更正原判读:「残留的 scrub 任务抢先落 ok=True」不成立——**没有第二个任务**,
322
- # 循环里各档就是同一线程按序跑的;错的不是执行体,是断言把「最后一档必为
323
- # heal」当成了不变式,而循环从不保证这一点。
324
- # 改法:钉**可从日志交叉核验**的不变式——last_tick_done 必须等于日志里最后
325
- # 跑过的那一档,且 ok 必须与该档真实结局一致(heal 必失败、scrub 必成功)。
326
- # 判别力不降反升:错配 / 漏记 / ok 翻转都会转红;且不再依赖 stop 时刻。
327
- _last_name = log[-1][0] if log else None
328
- _ltd = lp.last_tick_done
329
- ok(_ltd is not None and _ltd.get("name") == _last_name,
330
- "T3d last_tick_done 与最后跑过的一档一致(%s)" % _last_name, _ltd)
331
- ok(_ltd is not None and _ltd.get("ok") is (_last_name != "heal"),
332
- "T3d2 ok 与该档真实结局一致(heal 必失败 ⇒ ok=False)", _ltd)
333
- # 失败档「不静默」的**无条件**判据(不依赖调度次序):直接驱动一档必失败的
334
- # wrapped tick,出口必须落 ok=False——原 T3d 想钉的就是这条,此处确定性钉死。
335
- lp._wrap_ticks()
336
- def _boom():
337
- raise RuntimeError("t3-direct")
338
- lp._wrap_tick("heal", _boom)()
339
- ok(lp.last_tick_done is not None
340
- and lp.last_tick_done.get("name") == "heal"
341
- and lp.last_tick_done.get("ok") is False,
342
- "T3d3 失败档出口必记 ok=False(确定性:直接驱动,不依赖调度)",
343
- lp.last_tick_done)
344
-
345
-
346
- # ---------------------------------------------------------------- T4
347
- def t4():
348
- print("== T4 进度面:current_tick / last_tick_done / last_tick_error / "
349
- "stale_tick ==")
350
- lp = _new_loop()
351
- seen = {}
352
-
353
- def fn():
354
- seen["mem"] = lp.current_tick
355
- seen["stamp"] = SUS.read_stamp(lp.name, lp.d)
356
-
357
- lp._wrap_tick("scrub", fn)()
358
- ct = seen.get("mem") or {}
359
- ok(ct.get("name") == "scrub" and "started_at" in ct
360
- and ct.get("pid") == os.getpid(),
361
- "T4a tick 入口写 current_tick={name, started_at, pid}", ct)
362
- ok(((seen.get("stamp") or {}).get("current_tick") or {}).get("name")
363
- == "scrub",
364
- "T4a2 **进入档即刷既有状态面**(心跳戳里读得到 current_tick——"
365
- "卡住场景下也读得到)", seen.get("stamp"))
366
- ok(lp.current_tick is None,
367
- "T4b tick 出口清 current_tick", lp.current_tick)
368
- ok(lp.last_tick_done is not None
369
- and lp.last_tick_done.get("name") == "scrub"
370
- and lp.last_tick_done.get("ok") is True
371
- and "t" in lp.last_tick_done,
372
- "T4b2 tick 出口记 last_tick_done={name, t, ok}", lp.last_tick_done)
373
-
374
- lp._wrap_tick("heal", lambda: (_ for _ in ()).throw(ValueError("t4-e")))()
375
- ok(lp.last_tick_error is not None
376
- and lp.last_tick_error.get("name") == "heal"
377
- and "ValueError: t4-e" in lp.last_tick_error.get("error", ""),
378
- "T4c 失败档记 last_tick_error(类名+摘要)", lp.last_tick_error)
379
- ok(lp.last_tick_done is not None and lp.last_tick_done.get("ok") is False,
380
- "T4c2 失败档 last_tick_done.ok=False", lp.last_tick_done)
381
-
382
- st = lp.status()
383
- ok("current_tick" in st and "last_tick_done" in st
384
- and "last_tick_error" in st,
385
- "T4d status 输出含进度三字段(cg(op=sustain,action=status) 同源)",
386
- sorted(st))
387
- ok(st["last_tick_done"]["name"] == "heal"
388
- and st["last_tick_done"]["ok"] is False,
389
- "T4d2 status 的 last_tick_done 反映最近一档(失败态可见)", st["last_tick_done"])
390
-
391
- lp.current_tick = {"name": "sleep", "started_at": time.time() - 9000.0,
392
- "pid": os.getpid()}
393
- st2 = lp.status()
394
- ok(bool(st2["stale_tick"]) and st2["stale_tick"].get("tick") == "sleep",
395
- "T4e 过期 current_tick → status 报 stale_tick(档名=sleep)",
396
- st2["stale_tick"])
397
- ok(bool(st2["stale_tick"])
398
- and "sleep" in st2["stale_tick"].get("alert", "")
399
- and "9000" in st2["stale_tick"].get("alert", ""),
400
- "T4e2 stale_tick.alert 含档名与已运行时长", st2["stale_tick"])
401
- ok(st2["current_tick"].get("running_s") >= 9000,
402
- "T4e3 current_tick 附已运行秒数 running_s", st2["current_tick"])
403
- lp.current_tick = {"name": "sleep", "started_at": time.time() - 10.0,
404
- "pid": os.getpid()}
405
- ok(lp.status()["stale_tick"] is None,
406
- "T4f 负对照:未超阈值不报 stale_tick(不误报)")
407
- # 跨进程回落:内存清空后仍能从既有状态面读到(写点是戳,不是内存独有)
408
- lp.last_tick_done = None
409
- st3 = lp.status()
410
- ok(st3["last_tick_done"] is not None,
411
- "T4g 跨进程回落:内存清空后 last_tick_done 仍可从戳读到",
412
- st3["last_tick_done"])
413
-
414
-
415
- # ---------------------------------------------------------------- T5
416
- def t5():
417
- print("== T5 审计断言:加固面 subprocess.run 带 timeout+DEVNULL;"
418
- "whitebox Popen 保持协议面 ==")
419
-
420
- def run_calls(rel):
421
- tree = ast.parse(_rel_text(rel))
422
- out = []
423
- for node in ast.walk(tree):
424
- if (isinstance(node, ast.Call)
425
- and isinstance(node.func, ast.Attribute)
426
- and node.func.attr == "run"
427
- and isinstance(node.func.value, ast.Name)
428
- and node.func.value.id == "subprocess"):
429
- out.append(node)
430
- return out
431
-
432
- def has_kw(node, key, devnull=False):
433
- for kw in node.keywords:
434
- if kw.arg != key:
435
- continue
436
- if not devnull:
437
- return True
438
- v = kw.value
439
- return (isinstance(v, ast.Attribute) and v.attr == "DEVNULL"
440
- and isinstance(v.value, ast.Name)
441
- and v.value.id == "subprocess")
442
- return False
443
-
444
- for rel in _AUDIT_RUN_FILES:
445
- nodes = run_calls(rel)
446
- ok(len(nodes) >= 1, "T5 前置:%s 内有 subprocess.run 调用(%d 处)"
447
- % (rel, len(nodes)))
448
- for i, node in enumerate(nodes, 1):
449
- ok(has_kw(node, "timeout"),
450
- "T5a %s:%d subprocess.run 带 timeout=" % (rel, node.lineno))
451
- ok(has_kw(node, "stdin", devnull=True),
452
- "T5b %s:%d subprocess.run 带 stdin=subprocess.DEVNULL"
453
- % (rel, node.lineno))
454
-
455
- # whitebox:长驻对话协议面(stdin=PIPE)——**不在加固面**,保持原形态
456
- tree = ast.parse(_rel_text(_WHITEBOX_REL))
457
- popens = [n for n in ast.walk(tree)
458
- if isinstance(n, ast.Call)
459
- and isinstance(n.func, ast.Attribute)
460
- and n.func.attr == "Popen"
461
- and isinstance(n.func.value, ast.Name)
462
- and n.func.value.id == "subprocess"]
463
- ok(len(popens) >= 1, "T5c 前置:whitebox.py 内有 subprocess.Popen(%d 处)"
464
- % len(popens))
465
- for node in popens:
466
- stdin_kw = next((kw for kw in node.keywords if kw.arg == "stdin"), None)
467
- ok(stdin_kw is not None
468
- and isinstance(stdin_kw.value, ast.Attribute)
469
- and stdin_kw.value.attr == "PIPE",
470
- "T5d whitebox Popen 保持协议面原形态(stdin=PIPE,不加固)"
471
- "(%s:%d)" % (_WHITEBOX_REL, node.lineno))
472
-
473
-
474
- # ---------------------------------------------------------------- 变异表
475
- # 锚点 = (名字, rel, old, new)。每次变异必须让套件**转红**:
476
- # M1 主修删 timeout=(_git 退回无界等待)→ T1b / T2a 红
477
- # M2 主修删 stdin=DEVNULL(子进程继承活管道 stdin)→ T1c 红
478
- # M3 进度面删「进入写点」→ T4a / T4a2 红
479
- # M4 六档 except 删 last_tick_error 记录(退回全静默)→ T3c / T4c 红
480
- _MUTATIONS = (
481
- ("删 timeout=(_git 退回无界等待)", "md_cg/sleep.py",
482
- " env=env, shell=False,\n"
483
- " timeout=_GIT_TIMEOUT_S,\n"
484
- " stdin=subprocess.DEVNULL)",
485
- " env=env, shell=False,\n"
486
- " stdin=subprocess.DEVNULL)"),
487
- ("删 stdin=DEVNULL(继承活管道 stdin)", "md_cg/sleep.py",
488
- " env=env, shell=False,\n"
489
- " timeout=_GIT_TIMEOUT_S,\n"
490
- " stdin=subprocess.DEVNULL)",
491
- " env=env, shell=False,\n"
492
- " timeout=_GIT_TIMEOUT_S)"),
493
- ("删进度面进入写点(卡住读不到档)", "md_cg/sustain.py",
494
- ' self.current_tick = {"name": name, "started_at": time.time(),\n'
495
- ' "pid": os.getpid()}\n'
496
- ' self._flush_progress()\n',
497
- ""),
498
- ("删失败档 last_tick_error(退回全静默)", "md_cg/sustain.py",
499
- " except Exception as e: # noqa: BLE001\n"
500
- " ok_ = False\n"
501
- " self.last_tick_error = {\"name\": name, \"t\": time.time(),\n"
502
- " \"error\": \"%s: %s\" % (type(e).__name__,\n"
503
- " str(e)[:200])}\n",
504
- " except Exception: # noqa: BLE001\n"
505
- " ok_ = False\n"),
506
- )
507
-
508
- #: 空转检出对照(meta 自证,`--mutate --null`):new==old 的「无害变异」——
509
- #: 行为零变化、自身红项必须为 0 且被判 MISS。若哪天「本轮红项」判定口径
510
- #: 退化为累计计数(累计恒非空),本对照立即转 FAIL(钉住的正是复核打回
511
- #: 实证过的那条假阳性通道)。锚点取 `_git` 调用里一行行为零变化的文本。
512
- _NULL_MUTATION = ("空转对照(new==old,行为零变化)", "md_cg/sleep.py",
513
- " env=env, shell=False,\n",
514
- " env=env, shell=False,\n")
515
-
516
-
517
- def _exec_module(name: str, rel: str, text: str):
518
- ns = {"__name__": name, "__package__": "md_cg",
519
- "__file__": os.path.join(_REPO, rel)}
520
- exec(compile(text, rel, "exec"), ns) # noqa: S102 —— 基线自证用
521
- m = types.ModuleType(name)
522
- m.__dict__.update(ns)
523
- return m
524
-
525
-
526
- def _run_groups() -> int:
527
- for fn in (t1, t2, t3, t4, t5):
528
- try:
529
- fn()
530
- except Exception as e: # noqa: BLE001
531
- ok(False, "%s 组抛异常:%s: %s" % (fn.__name__, type(e).__name__, e))
532
- return len(_FAIL)
533
-
534
-
535
- def _mutate_once(name: str, rel: str, old: str, new: str):
536
- """跑一条变异并返回**本轮自身**读数 (reds_self, reds_lines, detail)。
537
-
538
- 红项口径(复核打回修复,2026-10-06):`_FAIL` 是**全局累计**列表,
539
- 故「本轮红项」必须取**调用前后长度差**——直接拿 `len(_FAIL)` 当本轮
540
- 红项会让「判据空转」检测失效(累计值恒非空 ⇒ 空转变异也会被记成
541
- 「红」并放行)。本轮自身红项还须与输出里 FAIL 行数**账实相符**。
542
- """
543
- src = _rel_text(rel)
544
- if old not in src:
545
- return None, [], "ANCHOR-MISS:锚点在 %s 源码里找不到(实现改了却没同步" \
546
- "本表)" % rel
547
- base = len(_FAIL) # 本轮起点:只数本轮自身的红项
548
- _SRC[rel] = src.replace(old, new, 1)
549
- try:
550
- mut = _exec_module("md_cg._bounded_mut", rel, _SRC[rel])
551
- if rel == "md_cg/sleep.py":
552
- globals()["SL"] = mut
553
- else:
554
- globals()["SUS"] = mut
555
- with contextlib.redirect_stdout(buf := io.StringIO()):
556
- _run_groups()
557
- detail = buf.getvalue()
558
- finally:
559
- globals()["SL"] = _REAL_SL
560
- globals()["SUS"] = _REAL_SUS
561
- _SRC.pop(rel, None)
562
- reds = len(_FAIL) - base # **本轮自身**红项数
563
- reds_lines = [l for l in detail.splitlines()
564
- if l.strip().startswith("FAIL ")]
565
- return reds, reds_lines, detail
566
-
567
-
568
- def _mutate_mode(list_only: bool = False) -> int:
569
- print("!! 定点变异自证:逐条把机制改回「改动前/错误」形态,套件必须转红"
570
- "(红项 = 本轮自身,非法用全局累计值)\n")
571
- if list_only:
572
- for name, rel, _o, _n in _MUTATIONS:
573
- print(" %-38s [%s]" % (name, rel))
574
- return 0
575
- anchor_miss, bad = [], []
576
- base0 = len(_FAIL)
577
- with contextlib.redirect_stdout(io.StringIO()):
578
- _run_groups()
579
- clean = len(_FAIL) - base0
580
- print(" 未变异基线:失败=%d(必须为 0)" % clean)
581
- if clean:
582
- bad.append("未变异基线即失败")
583
-
584
- for name, rel, old, new in _MUTATIONS:
585
- reds, reds_lines, detail = _mutate_once(name, rel, old, new)
586
- if reds is None:
587
- print(" ANCHOR-MISS %s —— %s" % (name, detail))
588
- anchor_miss.append(name)
589
- continue
590
- verdict = "红" if reds else "**仍全绿 = 该判据空转**"
591
- print(" %s %-38s 自身红项=%d(本轮;基线=%d) %s"
592
- % ("OK " if reds else "MISS ", name, reds, clean, verdict))
593
- for l in reds_lines: # **全量**打印(回报即读数,不截断)
594
- print(" " + l.strip()[5:])
595
- if len(reds_lines) != reds:
596
- # 账实不符 = 计数面自身有缺陷——按失败判(fail-closed)
597
- print(" !账实不符:FAIL 行数=%d ≠ 自身红项=%d——计数面缺陷"
598
- % (len(reds_lines), reds))
599
- bad.append(name + "(账实不符)")
600
- if not reds:
601
- bad.append(name)
602
-
603
- if anchor_miss:
604
- print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
605
- print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
606
- return 2
607
- print("\n定点变异自证:%s"
608
- % ("PASS(每处机制都有一条断言把它钉死)" if not bad
609
- else "FAIL —— " + "、".join(bad)))
610
- return 0 if not bad else 1
611
-
612
-
613
- def _null_mode() -> int:
614
- """空转检出对照(meta 自证):new==old 的「无害变异」必须被判 MISS。
615
-
616
- 钉住的缺陷类别(复核打回实证):若「本轮红项」误用全局累计值(累计恒
617
- 非空),空转变异会被记成「红」并放行——`--mutate` 的 fail-closed 承诺
618
- (「变异未按预期转红 = 退出码 1」)随之失效。本对照即钉住该检出能力。
619
- """
620
- print("!! 空转检出对照:一条 new==old 的「无害变异」——必须被判 MISS"
621
- "(不得凭任何累计值蒙混)\n")
622
- name, rel, old, new = _NULL_MUTATION
623
- reds, reds_lines, detail = _mutate_once(name, rel, old, new)
624
- if reds is None:
625
- print(" ANCHOR-MISS %s —— %s" % (name, detail))
626
- return 2
627
- detected = reds == 0 and not reds_lines
628
- print(" 变异=%s 自身红项=%d(本轮) FAIL 行数=%d ⇒ %s"
629
- % (name, reds, len(reds_lines),
630
- "MISS(如期检出空转,判定有效)" if detected
631
- else "红(**空转漏检 = 判据失效**,fail-closed 不成立)"))
632
- print("空转检出对照:%s" % ("PASS" if detected else "FAIL"))
633
- return 0 if detected else 1
634
-
635
-
636
- def main() -> int:
637
- _sandbox_env()
638
- try:
639
- if "--mutate" in sys.argv:
640
- if "--null" in sys.argv:
641
- return _null_mode()
642
- return _mutate_mode("--list" in sys.argv)
643
- n = _run_groups()
644
- print("\nSUMMARY: 常驻卡死防护守卫:%d 通过,%d 失败" % (len(_PASS), n))
645
- return 0 if not n else 1
646
- finally:
647
- _restore_env()
648
- shutil.rmtree(_TMP, ignore_errors=True)
649
-
650
-
651
- if __name__ == "__main__":
652
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """常驻循环卡死防护与观测守卫(issue #63)。
3
+
4
+ 背景(外部 issue #63 三条根因,全部本文件钉死):
5
+
6
+ ① `sleep._git()` **无 timeout=**——子进程无界等待(实测停 9.5 小时);
7
+ ② 同处**未指定 stdin** ⇒ 子进程继承父进程 stdin(DSH 常驻宿主的
8
+ JSON-RPC 活管道)——活管道下读 stdin 的子进程永不 EOF;
9
+ ③ tick 台账在 `run_cycle` **返回后**才写 ⇒ 卡住期间外部无法知道卡在哪档
10
+ (`phases` 空)。
11
+
12
+ 修法的可判据面:
13
+
14
+ T1 参数面——`sleep._git` 调 `subprocess.run` 必带
15
+ `timeout=_GIT_TIMEOUT_S` 与 `stdin=subprocess.DEVNULL`(捕获 kwargs 判据);
16
+ 旁证(机理复现,等价形态):活管道(PIPE 不写不关)下读 stdin 的子进程
17
+ 悬挂;DEVNULL 下 0.02s 级立即 EOF 返回。旁证二:真挂起子进程 + 同形态
18
+ timeout → 真 `TimeoutExpired` 且有界(本机 Python 超时机制在位)。
19
+ T2 真超时——替身按 `subprocess.run(timeout=)` 契约行事(跑满一个 timeout
20
+ 后抛 `TimeoutExpired`):`_git_ok` 抛 `SleepError`(`SleepGitTimeout`),
21
+ 消息含「超时」「已被 kill」与命令名,耗时 **≈ timeout(有界)**;
22
+ 并钉「可区分」:rc≠0 走「失败」文案、与超时文案分开。
23
+ T3 循环续走回归——某档 tick 抛异常 → `_run` 不中断(该档下一轮照常,
24
+ 其它档不受影响)——既有能力回归。
25
+ T4 进度面——tick 入口写 `current_tick`(且**进入即刷既有心跳戳**)/ 出口清
26
+ 并记 `last_tick_done`;失败档记 `last_tick_error`(容忍≠静默);`status`
27
+ 展示三字段;构造过期 `current_tick` → `status` 报 `stale_tick`
28
+ (含档名与已运行时长;负对照:未超不报)。
29
+ T5 审计断言——interop / audit / units / bench×3 / sleep 的 `subprocess.run`
30
+ 调用(AST 参数面)带 timeout 与 `stdin=DEVNULL`;whitebox 的 Popen
31
+ 保持协议面原形态(stdin=PIPE,**不在加固面**)。
32
+
33
+ 运行:python -X utf8 -m md_cg.test_sustain_bounded
34
+ python -X utf8 -m md_cg.test_sustain_bounded --mutate # 变异自证
35
+ python -X utf8 -m md_cg.test_sustain_bounded --mutate --list # 只列变异表
36
+ python -X utf8 -m md_cg.test_sustain_bounded --mutate --null # 空转检出对照
37
+
38
+ 退出码(fail-closed):0 = 全绿;1 = 有断言失败 / 变异未按预期转红;
39
+ 2 = ANCHOR-MISS(变异锚点在当前源码里找不到——实现改了却没同步本表)。
40
+
41
+ **红项口径(复核打回修复,2026-10-06)**:每条变异的「自身红项」= 该条运行
42
+ 前后 `_FAIL` 长度差——**不得**拿 `len(_FAIL)` 当本轮红项(累计值恒非空,
43
+ 会让「判据空转」检测失效、空转变异被静默放行);红项行**全量**打印且与
44
+ 自身红项数**账实相符**(不符按失败判)。该缺陷类别由 `--mutate --null`
45
+ (new==old 的无害变异必须被判 MISS)钉住。
46
+
47
+ **基线纪律**:不以 git HEAD 为基线源——「改动前形态」由在当前工作区源码上做
48
+ **定点文本变异**(`_MUTATIONS`)复现,锚点漂移即退出码 2。
49
+ """
50
+ from __future__ import annotations
51
+
52
+ import ast
53
+ import contextlib
54
+ import io
55
+ import os
56
+ import shutil
57
+ import subprocess
58
+ import sys
59
+ import tempfile
60
+ import time
61
+ import types
62
+
63
+ from . import sleep as SL
64
+ from . import sustain as SUS
65
+
66
+ _PASS = []
67
+ _FAIL = []
68
+ _SRC = {}
69
+ _TMP = tempfile.mkdtemp(prefix="mdcg_bounded_")
70
+ _SAVED = {}
71
+ _REAL_SL = SL
72
+ _REAL_SUS = SUS
73
+
74
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
75
+
76
+ #: T5 的审计面:这些文件里的 `subprocess.run` 调用必须带 timeout 与
77
+ #: stdin=DEVNULL(issue #63 同批加固);whitebox 的 Popen 单列(不在加固面)。
78
+ _AUDIT_RUN_FILES = ("md_cg/sleep.py", "md_cg/interop.py", "md_cg/audit.py",
79
+ "md_cg/units.py", "md_cg/bench_locomo_zh.py",
80
+ "md_cg/bench_zh_mad.py", "md_cg/bench_governance.py")
81
+ #: 不在加固面的既有正确形态(免误伤):whitebox 的 Popen 是**长驻对话协议面**
82
+ #: (stdin=PIPE 与后端持续对话,给 DEVNULL 会改变协议语义)。
83
+ _WHITEBOX_REL = "md_cg/whitebox.py"
84
+
85
+
86
+ def ok(cond, msg, extra=""):
87
+ (_PASS if cond else _FAIL).append(msg)
88
+ print((" PASS " if cond else " FAIL ") + msg
89
+ + ((" ← " + str(extra)) if (extra and not cond) else ""))
90
+
91
+
92
+ def _rel_text(rel: str) -> str:
93
+ if rel in _SRC:
94
+ return _SRC[rel]
95
+ with open(os.path.join(_REPO, rel), encoding="utf-8") as f:
96
+ return f.read()
97
+
98
+
99
+ def _sandbox_env():
100
+ for k in ("MDCG_ROOT", "MDCG_AUX_ROOT", "MDCG_STATE_ROOT",
101
+ "MDCG_SUSTAIN_DIR", "MDCG_SUSTAIN", "MDCG_SLEEP_GITDIR",
102
+ "MDCG_SLEEP_SHADOW"):
103
+ _SAVED[k] = os.environ.get(k)
104
+ os.environ.pop(k, None)
105
+ os.environ["MDCG_SUSTAIN_DIR"] = os.path.join(_TMP, "sustain")
106
+ os.environ["MDCG_ROOT"] = os.path.join(_TMP, "data")
107
+
108
+
109
+ def _restore_env():
110
+ for k, v in _SAVED.items():
111
+ if v is None:
112
+ os.environ.pop(k, None)
113
+ else:
114
+ os.environ[k] = v
115
+
116
+
117
+ class _FakeCG:
118
+ """最小 cg 替身:SustainLoop 只消费 .root(写戳 / 会话账本读点)。"""
119
+
120
+ def __init__(self, root):
121
+ self.root = root
122
+
123
+
124
+ def _new_loop(**kw):
125
+ root = os.path.join(_TMP, "data")
126
+ os.makedirs(root, exist_ok=True)
127
+ d = os.path.join(_TMP, "sustain")
128
+ os.makedirs(d, exist_ok=True)
129
+ kw.setdefault("name", "md_cg_bounded")
130
+ kw.setdefault("auto_sleep", True)
131
+ kw.setdefault("sleep_merge", "auto")
132
+ kw.setdefault("sleep_window", "")
133
+ kw.setdefault("sleep_scrub_apply", False)
134
+ return SUS.SustainLoop(_FakeCG(root), d=d, **kw)
135
+
136
+
137
+ # ---------------------------------------------------------------- T1
138
+ def t1():
139
+ print("== T1 参数面:_git 必带 timeout=_GIT_TIMEOUT_S 与 stdin=DEVNULL ==")
140
+ S = globals()["SL"]
141
+ real_run = subprocess.run
142
+ calls = []
143
+
144
+ def fake(argv, **kw):
145
+ calls.append((list(argv), dict(kw)))
146
+ return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
147
+
148
+ subprocess.run = fake
149
+ try:
150
+ S._git("<G>", "<root>", "status", "--short")
151
+ finally:
152
+ subprocess.run = real_run
153
+ ok(len(calls) == 1, "T1 前置:_git 恰调 subprocess.run 一次", calls)
154
+ if calls:
155
+ argv, kw = calls[0]
156
+ # 回显面**剔除 env**(含本机敏感变量,纪律第 9 条:敏感信息隔离)
157
+ safe = {k: v for k, v in kw.items() if k != "env"}
158
+ ok(argv[:3] == ["git", "--git-dir=<G>", "--work-tree=<root>"],
159
+ "T1a argv 显式 --git-dir / --work-tree(唯一出口形态不变)", argv)
160
+ ok(kw.get("timeout") == S._GIT_TIMEOUT_S
161
+ and isinstance(kw.get("timeout"), (int, float)),
162
+ "T1b **_git 必带 timeout=_GIT_TIMEOUT_S**(%r)——无界等待被闸住"
163
+ % (kw.get("timeout"),), safe)
164
+ ok(kw.get("stdin") is subprocess.DEVNULL,
165
+ "T1c **_git 必带 stdin=subprocess.DEVNULL**——不继承父进程 stdin"
166
+ "(常驻宿主下是 JSON-RPC 活管道)", safe)
167
+ ok(kw.get("shell") is False and kw.get("capture_output") is True,
168
+ "T1d 既有形态保持(shell=False + capture_output=True)", safe)
169
+ ok((kw.get("env") or {}).get("PYTHONUTF8") == "1",
170
+ "T1e env 带 PYTHONUTF8=1(既有形态保持;不回显 env 内容)")
171
+
172
+ # 机理旁证(等价形态):活管道 ⇒ 读 stdin 的子进程悬挂;DEVNULL ⇒ 立即 EOF
173
+ code = "import sys\nsys.stdin.read()\nprint('EOF-OK')\n"
174
+ p = subprocess.Popen([sys.executable, "-c", code], stdin=subprocess.PIPE,
175
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
176
+ text=True, encoding="utf-8", errors="replace")
177
+ try:
178
+ time.sleep(0.6)
179
+ hung = p.poll() is None
180
+ finally:
181
+ p.kill()
182
+ with contextlib.suppress(Exception):
183
+ p.communicate(timeout=5)
184
+ ok(hung, "T1f 机理旁证:**活管道**(PIPE 不写不关)下读 stdin 的子进程"
185
+ "悬挂(poll=None;DSH JSON-RPC 管道的等价形态)")
186
+ t0 = time.time()
187
+ r = subprocess.run([sys.executable, "-c", code], stdin=subprocess.DEVNULL,
188
+ capture_output=True, text=True, encoding="utf-8",
189
+ errors="replace", timeout=15)
190
+ dt = time.time() - t0
191
+ ok(r.returncode == 0 and "EOF-OK" in (r.stdout or ""),
192
+ "T1g 机理旁证:**stdin=DEVNULL** 下同一子进程立即 EOF 返回"
193
+ "(%.2fs)" % dt, (r.returncode, r.stdout, r.stderr))
194
+ t0 = time.time()
195
+ timed_out = False
196
+ try:
197
+ subprocess.run([sys.executable, "-c", "import time; time.sleep(30)"],
198
+ stdin=subprocess.DEVNULL, capture_output=True,
199
+ timeout=0.5)
200
+ except subprocess.TimeoutExpired:
201
+ timed_out = True
202
+ dt = time.time() - t0
203
+ ok(timed_out and dt < 5.0,
204
+ "T1h 机理旁证:真子进程 + timeout → 真 TimeoutExpired 且有界"
205
+ "(%.2fs)——本机 timeout 机制在位" % dt)
206
+
207
+
208
+ # ---------------------------------------------------------------- T2
209
+ def t2():
210
+ print("== T2 真超时:SleepError + 耗时≈timeout(有界)+ 消息含「超时」 ==")
211
+ S = globals()["SL"]
212
+ g = S._git.__globals__
213
+ real_run = subprocess.run
214
+ real_tmo = g["_GIT_TIMEOUT_S"]
215
+ calls = []
216
+
217
+ def fake(argv, **kw):
218
+ """按 `subprocess.run(timeout=)` 契约行事:跑满一个 timeout 后 kill 抛出。
219
+
220
+ 无 timeout(旧形态)⇒ 跑满 2s 才返回(无界等待的等价模拟——T1b/T2a
221
+ 会在该形态下转红)。
222
+ """
223
+ calls.append((list(argv), dict(kw)))
224
+ tmo = kw.get("timeout")
225
+ if tmo is None:
226
+ time.sleep(2.0)
227
+ return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
228
+ time.sleep(float(tmo))
229
+ raise subprocess.TimeoutExpired(cmd=argv, timeout=float(tmo))
230
+
231
+ g["_GIT_TIMEOUT_S"] = 0.3 # 测试用短 timeout(模块单点可调)
232
+ subprocess.run = fake
233
+ t0 = time.time()
234
+ raised = None
235
+ try:
236
+ try:
237
+ S._git_ok("<G>", "<root>", "status")
238
+ except S.SleepError as e:
239
+ raised = e
240
+ finally:
241
+ subprocess.run = real_run
242
+ g["_GIT_TIMEOUT_S"] = real_tmo
243
+ dt = time.time() - t0
244
+ ok(raised is not None and isinstance(raised, S.SleepGitTimeout),
245
+ "T2a 超时**不吞**:_git/_git_ok 抛 SleepError(SleepGitTimeout)", raised)
246
+ ok(raised is not None and "超时" in str(raised),
247
+ "T2b 消息含「超时」", str(raised))
248
+ ok(raised is not None and "已被 kill" in str(raised),
249
+ "T2c 消息含「已被 kill」(kill 语义明示)", str(raised))
250
+ ok(raised is not None and "status" in str(raised),
251
+ "T2d 消息含命令名", str(raised))
252
+ ok(raised is not None and "index.lock" in str(raised),
253
+ "T2e 消息含残留锁人工核删指引(不自动删)", str(raised))
254
+ ok(raised is not None and dt <= 0.3 * 3,
255
+ "T2f **耗时有界**(≈timeout:%.2fs ≤ 3×0.3s)——不是无界等待" % dt, dt)
256
+
257
+ # 可区分(issue #63):rc≠0 的失败走「失败」文案,与超时面分开
258
+ def fake_fail(argv, **kw):
259
+ return subprocess.CompletedProcess(argv, 1, stdout="",
260
+ stderr="fatal: boom")
261
+
262
+ subprocess.run = fake_fail
263
+ raised2 = None
264
+ try:
265
+ try:
266
+ S._git_ok("<G>", "<root>", "status")
267
+ except S.SleepError as e2:
268
+ raised2 = e2
269
+ finally:
270
+ subprocess.run = real_run
271
+ ok(raised2 is not None and "失败" in str(raised2)
272
+ and "超时" not in str(raised2),
273
+ "T2g **可区分**:rc≠0 走「失败」文案、不含「超时」(两条失败面分开)",
274
+ str(raised2))
275
+
276
+
277
+ # ---------------------------------------------------------------- T3
278
+ def t3():
279
+ print("== T3 循环续走回归:某档抛异常 → _run 不中断(下一轮照常)==")
280
+ lp = _new_loop(beat_interval=30.0, heal_interval=0.15, scrub_interval=0.3,
281
+ evolve_interval=60.0, tidy_interval=60.0,
282
+ sleep_interval=60.0)
283
+ log = []
284
+
285
+ def bad():
286
+ log.append(("heal", time.time()))
287
+ raise RuntimeError("t3-fail-once")
288
+
289
+ def good():
290
+ log.append(("scrub", time.time()))
291
+
292
+ lp._tick_heal = bad
293
+ lp._tick_scrub = good
294
+ lp._tick_evolve = lambda: log.append(("evolve", time.time()))
295
+ lp._tick_tidy = lambda: log.append(("tidy", time.time()))
296
+ lp._tick_sleep = lambda: log.append(("sleep", time.time()))
297
+ lp.start()
298
+ try:
299
+ time.sleep(1.1)
300
+ finally:
301
+ lp.stop()
302
+ n_heal = sum(1 for t, _ in log if t == "heal")
303
+ n_scrub = sum(1 for t, _ in log if t == "scrub")
304
+ ok(n_heal >= 2,
305
+ "T3a 某档 tick 抛异常后**不中断**:该档下一轮照常调度(heal×%d)"
306
+ % n_heal, log)
307
+ ok(n_scrub >= 1,
308
+ "T3b 其它档不受影响(scrub×%d)" % n_scrub, log)
309
+ ok(lp.last_tick_error is not None
310
+ and lp.last_tick_error.get("name") == "heal"
311
+ and "RuntimeError: t3-fail-once" in lp.last_tick_error.get("error", ""),
312
+ "T3c 异常**不再全静默**:last_tick_error 记 {档名, 类名+摘要}",
313
+ lp.last_tick_error)
314
+ # issue #213 Q9(2026-10-13 DSH 端):原 T3d 断言「最近一档 == 失败档」,
315
+ # 即 last_tick_done.get("ok") is False——该断言**结构性竞态**,不是负载敏感。
316
+ # 机理:_run 是**单线程顺序**执行(beat→heal→scrub→evolve→tidy→sleep,
317
+ # 固定次序,同一轮内逐个判到期)。heal(0.15s) 与 scrub(0.3s) 同轮到期时,
318
+ # **scrub 必然在 heal 之后写 last_tick_done**,把 heal 的 ok=False 覆盖成
319
+ # ok=True。故最后一档是 heal 还是 scrub,只取决于 stop() 落在哪——
320
+ # 实测扫 14 个 stop 时刻,**6 个失败**(0.5/0.6/0.9/1.0/1.3/1.4s)。
321
+ # 更正原判读:「残留的 scrub 任务抢先落 ok=True」不成立——**没有第二个任务**,
322
+ # 循环里各档就是同一线程按序跑的;错的不是执行体,是断言把「最后一档必为
323
+ # heal」当成了不变式,而循环从不保证这一点。
324
+ # 改法:钉**可从日志交叉核验**的不变式——last_tick_done 必须等于日志里最后
325
+ # 跑过的那一档,且 ok 必须与该档真实结局一致(heal 必失败、scrub 必成功)。
326
+ # 判别力不降反升:错配 / 漏记 / ok 翻转都会转红;且不再依赖 stop 时刻。
327
+ _last_name = log[-1][0] if log else None
328
+ _ltd = lp.last_tick_done
329
+ ok(_ltd is not None and _ltd.get("name") == _last_name,
330
+ "T3d last_tick_done 与最后跑过的一档一致(%s)" % _last_name, _ltd)
331
+ ok(_ltd is not None and _ltd.get("ok") is (_last_name != "heal"),
332
+ "T3d2 ok 与该档真实结局一致(heal 必失败 ⇒ ok=False)", _ltd)
333
+ # 失败档「不静默」的**无条件**判据(不依赖调度次序):直接驱动一档必失败的
334
+ # wrapped tick,出口必须落 ok=False——原 T3d 想钉的就是这条,此处确定性钉死。
335
+ lp._wrap_ticks()
336
+ def _boom():
337
+ raise RuntimeError("t3-direct")
338
+ lp._wrap_tick("heal", _boom)()
339
+ ok(lp.last_tick_done is not None
340
+ and lp.last_tick_done.get("name") == "heal"
341
+ and lp.last_tick_done.get("ok") is False,
342
+ "T3d3 失败档出口必记 ok=False(确定性:直接驱动,不依赖调度)",
343
+ lp.last_tick_done)
344
+
345
+
346
+ # ---------------------------------------------------------------- T4
347
+ def t4():
348
+ print("== T4 进度面:current_tick / last_tick_done / last_tick_error / "
349
+ "stale_tick ==")
350
+ lp = _new_loop()
351
+ seen = {}
352
+
353
+ def fn():
354
+ seen["mem"] = lp.current_tick
355
+ seen["stamp"] = SUS.read_stamp(lp.name, lp.d)
356
+
357
+ lp._wrap_tick("scrub", fn)()
358
+ ct = seen.get("mem") or {}
359
+ ok(ct.get("name") == "scrub" and "started_at" in ct
360
+ and ct.get("pid") == os.getpid(),
361
+ "T4a tick 入口写 current_tick={name, started_at, pid}", ct)
362
+ ok(((seen.get("stamp") or {}).get("current_tick") or {}).get("name")
363
+ == "scrub",
364
+ "T4a2 **进入档即刷既有状态面**(心跳戳里读得到 current_tick——"
365
+ "卡住场景下也读得到)", seen.get("stamp"))
366
+ ok(lp.current_tick is None,
367
+ "T4b tick 出口清 current_tick", lp.current_tick)
368
+ ok(lp.last_tick_done is not None
369
+ and lp.last_tick_done.get("name") == "scrub"
370
+ and lp.last_tick_done.get("ok") is True
371
+ and "t" in lp.last_tick_done,
372
+ "T4b2 tick 出口记 last_tick_done={name, t, ok}", lp.last_tick_done)
373
+
374
+ lp._wrap_tick("heal", lambda: (_ for _ in ()).throw(ValueError("t4-e")))()
375
+ ok(lp.last_tick_error is not None
376
+ and lp.last_tick_error.get("name") == "heal"
377
+ and "ValueError: t4-e" in lp.last_tick_error.get("error", ""),
378
+ "T4c 失败档记 last_tick_error(类名+摘要)", lp.last_tick_error)
379
+ ok(lp.last_tick_done is not None and lp.last_tick_done.get("ok") is False,
380
+ "T4c2 失败档 last_tick_done.ok=False", lp.last_tick_done)
381
+
382
+ st = lp.status()
383
+ ok("current_tick" in st and "last_tick_done" in st
384
+ and "last_tick_error" in st,
385
+ "T4d status 输出含进度三字段(cg(op=sustain,action=status) 同源)",
386
+ sorted(st))
387
+ ok(st["last_tick_done"]["name"] == "heal"
388
+ and st["last_tick_done"]["ok"] is False,
389
+ "T4d2 status 的 last_tick_done 反映最近一档(失败态可见)", st["last_tick_done"])
390
+
391
+ lp.current_tick = {"name": "sleep", "started_at": time.time() - 9000.0,
392
+ "pid": os.getpid()}
393
+ st2 = lp.status()
394
+ ok(bool(st2["stale_tick"]) and st2["stale_tick"].get("tick") == "sleep",
395
+ "T4e 过期 current_tick → status 报 stale_tick(档名=sleep)",
396
+ st2["stale_tick"])
397
+ ok(bool(st2["stale_tick"])
398
+ and "sleep" in st2["stale_tick"].get("alert", "")
399
+ and "9000" in st2["stale_tick"].get("alert", ""),
400
+ "T4e2 stale_tick.alert 含档名与已运行时长", st2["stale_tick"])
401
+ ok(st2["current_tick"].get("running_s") >= 9000,
402
+ "T4e3 current_tick 附已运行秒数 running_s", st2["current_tick"])
403
+ lp.current_tick = {"name": "sleep", "started_at": time.time() - 10.0,
404
+ "pid": os.getpid()}
405
+ ok(lp.status()["stale_tick"] is None,
406
+ "T4f 负对照:未超阈值不报 stale_tick(不误报)")
407
+ # 跨进程回落:内存清空后仍能从既有状态面读到(写点是戳,不是内存独有)
408
+ lp.last_tick_done = None
409
+ st3 = lp.status()
410
+ ok(st3["last_tick_done"] is not None,
411
+ "T4g 跨进程回落:内存清空后 last_tick_done 仍可从戳读到",
412
+ st3["last_tick_done"])
413
+
414
+
415
+ # ---------------------------------------------------------------- T5
416
+ def t5():
417
+ print("== T5 审计断言:加固面 subprocess.run 带 timeout+DEVNULL;"
418
+ "whitebox Popen 保持协议面 ==")
419
+
420
+ def run_calls(rel):
421
+ tree = ast.parse(_rel_text(rel))
422
+ out = []
423
+ for node in ast.walk(tree):
424
+ if (isinstance(node, ast.Call)
425
+ and isinstance(node.func, ast.Attribute)
426
+ and node.func.attr == "run"
427
+ and isinstance(node.func.value, ast.Name)
428
+ and node.func.value.id == "subprocess"):
429
+ out.append(node)
430
+ return out
431
+
432
+ def has_kw(node, key, devnull=False):
433
+ for kw in node.keywords:
434
+ if kw.arg != key:
435
+ continue
436
+ if not devnull:
437
+ return True
438
+ v = kw.value
439
+ return (isinstance(v, ast.Attribute) and v.attr == "DEVNULL"
440
+ and isinstance(v.value, ast.Name)
441
+ and v.value.id == "subprocess")
442
+ return False
443
+
444
+ for rel in _AUDIT_RUN_FILES:
445
+ nodes = run_calls(rel)
446
+ ok(len(nodes) >= 1, "T5 前置:%s 内有 subprocess.run 调用(%d 处)"
447
+ % (rel, len(nodes)))
448
+ for i, node in enumerate(nodes, 1):
449
+ ok(has_kw(node, "timeout"),
450
+ "T5a %s:%d subprocess.run 带 timeout=" % (rel, node.lineno))
451
+ ok(has_kw(node, "stdin", devnull=True),
452
+ "T5b %s:%d subprocess.run 带 stdin=subprocess.DEVNULL"
453
+ % (rel, node.lineno))
454
+
455
+ # whitebox:长驻对话协议面(stdin=PIPE)——**不在加固面**,保持原形态
456
+ tree = ast.parse(_rel_text(_WHITEBOX_REL))
457
+ popens = [n for n in ast.walk(tree)
458
+ if isinstance(n, ast.Call)
459
+ and isinstance(n.func, ast.Attribute)
460
+ and n.func.attr == "Popen"
461
+ and isinstance(n.func.value, ast.Name)
462
+ and n.func.value.id == "subprocess"]
463
+ ok(len(popens) >= 1, "T5c 前置:whitebox.py 内有 subprocess.Popen(%d 处)"
464
+ % len(popens))
465
+ for node in popens:
466
+ stdin_kw = next((kw for kw in node.keywords if kw.arg == "stdin"), None)
467
+ ok(stdin_kw is not None
468
+ and isinstance(stdin_kw.value, ast.Attribute)
469
+ and stdin_kw.value.attr == "PIPE",
470
+ "T5d whitebox Popen 保持协议面原形态(stdin=PIPE,不加固)"
471
+ "(%s:%d)" % (_WHITEBOX_REL, node.lineno))
472
+
473
+
474
+ # ---------------------------------------------------------------- 变异表
475
+ # 锚点 = (名字, rel, old, new)。每次变异必须让套件**转红**:
476
+ # M1 主修删 timeout=(_git 退回无界等待)→ T1b / T2a 红
477
+ # M2 主修删 stdin=DEVNULL(子进程继承活管道 stdin)→ T1c 红
478
+ # M3 进度面删「进入写点」→ T4a / T4a2 红
479
+ # M4 六档 except 删 last_tick_error 记录(退回全静默)→ T3c / T4c 红
480
+ _MUTATIONS = (
481
+ ("删 timeout=(_git 退回无界等待)", "md_cg/sleep.py",
482
+ " env=env, shell=False,\n"
483
+ " timeout=_GIT_TIMEOUT_S,\n"
484
+ " stdin=subprocess.DEVNULL)",
485
+ " env=env, shell=False,\n"
486
+ " stdin=subprocess.DEVNULL)"),
487
+ ("删 stdin=DEVNULL(继承活管道 stdin)", "md_cg/sleep.py",
488
+ " env=env, shell=False,\n"
489
+ " timeout=_GIT_TIMEOUT_S,\n"
490
+ " stdin=subprocess.DEVNULL)",
491
+ " env=env, shell=False,\n"
492
+ " timeout=_GIT_TIMEOUT_S)"),
493
+ ("删进度面进入写点(卡住读不到档)", "md_cg/sustain.py",
494
+ ' self.current_tick = {"name": name, "started_at": time.time(),\n'
495
+ ' "pid": os.getpid()}\n'
496
+ ' self._flush_progress()\n',
497
+ ""),
498
+ ("删失败档 last_tick_error(退回全静默)", "md_cg/sustain.py",
499
+ " except Exception as e: # noqa: BLE001\n"
500
+ " ok_ = False\n"
501
+ " self.last_tick_error = {\"name\": name, \"t\": time.time(),\n"
502
+ " \"error\": \"%s: %s\" % (type(e).__name__,\n"
503
+ " str(e)[:200])}\n",
504
+ " except Exception: # noqa: BLE001\n"
505
+ " ok_ = False\n"),
506
+ )
507
+
508
+ #: 空转检出对照(meta 自证,`--mutate --null`):new==old 的「无害变异」——
509
+ #: 行为零变化、自身红项必须为 0 且被判 MISS。若哪天「本轮红项」判定口径
510
+ #: 退化为累计计数(累计恒非空),本对照立即转 FAIL(钉住的正是复核打回
511
+ #: 实证过的那条假阳性通道)。锚点取 `_git` 调用里一行行为零变化的文本。
512
+ _NULL_MUTATION = ("空转对照(new==old,行为零变化)", "md_cg/sleep.py",
513
+ " env=env, shell=False,\n",
514
+ " env=env, shell=False,\n")
515
+
516
+
517
+ def _exec_module(name: str, rel: str, text: str):
518
+ ns = {"__name__": name, "__package__": "md_cg",
519
+ "__file__": os.path.join(_REPO, rel)}
520
+ exec(compile(text, rel, "exec"), ns) # noqa: S102 —— 基线自证用
521
+ m = types.ModuleType(name)
522
+ m.__dict__.update(ns)
523
+ return m
524
+
525
+
526
+ def _run_groups() -> int:
527
+ for fn in (t1, t2, t3, t4, t5):
528
+ try:
529
+ fn()
530
+ except Exception as e: # noqa: BLE001
531
+ ok(False, "%s 组抛异常:%s: %s" % (fn.__name__, type(e).__name__, e))
532
+ return len(_FAIL)
533
+
534
+
535
+ def _mutate_once(name: str, rel: str, old: str, new: str):
536
+ """跑一条变异并返回**本轮自身**读数 (reds_self, reds_lines, detail)。
537
+
538
+ 红项口径(复核打回修复,2026-10-06):`_FAIL` 是**全局累计**列表,
539
+ 故「本轮红项」必须取**调用前后长度差**——直接拿 `len(_FAIL)` 当本轮
540
+ 红项会让「判据空转」检测失效(累计值恒非空 ⇒ 空转变异也会被记成
541
+ 「红」并放行)。本轮自身红项还须与输出里 FAIL 行数**账实相符**。
542
+ """
543
+ src = _rel_text(rel)
544
+ if old not in src:
545
+ return None, [], "ANCHOR-MISS:锚点在 %s 源码里找不到(实现改了却没同步" \
546
+ "本表)" % rel
547
+ base = len(_FAIL) # 本轮起点:只数本轮自身的红项
548
+ _SRC[rel] = src.replace(old, new, 1)
549
+ try:
550
+ mut = _exec_module("md_cg._bounded_mut", rel, _SRC[rel])
551
+ if rel == "md_cg/sleep.py":
552
+ globals()["SL"] = mut
553
+ else:
554
+ globals()["SUS"] = mut
555
+ with contextlib.redirect_stdout(buf := io.StringIO()):
556
+ _run_groups()
557
+ detail = buf.getvalue()
558
+ finally:
559
+ globals()["SL"] = _REAL_SL
560
+ globals()["SUS"] = _REAL_SUS
561
+ _SRC.pop(rel, None)
562
+ reds = len(_FAIL) - base # **本轮自身**红项数
563
+ reds_lines = [l for l in detail.splitlines()
564
+ if l.strip().startswith("FAIL ")]
565
+ return reds, reds_lines, detail
566
+
567
+
568
+ def _mutate_mode(list_only: bool = False) -> int:
569
+ print("!! 定点变异自证:逐条把机制改回「改动前/错误」形态,套件必须转红"
570
+ "(红项 = 本轮自身,非法用全局累计值)\n")
571
+ if list_only:
572
+ for name, rel, _o, _n in _MUTATIONS:
573
+ print(" %-38s [%s]" % (name, rel))
574
+ return 0
575
+ anchor_miss, bad = [], []
576
+ base0 = len(_FAIL)
577
+ with contextlib.redirect_stdout(io.StringIO()):
578
+ _run_groups()
579
+ clean = len(_FAIL) - base0
580
+ print(" 未变异基线:失败=%d(必须为 0)" % clean)
581
+ if clean:
582
+ bad.append("未变异基线即失败")
583
+
584
+ for name, rel, old, new in _MUTATIONS:
585
+ reds, reds_lines, detail = _mutate_once(name, rel, old, new)
586
+ if reds is None:
587
+ print(" ANCHOR-MISS %s —— %s" % (name, detail))
588
+ anchor_miss.append(name)
589
+ continue
590
+ verdict = "红" if reds else "**仍全绿 = 该判据空转**"
591
+ print(" %s %-38s 自身红项=%d(本轮;基线=%d) %s"
592
+ % ("OK " if reds else "MISS ", name, reds, clean, verdict))
593
+ for l in reds_lines: # **全量**打印(回报即读数,不截断)
594
+ print(" " + l.strip()[5:])
595
+ if len(reds_lines) != reds:
596
+ # 账实不符 = 计数面自身有缺陷——按失败判(fail-closed)
597
+ print(" !账实不符:FAIL 行数=%d ≠ 自身红项=%d——计数面缺陷"
598
+ % (len(reds_lines), reds))
599
+ bad.append(name + "(账实不符)")
600
+ if not reds:
601
+ bad.append(name)
602
+
603
+ if anchor_miss:
604
+ print("\nANCHOR-MISS:%s" % "、".join(anchor_miss))
605
+ print("退出码 2(fail-closed):变异表锚点漂移即判失败,不得静默跳过")
606
+ return 2
607
+ print("\n定点变异自证:%s"
608
+ % ("PASS(每处机制都有一条断言把它钉死)" if not bad
609
+ else "FAIL —— " + "、".join(bad)))
610
+ return 0 if not bad else 1
611
+
612
+
613
+ def _null_mode() -> int:
614
+ """空转检出对照(meta 自证):new==old 的「无害变异」必须被判 MISS。
615
+
616
+ 钉住的缺陷类别(复核打回实证):若「本轮红项」误用全局累计值(累计恒
617
+ 非空),空转变异会被记成「红」并放行——`--mutate` 的 fail-closed 承诺
618
+ (「变异未按预期转红 = 退出码 1」)随之失效。本对照即钉住该检出能力。
619
+ """
620
+ print("!! 空转检出对照:一条 new==old 的「无害变异」——必须被判 MISS"
621
+ "(不得凭任何累计值蒙混)\n")
622
+ name, rel, old, new = _NULL_MUTATION
623
+ reds, reds_lines, detail = _mutate_once(name, rel, old, new)
624
+ if reds is None:
625
+ print(" ANCHOR-MISS %s —— %s" % (name, detail))
626
+ return 2
627
+ detected = reds == 0 and not reds_lines
628
+ print(" 变异=%s 自身红项=%d(本轮) FAIL 行数=%d ⇒ %s"
629
+ % (name, reds, len(reds_lines),
630
+ "MISS(如期检出空转,判定有效)" if detected
631
+ else "红(**空转漏检 = 判据失效**,fail-closed 不成立)"))
632
+ print("空转检出对照:%s" % ("PASS" if detected else "FAIL"))
633
+ return 0 if detected else 1
634
+
635
+
636
+ def main() -> int:
637
+ _sandbox_env()
638
+ try:
639
+ if "--mutate" in sys.argv:
640
+ if "--null" in sys.argv:
641
+ return _null_mode()
642
+ return _mutate_mode("--list" in sys.argv)
643
+ n = _run_groups()
644
+ print("\nSUMMARY: 常驻卡死防护守卫:%d 通过,%d 失败" % (len(_PASS), n))
645
+ return 0 if not n else 1
646
+ finally:
647
+ _restore_env()
648
+ shutil.rmtree(_TMP, ignore_errors=True)
649
+
650
+
651
+ if __name__ == "__main__":
652
+ sys.exit(main())