@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.
- package/data/policy.json +38 -38
- package/docs/discipline/templates/spec.txt.tmpl +1 -1
- package/dsh/cordis.yml.example +139 -139
- package/lib/hooks.d.ts +19 -0
- package/lib/hooks.js +29 -6
- package/lib/index.js +11 -2
- package/lib/lib/hook_audit.js +38 -2
- package/lib/lib/prompt_safety.js +14 -3
- package/lib/tools.d.ts +7 -0
- package/lib/tools.js +22 -1
- package/md_cg/_guard_kit.py +121 -121
- package/md_cg/anchor.py +114 -114
- package/md_cg/audit.py +15 -2
- package/md_cg/chain.py +3 -2
- package/md_cg/config_registry_guard.py +487 -487
- package/md_cg/conformance.py +747 -747
- package/md_cg/consolidate.py +1793 -1793
- package/md_cg/crypto.py +794 -794
- package/md_cg/hyperedge.py +262 -262
- package/md_cg/interface_schema.py +146 -146
- package/md_cg/lifecycle.py +426 -426
- package/md_cg/mdcos.py +12 -8
- package/md_cg/predict.py +1103 -1103
- package/md_cg/protect.py +654 -654
- package/md_cg/provenance.py +606 -606
- package/md_cg/queue_health.py +130 -130
- package/md_cg/refine.py +613 -613
- package/md_cg/retrieve.py +128 -128
- package/md_cg/revise.py +140 -140
- package/md_cg/rollback.py +657 -657
- package/md_cg/rollback_cli.py +124 -124
- package/md_cg/rotate.py +346 -346
- package/md_cg/routing.py +490 -490
- package/md_cg/self_surface.py +50 -50
- package/md_cg/semantic/canonical.py +144 -144
- package/md_cg/semantic/zh_en_atoms.py +141 -141
- package/md_cg/sources.py +1091 -1091
- package/md_cg/stg.py +3 -2
- package/md_cg/test_audit_rotate_parity.py +279 -279
- package/md_cg/test_autonomy_modes.py +2013 -2013
- package/md_cg/test_cn_recall_grams.py +206 -206
- package/md_cg/test_code_kind_forbidden.py +101 -0
- package/md_cg/test_condaccept.py +156 -156
- package/md_cg/test_condgate.py +141 -141
- package/md_cg/test_heartbeat_ledger.py +557 -557
- package/md_cg/test_i50e_readside_protection.py +658 -658
- package/md_cg/test_issue111_gate_order.py +76 -76
- package/md_cg/test_issue111_scoring_contract.py +86 -86
- package/md_cg/test_issue121_calibration_bounds.py +293 -293
- package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
- package/md_cg/test_issue147_pack_id_escape.py +378 -378
- package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
- package/md_cg/test_issue149_accel_default_face.py +248 -248
- package/md_cg/test_issue150_empty_query_terms.py +328 -328
- package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
- package/md_cg/test_issue152_sealed_postings.py +309 -309
- package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
- package/md_cg/test_issue157b_index_remainder.py +344 -344
- package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
- package/md_cg/test_issue191_import_trust.py +382 -382
- package/md_cg/test_issue193_write_scope.py +378 -378
- package/md_cg/test_issue212_writeface_gaps.py +349 -349
- package/md_cg/test_issue214_reject_sensitivity.py +266 -266
- package/md_cg/test_issue215_condition_source_gap.py +272 -272
- package/md_cg/test_issue216_clash_routes.py +214 -214
- package/md_cg/test_issue217_slot_routes.py +248 -248
- package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
- package/md_cg/test_issue258_pack_sensitivity.py +468 -468
- package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
- package/md_cg/test_issue274_read_node_id_none.py +341 -341
- package/md_cg/test_issue275_layer_param.py +250 -250
- package/md_cg/test_issue277_node_id_traversal.py +384 -384
- package/md_cg/test_issue278_neg_separated_tension.py +271 -271
- package/md_cg/test_issue278_neg_window.py +294 -294
- package/md_cg/test_issue278_negative_layering.py +83 -83
- package/md_cg/test_issue284_skip_not_pass.py +291 -291
- package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
- package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
- package/md_cg/test_issue303_design_boundaries.py +262 -262
- package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
- package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
- package/md_cg/test_issue321_mcp_deep_json.py +304 -304
- package/md_cg/test_issue322_node_write_lock.py +727 -727
- package/md_cg/test_issue324_write_size_fields.py +214 -214
- package/md_cg/test_issue325_audit_poison.py +229 -229
- package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
- package/md_cg/test_issue326_key_perms.py +355 -355
- package/md_cg/test_issue326_twin_parser_parity.py +323 -323
- package/md_cg/test_issue326_vm_call_frame.py +569 -569
- package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
- package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
- package/md_cg/test_issue348_insight_verify_op.py +199 -199
- package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
- package/md_cg/test_issue350_casefold_collision.py +235 -235
- package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
- package/md_cg/test_issue352_imgaudit.py +418 -418
- package/md_cg/test_issue352_pathsjson.py +537 -537
- package/md_cg/test_issue352_refindex.py +412 -412
- package/md_cg/test_issue352_rollback.py +604 -604
- package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
- package/md_cg/test_issue354_rust_index_containment.py +571 -571
- package/md_cg/test_issue354_rust_wal_containment.py +606 -606
- package/md_cg/test_issue358_truncation_observable.py +247 -247
- package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
- package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
- package/md_cg/test_issue362_neg_condition.py +468 -468
- package/md_cg/test_issue363_lexical_idf.py +275 -275
- package/md_cg/test_issue370_readcache_assembly.py +488 -488
- package/md_cg/test_issue376_heartbeat_failed.py +293 -293
- package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
- package/md_cg/test_issue378_protected_floor.py +310 -310
- package/md_cg/test_issue383_state_event_write_gate.py +462 -462
- package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
- package/md_cg/test_issue398_toolface_op_parity.py +511 -511
- package/md_cg/test_issue399_hive_json_shape.py +317 -317
- package/md_cg/test_issue401_wisdom_codegen.py +295 -295
- package/md_cg/test_issue404_heal_receipt.py +389 -389
- package/md_cg/test_issue409_compact_index_completeness.py +509 -509
- package/md_cg/test_issue410_verify_demote_write.py +366 -366
- package/md_cg/test_issue411_scrub_idempotence.py +575 -575
- package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
- package/md_cg/test_issue413_preimage_failclosed.py +239 -239
- package/md_cg/test_issue413_preimage_twin.py +339 -339
- package/md_cg/test_issue415_deps_gate_probe.py +357 -357
- package/md_cg/test_issue416_entry_key_subset.py +525 -525
- package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
- package/md_cg/test_issue425_ingest_library_path.py +331 -331
- package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
- package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
- package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
- package/md_cg/test_issue427_serve_status_shape.py +191 -191
- package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
- package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
- package/md_cg/test_issue434_435_float_gate.py +90 -90
- package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
- package/md_cg/test_issue43_default_policy.py +874 -874
- package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
- package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
- package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
- package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
- package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
- package/md_cg/test_issue451_audit_actor.py +313 -313
- package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
- package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
- package/md_cg/test_issue466_basis_registry.py +469 -469
- package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
- package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
- package/md_cg/test_issue470_wal_event_durable.py +427 -427
- package/md_cg/test_issue471_identity_readable.py +136 -136
- package/md_cg/test_issue472_audit_chain.py +90 -90
- package/md_cg/test_issue472_prune_ledger.py +105 -105
- package/md_cg/test_issue472_rollback_degraded.py +81 -81
- package/md_cg/test_issue491_compose_sandbox.py +460 -460
- package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
- package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
- package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
- package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
- package/md_cg/test_issue525_read_null_semantics.py +52 -52
- package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
- package/md_cg/test_issue547_audit_durable.py +96 -96
- package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
- package/md_cg/test_issue559_refine_prefix.py +69 -69
- package/md_cg/test_issue562_retired_faces.py +150 -0
- package/md_cg/test_issue71_queue_backlog.py +376 -376
- package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
- package/md_cg/test_issue82_credential_rules.py +271 -271
- package/md_cg/test_issue91_verifier_sandbox.py +314 -314
- package/md_cg/test_issue93_remember_redaction.py +282 -282
- package/md_cg/test_logref.py +1141 -1141
- package/md_cg/test_md_access_parity.py +330 -330
- package/md_cg/test_md_cg_no_hive_dep.py +139 -139
- package/md_cg/test_mutation_residue.py +119 -119
- package/md_cg/test_mutation_rollback.py +835 -835
- package/md_cg/test_n123_derive_expiry_chain.py +210 -210
- package/md_cg/test_n209_verify_write_face_gates.py +466 -466
- package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
- package/md_cg/test_neg_tail_honesty.py +733 -733
- package/md_cg/test_p21_tokens.py +294 -294
- package/md_cg/test_p27_docindex.py +792 -792
- package/md_cg/test_p28_refcheck.py +1053 -1053
- package/md_cg/test_p2_six_elements.py +476 -476
- package/md_cg/test_p33_ccg_wiring.py +300 -300
- package/md_cg/test_p3_legacy_closure.py +438 -438
- package/md_cg/test_p40_refine_worklist.py +244 -244
- package/md_cg/test_p4_freshness.py +781 -781
- package/md_cg/test_p9c_dedup_hints.py +288 -288
- package/md_cg/test_policy_required_ccg.py +444 -444
- package/md_cg/test_retr_s5.py +312 -312
- package/md_cg/test_s1_ast_judge.py +109 -109
- package/md_cg/test_state_event_op.py +521 -521
- package/md_cg/test_stgidx_index_parity.py +1024 -1024
- package/md_cg/test_sustain_bounded.py +652 -652
- package/md_cg/test_trust_edge_reachability.py +405 -405
- package/md_cg/test_w7_redlines.py +659 -659
- package/md_cg/test_write_return_shape.py +919 -919
- package/md_cg/test_writepipe.py +228 -228
- package/md_cg/trust.py +1114 -1114
- package/md_cg/twophase.py +303 -303
- package/md_cg/whitebox.py +536 -536
- package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
- package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
- package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
- package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
- package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
- package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
- package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
- package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
- package/md_cg/writepipe.py +1337 -1337
- package/package.json +3 -2
- package/scripts/workspace_index.py +328 -0
- package/src/hooks.ts +30 -6
- package/src/index.ts +14 -5
- package/src/lib/hook_audit.ts +282 -256
- package/src/lib/mdcg_client.ts +469 -469
- package/src/lib/prompt_safety.ts +17 -3
- package/src/tools.ts +23 -1
|
@@ -1,487 +1,487 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""统一配置层 · **一致性守卫**(本文件即判据;第一批:只加机制、不动语义)。
|
|
3
|
-
|
|
4
|
-
判据(任一条红 ⇒ 退出码 1)
|
|
5
|
-
-------------------------
|
|
6
|
-
G1 **schema/内部一致性**——每条 registry 条目给齐必填字段;face/layer/kind/
|
|
7
|
-
status 取值合法;key 唯一;`tunable` 与 `value_type` 相容。
|
|
8
|
-
G2 **锚点可解 + 缺省逐位相等**(本守卫的核心,防「登记与代码漂移」):
|
|
9
|
-
· `const`:锚点文件的模块级赋值**确有**该符号,且常量折叠后的值
|
|
10
|
-
== registry 登记的 value;
|
|
11
|
-
· `table`:既有真源表(`SLEEP_ENV_DEFAULTS`/`AUTO_DEFAULTS`/
|
|
12
|
-
`AUTONOMY_ENV_DEFAULTS`)里的键值 == registry 登记的 value;
|
|
13
|
-
· `env`:按锚点形态复核(字面量缺省 / 助手缺省符号 / 无缺省开关 /
|
|
14
|
-
助手实参),分叉条目必须**仍**分叉(≥2 个不同缺省)——分叉被修掉要
|
|
15
|
-
同步改登记,否则红。
|
|
16
|
-
G3 **生成件新鲜度**——`docs/reference/配置参数表_v0.1.md` 与
|
|
17
|
-
`md_cg/config_validate.py` 必须**逐字节等于**由真源重渲染的结果
|
|
18
|
-
(生成件陈旧 ⇒ 红;禁手改生成件)。
|
|
19
|
-
G4 **分区表覆盖完整**——三张既有真源表的每个键都必须在 registry 里登记
|
|
20
|
-
(漏登 ⇒ 红)。
|
|
21
|
-
|
|
22
|
-
# 不适用条件(补 · task-15):**不覆盖 `md_cg/config_registry_bulk.py` 的「生成件新鲜度」**
|
|
23
|
-
# —— 它是**冻结快照**(实测:整体重跑生成器会丢策展注释),守卫面在
|
|
24
|
-
# `scripts/check_config_env_registry.py` 的 C1。加/改 env 变量的完整清单见
|
|
25
|
-
# `scripts/gen_config_registry.py` 模块注释「★ 加一个 env 变量的完整清单」。
|
|
26
|
-
不适用条件
|
|
27
|
-
----------
|
|
28
|
-
· 不判「缺省值是否合理」(那是标定/裁定的活,见设计文档 §5);
|
|
29
|
-
· 不改任何读取点;不给 env 面「有效缺省」下数值判断(只判代码里**写着的**
|
|
30
|
-
缺省与登记是否一致)。
|
|
31
|
-
|
|
32
|
-
运行
|
|
33
|
-
----
|
|
34
|
-
python -X utf8 -m md_cg.config_registry_guard # 全绿裁决
|
|
35
|
-
python -X utf8 -m md_cg.config_registry_guard --mutate # 定点变异自证
|
|
36
|
-
python -X utf8 -m md_cg.config_registry_guard --mutate --list
|
|
37
|
-
python -X utf8 -m md_cg.config_registry_guard --verbose
|
|
38
|
-
|
|
39
|
-
退出码:0 = 全绿;1 = 有断言失败 / 变异未按预期转红;2 = ANCHOR-MISS
|
|
40
|
-
(变异锚点在当前源码里找不到——实现改了却没同步本表)。
|
|
41
|
-
|
|
42
|
-
**基线纪律**(沿用 `md_cg/test_sleep_p1.py` 先例):不以 git HEAD 为基线源——
|
|
43
|
-
「改动前形态」由在当前工作区源码文本上做**定点变异**复现,锚点漂移即退出码 2。
|
|
44
|
-
变异全程在**内存**里改源码文本(`_SRC` 覆盖),**不落盘**。
|
|
45
|
-
"""
|
|
46
|
-
from __future__ import annotations
|
|
47
|
-
|
|
48
|
-
import ast
|
|
49
|
-
import os
|
|
50
|
-
import sys
|
|
51
|
-
|
|
52
|
-
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
53
|
-
|
|
54
|
-
_PASS, _FAIL = [], []
|
|
55
|
-
_SRC = {}
|
|
56
|
-
_DOC = os.path.join(REPO, "docs", "reference", "配置参数表_v0.1.md")
|
|
57
|
-
_VALIDATOR = os.path.join(REPO, "md_cg", "config_validate.py")
|
|
58
|
-
|
|
59
|
-
TABLE_SPECS = (
|
|
60
|
-
("md_cg/sleep.py", "SLEEP_ENV_DEFAULTS", "SLEEP_ENV_KEYS"),
|
|
61
|
-
("md_cg/sustain.py", "AUTO_DEFAULTS", "AUTO_ENVS"),
|
|
62
|
-
("md_cg/autonomy_modes.py", "AUTONOMY_ENV_DEFAULTS", "AUTONOMY_ENV_KEYS"),
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def ok(cond, msg, extra=""):
|
|
67
|
-
(_PASS if cond else _FAIL).append(msg)
|
|
68
|
-
print((" PASS " if cond else " FAIL ") + msg
|
|
69
|
-
+ ((" ← " + str(extra)) if (extra and not cond) else ""))
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _read(rel: str) -> str:
|
|
73
|
-
if rel in _SRC:
|
|
74
|
-
return _SRC[rel]
|
|
75
|
-
with open(os.path.join(REPO, rel), encoding="utf-8") as f:
|
|
76
|
-
return f.read()
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
def _tree(rel: str):
|
|
80
|
-
try:
|
|
81
|
-
return ast.parse(_read(rel), filename=rel)
|
|
82
|
-
except (SyntaxError, FileNotFoundError):
|
|
83
|
-
return None
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
def _const_fold(el):
|
|
87
|
-
if isinstance(el, ast.Constant):
|
|
88
|
-
return el.value
|
|
89
|
-
if isinstance(el, ast.UnaryOp) and isinstance(el.op, (ast.USub, ast.UAdd)):
|
|
90
|
-
v = _const_fold(el.operand)
|
|
91
|
-
return -v if isinstance(el.op, ast.USub) else v
|
|
92
|
-
if isinstance(el, ast.BinOp):
|
|
93
|
-
l, r = _const_fold(el.left), _const_fold(el.right)
|
|
94
|
-
op = el.op
|
|
95
|
-
table = {ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b,
|
|
96
|
-
ast.Mult: lambda a, b: a * b, ast.FloorDiv: lambda a, b: a // b,
|
|
97
|
-
ast.Pow: lambda a, b: a ** b,
|
|
98
|
-
ast.LShift: lambda a, b: a << b, ast.RShift: lambda a, b: a >> b}
|
|
99
|
-
for t, fn in table.items():
|
|
100
|
-
if isinstance(op, t):
|
|
101
|
-
return fn(l, r)
|
|
102
|
-
raise ValueError("unsupported BinOp")
|
|
103
|
-
if isinstance(el, ast.Tuple):
|
|
104
|
-
return tuple(_const_fold(e) for e in el.elts)
|
|
105
|
-
if isinstance(el, ast.List):
|
|
106
|
-
return [_const_fold(e) for e in el.elts]
|
|
107
|
-
if isinstance(el, ast.Dict):
|
|
108
|
-
return {_const_fold(k): _const_fold(v)
|
|
109
|
-
for k, v in zip(el.keys, el.values)}
|
|
110
|
-
raise ValueError("non-constant")
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
def _module_value(rel: str, symbol: str):
|
|
114
|
-
"""模块级常量取值:返回 ("OK", value) / (其它, None)。"""
|
|
115
|
-
tree = _tree(rel)
|
|
116
|
-
if tree is None:
|
|
117
|
-
return "NOFILE", None
|
|
118
|
-
for node in tree.body:
|
|
119
|
-
val = None
|
|
120
|
-
if isinstance(node, ast.Assign) and any(
|
|
121
|
-
isinstance(t, ast.Name) and t.id == symbol for t in node.targets):
|
|
122
|
-
val = node.value
|
|
123
|
-
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) \
|
|
124
|
-
and node.target.id == symbol:
|
|
125
|
-
val = node.value
|
|
126
|
-
if val is not None:
|
|
127
|
-
try:
|
|
128
|
-
return "OK", _const_fold(val)
|
|
129
|
-
except Exception:
|
|
130
|
-
return "NONLITERAL", None
|
|
131
|
-
return "NOTFOUND", None
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
def _table_value(rel: str, symbol: str, key: str):
|
|
135
|
-
tree = _tree(rel)
|
|
136
|
-
if tree is None:
|
|
137
|
-
return "NOFILE", None
|
|
138
|
-
for node in tree.body:
|
|
139
|
-
if isinstance(node, ast.Assign) and any(
|
|
140
|
-
isinstance(t, ast.Name) and t.id == symbol for t in node.targets):
|
|
141
|
-
try:
|
|
142
|
-
d = ast.literal_eval(node.value)
|
|
143
|
-
except Exception:
|
|
144
|
-
return "NONLITERAL", None
|
|
145
|
-
return "OK", d.get(key, "<MISSING>")
|
|
146
|
-
return "NOTFOUND", None
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def _env_aliases(tree):
|
|
150
|
-
out = {}
|
|
151
|
-
for node in tree.body:
|
|
152
|
-
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) \
|
|
153
|
-
and isinstance(node.value.value, str):
|
|
154
|
-
for t in node.targets:
|
|
155
|
-
if isinstance(t, ast.Name):
|
|
156
|
-
out[t.id] = node.value.value
|
|
157
|
-
return out
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
def _env_sites(rel: str, env_name: str):
|
|
161
|
-
"""锚点文件里该 env 的读取点 → {"literal": set, "bare": bool, "helper": bool}。
|
|
162
|
-
|
|
163
|
-
`literal` = 非空字面量缺省(`get("X", d)` 的 d / `get("X") or "lit"` 的 lit)。
|
|
164
|
-
"""
|
|
165
|
-
tree = _tree(rel)
|
|
166
|
-
res = {"literal": set(), "bare": False, "helper": False}
|
|
167
|
-
if tree is None:
|
|
168
|
-
return res
|
|
169
|
-
holders = _env_aliases(tree)
|
|
170
|
-
parents = {}
|
|
171
|
-
for n in ast.walk(tree):
|
|
172
|
-
for c in ast.iter_child_nodes(n):
|
|
173
|
-
parents[c] = n
|
|
174
|
-
|
|
175
|
-
def name_of(arg):
|
|
176
|
-
if isinstance(arg, ast.Constant) and arg.value == env_name:
|
|
177
|
-
return True
|
|
178
|
-
if isinstance(arg, ast.Name) and holders.get(arg.id) == env_name:
|
|
179
|
-
return True
|
|
180
|
-
return False
|
|
181
|
-
|
|
182
|
-
for n in ast.walk(tree):
|
|
183
|
-
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \
|
|
184
|
-
and n.func.attr == "get" and n.args and name_of(n.args[0]):
|
|
185
|
-
if len(n.args) > 1:
|
|
186
|
-
try:
|
|
187
|
-
v = ast.literal_eval(n.args[1])
|
|
188
|
-
except Exception:
|
|
189
|
-
v = ast.unparse(n.args[1])
|
|
190
|
-
res["literal"].add(repr(v))
|
|
191
|
-
else:
|
|
192
|
-
p = parents.get(n)
|
|
193
|
-
lit = None
|
|
194
|
-
if isinstance(p, ast.BoolOp) and isinstance(p.op, ast.Or):
|
|
195
|
-
for v in p.values:
|
|
196
|
-
if v is n:
|
|
197
|
-
continue
|
|
198
|
-
try:
|
|
199
|
-
lit = ast.literal_eval(v)
|
|
200
|
-
except Exception:
|
|
201
|
-
lit = None
|
|
202
|
-
if lit not in (None, ""):
|
|
203
|
-
res["literal"].add(repr(lit))
|
|
204
|
-
else:
|
|
205
|
-
res["bare"] = True
|
|
206
|
-
continue
|
|
207
|
-
if isinstance(n, ast.Call):
|
|
208
|
-
for a in n.args:
|
|
209
|
-
if name_of(a):
|
|
210
|
-
res["helper"] = True
|
|
211
|
-
break
|
|
212
|
-
return res
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
# ---------------------------------------------------------------------------
|
|
216
|
-
# 判据
|
|
217
|
-
# ---------------------------------------------------------------------------
|
|
218
|
-
|
|
219
|
-
def g1_schema(cr):
|
|
220
|
-
required = [k for k, (req, _) in cr.SCHEMA.items() if req]
|
|
221
|
-
seen = set()
|
|
222
|
-
bad = 0
|
|
223
|
-
for e in cr.entries():
|
|
224
|
-
miss = [k for k in required if k not in e]
|
|
225
|
-
if miss:
|
|
226
|
-
bad += 1
|
|
227
|
-
ok(False, f"G1 {e.get('key')} 缺必填字段 {miss}")
|
|
228
|
-
if e["face"] not in cr.FACES or e["layer"] not in cr.LAYERS \
|
|
229
|
-
or e["kind"] not in cr.KINDS or e["status"] not in cr.STATUSES:
|
|
230
|
-
bad += 1
|
|
231
|
-
ok(False, f"G1 {e['key']} 分类取值非法")
|
|
232
|
-
if e["key"] in seen:
|
|
233
|
-
bad += 1
|
|
234
|
-
ok(False, f"G1 key 重复:{e['key']}")
|
|
235
|
-
seen.add(e["key"])
|
|
236
|
-
# tunable 的数值型判断:str 值须带显式语义(开关/枚举/数值语义)才算
|
|
237
|
-
if e["tunable"] and e["value_type"] == "str" and e.get("semantic") not in (
|
|
238
|
-
"value", "enum", "on", "off", "fail-open", "unset"):
|
|
239
|
-
bad += 1
|
|
240
|
-
ok(False, f"G1 {e['name']} tunable 但类型 str 且无语义标注")
|
|
241
|
-
elif e["tunable"] and e["value_type"] not in (
|
|
242
|
-
"int", "float", "bool", "tuple", "list", "dict", "str"):
|
|
243
|
-
bad += 1
|
|
244
|
-
ok(False, f"G1 {e['name']} tunable 但类型 {e['value_type']}")
|
|
245
|
-
ok(bad == 0, f"G1 schema/内部一致性({len(cr.entries())} 条)", f"{bad} 处不合规")
|
|
246
|
-
return bad
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
def g2_anchors(cr):
|
|
250
|
-
bad = 0
|
|
251
|
-
for e in cr.entries():
|
|
252
|
-
a = e["anchor"]
|
|
253
|
-
how = a.get("how")
|
|
254
|
-
if e["kind"] == "env" and not a.get("files"):
|
|
255
|
-
a["files"] = [a["file"]] if a.get("file") else []
|
|
256
|
-
if e["kind"] == "const":
|
|
257
|
-
st, v = _module_value(a["file"], a["symbol"])
|
|
258
|
-
if st != "OK" or v != e["value"]:
|
|
259
|
-
bad += 1
|
|
260
|
-
ok(False, f"G2 const {a['file']}::{a['symbol']} "
|
|
261
|
-
f"登记={e['value']!r} 代码={v!r}({st})")
|
|
262
|
-
elif e["kind"] == "table":
|
|
263
|
-
st, v = _table_value(a["file"], a["symbol"], a["key"])
|
|
264
|
-
if st != "OK" or v != e["value"]:
|
|
265
|
-
bad += 1
|
|
266
|
-
ok(False, f"G2 table {a['file']}::{a['symbol']}[{a['key']}] "
|
|
267
|
-
f"登记={e['value']!r} 代码={v!r}({st})")
|
|
268
|
-
else: # env
|
|
269
|
-
files = a.get("files") or [a["file"]]
|
|
270
|
-
if how == "env_literal":
|
|
271
|
-
obs = set()
|
|
272
|
-
for f in files:
|
|
273
|
-
obs |= _env_sites(f, e["name"])["literal"]
|
|
274
|
-
want = e["value"]
|
|
275
|
-
if isinstance(want, list):
|
|
276
|
-
if sorted(obs) != sorted(f"{w}" for w in want):
|
|
277
|
-
bad += 1
|
|
278
|
-
ok(False, f"G2 env 分叉 {e['name']} 登记={want} 观测={sorted(obs)}")
|
|
279
|
-
else:
|
|
280
|
-
if repr(want) not in obs:
|
|
281
|
-
bad += 1
|
|
282
|
-
ok(False, f"G2 env {e['name']} 登记={want!r} 未在 "
|
|
283
|
-
f"{files} 观测到(观测={sorted(obs)})")
|
|
284
|
-
elif how == "env_helper_default":
|
|
285
|
-
sym = a.get("symbol")
|
|
286
|
-
if e.get("value") is None and sym:
|
|
287
|
-
hit = any(_module_value(f, sym)[0] == "OK" for f in files)
|
|
288
|
-
if not hit:
|
|
289
|
-
bad += 1
|
|
290
|
-
ok(False, f"G2 env {e['name']} 助手缺省符号 {sym} "
|
|
291
|
-
f"在 {files} 无模块级赋值")
|
|
292
|
-
else:
|
|
293
|
-
ok(True, f"G2 env {e['name']}(字面量缺省,非符号)")
|
|
294
|
-
else: # env_flag / env_helper_arg
|
|
295
|
-
hit = False
|
|
296
|
-
for f in files:
|
|
297
|
-
s = _env_sites(f, e["name"])
|
|
298
|
-
if how == "env_helper_arg":
|
|
299
|
-
hit = hit or s["helper"]
|
|
300
|
-
else:
|
|
301
|
-
hit = hit or s["bare"] or s["literal"]
|
|
302
|
-
if not hit:
|
|
303
|
-
bad += 1
|
|
304
|
-
ok(False, f"G2 env {e['name']}({how})在 {files} 未检出读取点")
|
|
305
|
-
ok(bad == 0, f"G2 锚点可解 + 缺省逐位相等({len(cr.entries())} 条)", f"{bad} 条不符")
|
|
306
|
-
return bad
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
def g3_generated(cr):
|
|
310
|
-
from . import config_render as rnd
|
|
311
|
-
bad = 0
|
|
312
|
-
for path, text, label in (
|
|
313
|
-
(_DOC, rnd.render_doc(cr), "文档参数表"),
|
|
314
|
-
(_VALIDATOR, rnd.render_validator(cr), "校验器")):
|
|
315
|
-
cur = open(path, encoding="utf-8").read() if os.path.isfile(path) else ""
|
|
316
|
-
same = cur == text
|
|
317
|
-
if not same:
|
|
318
|
-
bad += 1
|
|
319
|
-
ok(same, f"G3 生成件新鲜度:{label} {os.path.relpath(path, REPO)}")
|
|
320
|
-
return bad
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
def g4_table_coverage(cr):
|
|
324
|
-
bad = 0
|
|
325
|
-
for rel, sym, _keysym in TABLE_SPECS:
|
|
326
|
-
st, d = _table_value(rel, sym, "__absent__")
|
|
327
|
-
tree = _tree(rel)
|
|
328
|
-
if tree is None:
|
|
329
|
-
bad += 1
|
|
330
|
-
ok(False, f"G4 无法解析 {rel}")
|
|
331
|
-
continue
|
|
332
|
-
keys = []
|
|
333
|
-
for node in tree.body:
|
|
334
|
-
if isinstance(node, ast.Assign) and any(
|
|
335
|
-
isinstance(t, ast.Name) and t.id == sym for t in node.targets):
|
|
336
|
-
try:
|
|
337
|
-
keys = list(ast.literal_eval(node.value).keys())
|
|
338
|
-
except Exception:
|
|
339
|
-
keys = []
|
|
340
|
-
reg = {e["anchor"].get("key") for e in cr.entries()
|
|
341
|
-
if e["kind"] == "table" and e["anchor"]["file"] == rel
|
|
342
|
-
and e["anchor"]["symbol"] == sym}
|
|
343
|
-
missing = [k for k in keys if k not in reg]
|
|
344
|
-
if missing:
|
|
345
|
-
bad += 1
|
|
346
|
-
ok(not missing, f"G4 分区表覆盖完整:{rel}::{sym}({len(keys)} 键)",
|
|
347
|
-
f"漏登 {missing}")
|
|
348
|
-
return bad
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
def run_all(cr=None):
|
|
352
|
-
_PASS.clear()
|
|
353
|
-
_FAIL.clear()
|
|
354
|
-
if cr is None:
|
|
355
|
-
from . import config_registry as cr
|
|
356
|
-
print("[统一配置层守卫] 判据 G1..G4")
|
|
357
|
-
total = g1_schema(cr) + g2_anchors(cr) + g3_generated(cr) + g4_table_coverage(cr)
|
|
358
|
-
print(f"\n结果:PASS {len(_PASS)} / FAIL {len(_FAIL)}")
|
|
359
|
-
return len(_FAIL)
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
# ---------------------------------------------------------------------------
|
|
363
|
-
# 定点变异自证
|
|
364
|
-
# ---------------------------------------------------------------------------
|
|
365
|
-
_MUTATIONS = []
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
def _mut(name, kind, rel, anchor, repl):
|
|
369
|
-
_MUTATIONS.append((name, kind, rel, anchor, repl))
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
# ① 改 registry 里的 const 缺省(登记侧漂移)
|
|
373
|
-
_mut("M1 registry-const-默认值改掉", "registry", None,
|
|
374
|
-
"WINDOW_SHORT_D", 4)
|
|
375
|
-
# ② 改代码里的 const 缺省(代码侧漂移)
|
|
376
|
-
_mut("M2 代码-const-默认值改掉", "code", "md_cg/admission.py",
|
|
377
|
-
"WINDOW_SHORT_D = 3", "WINDOW_SHORT_D = 4")
|
|
378
|
-
# ③ 改既有真源表的值(分区表漂移)
|
|
379
|
-
_mut("M3 既有表-sleep-interval-改掉", "table", "md_cg/sleep.py",
|
|
380
|
-
'"interval": "3600"', '"interval": "1800"')
|
|
381
|
-
# ④ 改 env 字面量缺省(env 面漂移)
|
|
382
|
-
_mut("M4 env-字面量缺省改掉", "code", "md_cg/mdcg.py",
|
|
383
|
-
'os.environ.get("MDCG_GATE_S2_COND", "1")',
|
|
384
|
-
'os.environ.get("MDCG_GATE_S2_COND", "0")')
|
|
385
|
-
# ⑤ 文档参数表陈旧
|
|
386
|
-
_mut("M5 文档参数表陈旧", "doc", None, "registry 条目合计", "registry 条目合计")
|
|
387
|
-
# ⑥ 校验器陈旧
|
|
388
|
-
_mut("M6 校验器陈旧", "validator", None, "RULES = ", "RULES = {} # ")
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
def _apply_mutation(name, kind, rel, anchor, repl):
|
|
392
|
-
"""应用一条变异;锚点找不到 ⇒ 返回 2(ANCHOR-MISS)。返回 0/2。"""
|
|
393
|
-
from . import config_registry as cr
|
|
394
|
-
if kind == "registry":
|
|
395
|
-
for e in cr.entries():
|
|
396
|
-
if e["name"] == anchor:
|
|
397
|
-
e["value"] = repl
|
|
398
|
-
return 0
|
|
399
|
-
return 2
|
|
400
|
-
if kind in ("code", "table"):
|
|
401
|
-
text = _read(rel)
|
|
402
|
-
if anchor not in text:
|
|
403
|
-
return 2
|
|
404
|
-
_SRC[rel] = text.replace(anchor, repl, 1)
|
|
405
|
-
return 0
|
|
406
|
-
if kind == "doc":
|
|
407
|
-
text = open(_DOC, encoding="utf-8").read()
|
|
408
|
-
_SRC["__doc__"] = text.replace(anchor, anchor + "(变异)", 1)
|
|
409
|
-
return 0
|
|
410
|
-
if kind == "validator":
|
|
411
|
-
text = open(_VALIDATOR, encoding="utf-8").read()
|
|
412
|
-
_SRC["__validator__"] = text.replace(anchor, repl, 1)
|
|
413
|
-
return 0
|
|
414
|
-
return 2
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
def _run_mutations():
|
|
418
|
-
from . import config_registry as cr
|
|
419
|
-
print("[定点变异自证] 预期:每条变异后守卫**必红**,复原后**全绿**")
|
|
420
|
-
bad = 0
|
|
421
|
-
for name, kind, rel, anchor, repl in _MUTATIONS:
|
|
422
|
-
# 复原(重新导入真源 + 清空源码覆盖)
|
|
423
|
-
_SRC.clear()
|
|
424
|
-
import importlib
|
|
425
|
-
from . import config_registry as _cr
|
|
426
|
-
importlib.reload(_cr)
|
|
427
|
-
code = _apply_mutation(name, kind, rel, anchor, repl)
|
|
428
|
-
if code == 2:
|
|
429
|
-
print(f" ANCHOR-MISS {name}(锚点 {anchor!r} 在 {rel} 找不到)")
|
|
430
|
-
return 2
|
|
431
|
-
fails = run_all(_cr)
|
|
432
|
-
red = fails > 0
|
|
433
|
-
ok(red, f"{name} ⇒ 守卫转红(FAIL={fails})", "未转红")
|
|
434
|
-
if not red:
|
|
435
|
-
bad += 1
|
|
436
|
-
_SRC.clear()
|
|
437
|
-
importlib.reload(_cr)
|
|
438
|
-
# 复原后全绿
|
|
439
|
-
_SRC.clear()
|
|
440
|
-
import importlib
|
|
441
|
-
from . import config_registry as _cr2
|
|
442
|
-
importlib.reload(_cr2)
|
|
443
|
-
fails = run_all(_cr2)
|
|
444
|
-
ok(fails == 0, f"复原后复跑全绿(FAIL={fails})", "未复原为绿")
|
|
445
|
-
if fails:
|
|
446
|
-
bad += 1
|
|
447
|
-
print(f"\n变异自证结果:{'全部按预期' if bad == 0 else str(bad) + ' 项不符'}")
|
|
448
|
-
return 1 if bad else 0
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
def main(argv):
|
|
452
|
-
if "--list" in argv:
|
|
453
|
-
for n, k, r, a, _ in _MUTATIONS:
|
|
454
|
-
print(f"{n} [{k}] {r or '-'} anchor={a!r}")
|
|
455
|
-
return 0
|
|
456
|
-
if "--mutate" in argv:
|
|
457
|
-
# 文档/校验器变异需经 _SRC;其余读盘
|
|
458
|
-
import md_cg.config_render as _r
|
|
459
|
-
real_doc = _r.render_doc
|
|
460
|
-
real_val = _r.render_validator
|
|
461
|
-
|
|
462
|
-
def doc_patched(cr, _rd=real_doc):
|
|
463
|
-
t = _rd(cr)
|
|
464
|
-
return _SRC.get("__doc__", t)
|
|
465
|
-
|
|
466
|
-
def val_patched(cr, _rv=real_val):
|
|
467
|
-
t = _rv(cr)
|
|
468
|
-
return _SRC.get("__validator__", t)
|
|
469
|
-
|
|
470
|
-
_r.render_doc = doc_patched
|
|
471
|
-
_r.render_validator = val_patched
|
|
472
|
-
return _run_mutations()
|
|
473
|
-
fails = run_all()
|
|
474
|
-
return 1 if fails else 0
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
if __name__ == "__main__":
|
|
478
|
-
raise SystemExit(main(sys.argv[1:]))
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
# pytest 收集入口(脚本式文件也可被 pytest 收)
|
|
482
|
-
def test_config_registry_guard():
|
|
483
|
-
assert run_all() == 0
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
def test_config_registry_guard_mutations():
|
|
487
|
-
assert main(["--mutate"]) == 0
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""统一配置层 · **一致性守卫**(本文件即判据;第一批:只加机制、不动语义)。
|
|
3
|
+
|
|
4
|
+
判据(任一条红 ⇒ 退出码 1)
|
|
5
|
+
-------------------------
|
|
6
|
+
G1 **schema/内部一致性**——每条 registry 条目给齐必填字段;face/layer/kind/
|
|
7
|
+
status 取值合法;key 唯一;`tunable` 与 `value_type` 相容。
|
|
8
|
+
G2 **锚点可解 + 缺省逐位相等**(本守卫的核心,防「登记与代码漂移」):
|
|
9
|
+
· `const`:锚点文件的模块级赋值**确有**该符号,且常量折叠后的值
|
|
10
|
+
== registry 登记的 value;
|
|
11
|
+
· `table`:既有真源表(`SLEEP_ENV_DEFAULTS`/`AUTO_DEFAULTS`/
|
|
12
|
+
`AUTONOMY_ENV_DEFAULTS`)里的键值 == registry 登记的 value;
|
|
13
|
+
· `env`:按锚点形态复核(字面量缺省 / 助手缺省符号 / 无缺省开关 /
|
|
14
|
+
助手实参),分叉条目必须**仍**分叉(≥2 个不同缺省)——分叉被修掉要
|
|
15
|
+
同步改登记,否则红。
|
|
16
|
+
G3 **生成件新鲜度**——`docs/reference/配置参数表_v0.1.md` 与
|
|
17
|
+
`md_cg/config_validate.py` 必须**逐字节等于**由真源重渲染的结果
|
|
18
|
+
(生成件陈旧 ⇒ 红;禁手改生成件)。
|
|
19
|
+
G4 **分区表覆盖完整**——三张既有真源表的每个键都必须在 registry 里登记
|
|
20
|
+
(漏登 ⇒ 红)。
|
|
21
|
+
|
|
22
|
+
# 不适用条件(补 · task-15):**不覆盖 `md_cg/config_registry_bulk.py` 的「生成件新鲜度」**
|
|
23
|
+
# —— 它是**冻结快照**(实测:整体重跑生成器会丢策展注释),守卫面在
|
|
24
|
+
# `scripts/check_config_env_registry.py` 的 C1。加/改 env 变量的完整清单见
|
|
25
|
+
# `scripts/gen_config_registry.py` 模块注释「★ 加一个 env 变量的完整清单」。
|
|
26
|
+
不适用条件
|
|
27
|
+
----------
|
|
28
|
+
· 不判「缺省值是否合理」(那是标定/裁定的活,见设计文档 §5);
|
|
29
|
+
· 不改任何读取点;不给 env 面「有效缺省」下数值判断(只判代码里**写着的**
|
|
30
|
+
缺省与登记是否一致)。
|
|
31
|
+
|
|
32
|
+
运行
|
|
33
|
+
----
|
|
34
|
+
python -X utf8 -m md_cg.config_registry_guard # 全绿裁决
|
|
35
|
+
python -X utf8 -m md_cg.config_registry_guard --mutate # 定点变异自证
|
|
36
|
+
python -X utf8 -m md_cg.config_registry_guard --mutate --list
|
|
37
|
+
python -X utf8 -m md_cg.config_registry_guard --verbose
|
|
38
|
+
|
|
39
|
+
退出码:0 = 全绿;1 = 有断言失败 / 变异未按预期转红;2 = ANCHOR-MISS
|
|
40
|
+
(变异锚点在当前源码里找不到——实现改了却没同步本表)。
|
|
41
|
+
|
|
42
|
+
**基线纪律**(沿用 `md_cg/test_sleep_p1.py` 先例):不以 git HEAD 为基线源——
|
|
43
|
+
「改动前形态」由在当前工作区源码文本上做**定点变异**复现,锚点漂移即退出码 2。
|
|
44
|
+
变异全程在**内存**里改源码文本(`_SRC` 覆盖),**不落盘**。
|
|
45
|
+
"""
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import ast
|
|
49
|
+
import os
|
|
50
|
+
import sys
|
|
51
|
+
|
|
52
|
+
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
53
|
+
|
|
54
|
+
_PASS, _FAIL = [], []
|
|
55
|
+
_SRC = {}
|
|
56
|
+
_DOC = os.path.join(REPO, "docs", "reference", "配置参数表_v0.1.md")
|
|
57
|
+
_VALIDATOR = os.path.join(REPO, "md_cg", "config_validate.py")
|
|
58
|
+
|
|
59
|
+
TABLE_SPECS = (
|
|
60
|
+
("md_cg/sleep.py", "SLEEP_ENV_DEFAULTS", "SLEEP_ENV_KEYS"),
|
|
61
|
+
("md_cg/sustain.py", "AUTO_DEFAULTS", "AUTO_ENVS"),
|
|
62
|
+
("md_cg/autonomy_modes.py", "AUTONOMY_ENV_DEFAULTS", "AUTONOMY_ENV_KEYS"),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ok(cond, msg, extra=""):
|
|
67
|
+
(_PASS if cond else _FAIL).append(msg)
|
|
68
|
+
print((" PASS " if cond else " FAIL ") + msg
|
|
69
|
+
+ ((" ← " + str(extra)) if (extra and not cond) else ""))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _read(rel: str) -> str:
|
|
73
|
+
if rel in _SRC:
|
|
74
|
+
return _SRC[rel]
|
|
75
|
+
with open(os.path.join(REPO, rel), encoding="utf-8") as f:
|
|
76
|
+
return f.read()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _tree(rel: str):
|
|
80
|
+
try:
|
|
81
|
+
return ast.parse(_read(rel), filename=rel)
|
|
82
|
+
except (SyntaxError, FileNotFoundError):
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _const_fold(el):
|
|
87
|
+
if isinstance(el, ast.Constant):
|
|
88
|
+
return el.value
|
|
89
|
+
if isinstance(el, ast.UnaryOp) and isinstance(el.op, (ast.USub, ast.UAdd)):
|
|
90
|
+
v = _const_fold(el.operand)
|
|
91
|
+
return -v if isinstance(el.op, ast.USub) else v
|
|
92
|
+
if isinstance(el, ast.BinOp):
|
|
93
|
+
l, r = _const_fold(el.left), _const_fold(el.right)
|
|
94
|
+
op = el.op
|
|
95
|
+
table = {ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b,
|
|
96
|
+
ast.Mult: lambda a, b: a * b, ast.FloorDiv: lambda a, b: a // b,
|
|
97
|
+
ast.Pow: lambda a, b: a ** b,
|
|
98
|
+
ast.LShift: lambda a, b: a << b, ast.RShift: lambda a, b: a >> b}
|
|
99
|
+
for t, fn in table.items():
|
|
100
|
+
if isinstance(op, t):
|
|
101
|
+
return fn(l, r)
|
|
102
|
+
raise ValueError("unsupported BinOp")
|
|
103
|
+
if isinstance(el, ast.Tuple):
|
|
104
|
+
return tuple(_const_fold(e) for e in el.elts)
|
|
105
|
+
if isinstance(el, ast.List):
|
|
106
|
+
return [_const_fold(e) for e in el.elts]
|
|
107
|
+
if isinstance(el, ast.Dict):
|
|
108
|
+
return {_const_fold(k): _const_fold(v)
|
|
109
|
+
for k, v in zip(el.keys, el.values)}
|
|
110
|
+
raise ValueError("non-constant")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _module_value(rel: str, symbol: str):
|
|
114
|
+
"""模块级常量取值:返回 ("OK", value) / (其它, None)。"""
|
|
115
|
+
tree = _tree(rel)
|
|
116
|
+
if tree is None:
|
|
117
|
+
return "NOFILE", None
|
|
118
|
+
for node in tree.body:
|
|
119
|
+
val = None
|
|
120
|
+
if isinstance(node, ast.Assign) and any(
|
|
121
|
+
isinstance(t, ast.Name) and t.id == symbol for t in node.targets):
|
|
122
|
+
val = node.value
|
|
123
|
+
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) \
|
|
124
|
+
and node.target.id == symbol:
|
|
125
|
+
val = node.value
|
|
126
|
+
if val is not None:
|
|
127
|
+
try:
|
|
128
|
+
return "OK", _const_fold(val)
|
|
129
|
+
except Exception:
|
|
130
|
+
return "NONLITERAL", None
|
|
131
|
+
return "NOTFOUND", None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _table_value(rel: str, symbol: str, key: str):
|
|
135
|
+
tree = _tree(rel)
|
|
136
|
+
if tree is None:
|
|
137
|
+
return "NOFILE", None
|
|
138
|
+
for node in tree.body:
|
|
139
|
+
if isinstance(node, ast.Assign) and any(
|
|
140
|
+
isinstance(t, ast.Name) and t.id == symbol for t in node.targets):
|
|
141
|
+
try:
|
|
142
|
+
d = ast.literal_eval(node.value)
|
|
143
|
+
except Exception:
|
|
144
|
+
return "NONLITERAL", None
|
|
145
|
+
return "OK", d.get(key, "<MISSING>")
|
|
146
|
+
return "NOTFOUND", None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _env_aliases(tree):
|
|
150
|
+
out = {}
|
|
151
|
+
for node in tree.body:
|
|
152
|
+
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) \
|
|
153
|
+
and isinstance(node.value.value, str):
|
|
154
|
+
for t in node.targets:
|
|
155
|
+
if isinstance(t, ast.Name):
|
|
156
|
+
out[t.id] = node.value.value
|
|
157
|
+
return out
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _env_sites(rel: str, env_name: str):
|
|
161
|
+
"""锚点文件里该 env 的读取点 → {"literal": set, "bare": bool, "helper": bool}。
|
|
162
|
+
|
|
163
|
+
`literal` = 非空字面量缺省(`get("X", d)` 的 d / `get("X") or "lit"` 的 lit)。
|
|
164
|
+
"""
|
|
165
|
+
tree = _tree(rel)
|
|
166
|
+
res = {"literal": set(), "bare": False, "helper": False}
|
|
167
|
+
if tree is None:
|
|
168
|
+
return res
|
|
169
|
+
holders = _env_aliases(tree)
|
|
170
|
+
parents = {}
|
|
171
|
+
for n in ast.walk(tree):
|
|
172
|
+
for c in ast.iter_child_nodes(n):
|
|
173
|
+
parents[c] = n
|
|
174
|
+
|
|
175
|
+
def name_of(arg):
|
|
176
|
+
if isinstance(arg, ast.Constant) and arg.value == env_name:
|
|
177
|
+
return True
|
|
178
|
+
if isinstance(arg, ast.Name) and holders.get(arg.id) == env_name:
|
|
179
|
+
return True
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
for n in ast.walk(tree):
|
|
183
|
+
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \
|
|
184
|
+
and n.func.attr == "get" and n.args and name_of(n.args[0]):
|
|
185
|
+
if len(n.args) > 1:
|
|
186
|
+
try:
|
|
187
|
+
v = ast.literal_eval(n.args[1])
|
|
188
|
+
except Exception:
|
|
189
|
+
v = ast.unparse(n.args[1])
|
|
190
|
+
res["literal"].add(repr(v))
|
|
191
|
+
else:
|
|
192
|
+
p = parents.get(n)
|
|
193
|
+
lit = None
|
|
194
|
+
if isinstance(p, ast.BoolOp) and isinstance(p.op, ast.Or):
|
|
195
|
+
for v in p.values:
|
|
196
|
+
if v is n:
|
|
197
|
+
continue
|
|
198
|
+
try:
|
|
199
|
+
lit = ast.literal_eval(v)
|
|
200
|
+
except Exception:
|
|
201
|
+
lit = None
|
|
202
|
+
if lit not in (None, ""):
|
|
203
|
+
res["literal"].add(repr(lit))
|
|
204
|
+
else:
|
|
205
|
+
res["bare"] = True
|
|
206
|
+
continue
|
|
207
|
+
if isinstance(n, ast.Call):
|
|
208
|
+
for a in n.args:
|
|
209
|
+
if name_of(a):
|
|
210
|
+
res["helper"] = True
|
|
211
|
+
break
|
|
212
|
+
return res
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# ---------------------------------------------------------------------------
|
|
216
|
+
# 判据
|
|
217
|
+
# ---------------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
def g1_schema(cr):
|
|
220
|
+
required = [k for k, (req, _) in cr.SCHEMA.items() if req]
|
|
221
|
+
seen = set()
|
|
222
|
+
bad = 0
|
|
223
|
+
for e in cr.entries():
|
|
224
|
+
miss = [k for k in required if k not in e]
|
|
225
|
+
if miss:
|
|
226
|
+
bad += 1
|
|
227
|
+
ok(False, f"G1 {e.get('key')} 缺必填字段 {miss}")
|
|
228
|
+
if e["face"] not in cr.FACES or e["layer"] not in cr.LAYERS \
|
|
229
|
+
or e["kind"] not in cr.KINDS or e["status"] not in cr.STATUSES:
|
|
230
|
+
bad += 1
|
|
231
|
+
ok(False, f"G1 {e['key']} 分类取值非法")
|
|
232
|
+
if e["key"] in seen:
|
|
233
|
+
bad += 1
|
|
234
|
+
ok(False, f"G1 key 重复:{e['key']}")
|
|
235
|
+
seen.add(e["key"])
|
|
236
|
+
# tunable 的数值型判断:str 值须带显式语义(开关/枚举/数值语义)才算
|
|
237
|
+
if e["tunable"] and e["value_type"] == "str" and e.get("semantic") not in (
|
|
238
|
+
"value", "enum", "on", "off", "fail-open", "unset"):
|
|
239
|
+
bad += 1
|
|
240
|
+
ok(False, f"G1 {e['name']} tunable 但类型 str 且无语义标注")
|
|
241
|
+
elif e["tunable"] and e["value_type"] not in (
|
|
242
|
+
"int", "float", "bool", "tuple", "list", "dict", "str"):
|
|
243
|
+
bad += 1
|
|
244
|
+
ok(False, f"G1 {e['name']} tunable 但类型 {e['value_type']}")
|
|
245
|
+
ok(bad == 0, f"G1 schema/内部一致性({len(cr.entries())} 条)", f"{bad} 处不合规")
|
|
246
|
+
return bad
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def g2_anchors(cr):
|
|
250
|
+
bad = 0
|
|
251
|
+
for e in cr.entries():
|
|
252
|
+
a = e["anchor"]
|
|
253
|
+
how = a.get("how")
|
|
254
|
+
if e["kind"] == "env" and not a.get("files"):
|
|
255
|
+
a["files"] = [a["file"]] if a.get("file") else []
|
|
256
|
+
if e["kind"] == "const":
|
|
257
|
+
st, v = _module_value(a["file"], a["symbol"])
|
|
258
|
+
if st != "OK" or v != e["value"]:
|
|
259
|
+
bad += 1
|
|
260
|
+
ok(False, f"G2 const {a['file']}::{a['symbol']} "
|
|
261
|
+
f"登记={e['value']!r} 代码={v!r}({st})")
|
|
262
|
+
elif e["kind"] == "table":
|
|
263
|
+
st, v = _table_value(a["file"], a["symbol"], a["key"])
|
|
264
|
+
if st != "OK" or v != e["value"]:
|
|
265
|
+
bad += 1
|
|
266
|
+
ok(False, f"G2 table {a['file']}::{a['symbol']}[{a['key']}] "
|
|
267
|
+
f"登记={e['value']!r} 代码={v!r}({st})")
|
|
268
|
+
else: # env
|
|
269
|
+
files = a.get("files") or [a["file"]]
|
|
270
|
+
if how == "env_literal":
|
|
271
|
+
obs = set()
|
|
272
|
+
for f in files:
|
|
273
|
+
obs |= _env_sites(f, e["name"])["literal"]
|
|
274
|
+
want = e["value"]
|
|
275
|
+
if isinstance(want, list):
|
|
276
|
+
if sorted(obs) != sorted(f"{w}" for w in want):
|
|
277
|
+
bad += 1
|
|
278
|
+
ok(False, f"G2 env 分叉 {e['name']} 登记={want} 观测={sorted(obs)}")
|
|
279
|
+
else:
|
|
280
|
+
if repr(want) not in obs:
|
|
281
|
+
bad += 1
|
|
282
|
+
ok(False, f"G2 env {e['name']} 登记={want!r} 未在 "
|
|
283
|
+
f"{files} 观测到(观测={sorted(obs)})")
|
|
284
|
+
elif how == "env_helper_default":
|
|
285
|
+
sym = a.get("symbol")
|
|
286
|
+
if e.get("value") is None and sym:
|
|
287
|
+
hit = any(_module_value(f, sym)[0] == "OK" for f in files)
|
|
288
|
+
if not hit:
|
|
289
|
+
bad += 1
|
|
290
|
+
ok(False, f"G2 env {e['name']} 助手缺省符号 {sym} "
|
|
291
|
+
f"在 {files} 无模块级赋值")
|
|
292
|
+
else:
|
|
293
|
+
ok(True, f"G2 env {e['name']}(字面量缺省,非符号)")
|
|
294
|
+
else: # env_flag / env_helper_arg
|
|
295
|
+
hit = False
|
|
296
|
+
for f in files:
|
|
297
|
+
s = _env_sites(f, e["name"])
|
|
298
|
+
if how == "env_helper_arg":
|
|
299
|
+
hit = hit or s["helper"]
|
|
300
|
+
else:
|
|
301
|
+
hit = hit or s["bare"] or s["literal"]
|
|
302
|
+
if not hit:
|
|
303
|
+
bad += 1
|
|
304
|
+
ok(False, f"G2 env {e['name']}({how})在 {files} 未检出读取点")
|
|
305
|
+
ok(bad == 0, f"G2 锚点可解 + 缺省逐位相等({len(cr.entries())} 条)", f"{bad} 条不符")
|
|
306
|
+
return bad
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def g3_generated(cr):
|
|
310
|
+
from . import config_render as rnd
|
|
311
|
+
bad = 0
|
|
312
|
+
for path, text, label in (
|
|
313
|
+
(_DOC, rnd.render_doc(cr), "文档参数表"),
|
|
314
|
+
(_VALIDATOR, rnd.render_validator(cr), "校验器")):
|
|
315
|
+
cur = open(path, encoding="utf-8").read() if os.path.isfile(path) else ""
|
|
316
|
+
same = cur == text
|
|
317
|
+
if not same:
|
|
318
|
+
bad += 1
|
|
319
|
+
ok(same, f"G3 生成件新鲜度:{label} {os.path.relpath(path, REPO)}")
|
|
320
|
+
return bad
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def g4_table_coverage(cr):
|
|
324
|
+
bad = 0
|
|
325
|
+
for rel, sym, _keysym in TABLE_SPECS:
|
|
326
|
+
st, d = _table_value(rel, sym, "__absent__")
|
|
327
|
+
tree = _tree(rel)
|
|
328
|
+
if tree is None:
|
|
329
|
+
bad += 1
|
|
330
|
+
ok(False, f"G4 无法解析 {rel}")
|
|
331
|
+
continue
|
|
332
|
+
keys = []
|
|
333
|
+
for node in tree.body:
|
|
334
|
+
if isinstance(node, ast.Assign) and any(
|
|
335
|
+
isinstance(t, ast.Name) and t.id == sym for t in node.targets):
|
|
336
|
+
try:
|
|
337
|
+
keys = list(ast.literal_eval(node.value).keys())
|
|
338
|
+
except Exception:
|
|
339
|
+
keys = []
|
|
340
|
+
reg = {e["anchor"].get("key") for e in cr.entries()
|
|
341
|
+
if e["kind"] == "table" and e["anchor"]["file"] == rel
|
|
342
|
+
and e["anchor"]["symbol"] == sym}
|
|
343
|
+
missing = [k for k in keys if k not in reg]
|
|
344
|
+
if missing:
|
|
345
|
+
bad += 1
|
|
346
|
+
ok(not missing, f"G4 分区表覆盖完整:{rel}::{sym}({len(keys)} 键)",
|
|
347
|
+
f"漏登 {missing}")
|
|
348
|
+
return bad
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def run_all(cr=None):
|
|
352
|
+
_PASS.clear()
|
|
353
|
+
_FAIL.clear()
|
|
354
|
+
if cr is None:
|
|
355
|
+
from . import config_registry as cr
|
|
356
|
+
print("[统一配置层守卫] 判据 G1..G4")
|
|
357
|
+
total = g1_schema(cr) + g2_anchors(cr) + g3_generated(cr) + g4_table_coverage(cr)
|
|
358
|
+
print(f"\n结果:PASS {len(_PASS)} / FAIL {len(_FAIL)}")
|
|
359
|
+
return len(_FAIL)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# ---------------------------------------------------------------------------
|
|
363
|
+
# 定点变异自证
|
|
364
|
+
# ---------------------------------------------------------------------------
|
|
365
|
+
_MUTATIONS = []
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _mut(name, kind, rel, anchor, repl):
|
|
369
|
+
_MUTATIONS.append((name, kind, rel, anchor, repl))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
# ① 改 registry 里的 const 缺省(登记侧漂移)
|
|
373
|
+
_mut("M1 registry-const-默认值改掉", "registry", None,
|
|
374
|
+
"WINDOW_SHORT_D", 4)
|
|
375
|
+
# ② 改代码里的 const 缺省(代码侧漂移)
|
|
376
|
+
_mut("M2 代码-const-默认值改掉", "code", "md_cg/admission.py",
|
|
377
|
+
"WINDOW_SHORT_D = 3", "WINDOW_SHORT_D = 4")
|
|
378
|
+
# ③ 改既有真源表的值(分区表漂移)
|
|
379
|
+
_mut("M3 既有表-sleep-interval-改掉", "table", "md_cg/sleep.py",
|
|
380
|
+
'"interval": "3600"', '"interval": "1800"')
|
|
381
|
+
# ④ 改 env 字面量缺省(env 面漂移)
|
|
382
|
+
_mut("M4 env-字面量缺省改掉", "code", "md_cg/mdcg.py",
|
|
383
|
+
'os.environ.get("MDCG_GATE_S2_COND", "1")',
|
|
384
|
+
'os.environ.get("MDCG_GATE_S2_COND", "0")')
|
|
385
|
+
# ⑤ 文档参数表陈旧
|
|
386
|
+
_mut("M5 文档参数表陈旧", "doc", None, "registry 条目合计", "registry 条目合计")
|
|
387
|
+
# ⑥ 校验器陈旧
|
|
388
|
+
_mut("M6 校验器陈旧", "validator", None, "RULES = ", "RULES = {} # ")
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _apply_mutation(name, kind, rel, anchor, repl):
|
|
392
|
+
"""应用一条变异;锚点找不到 ⇒ 返回 2(ANCHOR-MISS)。返回 0/2。"""
|
|
393
|
+
from . import config_registry as cr
|
|
394
|
+
if kind == "registry":
|
|
395
|
+
for e in cr.entries():
|
|
396
|
+
if e["name"] == anchor:
|
|
397
|
+
e["value"] = repl
|
|
398
|
+
return 0
|
|
399
|
+
return 2
|
|
400
|
+
if kind in ("code", "table"):
|
|
401
|
+
text = _read(rel)
|
|
402
|
+
if anchor not in text:
|
|
403
|
+
return 2
|
|
404
|
+
_SRC[rel] = text.replace(anchor, repl, 1)
|
|
405
|
+
return 0
|
|
406
|
+
if kind == "doc":
|
|
407
|
+
text = open(_DOC, encoding="utf-8").read()
|
|
408
|
+
_SRC["__doc__"] = text.replace(anchor, anchor + "(变异)", 1)
|
|
409
|
+
return 0
|
|
410
|
+
if kind == "validator":
|
|
411
|
+
text = open(_VALIDATOR, encoding="utf-8").read()
|
|
412
|
+
_SRC["__validator__"] = text.replace(anchor, repl, 1)
|
|
413
|
+
return 0
|
|
414
|
+
return 2
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _run_mutations():
|
|
418
|
+
from . import config_registry as cr
|
|
419
|
+
print("[定点变异自证] 预期:每条变异后守卫**必红**,复原后**全绿**")
|
|
420
|
+
bad = 0
|
|
421
|
+
for name, kind, rel, anchor, repl in _MUTATIONS:
|
|
422
|
+
# 复原(重新导入真源 + 清空源码覆盖)
|
|
423
|
+
_SRC.clear()
|
|
424
|
+
import importlib
|
|
425
|
+
from . import config_registry as _cr
|
|
426
|
+
importlib.reload(_cr)
|
|
427
|
+
code = _apply_mutation(name, kind, rel, anchor, repl)
|
|
428
|
+
if code == 2:
|
|
429
|
+
print(f" ANCHOR-MISS {name}(锚点 {anchor!r} 在 {rel} 找不到)")
|
|
430
|
+
return 2
|
|
431
|
+
fails = run_all(_cr)
|
|
432
|
+
red = fails > 0
|
|
433
|
+
ok(red, f"{name} ⇒ 守卫转红(FAIL={fails})", "未转红")
|
|
434
|
+
if not red:
|
|
435
|
+
bad += 1
|
|
436
|
+
_SRC.clear()
|
|
437
|
+
importlib.reload(_cr)
|
|
438
|
+
# 复原后全绿
|
|
439
|
+
_SRC.clear()
|
|
440
|
+
import importlib
|
|
441
|
+
from . import config_registry as _cr2
|
|
442
|
+
importlib.reload(_cr2)
|
|
443
|
+
fails = run_all(_cr2)
|
|
444
|
+
ok(fails == 0, f"复原后复跑全绿(FAIL={fails})", "未复原为绿")
|
|
445
|
+
if fails:
|
|
446
|
+
bad += 1
|
|
447
|
+
print(f"\n变异自证结果:{'全部按预期' if bad == 0 else str(bad) + ' 项不符'}")
|
|
448
|
+
return 1 if bad else 0
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def main(argv):
|
|
452
|
+
if "--list" in argv:
|
|
453
|
+
for n, k, r, a, _ in _MUTATIONS:
|
|
454
|
+
print(f"{n} [{k}] {r or '-'} anchor={a!r}")
|
|
455
|
+
return 0
|
|
456
|
+
if "--mutate" in argv:
|
|
457
|
+
# 文档/校验器变异需经 _SRC;其余读盘
|
|
458
|
+
import md_cg.config_render as _r
|
|
459
|
+
real_doc = _r.render_doc
|
|
460
|
+
real_val = _r.render_validator
|
|
461
|
+
|
|
462
|
+
def doc_patched(cr, _rd=real_doc):
|
|
463
|
+
t = _rd(cr)
|
|
464
|
+
return _SRC.get("__doc__", t)
|
|
465
|
+
|
|
466
|
+
def val_patched(cr, _rv=real_val):
|
|
467
|
+
t = _rv(cr)
|
|
468
|
+
return _SRC.get("__validator__", t)
|
|
469
|
+
|
|
470
|
+
_r.render_doc = doc_patched
|
|
471
|
+
_r.render_validator = val_patched
|
|
472
|
+
return _run_mutations()
|
|
473
|
+
fails = run_all()
|
|
474
|
+
return 1 if fails else 0
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
if __name__ == "__main__":
|
|
478
|
+
raise SystemExit(main(sys.argv[1:]))
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
# pytest 收集入口(脚本式文件也可被 pytest 收)
|
|
482
|
+
def test_config_registry_guard():
|
|
483
|
+
assert run_all() == 0
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def test_config_registry_guard_mutations():
|
|
487
|
+
assert main(["--mutate"]) == 0
|