@furongjun1999/dsh-memory 0.9.6 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/data/policy.json +38 -38
  2. package/docs/discipline/templates/spec.txt.tmpl +1 -1
  3. package/dsh/cordis.yml.example +139 -139
  4. package/lib/hooks.d.ts +19 -0
  5. package/lib/hooks.js +29 -6
  6. package/lib/index.js +11 -2
  7. package/lib/lib/hook_audit.js +38 -2
  8. package/lib/lib/prompt_safety.js +14 -3
  9. package/lib/tools.d.ts +7 -0
  10. package/lib/tools.js +22 -1
  11. package/md_cg/_guard_kit.py +121 -121
  12. package/md_cg/anchor.py +114 -114
  13. package/md_cg/audit.py +15 -2
  14. package/md_cg/chain.py +3 -2
  15. package/md_cg/config_registry_guard.py +487 -487
  16. package/md_cg/conformance.py +747 -747
  17. package/md_cg/consolidate.py +1793 -1793
  18. package/md_cg/crypto.py +794 -794
  19. package/md_cg/hyperedge.py +262 -262
  20. package/md_cg/interface_schema.py +146 -146
  21. package/md_cg/lifecycle.py +426 -426
  22. package/md_cg/mdcos.py +12 -8
  23. package/md_cg/predict.py +1103 -1103
  24. package/md_cg/protect.py +654 -654
  25. package/md_cg/provenance.py +606 -606
  26. package/md_cg/queue_health.py +130 -130
  27. package/md_cg/refine.py +613 -613
  28. package/md_cg/retrieve.py +128 -128
  29. package/md_cg/revise.py +140 -140
  30. package/md_cg/rollback.py +657 -657
  31. package/md_cg/rollback_cli.py +124 -124
  32. package/md_cg/rotate.py +346 -346
  33. package/md_cg/routing.py +490 -490
  34. package/md_cg/self_surface.py +50 -50
  35. package/md_cg/semantic/canonical.py +144 -144
  36. package/md_cg/semantic/zh_en_atoms.py +141 -141
  37. package/md_cg/sources.py +1091 -1091
  38. package/md_cg/stg.py +3 -2
  39. package/md_cg/test_audit_rotate_parity.py +279 -279
  40. package/md_cg/test_autonomy_modes.py +2013 -2013
  41. package/md_cg/test_cn_recall_grams.py +206 -206
  42. package/md_cg/test_code_kind_forbidden.py +101 -0
  43. package/md_cg/test_condaccept.py +156 -156
  44. package/md_cg/test_condgate.py +141 -141
  45. package/md_cg/test_heartbeat_ledger.py +557 -557
  46. package/md_cg/test_i50e_readside_protection.py +658 -658
  47. package/md_cg/test_issue111_gate_order.py +76 -76
  48. package/md_cg/test_issue111_scoring_contract.py +86 -86
  49. package/md_cg/test_issue121_calibration_bounds.py +293 -293
  50. package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
  51. package/md_cg/test_issue147_pack_id_escape.py +378 -378
  52. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
  53. package/md_cg/test_issue149_accel_default_face.py +248 -248
  54. package/md_cg/test_issue150_empty_query_terms.py +328 -328
  55. package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
  56. package/md_cg/test_issue152_sealed_postings.py +309 -309
  57. package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
  58. package/md_cg/test_issue157b_index_remainder.py +344 -344
  59. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
  60. package/md_cg/test_issue191_import_trust.py +382 -382
  61. package/md_cg/test_issue193_write_scope.py +378 -378
  62. package/md_cg/test_issue212_writeface_gaps.py +349 -349
  63. package/md_cg/test_issue214_reject_sensitivity.py +266 -266
  64. package/md_cg/test_issue215_condition_source_gap.py +272 -272
  65. package/md_cg/test_issue216_clash_routes.py +214 -214
  66. package/md_cg/test_issue217_slot_routes.py +248 -248
  67. package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
  68. package/md_cg/test_issue258_pack_sensitivity.py +468 -468
  69. package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
  70. package/md_cg/test_issue274_read_node_id_none.py +341 -341
  71. package/md_cg/test_issue275_layer_param.py +250 -250
  72. package/md_cg/test_issue277_node_id_traversal.py +384 -384
  73. package/md_cg/test_issue278_neg_separated_tension.py +271 -271
  74. package/md_cg/test_issue278_neg_window.py +294 -294
  75. package/md_cg/test_issue278_negative_layering.py +83 -83
  76. package/md_cg/test_issue284_skip_not_pass.py +291 -291
  77. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
  78. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
  79. package/md_cg/test_issue303_design_boundaries.py +262 -262
  80. package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
  81. package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
  82. package/md_cg/test_issue321_mcp_deep_json.py +304 -304
  83. package/md_cg/test_issue322_node_write_lock.py +727 -727
  84. package/md_cg/test_issue324_write_size_fields.py +214 -214
  85. package/md_cg/test_issue325_audit_poison.py +229 -229
  86. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
  87. package/md_cg/test_issue326_key_perms.py +355 -355
  88. package/md_cg/test_issue326_twin_parser_parity.py +323 -323
  89. package/md_cg/test_issue326_vm_call_frame.py +569 -569
  90. package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
  91. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
  92. package/md_cg/test_issue348_insight_verify_op.py +199 -199
  93. package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
  94. package/md_cg/test_issue350_casefold_collision.py +235 -235
  95. package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
  96. package/md_cg/test_issue352_imgaudit.py +418 -418
  97. package/md_cg/test_issue352_pathsjson.py +537 -537
  98. package/md_cg/test_issue352_refindex.py +412 -412
  99. package/md_cg/test_issue352_rollback.py +604 -604
  100. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
  101. package/md_cg/test_issue354_rust_index_containment.py +571 -571
  102. package/md_cg/test_issue354_rust_wal_containment.py +606 -606
  103. package/md_cg/test_issue358_truncation_observable.py +247 -247
  104. package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
  105. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
  106. package/md_cg/test_issue362_neg_condition.py +468 -468
  107. package/md_cg/test_issue363_lexical_idf.py +275 -275
  108. package/md_cg/test_issue370_readcache_assembly.py +488 -488
  109. package/md_cg/test_issue376_heartbeat_failed.py +293 -293
  110. package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
  111. package/md_cg/test_issue378_protected_floor.py +310 -310
  112. package/md_cg/test_issue383_state_event_write_gate.py +462 -462
  113. package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
  114. package/md_cg/test_issue398_toolface_op_parity.py +511 -511
  115. package/md_cg/test_issue399_hive_json_shape.py +317 -317
  116. package/md_cg/test_issue401_wisdom_codegen.py +295 -295
  117. package/md_cg/test_issue404_heal_receipt.py +389 -389
  118. package/md_cg/test_issue409_compact_index_completeness.py +509 -509
  119. package/md_cg/test_issue410_verify_demote_write.py +366 -366
  120. package/md_cg/test_issue411_scrub_idempotence.py +575 -575
  121. package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
  122. package/md_cg/test_issue413_preimage_failclosed.py +239 -239
  123. package/md_cg/test_issue413_preimage_twin.py +339 -339
  124. package/md_cg/test_issue415_deps_gate_probe.py +357 -357
  125. package/md_cg/test_issue416_entry_key_subset.py +525 -525
  126. package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
  127. package/md_cg/test_issue425_ingest_library_path.py +331 -331
  128. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
  129. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
  130. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
  131. package/md_cg/test_issue427_serve_status_shape.py +191 -191
  132. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
  133. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
  134. package/md_cg/test_issue434_435_float_gate.py +90 -90
  135. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
  136. package/md_cg/test_issue43_default_policy.py +874 -874
  137. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
  138. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
  139. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
  140. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
  141. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
  142. package/md_cg/test_issue451_audit_actor.py +313 -313
  143. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
  144. package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
  145. package/md_cg/test_issue466_basis_registry.py +469 -469
  146. package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
  147. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
  148. package/md_cg/test_issue470_wal_event_durable.py +427 -427
  149. package/md_cg/test_issue471_identity_readable.py +136 -136
  150. package/md_cg/test_issue472_audit_chain.py +90 -90
  151. package/md_cg/test_issue472_prune_ledger.py +105 -105
  152. package/md_cg/test_issue472_rollback_degraded.py +81 -81
  153. package/md_cg/test_issue491_compose_sandbox.py +460 -460
  154. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
  155. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
  156. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
  157. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
  158. package/md_cg/test_issue525_read_null_semantics.py +52 -52
  159. package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
  160. package/md_cg/test_issue547_audit_durable.py +96 -96
  161. package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
  162. package/md_cg/test_issue559_refine_prefix.py +69 -69
  163. package/md_cg/test_issue562_retired_faces.py +150 -0
  164. package/md_cg/test_issue71_queue_backlog.py +376 -376
  165. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
  166. package/md_cg/test_issue82_credential_rules.py +271 -271
  167. package/md_cg/test_issue91_verifier_sandbox.py +314 -314
  168. package/md_cg/test_issue93_remember_redaction.py +282 -282
  169. package/md_cg/test_logref.py +1141 -1141
  170. package/md_cg/test_md_access_parity.py +330 -330
  171. package/md_cg/test_md_cg_no_hive_dep.py +139 -139
  172. package/md_cg/test_mutation_residue.py +119 -119
  173. package/md_cg/test_mutation_rollback.py +835 -835
  174. package/md_cg/test_n123_derive_expiry_chain.py +210 -210
  175. package/md_cg/test_n209_verify_write_face_gates.py +466 -466
  176. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  177. package/md_cg/test_neg_tail_honesty.py +733 -733
  178. package/md_cg/test_p21_tokens.py +294 -294
  179. package/md_cg/test_p27_docindex.py +792 -792
  180. package/md_cg/test_p28_refcheck.py +1053 -1053
  181. package/md_cg/test_p2_six_elements.py +476 -476
  182. package/md_cg/test_p33_ccg_wiring.py +300 -300
  183. package/md_cg/test_p3_legacy_closure.py +438 -438
  184. package/md_cg/test_p40_refine_worklist.py +244 -244
  185. package/md_cg/test_p4_freshness.py +781 -781
  186. package/md_cg/test_p9c_dedup_hints.py +288 -288
  187. package/md_cg/test_policy_required_ccg.py +444 -444
  188. package/md_cg/test_retr_s5.py +312 -312
  189. package/md_cg/test_s1_ast_judge.py +109 -109
  190. package/md_cg/test_state_event_op.py +521 -521
  191. package/md_cg/test_stgidx_index_parity.py +1024 -1024
  192. package/md_cg/test_sustain_bounded.py +652 -652
  193. package/md_cg/test_trust_edge_reachability.py +405 -405
  194. package/md_cg/test_w7_redlines.py +659 -659
  195. package/md_cg/test_write_return_shape.py +919 -919
  196. package/md_cg/test_writepipe.py +228 -228
  197. package/md_cg/trust.py +1114 -1114
  198. package/md_cg/twophase.py +303 -303
  199. package/md_cg/whitebox.py +536 -536
  200. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
  201. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
  202. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
  203. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
  204. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
  205. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
  206. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
  207. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
  208. package/md_cg/writepipe.py +1337 -1337
  209. package/package.json +3 -2
  210. package/scripts/workspace_index.py +328 -0
  211. package/src/hooks.ts +30 -6
  212. package/src/index.ts +14 -5
  213. package/src/lib/hook_audit.ts +282 -256
  214. package/src/lib/mdcg_client.ts +469 -469
  215. package/src/lib/prompt_safety.ts +17 -3
  216. package/src/tools.ts +23 -1
