@furongjun1999/dsh-memory 0.9.6 → 0.9.8
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/README.md +150 -662
- package/codebuddy/CODEBUDDY.md +333 -204
- package/data/policy.json +38 -38
- package/docs/README.md +18 -0
- package/docs/discipline/harnesses.yaml +11 -3
- package/docs/discipline/templates/compact.txt.tmpl +20 -18
- package/docs/discipline/templates/full.md.tmpl +63 -61
- package/docs/discipline/templates/rules.mdc.tmpl +5 -3
- package/docs/discipline/templates/skill.md.tmpl +25 -23
- package/docs/discipline/templates/spec.txt.tmpl +2 -2
- package/docs/discipline/templates/zcode-user.md.tmpl +1 -1
- package/dsh/cordis.yml.example +139 -139
- package/lib/hooks.d.ts +19 -0
- package/lib/hooks.js +30 -7
- package/lib/index.js +18 -3
- package/lib/init.js +19 -4
- package/lib/lib/hook_audit.js +64 -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/sustain.py +10 -1
- 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 +9 -3
- 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_n184_keys_concurrent_provision.py +1 -1
- 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_read_scope_b27.py +2 -2
- package/md_cg/test_retr_s5.py +312 -312
- package/md_cg/test_s1_ast_judge.py +109 -109
- package/md_cg/test_security_audit_v21.py +249 -249
- 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_bad_stamp.py +178 -0
- 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 +932 -908
- package/src/index.ts +21 -6
- package/src/init.ts +16 -4
- package/src/lib/hook_audit.ts +48 -2
- package/src/lib/mdcg_client.ts +469 -469
- package/src/lib/prompt_safety.ts +17 -3
- package/src/tools.ts +23 -1
- package/zcode/AGENTS.md +333 -204
|
@@ -1,340 +1,340 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
# 功能名:前像命名的**孪生等价性**与同秒不互踩(issue #413)
|
|
3
|
-
# 生效条件:python -X utf8 -m md_cg.test_issue413_preimage_twin [--mutate];被测面=md_cg/protect.py 的 _preimage_name(唯一命名单点)、snapshot(裸守卫 _allow 侧)、snapshot_preimage(执行时点前像侧)、_allow(前像缺失时的放行)
|
|
4
|
-
# 子功能:F 组=孪生等价性(同一单点 + 载体同构 + 形态保持 + 同秒不互踩);A 组=_allow「前像缺失」两态可达性取证 + 可见化/登记断言;K 组=非恒真与过度方向(跨秒、合法后缀、探测有界、无冲突不加后缀);E 组=枚举完备性与回退自证(_guard_kit 两骨架)
|
|
5
|
-
# 执行:--mutate 时在镜像树里回缺陷(去掉探测)/ 过度(无冲突也加后缀)/ 只加固一侧(snapshot 改回裸名),守卫必须按指定项转红;另调 _guard_kit 两骨架
|
|
6
|
-
# 验证方式:全部 PASS 即通过(退出码 0);变异与骨架红项集合须与预期逐项相符
|
|
7
|
-
# 不适用条件:不改 #413 的**语义裁定**(前像缺失时 fail-open 还是 fail-closed 归维护者;本守卫只**登记**现状并让它在返回体/审计里可见);不判 _protected_history 的保留策略与清理;不判加密库里前像的逐字节可复现性(protect.snapshot_preimage docstring 已登记该边界);不判 test_mutation_rollback 的读数口径(它已按不变量重钉,本件不改它)
|
|
8
|
-
"""issue #413 守卫:**同语义两处实现、只加固了一侧** —— 本件把「孪生等价性」钉成判据。
|
|
9
|
-
|
|
10
|
-
病象(修前):`snapshot()`(裸守卫 `_allow` 路径)与 `snapshot_preimage()`(执行时点前像)
|
|
11
|
-
**各写一套文件名拼接**:前者裸秒级 `%Y%m%d-%H%M%S`,后者秒级 + 6 位微秒。同一秒内两次
|
|
12
|
-
`snapshot()` 会拿到**同一路径** ⇒ 先那张前像被后来者覆盖(回滚句柄指向错误时点)。
|
|
13
|
-
#413 修法:抽出**唯一命名单点** `_preimage_name(d, suffix="")`(基名 + suffix,已存在即取
|
|
14
|
-
下一个空闲名),两侧都改调它。
|
|
15
|
-
|
|
16
|
-
**等价性的边界(先问载体,再写断言)**:两侧**载体同构**才可直接比字符串——本件实测:两者都
|
|
17
|
-
「写一个 .md 到 `_protected_history/<id>/`」且都**返回相对路径字符串**(载体同构 ✔);**有意不同**
|
|
18
|
-
的是审计 action(`snapshot` vs `preimage`)与 reason ⇒ F 组断言「命名单点等价 + 载体同构」,
|
|
19
|
-
并**另行断言那两处差异仍在**(等价性 ≠ 全等)。
|
|
20
|
-
|
|
21
|
-
⚠ 覆盖边界(如实登记):本守卫**只读** `protect.py`(#413 已定稿),故「前像缺失仍 override
|
|
22
|
-
放行」**不改语义**,只做**取证 + 可见化断言**(返回体 snapshot=None + 审计面留 snapshot:null 的
|
|
23
|
-
override 记录)。fail-open/fail-closed 的裁定归维护者。
|
|
24
|
-
"""
|
|
25
|
-
import json
|
|
26
|
-
import os
|
|
27
|
-
import re
|
|
28
|
-
import shutil
|
|
29
|
-
import subprocess
|
|
30
|
-
import sys
|
|
31
|
-
import tempfile
|
|
32
|
-
from unittest import mock
|
|
33
|
-
|
|
34
|
-
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
35
|
-
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
36
|
-
if _REPO not in sys.path:
|
|
37
|
-
sys.path.insert(0, _REPO)
|
|
38
|
-
|
|
39
|
-
from md_cg import _guard_kit as GK # noqa: E402
|
|
40
|
-
from md_cg import protect # noqa: E402
|
|
41
|
-
from md_cg.mdcos import MdCGOS # noqa: E402
|
|
42
|
-
|
|
43
|
-
FAILS = []
|
|
44
|
-
_TMP = tempfile.mkdtemp(prefix="iss413_")
|
|
45
|
-
_CCG = chr(10).join(["# 功能名:前像目标节点", "# 生效条件:本地合成库",
|
|
46
|
-
"# 子功能:无", "# 执行:无", "# 验证方式:test",
|
|
47
|
-
"# 不适用条件:无", "# 正文:前像目标正文"])
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def _check(name, cond, detail=""):
|
|
51
|
-
if cond:
|
|
52
|
-
print(" PASS " + name)
|
|
53
|
-
else:
|
|
54
|
-
print(" FAIL " + name + " " + str(detail)[:220])
|
|
55
|
-
FAILS.append(name)
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def _prot_lib(tag):
|
|
59
|
-
"""合成库 + 一个受保护节点(self 层 ⇒ is_immutable 真 ⇒ guard_write 走 _allow)。"""
|
|
60
|
-
d = os.path.join(_TMP, tag)
|
|
61
|
-
os.makedirs(d, exist_ok=True)
|
|
62
|
-
cg = MdCGOS(d)
|
|
63
|
-
cg.add("pr_t", _CCG, layer="self")
|
|
64
|
-
cg.flush()
|
|
65
|
-
return cg
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
def _names(cg, nid="pr_t"):
|
|
69
|
-
d = os.path.join(cg.root, protect.HISTORY_DIR, nid)
|
|
70
|
-
if not os.path.isdir(d):
|
|
71
|
-
return []
|
|
72
|
-
return sorted(f for f in os.listdir(d) if f.endswith(".md"))
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
print("== F 组:孪生等价性(#326-③ F04 形态) ==")
|
|
76
|
-
_SRC = open(os.path.join(_REPO, "md_cg", "protect.py"), encoding="utf-8").read()
|
|
77
|
-
_SEC = _SRC # 全文件口径("留痕"在本文件出现 2 次,split("留痕")[-1] 只会留尾部——实测踩过)
|
|
78
|
-
_check("F01 留痕区里秒级裸名拼接只剩**单点内**那一处(无第三处裸命名;调用点恰 2 处)",
|
|
79
|
-
_SEC.count('strftime("%Y%m%d-%H%M%S"') == 1
|
|
80
|
-
and _SEC.count("_preimage_name(") == 3, # 实测:def 1 + 调用 2
|
|
81
|
-
(_SEC.count('strftime("%Y%m%d-%H%M%S"'),
|
|
82
|
-
_SEC.count("_preimage_name(")))
|
|
83
|
-
_check("F02 两侧都经 _preimage_name(裸守卫侧无 suffix / 执行时点侧带 6 位微秒 suffix)",
|
|
84
|
-
"_preimage_name(d)" in _SEC and "_preimage_name(d, \"-%06d\"" in _SEC)
|
|
85
|
-
|
|
86
|
-
_cg = _prot_lib("twin")
|
|
87
|
-
_calls = []
|
|
88
|
-
_orig = protect._preimage_name
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
def _spy(d, suffix=""):
|
|
92
|
-
_calls.append(suffix)
|
|
93
|
-
return _orig(d, suffix)
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
with mock.patch.object(protect, "_preimage_name", _spy):
|
|
97
|
-
_r1 = protect.snapshot(_cg, "pr_t")
|
|
98
|
-
_r2 = protect.snapshot_preimage(_cg, "pr_t", action="B", pid="pid_1")
|
|
99
|
-
_check("F03 **双链等价性**:两条链都命中同一单点(spy 命中 2 次:suffix 空 / 微秒各一)",
|
|
100
|
-
len(_calls) == 2 and _calls[0] == "" and len(_calls[1]) == 7, _calls)
|
|
101
|
-
_check("F04 **载体同构**:两侧都返回 str 相对路径、各写一个 .md(可直接比字符串的前提)",
|
|
102
|
-
isinstance(_r1, str) and isinstance(_r2, str)
|
|
103
|
-
and not os.path.isabs(_r2) and len(_names(_cg)) == 2, (_r1, _r2, _names(_cg)))
|
|
104
|
-
_check("F05 两侧产物**互不覆盖**(同秒两张不同文件;修前二者路径相同)",
|
|
105
|
-
_r1 != _r2 and len(set(_names(_cg))) == 2, (_r1, _r2, _names(_cg)))
|
|
106
|
-
_check("F06 形态保持:裸守卫侧=秒级(无微秒);执行时点侧=秒级+6 位微秒(既有守卫钉死)",
|
|
107
|
-
bool(re.fullmatch(r"\d{8}-\d{6}(-\d+)?\.md", os.path.basename(_r1)))
|
|
108
|
-
and bool(re.fullmatch(r"\d{8}-\d{6}-\d{6}(-\d+)?\.md", os.path.basename(_r2))),
|
|
109
|
-
(_r1, _r2))
|
|
110
|
-
_r3 = protect.snapshot(_cg, "pr_t")
|
|
111
|
-
_r4 = protect.snapshot(_cg, "pr_t")
|
|
112
|
-
_check("F07 同侧同秒两次:四条路径两两不同(修前四条全等 ⇒ 前像被踩掉)",
|
|
113
|
-
len({_r1, _r2, _r3, _r4}) == 4, (_r1, _r2, _r3, _r4))
|
|
114
|
-
_check("F08 落盘文件数 == 返回路径数(没有「返回了却没写」或「写了却没返回」)",
|
|
115
|
-
len(_names(_cg)) == 4, _names(_cg))
|
|
116
|
-
_check("F09 **等价性 ≠ 全等**:两侧审计 action 有意不同(snapshot vs preimage),此差异须仍在",
|
|
117
|
-
"\"snapshot\"" in _SEC and "\"preimage\"" in _SEC)
|
|
118
|
-
_cg.close()
|
|
119
|
-
|
|
120
|
-
print("== A 组:_allow 的「前像缺失」两态取证 + 可见化/登记 ==")
|
|
121
|
-
_cga = _prot_lib("allow")
|
|
122
|
-
_nx = protect.guard_write(_cga, "no_such_node", override=True)
|
|
123
|
-
_check("A01 态①「节点不存在」**不可达** _allow:guard_write 返回 None(不存在即放行)",
|
|
124
|
-
_nx is None, _nx)
|
|
125
|
-
_check("A02 且 snapshot(不存在节点) 返回 None(该态自证:前像确实拍不出来)",
|
|
126
|
-
protect.snapshot(_cga, "no_such_node") is None)
|
|
127
|
-
# ★2026-10-18 契约变更(80aa70d8 #413-2):前像拍不出来时**不再放行**——`_allow` 改为
|
|
128
|
-
# fail-closed(N228:无前像的 override 不可回滚)。旧断言钉的是「放行 + snapshot=None
|
|
129
|
-
# 可观测」的旧契约;现改为钉 fail-closed:抛 ProtectionError、错误串点名前像不可得、
|
|
130
|
-
# 审计面留 `<action>_denied` 行(拒绝事件同样不静默)。
|
|
131
|
-
_err = None
|
|
132
|
-
with mock.patch.object(MdCGOS, "_write_node",
|
|
133
|
-
side_effect=OSError("模拟前像写盘失败")):
|
|
134
|
-
try:
|
|
135
|
-
_fa = protect.guard_write(_cga, "pr_t", override=True, actor="guard413")
|
|
136
|
-
except protect.ProtectionError as exc:
|
|
137
|
-
_err = str(exc)
|
|
138
|
-
_fa = None
|
|
139
|
-
_check("A03 态②「启用但失败」**可达**:前像写失败 ⇒ fail-closed 抛 ProtectionError",
|
|
140
|
-
_err is not None and _fa is None, (_err, _fa))
|
|
141
|
-
_check("A04 可见化:错误串点明「前像不可得」且声明 fail-closed(拒绝可观测)",
|
|
142
|
-
bool(_err) and "前像不可得" in _err and "fail-closed" in _err, _err)
|
|
143
|
-
_ap = os.path.join(_cga.root, protect.AUDIT_FILE)
|
|
144
|
-
_rows = []
|
|
145
|
-
if os.path.exists(_ap):
|
|
146
|
-
with open(_ap, encoding="utf-8") as _f:
|
|
147
|
-
_rows = [json.loads(l) for l in _f if l.strip()]
|
|
148
|
-
_denied = [r for r in _rows if str(r.get("action") or "").endswith("_denied")]
|
|
149
|
-
_check("A05 登记:审计面留有该 `<action>_denied` 行(拒绝不静默)",
|
|
150
|
-
bool(_denied),
|
|
151
|
-
[{"a": r.get("action"), "s": r.get("snapshot")} for r in _rows][-3:])
|
|
152
|
-
_check("A06 语义已按 #413-2 收口:前像缺失时**不再**返回 override=True(可回滚优先)",
|
|
153
|
-
_fa is None)
|
|
154
|
-
_cga.close()
|
|
155
|
-
|
|
156
|
-
print("== K 组:非恒真对照与过度方向 ==")
|
|
157
|
-
_cgk = _prot_lib("k")
|
|
158
|
-
_d = os.path.join(_cgk.root, protect.HISTORY_DIR, "pr_t")
|
|
159
|
-
os.makedirs(_d, exist_ok=True)
|
|
160
|
-
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000001"):
|
|
161
|
-
_k1 = protect._preimage_name(_d)
|
|
162
|
-
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000002"):
|
|
163
|
-
_k2 = protect._preimage_name(_d)
|
|
164
|
-
_check("K01 跨秒:两个名字不同且都**无**冲突后缀(形态不被探测改写)",
|
|
165
|
-
_k1 != _k2
|
|
166
|
-
and bool(re.fullmatch(r"\d{8}-\d{6}\.md", os.path.basename(_k1)))
|
|
167
|
-
and bool(re.fullmatch(r"\d{8}-\d{6}\.md", os.path.basename(_k2))), (_k1, _k2))
|
|
168
|
-
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000003"):
|
|
169
|
-
open(os.path.join(_d, "20260101-000003.md"), "w", encoding="utf-8").close()
|
|
170
|
-
open(os.path.join(_d, "20260101-000003-1.md"), "w", encoding="utf-8").close()
|
|
171
|
-
_k3 = protect._preimage_name(_d)
|
|
172
|
-
_check("K02 已存在 base 与 base-1 ⇒ 取 base-2(不覆盖既有前像)",
|
|
173
|
-
os.path.basename(_k3) == "20260101-000003-2.md", os.path.basename(_k3))
|
|
174
|
-
_check("K03 合法后缀名不被误判为空闲:不返回已占用的 base.md / base-1.md",
|
|
175
|
-
os.path.basename(_k3) not in ("20260101-000003.md", "20260101-000003-1.md"))
|
|
176
|
-
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000004"):
|
|
177
|
-
open(os.path.join(_d, "20260101-000004.md"), "w", encoding="utf-8").close()
|
|
178
|
-
for _i in range(1, 50):
|
|
179
|
-
open(os.path.join(_d, "20260101-000004-%d.md" % _i), "w", encoding="utf-8").close()
|
|
180
|
-
_k4 = protect._preimage_name(_d)
|
|
181
|
-
_check("K04 探测有界且正确:50 个连续名占满 ⇒ 取第 51 个(不超时、不跳号)",
|
|
182
|
-
os.path.basename(_k4) == "20260101-000004-50.md", os.path.basename(_k4))
|
|
183
|
-
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000005"):
|
|
184
|
-
_k5 = protect._preimage_name(_d)
|
|
185
|
-
_check("K05 无冲突 ⇒ 名字不含任何后缀(既有形态一字不动)",
|
|
186
|
-
os.path.basename(_k5) == "20260101-000005.md", os.path.basename(_k5))
|
|
187
|
-
_cgk.close()
|
|
188
|
-
|
|
189
|
-
print("== E 组:骨架①枚举完备性 ==")
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
def _discover(texts):
|
|
193
|
-
"""守卫自己的枚举:命中「**绕过单点**直接拼快照文件名」的命名点。"""
|
|
194
|
-
import ast as _ast
|
|
195
|
-
hits = []
|
|
196
|
-
for rel, src in texts.items():
|
|
197
|
-
try:
|
|
198
|
-
tree = _ast.parse(src)
|
|
199
|
-
except SyntaxError:
|
|
200
|
-
continue
|
|
201
|
-
for node in _ast.walk(tree):
|
|
202
|
-
if not isinstance(node, _ast.FunctionDef):
|
|
203
|
-
continue
|
|
204
|
-
seg = _ast.get_source_segment(src, node) or ""
|
|
205
|
-
if "strftime" in seg and "_preimage_name" not in seg:
|
|
206
|
-
hits.append((rel, node.lineno))
|
|
207
|
-
return hits
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
_OLD = "def snapshot(cg, nid):" + chr(10) + " d = getattr(cg, \"root\", \"x\")" + chr(10)
|
|
211
|
-
_OLD = _OLD + " p = os.path.join(d, time.strftime(\"%Y%m%d-%H%M%S\", time.localtime()) + \".md\")"
|
|
212
|
-
_OLD = _OLD + chr(10) + " return p"
|
|
213
|
-
_NEW = "def snapshot(cg, nid):" + chr(10) + " d = getattr(cg, \"root\", \"x\")" + chr(10)
|
|
214
|
-
_NEW = _NEW + " return _preimage_name(d)"
|
|
215
|
-
_ok_e, _det_e = GK.assert_enumeration_complete(
|
|
216
|
-
_discover,
|
|
217
|
-
[("应命中·旧形态(绕过单点直拼秒级名)", _OLD, True, "protect_old.py"),
|
|
218
|
-
("不应命中·新形态(经单点)", _NEW, False, "protect_new.py"),
|
|
219
|
-
("不应命中·无关函数", "def other():" + chr(10) + " return 1", False, "x.py")])
|
|
220
|
-
_check("E01 骨架①枚举完备性(应命中/不应命中两侧)", _ok_e, _det_e)
|
|
221
|
-
|
|
222
|
-
print("== 骨架② / 变异 ==")
|
|
223
|
-
_NL = "\r\n" if b"\r\n" in open(os.path.join(_REPO, "md_cg", "protect.py"),
|
|
224
|
-
"rb").read()[:8192] else "\n"
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
def _j(*lines):
|
|
228
|
-
return _NL.join(lines)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
_PROBE = _j(" _n = 1", " while os.path.exists(p):",
|
|
232
|
-
" p = os.path.join(d, \"%s-%d.md\" % (base, _n))", " _n += 1")
|
|
233
|
-
_Q = chr(34) # 内层双引号一律用 _Q 拼,避免本文件出现转义引号
|
|
234
|
-
_M1 = ("M1 回缺陷:去掉探测(同秒互踩)", "md_cg/protect.py",
|
|
235
|
-
[(_PROBE, " pass # 变异:不探测(回到 #413 修前)")],
|
|
236
|
-
# F05 不参与判别(两侧本就差一个 suffix);真正打回缺陷的是 F07/F08(互踩/少落盘)
|
|
237
|
-
("F07", "F08", "K02", "K03", "K04"))
|
|
238
|
-
_M2 = ("M2 过度:无冲突也加后缀(形态被改写)", "md_cg/protect.py",
|
|
239
|
-
[(_j(" p = os.path.join(d, base + " + _Q + ".md" + _Q + ")"),
|
|
240
|
-
_j(" p = os.path.join(d, base + " + _Q + "-1.md" + _Q + ")"))],
|
|
241
|
-
# F06 不参与判别(正则允许 -N 后缀)⇒ 由 K01/K05(无形变)承担
|
|
242
|
-
("K01", "K05"))
|
|
243
|
-
# M3 只加固一侧:把 snapshot 侧改回裸名(另一侧仍走单点)——孪生等价性必须因此转红。
|
|
244
|
-
_RAW_SNAP = (" p = os.path.join(d, time.strftime(" + _Q + "%Y%m%d-%H%M%S" + _Q
|
|
245
|
-
+ ", time.localtime()) + " + _Q + ".md" + _Q + ")")
|
|
246
|
-
_M3 = ("M3 只加固一侧:snapshot 改回裸名(孪生不等价)", "md_cg/protect.py",
|
|
247
|
-
[(" p = _preimage_name(d)", _RAW_SNAP)],
|
|
248
|
-
# 只加固一侧 ⇒ 结构面(F01 出现第二处裸名)+ 双链(F02/F03)+ 互踩(F07/F08)全红
|
|
249
|
-
("F01", "F02", "F03", "F07", "F08"))
|
|
250
|
-
_MUTATIONS = (_M1, _M2, _M3)
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
def _mirror_build():
|
|
254
|
-
dst = tempfile.mkdtemp(prefix="iss413_mut_")
|
|
255
|
-
for name in ("md_cg", "scripts"):
|
|
256
|
-
src = os.path.join(_REPO, name)
|
|
257
|
-
if os.path.isdir(src):
|
|
258
|
-
shutil.copytree(src, os.path.join(dst, name),
|
|
259
|
-
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
|
260
|
-
for name in sorted(os.listdir(_REPO)):
|
|
261
|
-
p = os.path.join(_REPO, name)
|
|
262
|
-
if os.path.isfile(p) and (name.endswith(".py")
|
|
263
|
-
or name in ("README.md", "pyproject.toml")):
|
|
264
|
-
shutil.copy2(p, os.path.join(dst, name))
|
|
265
|
-
return dst
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
def _run_in(tree):
|
|
269
|
-
env = dict(os.environ)
|
|
270
|
-
env.update({"PYTHONPATH": tree, "PYTHONUTF8": "1",
|
|
271
|
-
"PYTHONDONTWRITEBYTECODE": "1"})
|
|
272
|
-
env.pop("MDCG_ROOT", None)
|
|
273
|
-
pr = subprocess.run([sys.executable, "-X", "utf8", "-m",
|
|
274
|
-
"md_cg.test_issue413_preimage_twin"],
|
|
275
|
-
cwd=tree, env=env, capture_output=True, text=True,
|
|
276
|
-
encoding="utf-8", errors="replace", timeout=1800)
|
|
277
|
-
out = (pr.stdout or "") + (pr.stderr or "")
|
|
278
|
-
reds = [ln.split("FAIL ", 1)[1].strip()
|
|
279
|
-
for ln in out.splitlines() if ln.strip().startswith("FAIL ")]
|
|
280
|
-
return pr.returncode, reds, out
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
def _mutate():
|
|
284
|
-
tree = _mirror_build()
|
|
285
|
-
bad = []
|
|
286
|
-
try:
|
|
287
|
-
rc, reds, out = _run_in(tree)
|
|
288
|
-
print(" 未变异镜像基线:rc=%d 红项=%d(必须 rc=0 且 0 红)" % (rc, len(reds)))
|
|
289
|
-
if rc != 0 or reds:
|
|
290
|
-
print(chr(10).join(out.splitlines()[-20:]))
|
|
291
|
-
for desc, rel, pairs, exp in _MUTATIONS:
|
|
292
|
-
p = os.path.join(tree, rel)
|
|
293
|
-
t = open(p, encoding="utf-8", newline="").read()
|
|
294
|
-
if any(t.count(o) != 1 for o, _n in pairs):
|
|
295
|
-
bad.append("%s 锚点命中 %s" % (desc, [t.count(o) for o, _n in pairs]))
|
|
296
|
-
print(" ANCHOR-MISS " + desc)
|
|
297
|
-
continue
|
|
298
|
-
bak = t
|
|
299
|
-
for o, n in pairs:
|
|
300
|
-
t = t.replace(o, n, 1)
|
|
301
|
-
open(p, "w", encoding="utf-8", newline="").write(t)
|
|
302
|
-
for r, dd, ff in os.walk(tree):
|
|
303
|
-
if os.path.basename(r) == "__pycache__":
|
|
304
|
-
shutil.rmtree(r, ignore_errors=True)
|
|
305
|
-
rc2, reds2, _o2 = _run_in(tree)
|
|
306
|
-
open(p, "w", encoding="utf-8", newline="").write(bak)
|
|
307
|
-
hit = sorted({r.split(" ")[0] for r in reds2})
|
|
308
|
-
if rc2 != 0 and hit == sorted(exp):
|
|
309
|
-
print(" OK %s 红项=%d 指定命中=%d/%d" % (desc, len(reds2), len(hit), len(exp)))
|
|
310
|
-
else:
|
|
311
|
-
bad.append(desc)
|
|
312
|
-
print(" MISMATCH %s 实际=%s 期望=%s rc=%d" % (desc, hit, sorted(exp), rc2))
|
|
313
|
-
for r in reds2[:6]:
|
|
314
|
-
print(" FAIL " + r)
|
|
315
|
-
ok_r, det_r = GK.assert_revert_reddens(
|
|
316
|
-
_mirror_build,
|
|
317
|
-
[("md_cg/protect.py", _PROBE.replace("\r\n", "\n"), " pass # 回退:不探测")],
|
|
318
|
-
_run_in, ("F07", "F08", "K02", "K03", "K04"), "md_cg/protect.py")
|
|
319
|
-
print(" 骨架②回退即红:%s %s" % ("OK" if ok_r else "MISMATCH",
|
|
320
|
-
json.dumps(det_r, ensure_ascii=False)[:200]))
|
|
321
|
-
if not ok_r:
|
|
322
|
-
bad.append("骨架②未按预期转红")
|
|
323
|
-
print("定点变异自证:%s(%d 条不合格)" % ("PASS" if not bad else "FAIL", len(bad)))
|
|
324
|
-
return len(bad)
|
|
325
|
-
finally:
|
|
326
|
-
shutil.rmtree(tree, ignore_errors=True)
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
shutil.rmtree(_TMP, ignore_errors=True)
|
|
330
|
-
print("")
|
|
331
|
-
print("issue #413 结果:%s" % ("全部通过" if not FAILS else "%d 失败" % len(FAILS)))
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
def main():
|
|
335
|
-
_bad = _mutate() if "--mutate" in sys.argv else 0
|
|
336
|
-
return 1 if (FAILS or _bad) else 0
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
if __name__ == "__main__":
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# 功能名:前像命名的**孪生等价性**与同秒不互踩(issue #413)
|
|
3
|
+
# 生效条件:python -X utf8 -m md_cg.test_issue413_preimage_twin [--mutate];被测面=md_cg/protect.py 的 _preimage_name(唯一命名单点)、snapshot(裸守卫 _allow 侧)、snapshot_preimage(执行时点前像侧)、_allow(前像缺失时的放行)
|
|
4
|
+
# 子功能:F 组=孪生等价性(同一单点 + 载体同构 + 形态保持 + 同秒不互踩);A 组=_allow「前像缺失」两态可达性取证 + 可见化/登记断言;K 组=非恒真与过度方向(跨秒、合法后缀、探测有界、无冲突不加后缀);E 组=枚举完备性与回退自证(_guard_kit 两骨架)
|
|
5
|
+
# 执行:--mutate 时在镜像树里回缺陷(去掉探测)/ 过度(无冲突也加后缀)/ 只加固一侧(snapshot 改回裸名),守卫必须按指定项转红;另调 _guard_kit 两骨架
|
|
6
|
+
# 验证方式:全部 PASS 即通过(退出码 0);变异与骨架红项集合须与预期逐项相符
|
|
7
|
+
# 不适用条件:不改 #413 的**语义裁定**(前像缺失时 fail-open 还是 fail-closed 归维护者;本守卫只**登记**现状并让它在返回体/审计里可见);不判 _protected_history 的保留策略与清理;不判加密库里前像的逐字节可复现性(protect.snapshot_preimage docstring 已登记该边界);不判 test_mutation_rollback 的读数口径(它已按不变量重钉,本件不改它)
|
|
8
|
+
"""issue #413 守卫:**同语义两处实现、只加固了一侧** —— 本件把「孪生等价性」钉成判据。
|
|
9
|
+
|
|
10
|
+
病象(修前):`snapshot()`(裸守卫 `_allow` 路径)与 `snapshot_preimage()`(执行时点前像)
|
|
11
|
+
**各写一套文件名拼接**:前者裸秒级 `%Y%m%d-%H%M%S`,后者秒级 + 6 位微秒。同一秒内两次
|
|
12
|
+
`snapshot()` 会拿到**同一路径** ⇒ 先那张前像被后来者覆盖(回滚句柄指向错误时点)。
|
|
13
|
+
#413 修法:抽出**唯一命名单点** `_preimage_name(d, suffix="")`(基名 + suffix,已存在即取
|
|
14
|
+
下一个空闲名),两侧都改调它。
|
|
15
|
+
|
|
16
|
+
**等价性的边界(先问载体,再写断言)**:两侧**载体同构**才可直接比字符串——本件实测:两者都
|
|
17
|
+
「写一个 .md 到 `_protected_history/<id>/`」且都**返回相对路径字符串**(载体同构 ✔);**有意不同**
|
|
18
|
+
的是审计 action(`snapshot` vs `preimage`)与 reason ⇒ F 组断言「命名单点等价 + 载体同构」,
|
|
19
|
+
并**另行断言那两处差异仍在**(等价性 ≠ 全等)。
|
|
20
|
+
|
|
21
|
+
⚠ 覆盖边界(如实登记):本守卫**只读** `protect.py`(#413 已定稿),故「前像缺失仍 override
|
|
22
|
+
放行」**不改语义**,只做**取证 + 可见化断言**(返回体 snapshot=None + 审计面留 snapshot:null 的
|
|
23
|
+
override 记录)。fail-open/fail-closed 的裁定归维护者。
|
|
24
|
+
"""
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import shutil
|
|
29
|
+
import subprocess
|
|
30
|
+
import sys
|
|
31
|
+
import tempfile
|
|
32
|
+
from unittest import mock
|
|
33
|
+
|
|
34
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
35
|
+
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
36
|
+
if _REPO not in sys.path:
|
|
37
|
+
sys.path.insert(0, _REPO)
|
|
38
|
+
|
|
39
|
+
from md_cg import _guard_kit as GK # noqa: E402
|
|
40
|
+
from md_cg import protect # noqa: E402
|
|
41
|
+
from md_cg.mdcos import MdCGOS # noqa: E402
|
|
42
|
+
|
|
43
|
+
FAILS = []
|
|
44
|
+
_TMP = tempfile.mkdtemp(prefix="iss413_")
|
|
45
|
+
_CCG = chr(10).join(["# 功能名:前像目标节点", "# 生效条件:本地合成库",
|
|
46
|
+
"# 子功能:无", "# 执行:无", "# 验证方式:test",
|
|
47
|
+
"# 不适用条件:无", "# 正文:前像目标正文"])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _check(name, cond, detail=""):
|
|
51
|
+
if cond:
|
|
52
|
+
print(" PASS " + name)
|
|
53
|
+
else:
|
|
54
|
+
print(" FAIL " + name + " " + str(detail)[:220])
|
|
55
|
+
FAILS.append(name)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _prot_lib(tag):
|
|
59
|
+
"""合成库 + 一个受保护节点(self 层 ⇒ is_immutable 真 ⇒ guard_write 走 _allow)。"""
|
|
60
|
+
d = os.path.join(_TMP, tag)
|
|
61
|
+
os.makedirs(d, exist_ok=True)
|
|
62
|
+
cg = MdCGOS(d)
|
|
63
|
+
cg.add("pr_t", _CCG, layer="self")
|
|
64
|
+
cg.flush()
|
|
65
|
+
return cg
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _names(cg, nid="pr_t"):
|
|
69
|
+
d = os.path.join(cg.root, protect.HISTORY_DIR, nid)
|
|
70
|
+
if not os.path.isdir(d):
|
|
71
|
+
return []
|
|
72
|
+
return sorted(f for f in os.listdir(d) if f.endswith(".md"))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
print("== F 组:孪生等价性(#326-③ F04 形态) ==")
|
|
76
|
+
_SRC = open(os.path.join(_REPO, "md_cg", "protect.py"), encoding="utf-8").read()
|
|
77
|
+
_SEC = _SRC # 全文件口径("留痕"在本文件出现 2 次,split("留痕")[-1] 只会留尾部——实测踩过)
|
|
78
|
+
_check("F01 留痕区里秒级裸名拼接只剩**单点内**那一处(无第三处裸命名;调用点恰 2 处)",
|
|
79
|
+
_SEC.count('strftime("%Y%m%d-%H%M%S"') == 1
|
|
80
|
+
and _SEC.count("_preimage_name(") == 3, # 实测:def 1 + 调用 2
|
|
81
|
+
(_SEC.count('strftime("%Y%m%d-%H%M%S"'),
|
|
82
|
+
_SEC.count("_preimage_name(")))
|
|
83
|
+
_check("F02 两侧都经 _preimage_name(裸守卫侧无 suffix / 执行时点侧带 6 位微秒 suffix)",
|
|
84
|
+
"_preimage_name(d)" in _SEC and "_preimage_name(d, \"-%06d\"" in _SEC)
|
|
85
|
+
|
|
86
|
+
_cg = _prot_lib("twin")
|
|
87
|
+
_calls = []
|
|
88
|
+
_orig = protect._preimage_name
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _spy(d, suffix=""):
|
|
92
|
+
_calls.append(suffix)
|
|
93
|
+
return _orig(d, suffix)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
with mock.patch.object(protect, "_preimage_name", _spy):
|
|
97
|
+
_r1 = protect.snapshot(_cg, "pr_t")
|
|
98
|
+
_r2 = protect.snapshot_preimage(_cg, "pr_t", action="B", pid="pid_1")
|
|
99
|
+
_check("F03 **双链等价性**:两条链都命中同一单点(spy 命中 2 次:suffix 空 / 微秒各一)",
|
|
100
|
+
len(_calls) == 2 and _calls[0] == "" and len(_calls[1]) == 7, _calls)
|
|
101
|
+
_check("F04 **载体同构**:两侧都返回 str 相对路径、各写一个 .md(可直接比字符串的前提)",
|
|
102
|
+
isinstance(_r1, str) and isinstance(_r2, str)
|
|
103
|
+
and not os.path.isabs(_r2) and len(_names(_cg)) == 2, (_r1, _r2, _names(_cg)))
|
|
104
|
+
_check("F05 两侧产物**互不覆盖**(同秒两张不同文件;修前二者路径相同)",
|
|
105
|
+
_r1 != _r2 and len(set(_names(_cg))) == 2, (_r1, _r2, _names(_cg)))
|
|
106
|
+
_check("F06 形态保持:裸守卫侧=秒级(无微秒);执行时点侧=秒级+6 位微秒(既有守卫钉死)",
|
|
107
|
+
bool(re.fullmatch(r"\d{8}-\d{6}(-\d+)?\.md", os.path.basename(_r1)))
|
|
108
|
+
and bool(re.fullmatch(r"\d{8}-\d{6}-\d{6}(-\d+)?\.md", os.path.basename(_r2))),
|
|
109
|
+
(_r1, _r2))
|
|
110
|
+
_r3 = protect.snapshot(_cg, "pr_t")
|
|
111
|
+
_r4 = protect.snapshot(_cg, "pr_t")
|
|
112
|
+
_check("F07 同侧同秒两次:四条路径两两不同(修前四条全等 ⇒ 前像被踩掉)",
|
|
113
|
+
len({_r1, _r2, _r3, _r4}) == 4, (_r1, _r2, _r3, _r4))
|
|
114
|
+
_check("F08 落盘文件数 == 返回路径数(没有「返回了却没写」或「写了却没返回」)",
|
|
115
|
+
len(_names(_cg)) == 4, _names(_cg))
|
|
116
|
+
_check("F09 **等价性 ≠ 全等**:两侧审计 action 有意不同(snapshot vs preimage),此差异须仍在",
|
|
117
|
+
"\"snapshot\"" in _SEC and "\"preimage\"" in _SEC)
|
|
118
|
+
_cg.close()
|
|
119
|
+
|
|
120
|
+
print("== A 组:_allow 的「前像缺失」两态取证 + 可见化/登记 ==")
|
|
121
|
+
_cga = _prot_lib("allow")
|
|
122
|
+
_nx = protect.guard_write(_cga, "no_such_node", override=True)
|
|
123
|
+
_check("A01 态①「节点不存在」**不可达** _allow:guard_write 返回 None(不存在即放行)",
|
|
124
|
+
_nx is None, _nx)
|
|
125
|
+
_check("A02 且 snapshot(不存在节点) 返回 None(该态自证:前像确实拍不出来)",
|
|
126
|
+
protect.snapshot(_cga, "no_such_node") is None)
|
|
127
|
+
# ★2026-10-18 契约变更(80aa70d8 #413-2):前像拍不出来时**不再放行**——`_allow` 改为
|
|
128
|
+
# fail-closed(N228:无前像的 override 不可回滚)。旧断言钉的是「放行 + snapshot=None
|
|
129
|
+
# 可观测」的旧契约;现改为钉 fail-closed:抛 ProtectionError、错误串点名前像不可得、
|
|
130
|
+
# 审计面留 `<action>_denied` 行(拒绝事件同样不静默)。
|
|
131
|
+
_err = None
|
|
132
|
+
with mock.patch.object(MdCGOS, "_write_node",
|
|
133
|
+
side_effect=OSError("模拟前像写盘失败")):
|
|
134
|
+
try:
|
|
135
|
+
_fa = protect.guard_write(_cga, "pr_t", override=True, actor="guard413")
|
|
136
|
+
except protect.ProtectionError as exc:
|
|
137
|
+
_err = str(exc)
|
|
138
|
+
_fa = None
|
|
139
|
+
_check("A03 态②「启用但失败」**可达**:前像写失败 ⇒ fail-closed 抛 ProtectionError",
|
|
140
|
+
_err is not None and _fa is None, (_err, _fa))
|
|
141
|
+
_check("A04 可见化:错误串点明「前像不可得」且声明 fail-closed(拒绝可观测)",
|
|
142
|
+
bool(_err) and "前像不可得" in _err and "fail-closed" in _err, _err)
|
|
143
|
+
_ap = os.path.join(_cga.root, protect.AUDIT_FILE)
|
|
144
|
+
_rows = []
|
|
145
|
+
if os.path.exists(_ap):
|
|
146
|
+
with open(_ap, encoding="utf-8") as _f:
|
|
147
|
+
_rows = [json.loads(l) for l in _f if l.strip()]
|
|
148
|
+
_denied = [r for r in _rows if str(r.get("action") or "").endswith("_denied")]
|
|
149
|
+
_check("A05 登记:审计面留有该 `<action>_denied` 行(拒绝不静默)",
|
|
150
|
+
bool(_denied),
|
|
151
|
+
[{"a": r.get("action"), "s": r.get("snapshot")} for r in _rows][-3:])
|
|
152
|
+
_check("A06 语义已按 #413-2 收口:前像缺失时**不再**返回 override=True(可回滚优先)",
|
|
153
|
+
_fa is None)
|
|
154
|
+
_cga.close()
|
|
155
|
+
|
|
156
|
+
print("== K 组:非恒真对照与过度方向 ==")
|
|
157
|
+
_cgk = _prot_lib("k")
|
|
158
|
+
_d = os.path.join(_cgk.root, protect.HISTORY_DIR, "pr_t")
|
|
159
|
+
os.makedirs(_d, exist_ok=True)
|
|
160
|
+
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000001"):
|
|
161
|
+
_k1 = protect._preimage_name(_d)
|
|
162
|
+
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000002"):
|
|
163
|
+
_k2 = protect._preimage_name(_d)
|
|
164
|
+
_check("K01 跨秒:两个名字不同且都**无**冲突后缀(形态不被探测改写)",
|
|
165
|
+
_k1 != _k2
|
|
166
|
+
and bool(re.fullmatch(r"\d{8}-\d{6}\.md", os.path.basename(_k1)))
|
|
167
|
+
and bool(re.fullmatch(r"\d{8}-\d{6}\.md", os.path.basename(_k2))), (_k1, _k2))
|
|
168
|
+
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000003"):
|
|
169
|
+
open(os.path.join(_d, "20260101-000003.md"), "w", encoding="utf-8").close()
|
|
170
|
+
open(os.path.join(_d, "20260101-000003-1.md"), "w", encoding="utf-8").close()
|
|
171
|
+
_k3 = protect._preimage_name(_d)
|
|
172
|
+
_check("K02 已存在 base 与 base-1 ⇒ 取 base-2(不覆盖既有前像)",
|
|
173
|
+
os.path.basename(_k3) == "20260101-000003-2.md", os.path.basename(_k3))
|
|
174
|
+
_check("K03 合法后缀名不被误判为空闲:不返回已占用的 base.md / base-1.md",
|
|
175
|
+
os.path.basename(_k3) not in ("20260101-000003.md", "20260101-000003-1.md"))
|
|
176
|
+
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000004"):
|
|
177
|
+
open(os.path.join(_d, "20260101-000004.md"), "w", encoding="utf-8").close()
|
|
178
|
+
for _i in range(1, 50):
|
|
179
|
+
open(os.path.join(_d, "20260101-000004-%d.md" % _i), "w", encoding="utf-8").close()
|
|
180
|
+
_k4 = protect._preimage_name(_d)
|
|
181
|
+
_check("K04 探测有界且正确:50 个连续名占满 ⇒ 取第 51 个(不超时、不跳号)",
|
|
182
|
+
os.path.basename(_k4) == "20260101-000004-50.md", os.path.basename(_k4))
|
|
183
|
+
with mock.patch.object(protect.time, "strftime", side_effect=lambda f, t: "20260101-000005"):
|
|
184
|
+
_k5 = protect._preimage_name(_d)
|
|
185
|
+
_check("K05 无冲突 ⇒ 名字不含任何后缀(既有形态一字不动)",
|
|
186
|
+
os.path.basename(_k5) == "20260101-000005.md", os.path.basename(_k5))
|
|
187
|
+
_cgk.close()
|
|
188
|
+
|
|
189
|
+
print("== E 组:骨架①枚举完备性 ==")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _discover(texts):
|
|
193
|
+
"""守卫自己的枚举:命中「**绕过单点**直接拼快照文件名」的命名点。"""
|
|
194
|
+
import ast as _ast
|
|
195
|
+
hits = []
|
|
196
|
+
for rel, src in texts.items():
|
|
197
|
+
try:
|
|
198
|
+
tree = _ast.parse(src)
|
|
199
|
+
except SyntaxError:
|
|
200
|
+
continue
|
|
201
|
+
for node in _ast.walk(tree):
|
|
202
|
+
if not isinstance(node, _ast.FunctionDef):
|
|
203
|
+
continue
|
|
204
|
+
seg = _ast.get_source_segment(src, node) or ""
|
|
205
|
+
if "strftime" in seg and "_preimage_name" not in seg:
|
|
206
|
+
hits.append((rel, node.lineno))
|
|
207
|
+
return hits
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
_OLD = "def snapshot(cg, nid):" + chr(10) + " d = getattr(cg, \"root\", \"x\")" + chr(10)
|
|
211
|
+
_OLD = _OLD + " p = os.path.join(d, time.strftime(\"%Y%m%d-%H%M%S\", time.localtime()) + \".md\")"
|
|
212
|
+
_OLD = _OLD + chr(10) + " return p"
|
|
213
|
+
_NEW = "def snapshot(cg, nid):" + chr(10) + " d = getattr(cg, \"root\", \"x\")" + chr(10)
|
|
214
|
+
_NEW = _NEW + " return _preimage_name(d)"
|
|
215
|
+
_ok_e, _det_e = GK.assert_enumeration_complete(
|
|
216
|
+
_discover,
|
|
217
|
+
[("应命中·旧形态(绕过单点直拼秒级名)", _OLD, True, "protect_old.py"),
|
|
218
|
+
("不应命中·新形态(经单点)", _NEW, False, "protect_new.py"),
|
|
219
|
+
("不应命中·无关函数", "def other():" + chr(10) + " return 1", False, "x.py")])
|
|
220
|
+
_check("E01 骨架①枚举完备性(应命中/不应命中两侧)", _ok_e, _det_e)
|
|
221
|
+
|
|
222
|
+
print("== 骨架② / 变异 ==")
|
|
223
|
+
_NL = "\r\n" if b"\r\n" in open(os.path.join(_REPO, "md_cg", "protect.py"),
|
|
224
|
+
"rb").read()[:8192] else "\n"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _j(*lines):
|
|
228
|
+
return _NL.join(lines)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
_PROBE = _j(" _n = 1", " while os.path.exists(p):",
|
|
232
|
+
" p = os.path.join(d, \"%s-%d.md\" % (base, _n))", " _n += 1")
|
|
233
|
+
_Q = chr(34) # 内层双引号一律用 _Q 拼,避免本文件出现转义引号
|
|
234
|
+
_M1 = ("M1 回缺陷:去掉探测(同秒互踩)", "md_cg/protect.py",
|
|
235
|
+
[(_PROBE, " pass # 变异:不探测(回到 #413 修前)")],
|
|
236
|
+
# F05 不参与判别(两侧本就差一个 suffix);真正打回缺陷的是 F07/F08(互踩/少落盘)
|
|
237
|
+
("F07", "F08", "K02", "K03", "K04"))
|
|
238
|
+
_M2 = ("M2 过度:无冲突也加后缀(形态被改写)", "md_cg/protect.py",
|
|
239
|
+
[(_j(" p = os.path.join(d, base + " + _Q + ".md" + _Q + ")"),
|
|
240
|
+
_j(" p = os.path.join(d, base + " + _Q + "-1.md" + _Q + ")"))],
|
|
241
|
+
# F06 不参与判别(正则允许 -N 后缀)⇒ 由 K01/K05(无形变)承担
|
|
242
|
+
("K01", "K05"))
|
|
243
|
+
# M3 只加固一侧:把 snapshot 侧改回裸名(另一侧仍走单点)——孪生等价性必须因此转红。
|
|
244
|
+
_RAW_SNAP = (" p = os.path.join(d, time.strftime(" + _Q + "%Y%m%d-%H%M%S" + _Q
|
|
245
|
+
+ ", time.localtime()) + " + _Q + ".md" + _Q + ")")
|
|
246
|
+
_M3 = ("M3 只加固一侧:snapshot 改回裸名(孪生不等价)", "md_cg/protect.py",
|
|
247
|
+
[(" p = _preimage_name(d)", _RAW_SNAP)],
|
|
248
|
+
# 只加固一侧 ⇒ 结构面(F01 出现第二处裸名)+ 双链(F02/F03)+ 互踩(F07/F08)全红
|
|
249
|
+
("F01", "F02", "F03", "F07", "F08"))
|
|
250
|
+
_MUTATIONS = (_M1, _M2, _M3)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _mirror_build():
|
|
254
|
+
dst = tempfile.mkdtemp(prefix="iss413_mut_")
|
|
255
|
+
for name in ("md_cg", "scripts"):
|
|
256
|
+
src = os.path.join(_REPO, name)
|
|
257
|
+
if os.path.isdir(src):
|
|
258
|
+
shutil.copytree(src, os.path.join(dst, name),
|
|
259
|
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
|
260
|
+
for name in sorted(os.listdir(_REPO)):
|
|
261
|
+
p = os.path.join(_REPO, name)
|
|
262
|
+
if os.path.isfile(p) and (name.endswith(".py")
|
|
263
|
+
or name in ("README.md", "pyproject.toml")):
|
|
264
|
+
shutil.copy2(p, os.path.join(dst, name))
|
|
265
|
+
return dst
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _run_in(tree):
|
|
269
|
+
env = dict(os.environ)
|
|
270
|
+
env.update({"PYTHONPATH": tree, "PYTHONUTF8": "1",
|
|
271
|
+
"PYTHONDONTWRITEBYTECODE": "1"})
|
|
272
|
+
env.pop("MDCG_ROOT", None)
|
|
273
|
+
pr = subprocess.run([sys.executable, "-X", "utf8", "-m",
|
|
274
|
+
"md_cg.test_issue413_preimage_twin"],
|
|
275
|
+
cwd=tree, env=env, capture_output=True, text=True,
|
|
276
|
+
encoding="utf-8", errors="replace", timeout=1800)
|
|
277
|
+
out = (pr.stdout or "") + (pr.stderr or "")
|
|
278
|
+
reds = [ln.split("FAIL ", 1)[1].strip()
|
|
279
|
+
for ln in out.splitlines() if ln.strip().startswith("FAIL ")]
|
|
280
|
+
return pr.returncode, reds, out
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _mutate():
|
|
284
|
+
tree = _mirror_build()
|
|
285
|
+
bad = []
|
|
286
|
+
try:
|
|
287
|
+
rc, reds, out = _run_in(tree)
|
|
288
|
+
print(" 未变异镜像基线:rc=%d 红项=%d(必须 rc=0 且 0 红)" % (rc, len(reds)))
|
|
289
|
+
if rc != 0 or reds:
|
|
290
|
+
print(chr(10).join(out.splitlines()[-20:]))
|
|
291
|
+
for desc, rel, pairs, exp in _MUTATIONS:
|
|
292
|
+
p = os.path.join(tree, rel)
|
|
293
|
+
t = open(p, encoding="utf-8", newline="").read()
|
|
294
|
+
if any(t.count(o) != 1 for o, _n in pairs):
|
|
295
|
+
bad.append("%s 锚点命中 %s" % (desc, [t.count(o) for o, _n in pairs]))
|
|
296
|
+
print(" ANCHOR-MISS " + desc)
|
|
297
|
+
continue
|
|
298
|
+
bak = t
|
|
299
|
+
for o, n in pairs:
|
|
300
|
+
t = t.replace(o, n, 1)
|
|
301
|
+
open(p, "w", encoding="utf-8", newline="").write(t)
|
|
302
|
+
for r, dd, ff in os.walk(tree):
|
|
303
|
+
if os.path.basename(r) == "__pycache__":
|
|
304
|
+
shutil.rmtree(r, ignore_errors=True)
|
|
305
|
+
rc2, reds2, _o2 = _run_in(tree)
|
|
306
|
+
open(p, "w", encoding="utf-8", newline="").write(bak)
|
|
307
|
+
hit = sorted({r.split(" ")[0] for r in reds2})
|
|
308
|
+
if rc2 != 0 and hit == sorted(exp):
|
|
309
|
+
print(" OK %s 红项=%d 指定命中=%d/%d" % (desc, len(reds2), len(hit), len(exp)))
|
|
310
|
+
else:
|
|
311
|
+
bad.append(desc)
|
|
312
|
+
print(" MISMATCH %s 实际=%s 期望=%s rc=%d" % (desc, hit, sorted(exp), rc2))
|
|
313
|
+
for r in reds2[:6]:
|
|
314
|
+
print(" FAIL " + r)
|
|
315
|
+
ok_r, det_r = GK.assert_revert_reddens(
|
|
316
|
+
_mirror_build,
|
|
317
|
+
[("md_cg/protect.py", _PROBE.replace("\r\n", "\n"), " pass # 回退:不探测")],
|
|
318
|
+
_run_in, ("F07", "F08", "K02", "K03", "K04"), "md_cg/protect.py")
|
|
319
|
+
print(" 骨架②回退即红:%s %s" % ("OK" if ok_r else "MISMATCH",
|
|
320
|
+
json.dumps(det_r, ensure_ascii=False)[:200]))
|
|
321
|
+
if not ok_r:
|
|
322
|
+
bad.append("骨架②未按预期转红")
|
|
323
|
+
print("定点变异自证:%s(%d 条不合格)" % ("PASS" if not bad else "FAIL", len(bad)))
|
|
324
|
+
return len(bad)
|
|
325
|
+
finally:
|
|
326
|
+
shutil.rmtree(tree, ignore_errors=True)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
shutil.rmtree(_TMP, ignore_errors=True)
|
|
330
|
+
print("")
|
|
331
|
+
print("issue #413 结果:%s" % ("全部通过" if not FAILS else "%d 失败" % len(FAILS)))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def main():
|
|
335
|
+
_bad = _mutate() if "--mutate" in sys.argv else 0
|
|
336
|
+
return 1 if (FAILS or _bad) else 0
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
if __name__ == "__main__":
|
|
340
340
|
sys.exit(main())
|