@@ -1,454 +1,454 @@
1
- # -*- coding: utf-8 -*-
2
- # 功能名:元认知读面与台账的密级收口守卫(#445 反思台账 / #426-D self_check 查询原文)
3
- # 生效条件:python -u -X utf8 -m md_cg.test_issue445_metacognition_ledger_gate [--mutate];
4
- # 被测面=md_cg/metacognition.py 的 _can_read_record / _redact_query / _reflections /
5
- # _log / self_check / blindspots / history(真实 MdCGSecure 实例 + 临时 root)
6
- # 子功能:A self_check 不回原文 · B blindspots 不回原文 · C history 不回原文 ·
7
- # D 台账不落原文(只落摘要)· E 不可写身份不得追加台账 · G 无身份模型(纯 MdCGOS)
8
- # 既有读数不变 · I 记录缺 sensitivity ⇒ 非设计者 fail-closed ·
9
- # J **第四读面** autonomy.proposals(经 cg(op=insight, action=explore) 暴露)不回原文
10
- # 执行:默认跑全部腿并做源码锚点自检(锚点缺失 ⇒ exit 2,fail-closed);
11
- # --mutate 时在镜像树里逐条撤闸,守卫必须按指定项转红
12
- # 验证方式:全部 PASS 且 --mutate 每条变异的红项集合与预期逐项相符 ⇒ 退出码 0
13
- # 不适用条件:① 不改写历史文件——升级前已明文落盘的 `_reflection.jsonl` 仍含原文
14
- # (写面在 md_cg/mdcg.py::reflect,不在本单元授权文件内,已按 NEED_FILE 上报);
15
- # ② 不覆盖 `_metacognition.jsonl` 的物理轮转/清理;③ 不判 trace/trust/calibration
16
- # 三个纯数值面的**数值正确性**(它们的数据源已随 `_reflections` 一并按可见性过滤,
17
- # 本腿只判「低权读者不再拿到任何记录 ⇒ 三面退化为空/insufficient_data」这一事)。
18
- """issue #445 / #426-D 守卫:查询原文不得经元认知读面回流,台账不得落原文。
19
-
20
- 病象(修前实测,见 `.tmp/U04/probe_445_426d.py` 与复核探针 `.tmp/review_u04/probe_output_role.py`):
21
- · 访客(无令牌,clearance=internal, can_write=False)
22
- - `mdcg_metacognition self_check` 的 `similar_history[].query` 回出属主原文;
23
- - `history` 逐条回 `{"op":"self_check","query":<原文>}`;
24
- - 每次 self_check 还往 `_metacognition.jsonl` **持久追加**(10 次 ≈ +60KB)。
25
- · role=output(clearance=internal, can_write=False, ops 含 insight)经
26
- `cg(op=insight, action=explore)` 拿到 `proposals[].query` 原文——**第四读面**
27
- (autonomy.proposals 直读 `metacognition._reflections`)。首版只堵了前三面,
28
- 复核打回后把判据收到**台账唯一读取点** `_reflections`,第四面自动继承。
29
- · `_reflection.jsonl` 明文存 `reflect()` 的 query(写面在 mdcg.py,不在本单元授权面)。
30
-
31
- 修法(判据单点,均落在 md_cg/metacognition.py):
32
- · `_can_read_record(cg, rec)` —— 台账记录读可见性单点:无身份模型/设计者不设限;
33
- 记录缺 `sensitivity` 键 ⇒ **fail-closed 不可读**(与 consistency_history 对
34
- 「升级前无 sensitivity 键旧记录」的处置同口径;`reflect()` 恒不写该键 ⇒ 对
35
- 非设计者即全量 fail-closed);有密级 ⇒ 委派 `security.visible_to`
36
- (= `cg._readable`,clearance × 密级 ∧ 会话绑定)。
37
- · `_reflections(cg)` —— **台账唯一读取点**,在这里过滤:trace / trust /
38
- blindspots / self_check / autonomy.proposals **五个消费面**一并继承,
39
- 不在各面各写一份判据(本仓反复栽过的「同一判据两份」形态)。
40
- · `_redact_query(rec)` —— `_metacognition.jsonl` 读面去原文(该台账有自己的
41
- 读取点 `history`,不在 `_reflections` 路径上)。
42
- · `_log` —— 台账只落 `query_digest`(sha1 前 8 位) + `query_len`;`can_write=False`
43
- 的身份**不写盘**(只算不留痕)。
44
- """
45
- from __future__ import annotations
46
-
47
- import os
48
- import shutil
49
- import subprocess
50
- import sys
51
- import tempfile
52
-
53
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
54
- _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
55
- if _REPO not in sys.path:
56
- sys.path.insert(0, _REPO)
57
-
58
- _TMP = tempfile.mkdtemp(prefix="iss445_")
59
- os.environ.update({"MDCG_ROOT": _TMP + "/brain", "MDCG_STATE_ROOT": _TMP + "/state",
60
- "MDCG_AUX_ROOT": _TMP + "/auxstore", "MDCG_DATA_ROOT": _TMP + "/datastore",
61
- "MDCG_EXPORT_ROOT": _TMP, "MDCG_SUSTAIN": "0", "MDCG_SLEEP": "0"})
62
- for _k in ("MDCG_TOKEN", "MDCG_VERIFY_KEY"):
63
- os.environ.pop(_k, None)
64
-
65
- from md_cg import metacognition as mc # noqa: E402
66
- from md_cg import mcp_server as ms # noqa: E402
67
- from md_cg.mdcg import STATE_BLINDSPOT # noqa: E402
68
- from md_cg.mdcos import MdCGOS, MdCGSecure # noqa: E402
69
- from md_cg.security import Principal # noqa: E402
70
- from md_cg.tokens import role_spec # noqa: E402
71
-
72
- PASSED, FAILS = [], []
73
- Q = "PRIVQ999 我确诊重度抑郁 在服用舍曲林 律师李四 离婚诉讼"
74
- NEEDLE = "舍曲林"
75
-
76
-
77
- def _check(name, cond, detail=""):
78
- if cond:
79
- print(" PASS " + name)
80
- PASSED.append(name)
81
- else:
82
- print(" FAIL " + name + " " + str(detail)[:300])
83
- FAILS.append(name)
84
-
85
-
86
- def _mk(root, role, clearance, can_write, can_admin, session=None, ops=None,
87
- layers=None, auth_mode="direct"):
88
- return MdCGSecure(root, principal=Principal(
89
- role=role, clearance=clearance, can_write=can_write,
90
- can_admin=can_admin, session=session, ops_allow=ops,
91
- layers_allow=layers, auth_mode=auth_mode), autoflush=1)
92
-
93
-
94
- def _blind(q, state=STATE_BLINDSPOT):
95
- return [({"id": "x", "frontmatter": {}, "content": "", "path": "x"},
96
- 1.0, {"state": state})]
97
-
98
-
99
- def group_a():
100
- print("\n[A] self_check 读面:低权读者拿不到原文")
101
- own = _mk(_TMP + "/a", "designer", "private", True, True)
102
- g = role_spec("guest")
103
- guest = _mk(_TMP + "/a", "guest", "internal", False, False,
104
- ops=g["ops_allow"], layers=g["layers_allow"],
105
- auth_mode="anonymous")
106
- own.self_check(Q)
107
- own.reflect(Q, _blind(Q))
108
- sc = guest.self_check("PRIVQ999 我确诊重度抑郁")
109
- hist = sc.get("similar_history") or []
110
- _check("A1 访客 self_check 的 similar_history 不含原文",
111
- NEEDLE not in str(sc), str(sc)[:200])
112
- _check("A2 访客的相似历史为空(不可见记录连 similarity/计数都不回)",
113
- hist == [] and sc.get("prior_attempts") == 0,
114
- str({k: sc.get(k) for k in ("prior_attempts", "similar_history")})[:200])
115
- _check("A3 属主 self_check 仍读得到原文(反向腿:不过度关闭)",
116
- NEEDLE in str(own.self_check("PRIVQ999 我确诊重度抑郁")),
117
- str(own.self_check("PRIVQ999 我确诊重度抑郁"))[:200])
118
- own.close()
119
- guest.close()
120
-
121
-
122
- def group_b():
123
- print("\n[B] blindspots 读面:低权读者拿不到原文")
124
- own = _mk(_TMP + "/b", "designer", "private", True, True)
125
- g = role_spec("guest")
126
- guest = _mk(_TMP + "/b", "guest", "internal", False, False,
127
- ops=g["ops_allow"], layers=g["layers_allow"],
128
- auth_mode="anonymous")
129
- own.reflect(Q, _blind(Q))
130
- own.reflect(Q, _blind(Q))
131
- b_own = mc.blindspots(own)
132
- b_g = mc.blindspots(guest)
133
- _check("B1 属主 blindspots 仍聚合出该盲区(反向腿:不过度关闭)",
134
- b_own.get("n_queries") == 1
135
- and NEEDLE in str(b_own.get("items") or []),
136
- str(b_own.get("items"))[:200])
137
- _check("B2 访客 blindspots 不含原文",
138
- NEEDLE not in str(b_g), str(b_g)[:200])
139
- _check("B3 访客 blindspots 连条目也不聚合(不可见记录不进计数)",
140
- b_g.get("n_queries") == 0, str(b_g.get("n_queries")))
141
- own.close()
142
- guest.close()
143
-
144
-
145
- def group_c():
146
- print("\n[C] history 读面:低权读者拿不到原文")
147
- own = _mk(_TMP + "/c", "designer", "private", True, True)
148
- g = role_spec("guest")
149
- guest = _mk(_TMP + "/c", "guest", "internal", False, False,
150
- ops=g["ops_allow"], layers=g["layers_allow"],
151
- auth_mode="anonymous")
152
- own.self_check(Q)
153
- own.reflect(Q, _blind(Q))
154
- h_g = mc.history(guest)
155
- h_o = mc.history(own)
156
- _check("C1 访客 history 不含原文", NEEDLE not in str(h_g), str(h_g)[:200])
157
- _check("C2 访客 history 记录被去原文(query_redacted,无 query/摘要)",
158
- bool(h_g.get("records")) and all(
159
- r.get("query_redacted") and "query" not in r
160
- and "query_digest" not in r for r in h_g["records"]),
161
- str(h_g["records"])[:200])
162
- _check("C3 属主 history 仍读到全部记录(台账治本:原文只在调用方上下文)",
163
- bool(h_o.get("records")) and all(
164
- "query_digest" in r and "query" not in r for r in h_o["records"]),
165
- str(h_o["records"])[:200])
166
- sc_o = own.self_check("PRIVQ999 我确诊重度抑郁")
167
- _check("C4 属主经 self_check 仍读得到原文(反向腿:_reflection 面不过度关闭)",
168
- NEEDLE in str(sc_o), str(sc_o)[:200])
169
- own.close()
170
- guest.close()
171
-
172
-
173
- def group_j():
174
- print("\n[J] 第四读面 autonomy.proposals(cg op=insight action=explore)不回原文")
175
- own = _mk(_TMP + "/j", "designer", "private", True, True)
176
- sp = role_spec("output")
177
- out_cg = _mk(_TMP + "/j", "output", "internal", False, False,
178
- ops=sp["ops_allow"], layers=sp["layers_allow"],
179
- auth_mode="direct")
180
- own.reflect(Q, _blind(Q))
181
- own.reflect(Q, _blind(Q))
182
- r_out = ms._dispatch(out_cg, "cg", {"op": "insight", "action": "explore"})
183
- r_own = ms._dispatch(own, "cg", {"op": "insight", "action": "explore"})
184
- _check("J1 role=output 经 cg(op=insight, action=explore) 拿不到原文",
185
- NEEDLE not in str(r_out), str(r_out)[:300])
186
- _check("J2 output 的 proposals 为空(不可见记录不进聚合)",
187
- (r_out.get("proposals") or []) == [] and r_out.get("n_signals") == 0,
188
- str({"n_signals": r_out.get("n_signals"),
189
- "n_proposals": len(r_out.get("proposals") or [])}))
190
- _check("J3 属主同一入口仍拿到提案与原 query(反向腿:功能未关)",
191
- NEEDLE in str(r_own) and len(r_own.get("proposals") or []) >= 1,
192
- str(r_own)[:300])
193
- _check("J4 低权读者的 trace/trust 一并退化为空(同一读取点的连带面,如实登记)",
194
- mc.trace(out_cg).get("ok") is False
195
- and mc.trust(out_cg).get("p_gap") is None,
196
- str({"trace": mc.trace(out_cg).get("reason"),
197
- "p_gap": mc.trust(out_cg).get("p_gap")}))
198
- own.close()
199
- out_cg.close()
200
-
201
-
202
- def group_d():
203
- print("\n[D] 台账不落原文(_metacognition.jsonl 只落摘要)")
204
- own = _mk(_TMP + "/d", "designer", "private", True, True)
205
- own.self_check(Q)
206
- own.close()
207
- p = os.path.join(_TMP + "/d", "_metacognition.jsonl")
208
- raw = open(p, encoding="utf-8").read()
209
- _check("D1 台账文件不含查询原文", NEEDLE not in raw, raw[:200])
210
- _check("D2 台账含不可逆摘要 query_digest(sha1 前 8 位)",
211
- mc._digest(Q) in raw and '"query_digest"' in raw, raw[:200])
212
- _check("D3 台账含 query_len(长度可审计、原文不可逆)",
213
- '"query_len"' in raw, raw[:200])
214
-
215
-
216
- def group_e():
217
- print("\n[E] 不可写身份不得持久追加台账(#426-D D3 灌盘面)")
218
- g = role_spec("guest")
219
- guest = _mk(_TMP + "/e", "guest", "internal", False, False,
220
- ops=g["ops_allow"], layers=g["layers_allow"],
221
- auth_mode="anonymous")
222
- p = os.path.join(_TMP + "/e", "_metacognition.jsonl")
223
- n0 = os.path.getsize(p) if os.path.exists(p) else 0
224
- for _ in range(5):
225
- guest.self_check("灌" * 2000)
226
- n1 = os.path.getsize(p) if os.path.exists(p) else 0
227
- _check("E1 访客 5 次 self_check 后台账字节数不变", n0 == n1,
228
- "%d -> %d" % (n0, n1))
229
- _check("E2 访客 self_check 仍返回 ok(只算不写,功能保留)",
230
- guest.self_check("探针") .get("ok") is True)
231
- guest.close()
232
-
233
-
234
- def group_g():
235
- print("\n[G] 无身份模型(纯 MdCGOS)既有读数不变")
236
- cg = MdCGOS(_TMP + "/g")
237
- cg.reflect("量子纠缠退相干时间", _blind("x"))
238
- cg.reflect("量子纠缠退相干时间", _blind("x"))
239
- bs = cg.metacognition_blindspots()
240
- _check("G1 MdCGOS blindspots 仍聚合 query(无 principal ⇒ 不设限)",
241
- bs.get("n_queries") == 1
242
- and bs["items"][0].get("query") == "量子纠缠退相干时间",
243
- str(bs.get("items"))[:200])
244
- cg.self_check("量子纠缠退相干时间")
245
- h = cg.metacognition_history()
246
- _check("G2 MdCGOS history 记录仍可取(无 principal ⇒ 原样)",
247
- bool(h.get("records")) and "query_digest" in h["records"][0],
248
- str(h["records"])[:200])
249
- cg.close()
250
-
251
-
252
- def group_i():
253
- print("\n[I] 记录缺 sensitivity 键 ⇒ 非设计者一律去原文(fail-closed)")
254
- root = _TMP + "/i"
255
- os.makedirs(root, exist_ok=True)
256
- import json
257
- with open(os.path.join(root, "_reflection.jsonl"), "w", encoding="utf-8") as f:
258
- f.write(json.dumps({"t": 1.0, "query": Q, "d_curr": 1.0,
259
- "states": {"BLINDSPOT": 3}},
260
- ensure_ascii=False) + "\n")
261
- rec = {"t": 2.0, "query": Q, "d_curr": 1.0, "states": {"BLINDSPOT": 3}}
262
- with open(os.path.join(root, "_metacognition.jsonl"), "w", encoding="utf-8") as f:
263
- f.write(json.dumps(rec, ensure_ascii=False) + "\n")
264
- g = role_spec("guest")
265
- guest = _mk(root, "guest", "internal", False, False,
266
- ops=g["ops_allow"], layers=g["layers_allow"],
267
- auth_mode="anonymous")
268
- own = _mk(root, "designer", "private", True, True)
269
- _check("I1 缺键旧记录对低权读者不可读(_can_read_record=False)",
270
- mc._can_read_record(guest, rec) is False)
271
- _check("I2 缺键旧记录对设计者仍可读(_can_read_record=True)",
272
- mc._can_read_record(own, rec) is True)
273
- _check("I3 低权读者 history 对该记录去原文",
274
- NEEDLE not in str(mc.history(guest)), str(mc.history(guest))[:200])
275
- guest.close()
276
- own.close()
277
-
278
-
279
- def _anchor_check():
280
- """源码锚点自检:修复的关键字面量不在源码 ⇒ exit 2(fail-closed)。"""
281
- mc_src = open(os.path.join(_REPO, "md_cg", "metacognition.py"),
282
- encoding="utf-8").read()
283
- missing = [a for a in ("_can_read_record", "_redact_query", "query_digest",
284
- "query_redacted", "visible_to")
285
- if a not in mc_src]
286
- if missing:
287
- print("ANCHOR-MISS md_cg/metacognition.py: %s" % missing)
288
- return 2
289
- return 0
290
-
291
-
292
- # ================================================= M 组:反向腿②(定点变异)
293
- _MUTATIONS = (
294
- ("M1 撤 `_reflections` 的可见性过滤(台账唯一读取点回到原形态)",
295
- "md_cg/metacognition.py",
296
- ((" return [r for r in read_jsonl(path) if _can_read_record(cg, r)]",
297
- " return list(read_jsonl(path)) # M1 撤台账唯一读取点的可见性过滤"),),
298
- # 台账唯一读取点被撤 ⇒ 五个消费面同时漏:A1/A2(self_check)、B2/B3(blindspots)、
299
- # J1/J2(autonomy.proposals 第四读面)、J4(trace/trust 连带面)。
300
- # 这正是复核打回的那条:首版只在各面各写判据,autonomy 面漏掉。
301
- ("A1", "A2", "B2", "B3", "J1", "J2", "J4")),
302
- ("M2 撤「缺 sensitivity 键 ⇒ fail-closed」(改为缺键即放行,复刻 #447 的 fail-open 形态)",
303
- "md_cg/metacognition.py",
304
- ((" if not sens:" + chr(10)
305
- + " return False # 密级不可判 ⇒ fail-closed(宁可少读)",
306
- " if not sens:" + chr(10)
307
- + " return True # M2 缺键即放行(fail-open)"),),
308
- # 反思台账恒无 sensitivity 键(reflect() 不写该键)⇒ 撤 fail-closed 后
309
- # 非设计者又能读到全部反思记录:A1/A2、B2/B3、J1/J2、J4 一并转红;
310
- # C2/I1/I3 同红是**同一判据单点**的必然后果(`history` 读的
311
- # `_metacognition.jsonl` 同样按记录自带 sensitivity 判,缺键即放行)——
312
- # 与 M3(只撤 history 的过滤调用)在 C2/I3 上重叠,这是「判据在单点」
313
- # 的真实形状,不是红项串台:M2 撤的是**判据条件**,M3 撤的是**调用点**。
314
- ("A1", "A2", "B2", "B3", "C2", "I1", "I3", "J1", "J2", "J4")),
315
- ("M3 撤 history 读面过滤",
316
- "md_cg/metacognition.py",
317
- ((" recs = [r if _can_read_record(cg, r) else _redact_query(r) for r in recs]",
318
- " pass # M3 撤 history 读面过滤"),),
319
- # C2/I3 同红:C2 = 去原文标记消失;I3 = 缺 sensitivity 键的旧记录原样回原文。
320
- # C1 仍绿是**台账治本**的读数(`_metacognition.jsonl` 只落摘要,撤读面过滤也
321
- # 拿不到原文)——两腿分工:C1 判「盘面有没有原文」,C2/I3 判「读面有没有闸」。
322
- ("C2", "I3")),
323
- ("M4 台账回退为落原文",
324
- "md_cg/metacognition.py",
325
- ((" if \"query\" in rec:" + chr(10)
326
- + " _q = rec.pop(\"query\")" + chr(10)
327
- + " rec[\"query_digest\"] = _digest(_q)" + chr(10)
328
- + " rec[\"query_len\"] = len(str(_q or \"\"))" + chr(10)
329
- + " rec[\"query_redacted\"] = True",
330
- " pass # M4 台账回退为落原文"),),
331
- # D1/D2/D3 = 台账盘面三判据;C3/G2 = 反向腿(属主与 MdCGOS 都要求摘要在场)。
332
- ("C3", "D1", "D2", "D3", "G2")),
333
- ("M5 撤不可写身份的台账写闸",
334
- "md_cg/metacognition.py",
335
- ((" if _p is not None and not getattr(_p, \"can_write\", True):" + chr(10)
336
- + " return rec",
337
- " pass # M5 撤不可写身份的台账写闸"),),
338
- ("E1",)),
339
- )
340
-
341
- def _mirror_build():
342
- dst = tempfile.mkdtemp(prefix="iss445_mut_")
343
- for name in ("md_cg", "lib"):
344
- src = os.path.join(_REPO, name)
345
- if os.path.isdir(src):
346
- shutil.copytree(src, os.path.join(dst, name),
347
- ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
348
- for name in sorted(os.listdir(_REPO)):
349
- p = os.path.join(_REPO, name)
350
- if os.path.isfile(p) and name.endswith(".py"):
351
- shutil.copy2(p, os.path.join(dst, name))
352
- return dst
353
-
354
-
355
- def _run_in(tree):
356
- env = dict(os.environ)
357
- env["PYTHONPATH"] = tree
358
- env["PYTHONUTF8"] = "1"
359
- env["PYTHONDONTWRITEBYTECODE"] = "1"
360
- for k in ("MDCG_ROOT", "MDCG_STATE_ROOT", "MDCG_AUX_ROOT", "MDCG_DATA_ROOT",
361
- "MDCG_EXPORT_ROOT", "MDCG_INGEST_ROOT", "MDCG_TOKEN",
362
- "MDCG_TOKEN_FILE", "MDCG_VERIFY_KEY"):
363
- env.pop(k, None)
364
- pr = subprocess.run([sys.executable, "-u", "-X", "utf8", "-m",
365
- "md_cg.test_issue445_metacognition_ledger_gate"],
366
- capture_output=True, text=True, encoding="utf-8",
367
- errors="replace", cwd=tree, env=env, timeout=1800)
368
- out = (pr.stdout or "") + (pr.stderr or "")
369
- reds = [ln.split("FAIL ", 1)[1].strip()
370
- for ln in out.splitlines() if ln.strip().startswith("FAIL ")]
371
- return pr.returncode, reds, out
372
-
373
-
374
- def _apply_text(text, rel, pairs):
375
- eol = (chr(13) + chr(10)) if (chr(13) + chr(10)) in text else chr(10)
376
- for old, new in pairs:
377
- o = old.replace(chr(10), eol)
378
- n = new.replace(chr(10), eol)
379
- if text.count(o) != 1:
380
- return None, "锚点在 %s 里命中 %d 次" % (rel, text.count(o))
381
- text = text.replace(o, n, 1)
382
- return text, ""
383
-
384
-
385
- def _mutate():
386
- print("!! 反向腿②:逐条撤闸,守卫必须按指定项转红")
387
- tree = _mirror_build()
388
- bad = []
389
- try:
390
- rc, reds, out = _run_in(tree)
391
- print(" 未变异镜像基线:rc=%d 红项=%d(必须 rc=0 且 0 红)"
392
- % (rc, len(reds)))
393
- if rc != 0 or reds:
394
- bad.append("未变异镜像基线即红")
395
- print(chr(10).join(out.splitlines()[-20:]))
396
- for desc, rel, pairs, exp in _MUTATIONS:
397
- p = os.path.join(tree, rel)
398
- with open(p, encoding="utf-8", newline="") as f:
399
- bak = f.read()
400
- mut, why = _apply_text(bak, rel, pairs)
401
- if mut is None:
402
- bad.append("%s —— %s" % (desc, why))
403
- print(" ANCHOR-MISS " + desc + " " + why)
404
- continue
405
- with open(p, "w", encoding="utf-8", newline="") as f:
406
- f.write(mut)
407
- for root, _dd, _ff in os.walk(tree):
408
- if os.path.basename(root) == "__pycache__":
409
- shutil.rmtree(root, ignore_errors=True)
410
- rc2, reds2, out2 = _run_in(tree)
411
- with open(p, "w", encoding="utf-8", newline="") as f:
412
- f.write(bak)
413
- hit = sorted({r.split(" ")[0] for r in reds2})
414
- if rc2 != 0 and hit == sorted(exp):
415
- print(" OK %s 红项=%d 指定命中=%s" % (desc, len(reds2), hit))
416
- else:
417
- bad.append(desc)
418
- print(" MISMATCH %s 实际红项=%s 期望=%s rc=%d"
419
- % (desc, hit, sorted(exp), rc2))
420
- for r in reds2[:10]:
421
- print(" FAIL " + r)
422
- print("反向腿②:%s(%d 条不合格)"
423
- % ("PASS" if not bad else "FAIL", len(bad)))
424
- return len(bad)
425
- finally:
426
- shutil.rmtree(tree, ignore_errors=True)
427
-
428
-
429
- def main():
430
- print("== #445/#426-D 元认知读面与台账密级收口守卫 ==")
431
- try:
432
- _rc = _anchor_check()
433
- if _rc:
434
- return _rc
435
- group_a()
436
- group_b()
437
- group_c()
438
- group_j()
439
- group_d()
440
- group_e()
441
- group_g()
442
- group_i()
443
- finally:
444
- shutil.rmtree(_TMP, ignore_errors=True)
445
- print("=" * 68)
446
- print("#445/#426-D 守卫:%d 通过,%d 失败" % (len(PASSED), len(FAILS)))
447
- for f in FAILS:
448
- print(" 红项:" + f)
449
- _bad = _mutate() if "--mutate" in sys.argv else 0
450
- return 1 if (FAILS or _bad) else 0
451
-
452
-
453
- if __name__ == "__main__":
454
- sys.exit(main())
1
+ # -*- coding: utf-8 -*-
2
+ # 功能名:元认知读面与台账的密级收口守卫(#445 反思台账 / #426-D self_check 查询原文)
3
+ # 生效条件:python -u -X utf8 -m md_cg.test_issue445_metacognition_ledger_gate [--mutate];
4
+ # 被测面=md_cg/metacognition.py 的 _can_read_record / _redact_query / _reflections /
5
+ # _log / self_check / blindspots / history(真实 MdCGSecure 实例 + 临时 root)
6
+ # 子功能:A self_check 不回原文 · B blindspots 不回原文 · C history 不回原文 ·
7
+ # D 台账不落原文(只落摘要)· E 不可写身份不得追加台账 · G 无身份模型(纯 MdCGOS)
8
+ # 既有读数不变 · I 记录缺 sensitivity ⇒ 非设计者 fail-closed ·
9
+ # J **第四读面** autonomy.proposals(经 cg(op=insight, action=explore) 暴露)不回原文
10
+ # 执行:默认跑全部腿并做源码锚点自检(锚点缺失 ⇒ exit 2,fail-closed);
11
+ # --mutate 时在镜像树里逐条撤闸,守卫必须按指定项转红
12
+ # 验证方式:全部 PASS 且 --mutate 每条变异的红项集合与预期逐项相符 ⇒ 退出码 0
13
+ # 不适用条件:① 不改写历史文件——升级前已明文落盘的 `_reflection.jsonl` 仍含原文
14
+ # (写面在 md_cg/mdcg.py::reflect,不在本单元授权文件内,已按 NEED_FILE 上报);
15
+ # ② 不覆盖 `_metacognition.jsonl` 的物理轮转/清理;③ 不判 trace/trust/calibration
16
+ # 三个纯数值面的**数值正确性**(它们的数据源已随 `_reflections` 一并按可见性过滤,
17
+ # 本腿只判「低权读者不再拿到任何记录 ⇒ 三面退化为空/insufficient_data」这一事)。
18
+ """issue #445 / #426-D 守卫:查询原文不得经元认知读面回流,台账不得落原文。
19
+
20
+ 病象(修前实测,见 `.tmp/U04/probe_445_426d.py` 与复核探针 `.tmp/review_u04/probe_output_role.py`):
21
+ · 访客(无令牌,clearance=internal, can_write=False)
22
+ - `mdcg_metacognition self_check` 的 `similar_history[].query` 回出属主原文;
23
+ - `history` 逐条回 `{"op":"self_check","query":<原文>}`;
24
+ - 每次 self_check 还往 `_metacognition.jsonl` **持久追加**(10 次 ≈ +60KB)。
25
+ · role=output(clearance=internal, can_write=False, ops 含 insight)经
26
+ `cg(op=insight, action=explore)` 拿到 `proposals[].query` 原文——**第四读面**
27
+ (autonomy.proposals 直读 `metacognition._reflections`)。首版只堵了前三面,
28
+ 复核打回后把判据收到**台账唯一读取点** `_reflections`,第四面自动继承。
29
+ · `_reflection.jsonl` 明文存 `reflect()` 的 query(写面在 mdcg.py,不在本单元授权面)。
30
+
31
+ 修法(判据单点,均落在 md_cg/metacognition.py):
32
+ · `_can_read_record(cg, rec)` —— 台账记录读可见性单点:无身份模型/设计者不设限;
33
+ 记录缺 `sensitivity` 键 ⇒ **fail-closed 不可读**(与 consistency_history 对
34
+ 「升级前无 sensitivity 键旧记录」的处置同口径;`reflect()` 恒不写该键 ⇒ 对
35
+ 非设计者即全量 fail-closed);有密级 ⇒ 委派 `security.visible_to`
36
+ (= `cg._readable`,clearance × 密级 ∧ 会话绑定)。
37
+ · `_reflections(cg)` —— **台账唯一读取点**,在这里过滤:trace / trust /
38
+ blindspots / self_check / autonomy.proposals **五个消费面**一并继承,
39
+ 不在各面各写一份判据(本仓反复栽过的「同一判据两份」形态)。
40
+ · `_redact_query(rec)` —— `_metacognition.jsonl` 读面去原文(该台账有自己的
41
+ 读取点 `history`,不在 `_reflections` 路径上)。
42
+ · `_log` —— 台账只落 `query_digest`(sha1 前 8 位) + `query_len`;`can_write=False`
43
+ 的身份**不写盘**(只算不留痕)。
44
+ """
45
+ from __future__ import annotations
46
+
47
+ import os
48
+ import shutil
49
+ import subprocess
50
+ import sys
51
+ import tempfile
52
+
53
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
54
+ _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
55
+ if _REPO not in sys.path:
56
+ sys.path.insert(0, _REPO)
57
+
58
+ _TMP = tempfile.mkdtemp(prefix="iss445_")
59
+ os.environ.update({"MDCG_ROOT": _TMP + "/brain", "MDCG_STATE_ROOT": _TMP + "/state",
60
+ "MDCG_AUX_ROOT": _TMP + "/auxstore", "MDCG_DATA_ROOT": _TMP + "/datastore",
61
+ "MDCG_EXPORT_ROOT": _TMP, "MDCG_SUSTAIN": "0", "MDCG_SLEEP": "0"})
62
+ for _k in ("MDCG_TOKEN", "MDCG_VERIFY_KEY"):
63
+ os.environ.pop(_k, None)
64
+
65
+ from md_cg import metacognition as mc # noqa: E402
66
+ from md_cg import mcp_server as ms # noqa: E402
67
+ from md_cg.mdcg import STATE_BLINDSPOT # noqa: E402
68
+ from md_cg.mdcos import MdCGOS, MdCGSecure # noqa: E402
69
+ from md_cg.security import Principal # noqa: E402
70
+ from md_cg.tokens import role_spec # noqa: E402
71
+
72
+ PASSED, FAILS = [], []
73
+ Q = "PRIVQ999 我确诊重度抑郁 在服用舍曲林 律师李四 离婚诉讼"
74
+ NEEDLE = "舍曲林"
75
+
76
+
77
+ def _check(name, cond, detail=""):
78
+ if cond:
79
+ print(" PASS " + name)
80
+ PASSED.append(name)
81
+ else:
82
+ print(" FAIL " + name + " " + str(detail)[:300])
83
+ FAILS.append(name)
84
+
85
+
86
+ def _mk(root, role, clearance, can_write, can_admin, session=None, ops=None,
87
+ layers=None, auth_mode="direct"):
88
+ return MdCGSecure(root, principal=Principal(
89
+ role=role, clearance=clearance, can_write=can_write,
90
+ can_admin=can_admin, session=session, ops_allow=ops,
91
+ layers_allow=layers, auth_mode=auth_mode), autoflush=1)
92
+
93
+
94
+ def _blind(q, state=STATE_BLINDSPOT):
95
+ return [({"id": "x", "frontmatter": {}, "content": "", "path": "x"},
96
+ 1.0, {"state": state})]
97
+
98
+
99
+ def group_a():
100
+ print("\n[A] self_check 读面:低权读者拿不到原文")
101
+ own = _mk(_TMP + "/a", "designer", "private", True, True)
102
+ g = role_spec("guest")
103
+ guest = _mk(_TMP + "/a", "guest", "internal", False, False,
104
+ ops=g["ops_allow"], layers=g["layers_allow"],
105
+ auth_mode="anonymous")
106
+ own.self_check(Q)
107
+ own.reflect(Q, _blind(Q))
108
+ sc = guest.self_check("PRIVQ999 我确诊重度抑郁")
109
+ hist = sc.get("similar_history") or []
110
+ _check("A1 访客 self_check 的 similar_history 不含原文",
111
+ NEEDLE not in str(sc), str(sc)[:200])
112
+ _check("A2 访客的相似历史为空(不可见记录连 similarity/计数都不回)",
113
+ hist == [] and sc.get("prior_attempts") == 0,
114
+ str({k: sc.get(k) for k in ("prior_attempts", "similar_history")})[:200])
115
+ _check("A3 属主 self_check 仍读得到原文(反向腿:不过度关闭)",
116
+ NEEDLE in str(own.self_check("PRIVQ999 我确诊重度抑郁")),
117
+ str(own.self_check("PRIVQ999 我确诊重度抑郁"))[:200])
118
+ own.close()
119
+ guest.close()
120
+
121
+
122
+ def group_b():
123
+ print("\n[B] blindspots 读面:低权读者拿不到原文")
124
+ own = _mk(_TMP + "/b", "designer", "private", True, True)
125
+ g = role_spec("guest")
126
+ guest = _mk(_TMP + "/b", "guest", "internal", False, False,
127
+ ops=g["ops_allow"], layers=g["layers_allow"],
128
+ auth_mode="anonymous")
129
+ own.reflect(Q, _blind(Q))
130
+ own.reflect(Q, _blind(Q))
131
+ b_own = mc.blindspots(own)
132
+ b_g = mc.blindspots(guest)
133
+ _check("B1 属主 blindspots 仍聚合出该盲区(反向腿:不过度关闭)",
134
+ b_own.get("n_queries") == 1
135
+ and NEEDLE in str(b_own.get("items") or []),
136
+ str(b_own.get("items"))[:200])
137
+ _check("B2 访客 blindspots 不含原文",
138
+ NEEDLE not in str(b_g), str(b_g)[:200])
139
+ _check("B3 访客 blindspots 连条目也不聚合(不可见记录不进计数)",
140
+ b_g.get("n_queries") == 0, str(b_g.get("n_queries")))
141
+ own.close()
142
+ guest.close()
143
+
144
+
145
+ def group_c():
146
+ print("\n[C] history 读面:低权读者拿不到原文")
147
+ own = _mk(_TMP + "/c", "designer", "private", True, True)
148
+ g = role_spec("guest")
149
+ guest = _mk(_TMP + "/c", "guest", "internal", False, False,
150
+ ops=g["ops_allow"], layers=g["layers_allow"],
151
+ auth_mode="anonymous")
152
+ own.self_check(Q)
153
+ own.reflect(Q, _blind(Q))
154
+ h_g = mc.history(guest)
155
+ h_o = mc.history(own)
156
+ _check("C1 访客 history 不含原文", NEEDLE not in str(h_g), str(h_g)[:200])
157
+ _check("C2 访客 history 记录被去原文(query_redacted,无 query/摘要)",
158
+ bool(h_g.get("records")) and all(
159
+ r.get("query_redacted") and "query" not in r
160
+ and "query_digest" not in r for r in h_g["records"]),
161
+ str(h_g["records"])[:200])
162
+ _check("C3 属主 history 仍读到全部记录(台账治本:原文只在调用方上下文)",
163
+ bool(h_o.get("records")) and all(
164
+ "query_digest" in r and "query" not in r for r in h_o["records"]),
165
+ str(h_o["records"])[:200])
166
+ sc_o = own.self_check("PRIVQ999 我确诊重度抑郁")
167
+ _check("C4 属主经 self_check 仍读得到原文(反向腿:_reflection 面不过度关闭)",
168
+ NEEDLE in str(sc_o), str(sc_o)[:200])
169
+ own.close()
170
+ guest.close()
171
+
172
+
173
+ def group_j():
174
+ print("\n[J] 第四读面 autonomy.proposals(cg op=insight action=explore)不回原文")
175
+ own = _mk(_TMP + "/j", "designer", "private", True, True)
176
+ sp = role_spec("output")
177
+ out_cg = _mk(_TMP + "/j", "output", "internal", False, False,
178
+ ops=sp["ops_allow"], layers=sp["layers_allow"],
179
+ auth_mode="direct")
180
+ own.reflect(Q, _blind(Q))
181
+ own.reflect(Q, _blind(Q))
182
+ r_out = ms._dispatch(out_cg, "cg", {"op": "insight", "action": "explore"})
183
+ r_own = ms._dispatch(own, "cg", {"op": "insight", "action": "explore"})
184
+ _check("J1 role=output 经 cg(op=insight, action=explore) 拿不到原文",
185
+ NEEDLE not in str(r_out), str(r_out)[:300])
186
+ _check("J2 output 的 proposals 为空(不可见记录不进聚合)",
187
+ (r_out.get("proposals") or []) == [] and r_out.get("n_signals") == 0,
188
+ str({"n_signals": r_out.get("n_signals"),
189
+ "n_proposals": len(r_out.get("proposals") or [])}))
190
+ _check("J3 属主同一入口仍拿到提案与原 query(反向腿:功能未关)",
191
+ NEEDLE in str(r_own) and len(r_own.get("proposals") or []) >= 1,
192
+ str(r_own)[:300])
193
+ _check("J4 低权读者的 trace/trust 一并退化为空(同一读取点的连带面,如实登记)",
194
+ mc.trace(out_cg).get("ok") is False
195
+ and mc.trust(out_cg).get("p_gap") is None,
196
+ str({"trace": mc.trace(out_cg).get("reason"),
197
+ "p_gap": mc.trust(out_cg).get("p_gap")}))
198
+ own.close()
199
+ out_cg.close()
200
+
201
+
202
+ def group_d():
203
+ print("\n[D] 台账不落原文(_metacognition.jsonl 只落摘要)")
204
+ own = _mk(_TMP + "/d", "designer", "private", True, True)
205
+ own.self_check(Q)
206
+ own.close()
207
+ p = os.path.join(_TMP + "/d", "_metacognition.jsonl")
208
+ raw = open(p, encoding="utf-8").read()
209
+ _check("D1 台账文件不含查询原文", NEEDLE not in raw, raw[:200])
210
+ _check("D2 台账含不可逆摘要 query_digest(sha1 前 8 位)",
211
+ mc._digest(Q) in raw and '"query_digest"' in raw, raw[:200])
212
+ _check("D3 台账含 query_len(长度可审计、原文不可逆)",
213
+ '"query_len"' in raw, raw[:200])
214
+
215
+
216
+ def group_e():
217
+ print("\n[E] 不可写身份不得持久追加台账(#426-D D3 灌盘面)")
218
+ g = role_spec("guest")
219
+ guest = _mk(_TMP + "/e", "guest", "internal", False, False,
220
+ ops=g["ops_allow"], layers=g["layers_allow"],
221
+ auth_mode="anonymous")
222
+ p = os.path.join(_TMP + "/e", "_metacognition.jsonl")
223
+ n0 = os.path.getsize(p) if os.path.exists(p) else 0
224
+ for _ in range(5):
225
+ guest.self_check("灌" * 2000)
226
+ n1 = os.path.getsize(p) if os.path.exists(p) else 0
227
+ _check("E1 访客 5 次 self_check 后台账字节数不变", n0 == n1,
228
+ "%d -> %d" % (n0, n1))
229
+ _check("E2 访客 self_check 仍返回 ok(只算不写,功能保留)",
230
+ guest.self_check("探针") .get("ok") is True)
231
+ guest.close()
232
+
233
+
234
+ def group_g():
235
+ print("\n[G] 无身份模型(纯 MdCGOS)既有读数不变")
236
+ cg = MdCGOS(_TMP + "/g")
237
+ cg.reflect("量子纠缠退相干时间", _blind("x"))
238
+ cg.reflect("量子纠缠退相干时间", _blind("x"))
239
+ bs = cg.metacognition_blindspots()
240
+ _check("G1 MdCGOS blindspots 仍聚合 query(无 principal ⇒ 不设限)",
241
+ bs.get("n_queries") == 1
242
+ and bs["items"][0].get("query") == "量子纠缠退相干时间",
243
+ str(bs.get("items"))[:200])
244
+ cg.self_check("量子纠缠退相干时间")
245
+ h = cg.metacognition_history()
246
+ _check("G2 MdCGOS history 记录仍可取(无 principal ⇒ 原样)",
247
+ bool(h.get("records")) and "query_digest" in h["records"][0],
248
+ str(h["records"])[:200])
249
+ cg.close()
250
+
251
+
252
+ def group_i():
253
+ print("\n[I] 记录缺 sensitivity 键 ⇒ 非设计者一律去原文(fail-closed)")
254
+ root = _TMP + "/i"
255
+ os.makedirs(root, exist_ok=True)
256
+ import json
257
+ with open(os.path.join(root, "_reflection.jsonl"), "w", encoding="utf-8") as f:
258
+ f.write(json.dumps({"t": 1.0, "query": Q, "d_curr": 1.0,
259
+ "states": {"BLINDSPOT": 3}},
260
+ ensure_ascii=False) + "\n")
261
+ rec = {"t": 2.0, "query": Q, "d_curr": 1.0, "states": {"BLINDSPOT": 3}}
262
+ with open(os.path.join(root, "_metacognition.jsonl"), "w", encoding="utf-8") as f:
263
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
264
+ g = role_spec("guest")
265
+ guest = _mk(root, "guest", "internal", False, False,
266
+ ops=g["ops_allow"], layers=g["layers_allow"],
267
+ auth_mode="anonymous")
268
+ own = _mk(root, "designer", "private", True, True)
269
+ _check("I1 缺键旧记录对低权读者不可读(_can_read_record=False)",
270
+ mc._can_read_record(guest, rec) is False)
271
+ _check("I2 缺键旧记录对设计者仍可读(_can_read_record=True)",
272
+ mc._can_read_record(own, rec) is True)
273
+ _check("I3 低权读者 history 对该记录去原文",
274
+ NEEDLE not in str(mc.history(guest)), str(mc.history(guest))[:200])
275
+ guest.close()
276
+ own.close()
277
+
278
+
279
+ def _anchor_check():
280
+ """源码锚点自检:修复的关键字面量不在源码 ⇒ exit 2(fail-closed)。"""
281
+ mc_src = open(os.path.join(_REPO, "md_cg", "metacognition.py"),
282
+ encoding="utf-8").read()
283
+ missing = [a for a in ("_can_read_record", "_redact_query", "query_digest",
284
+ "query_redacted", "visible_to")
285
+ if a not in mc_src]
286
+ if missing:
287
+ print("ANCHOR-MISS md_cg/metacognition.py: %s" % missing)
288
+ return 2
289
+ return 0
290
+
291
+
292
+ # ================================================= M 组:反向腿②(定点变异)
293
+ _MUTATIONS = (
294
+ ("M1 撤 `_reflections` 的可见性过滤(台账唯一读取点回到原形态)",
295
+ "md_cg/metacognition.py",
296
+ ((" return [r for r in read_jsonl(path) if _can_read_record(cg, r)]",
297
+ " return list(read_jsonl(path)) # M1 撤台账唯一读取点的可见性过滤"),),
298
+ # 台账唯一读取点被撤 ⇒ 五个消费面同时漏:A1/A2(self_check)、B2/B3(blindspots)、
299
+ # J1/J2(autonomy.proposals 第四读面)、J4(trace/trust 连带面)。
300
+ # 这正是复核打回的那条:首版只在各面各写判据,autonomy 面漏掉。
301
+ ("A1", "A2", "B2", "B3", "J1", "J2", "J4")),
302
+ ("M2 撤「缺 sensitivity 键 ⇒ fail-closed」(改为缺键即放行,复刻 #447 的 fail-open 形态)",
303
+ "md_cg/metacognition.py",
304
+ ((" if not sens:" + chr(10)
305
+ + " return False # 密级不可判 ⇒ fail-closed(宁可少读)",
306
+ " if not sens:" + chr(10)
307
+ + " return True # M2 缺键即放行(fail-open)"),),
308
+ # 反思台账恒无 sensitivity 键(reflect() 不写该键)⇒ 撤 fail-closed 后
309
+ # 非设计者又能读到全部反思记录:A1/A2、B2/B3、J1/J2、J4 一并转红;
310
+ # C2/I1/I3 同红是**同一判据单点**的必然后果(`history` 读的
311
+ # `_metacognition.jsonl` 同样按记录自带 sensitivity 判,缺键即放行)——
312
+ # 与 M3(只撤 history 的过滤调用)在 C2/I3 上重叠,这是「判据在单点」
313
+ # 的真实形状,不是红项串台:M2 撤的是**判据条件**,M3 撤的是**调用点**。
314
+ ("A1", "A2", "B2", "B3", "C2", "I1", "I3", "J1", "J2", "J4")),
315
+ ("M3 撤 history 读面过滤",
316
+ "md_cg/metacognition.py",
317
+ ((" recs = [r if _can_read_record(cg, r) else _redact_query(r) for r in recs]",
318
+ " pass # M3 撤 history 读面过滤"),),
319
+ # C2/I3 同红:C2 = 去原文标记消失;I3 = 缺 sensitivity 键的旧记录原样回原文。
320
+ # C1 仍绿是**台账治本**的读数(`_metacognition.jsonl` 只落摘要,撤读面过滤也
321
+ # 拿不到原文)——两腿分工:C1 判「盘面有没有原文」,C2/I3 判「读面有没有闸」。
322
+ ("C2", "I3")),
323
+ ("M4 台账回退为落原文",
324
+ "md_cg/metacognition.py",
325
+ ((" if \"query\" in rec:" + chr(10)
326
+ + " _q = rec.pop(\"query\")" + chr(10)
327
+ + " rec[\"query_digest\"] = _digest(_q)" + chr(10)
328
+ + " rec[\"query_len\"] = len(str(_q or \"\"))" + chr(10)
329
+ + " rec[\"query_redacted\"] = True",
330
+ " pass # M4 台账回退为落原文"),),
331
+ # D1/D2/D3 = 台账盘面三判据;C3/G2 = 反向腿(属主与 MdCGOS 都要求摘要在场)。
332
+ ("C3", "D1", "D2", "D3", "G2")),
333
+ ("M5 撤不可写身份的台账写闸",
334
+ "md_cg/metacognition.py",
335
+ ((" if _p is not None and not getattr(_p, \"can_write\", True):" + chr(10)
336
+ + " return rec",
337
+ " pass # M5 撤不可写身份的台账写闸"),),
338
+ ("E1",)),
339
+ )
340
+
341
+ def _mirror_build():
342
+ dst = tempfile.mkdtemp(prefix="iss445_mut_")
343
+ for name in ("md_cg", "lib"):
344
+ src = os.path.join(_REPO, name)
345
+ if os.path.isdir(src):
346
+ shutil.copytree(src, os.path.join(dst, name),
347
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
348
+ for name in sorted(os.listdir(_REPO)):
349
+ p = os.path.join(_REPO, name)
350
+ if os.path.isfile(p) and name.endswith(".py"):
351
+ shutil.copy2(p, os.path.join(dst, name))
352
+ return dst
353
+
354
+
355
+ def _run_in(tree):
356
+ env = dict(os.environ)
357
+ env["PYTHONPATH"] = tree
358
+ env["PYTHONUTF8"] = "1"
359
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
360
+ for k in ("MDCG_ROOT", "MDCG_STATE_ROOT", "MDCG_AUX_ROOT", "MDCG_DATA_ROOT",
361
+ "MDCG_EXPORT_ROOT", "MDCG_INGEST_ROOT", "MDCG_TOKEN",
362
+ "MDCG_TOKEN_FILE", "MDCG_VERIFY_KEY"):
363
+ env.pop(k, None)
364
+ pr = subprocess.run([sys.executable, "-u", "-X", "utf8", "-m",
365
+ "md_cg.test_issue445_metacognition_ledger_gate"],
366
+ capture_output=True, text=True, encoding="utf-8",
367
+ errors="replace", cwd=tree, env=env, timeout=1800)
368
+ out = (pr.stdout or "") + (pr.stderr or "")
369
+ reds = [ln.split("FAIL ", 1)[1].strip()
370
+ for ln in out.splitlines() if ln.strip().startswith("FAIL ")]
371
+ return pr.returncode, reds, out
372
+
373
+
374
+ def _apply_text(text, rel, pairs):
375
+ eol = (chr(13) + chr(10)) if (chr(13) + chr(10)) in text else chr(10)
376
+ for old, new in pairs:
377
+ o = old.replace(chr(10), eol)
378
+ n = new.replace(chr(10), eol)
379
+ if text.count(o) != 1:
380
+ return None, "锚点在 %s 里命中 %d 次" % (rel, text.count(o))
381
+ text = text.replace(o, n, 1)
382
+ return text, ""
383
+
384
+
385
+ def _mutate():
386
+ print("!! 反向腿②:逐条撤闸,守卫必须按指定项转红")
387
+ tree = _mirror_build()
388
+ bad = []
389
+ try:
390
+ rc, reds, out = _run_in(tree)
391
+ print(" 未变异镜像基线:rc=%d 红项=%d(必须 rc=0 且 0 红)"
392
+ % (rc, len(reds)))
393
+ if rc != 0 or reds:
394
+ bad.append("未变异镜像基线即红")
395
+ print(chr(10).join(out.splitlines()[-20:]))
396
+ for desc, rel, pairs, exp in _MUTATIONS:
397
+ p = os.path.join(tree, rel)
398
+ with open(p, encoding="utf-8", newline="") as f:
399
+ bak = f.read()
400
+ mut, why = _apply_text(bak, rel, pairs)
401
+ if mut is None:
402
+ bad.append("%s —— %s" % (desc, why))
403
+ print(" ANCHOR-MISS " + desc + " " + why)
404
+ continue
405
+ with open(p, "w", encoding="utf-8", newline="") as f:
406
+ f.write(mut)
407
+ for root, _dd, _ff in os.walk(tree):
408
+ if os.path.basename(root) == "__pycache__":
409
+ shutil.rmtree(root, ignore_errors=True)
410
+ rc2, reds2, out2 = _run_in(tree)
411
+ with open(p, "w", encoding="utf-8", newline="") as f:
412
+ f.write(bak)
413
+ hit = sorted({r.split(" ")[0] for r in reds2})
414
+ if rc2 != 0 and hit == sorted(exp):
415
+ print(" OK %s 红项=%d 指定命中=%s" % (desc, len(reds2), hit))
416
+ else:
417
+ bad.append(desc)
418
+ print(" MISMATCH %s 实际红项=%s 期望=%s rc=%d"
419
+ % (desc, hit, sorted(exp), rc2))
420
+ for r in reds2[:10]:
421
+ print(" FAIL " + r)
422
+ print("反向腿②:%s(%d 条不合格)"
423
+ % ("PASS" if not bad else "FAIL", len(bad)))
424
+ return len(bad)
425
+ finally:
426
+ shutil.rmtree(tree, ignore_errors=True)
427
+
428
+
429
+ def main():
430
+ print("== #445/#426-D 元认知读面与台账密级收口守卫 ==")
431
+ try:
432
+ _rc = _anchor_check()
433
+ if _rc:
434
+ return _rc
435
+ group_a()
436
+ group_b()
437
+ group_c()
438
+ group_j()
439
+ group_d()
440
+ group_e()
441
+ group_g()
442
+ group_i()
443
+ finally:
444
+ shutil.rmtree(_TMP, ignore_errors=True)
445
+ print("=" * 68)
446
+ print("#445/#426-D 守卫:%d 通过,%d 失败" % (len(PASSED), len(FAILS)))
447
+ for f in FAILS:
448
+ print(" 红项:" + f)
449
+ _bad = _mutate() if "--mutate" in sys.argv else 0
450
+ return 1 if (FAILS or _bad) else 0
451
+
452
+
453
+ if __name__ == "__main__":
454
+ sys.exit(main())