@furongjun1999/dsh-memory 0.4.8 → 0.4.10

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 (232) hide show
  1. package/README.md +54 -26
  2. package/codebuddy/CODEBUDDY.md +196 -195
  3. package/codebuddy/README.md +13 -1
  4. package/codebuddy/mcp.json +9 -0
  5. package/docs/GBrain/345/217/257/345/200/237/351/211/264/347/202/271_/347/201/265/346/236/242/350/220/275/347/202/271/344/272/244/346/216/245_20260919.md +169 -0
  6. package/docs/README.md +1 -1
  7. package/docs/discipline/harnesses.yaml +18 -7
  8. package/docs/discipline/templates/full.md.tmpl +4 -3
  9. package/docs/experiments/linkref_backfill/candidates_20260917.json +726 -0
  10. package/docs/experiments/linkref_backfill/candidates_internal_20260917.json +602 -0
  11. package/docs/experiments/linkref_backfill/candidates_internal_v2.json +603 -0
  12. package/docs/experiments/linkref_backfill/candidates_secret_20260917.json +884 -0
  13. package/docs/experiments/linkref_backfill/candidates_secret_v2.json +789 -0
  14. package/docs/hive//345/244/232/347/253/257harness/351/200/232/344/277/241/345/245/221/347/272/246_v0.1.md +42 -0
  15. package/docs/hive//346/243/200/347/264/242/346/224/266/346/225/233/345/256/236/346/265/213/344/270/216S1b/350/256/276/350/256/241_v0.1.md +43 -0
  16. package/docs/hive//346/243/200/347/264/242/350/267/257/345/276/204/344/270/216/350/256/244/347/237/245/347/273/223/346/236/204/345/245/221/347/272/246_v0.1.md +102 -0
  17. package/docs/hive//347/234/237/345/256/236/345/272/223/347/253/257/345/210/260/347/253/257/345/256/236/346/265/213_S1b/344/270/216/345/217/254/345/233/236/346/235/203/350/241/241_v0.1.md +57 -0
  18. package/docs/hive//347/234/237/345/256/236/345/272/223/347/253/257/345/210/260/347/253/257/345/256/236/346/265/213_S7/345/200/222/346/216/222/345/200/231/351/200/211/345/261/202_v0.1.md +126 -0
  19. package/docs/hive//350/234/202/345/267/242/345/217/214/345/256/236/344/276/213/344/272/222/351/252/214_/350/256/276/350/256/241/345/256/232/347/250/277.md +503 -0
  20. package/docs/mdcg/D_meta_/345/267/245/347/250/213/345/214/226/346/226/271/346/241/210_v0.2.md +216 -0
  21. package/docs/mdcg/README/350/257/246/347/273/206/347/211/210_v0.4.5.md +631 -625
  22. package/docs/mdcg//344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/345/245/221/347/272/246_v0.1.md +82 -0
  23. package/docs/mdcg//345/205/250/345/272/223/344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/350/256/241/345/210/222_v0.1.md +600 -0
  24. package/docs/mdcg//345/212/237/350/203/275/350/260/203/347/224/250/346/230/240/345/260/204/350/241/250_v0.1.md +47 -45
  25. package/docs/mdcg//345/255/220/344/273/243/347/220/206/351/205/215/347/275/256/346/240/207/345/207/{206_v0.4.md → 206_v0.5.md} +92 -4
  26. package/docs/mdcg//347/201/265/346/236/242/350/256/260/345/277/206/345/212/250/350/257/215/345/215/217/350/256/256_v1.0-draft.md +172 -0
  27. package/docs/mdcg//347/216/257/344/272/214_/347/231/275/347/256/261/345/241/253/345/205/205/346/265/201/346/260/264/347/272/277_v0.1.md +31 -0
  28. package/docs/mdcg//350/267/250/347/253/257/351/252/214/350/257/201/344/270/216/345/220/214/346/255/245/345/215/217/350/256/256_v0.1.md +93 -0
  29. package/docs/theory//345/271/266/345/217/221/345/277/205/347/204/266/346/200/247/347/220/206/350/256/272_v0.2.md +2 -2
  30. package/docs/theory//347/220/206/350/256/272_/346/234/272/345/210/266_/344/273/243/347/240/201_/345/256/236/351/252/214_/347/274/272/345/217/243/347/237/251/351/230/265_v0.1.md +3 -3
  31. package/docs/theory//350/256/244/347/237/245/344/273/243/347/220/206/344/270/216/346/224/266/346/225/233/347/273/223/346/236/204_/346/235/241/344/273/266/350/256/272/351/207/215/346/236/204_v0.1.md +2 -2
  32. package/docs//345/267/245/344/275/234/347/272/252/345/276/213_/350/256/244/347/237/245/345/233/276/346/235/241/347/233/256_v1.1.json +434 -433
  33. package/docs//347/201/265/346/236/242/350/207/252/346/210/221/346/224/271/350/277/233/345/267/245/344/275/234/350/256/241/345/210/222_/345/244/226/351/203/250/347/240/224/347/251/266/347/263/273/345/210/227/345/220/270/346/224/266_v1_20260919.md +286 -0
  34. package/dsh/README.md +33 -0
  35. package/dsh/cordis.yml.example +13 -7
  36. package/dsh/hive-mcp-probe.mjs +94 -0
  37. package/dsh/hive-mcp.example.yml +62 -0
  38. package/dsh/update-lingshu.bat +11 -0
  39. package/dsh/update-lingshu.ps1 +337 -0
  40. package/lib/hooks.d.ts +3 -0
  41. package/lib/hooks.js +17 -23
  42. package/lib/index.d.ts +4 -2
  43. package/lib/index.js +29 -6
  44. package/lib/lib/datapath.d.ts +76 -1
  45. package/lib/lib/datapath.js +199 -13
  46. package/lib/lib/mdcg_client.d.ts +40 -3
  47. package/lib/lib/mdcg_client.js +46 -22
  48. package/lib/lib/mutual.js +4 -4
  49. package/lib/lib/token_store.js +4 -5
  50. package/md_cg/audit.py +17 -2
  51. package/md_cg/autonomy.py +86 -15
  52. package/md_cg/backfill.py +36 -1
  53. package/md_cg/backfill_bigdomain.py +34 -0
  54. package/md_cg/bench6_arms.py +28 -1
  55. package/md_cg/bench6_common.py +10 -1
  56. package/md_cg/bench6_competitors.py +6 -1
  57. package/md_cg/bench_axis_domain.py +9 -1
  58. package/md_cg/bench_blind_comp.py +7 -1
  59. package/md_cg/bench_en_atoms_public.py +9 -0
  60. package/md_cg/bench_governance.py +348 -0
  61. package/md_cg/bench_lme_zh.py +16 -1
  62. package/md_cg/bench_locomo.py +2 -1
  63. package/md_cg/bench_locomo_zh.py +16 -1
  64. package/md_cg/bench_locomo_zh_public.py +4 -1
  65. package/md_cg/bench_longmem.py +2 -1
  66. package/md_cg/bench_membench.py +27 -1
  67. package/md_cg/bench_p0.py +4 -1
  68. package/md_cg/bench_progressive.py +13 -1
  69. package/md_cg/bench_role_views.py +238 -0
  70. package/md_cg/bench_task_ab.py +8 -1
  71. package/md_cg/bench_task_ab_llm.py +13 -1
  72. package/md_cg/bench_unified_en.py +6 -1
  73. package/md_cg/bench_zh_mad.py +20 -1
  74. package/md_cg/blindspot_tickets.py +123 -0
  75. package/md_cg/branches.py +12 -1
  76. package/md_cg/build_postings.py +73 -0
  77. package/md_cg/ccgc.py +67 -2
  78. package/md_cg/census.py +5 -1
  79. package/md_cg/chain.py +24 -3
  80. package/md_cg/codeindex.py +134 -17
  81. package/md_cg/coldverify.py +265 -0
  82. package/md_cg/comment_gate.py +338 -0
  83. package/md_cg/cond_compose.py +190 -0
  84. package/md_cg/cond_facts.py +155 -0
  85. package/md_cg/cond_template.json +107 -0
  86. package/md_cg/condition_anchor.py +143 -0
  87. package/md_cg/conformance.py +69 -4
  88. package/md_cg/consistency.py +24 -1
  89. package/md_cg/consolidate.py +53 -2
  90. package/md_cg/corpus.py +4 -0
  91. package/md_cg/crosscheck.py +42 -2
  92. package/md_cg/crypto.py +35 -1
  93. package/md_cg/d_meta.py +310 -0
  94. package/md_cg/datapath.py +201 -26
  95. package/md_cg/docindex.py +122 -1
  96. package/md_cg/eval_common.py +29 -1
  97. package/md_cg/evidence.py +27 -1
  98. package/md_cg/evolution.py +21 -1
  99. package/md_cg/export.py +11 -1
  100. package/md_cg/forgetting.py +23 -1
  101. package/md_cg/fsutil.py +18 -1
  102. package/md_cg/hotcache.py +214 -0
  103. package/md_cg/hyperedge.py +251 -0
  104. package/md_cg/identity.py +18 -1
  105. package/md_cg/insight.py +17 -1
  106. package/md_cg/lexicon/build_cedict_en_zh.py +9 -0
  107. package/md_cg/lexicon/build_standard_en.py +171 -168
  108. package/md_cg/lexicon/expand_en_zh.py +6 -0
  109. package/md_cg/lifecycle.py +12 -1
  110. package/md_cg/linkref.py +281 -0
  111. package/md_cg/links.py +29 -1
  112. package/md_cg/mcp_server.py +362 -43
  113. package/md_cg/md_whitebox.py +53 -1
  114. package/md_cg/mdcg.py +1003 -27
  115. package/md_cg/mdcos.py +558 -36
  116. package/md_cg/metacognition.py +37 -2
  117. package/md_cg/migrate.py +4 -0
  118. package/md_cg/migrate_aeis.py +221 -213
  119. package/md_cg/migrate_roleplay.py +8 -0
  120. package/md_cg/migrate_wisdom_graph.py +14 -1
  121. package/md_cg/mreview/__main__.py +3 -0
  122. package/md_cg/mreview/bundle.py +8 -0
  123. package/md_cg/mreview/candidates.py +9 -0
  124. package/md_cg/mreview/govern.py +21 -1
  125. package/md_cg/mreview/locate.py +34 -0
  126. package/md_cg/mreview/pipeline.py +29 -1
  127. package/md_cg/mreview/ruleset.py +16 -1
  128. package/md_cg/nodefile.py +233 -3
  129. package/md_cg/pooling.py +23 -1
  130. package/md_cg/postings.py +298 -0
  131. package/md_cg/predict.py +89 -9
  132. package/md_cg/progressive.py +3 -0
  133. package/md_cg/protect.py +14 -1
  134. package/md_cg/protocol.py +372 -0
  135. package/md_cg/provenance.py +262 -0
  136. package/md_cg/reach.py +453 -0
  137. package/md_cg/refindex.py +47 -2
  138. package/md_cg/refine.py +20 -1
  139. package/md_cg/roleviews.py +89 -0
  140. package/md_cg/routing.py +76 -0
  141. package/md_cg/scrub.py +63 -2
  142. package/md_cg/security.py +26 -1
  143. package/md_cg/self_state.py +64 -1
  144. package/md_cg/selfreport.py +151 -0
  145. package/md_cg/semantic/canonical.py +5 -0
  146. package/md_cg/semantic/en_normalizer.py +364 -355
  147. package/md_cg/semantic/zh_en_atoms.py +139 -136
  148. package/md_cg/signer.py +41 -1
  149. package/md_cg/sources.py +583 -547
  150. package/md_cg/statushdr.py +179 -0
  151. package/md_cg/stg.py +59 -18
  152. package/md_cg/subgraph.py +23 -0
  153. package/md_cg/sustain.py +56 -1
  154. package/md_cg/tasks.py +26 -2
  155. package/md_cg/test_autonomy.py +26 -0
  156. package/md_cg/test_bench_governance.py +102 -0
  157. package/md_cg/test_blindspot_tickets.py +166 -0
  158. package/md_cg/test_ccgc.py +10 -0
  159. package/md_cg/test_codeindex.py +338 -0
  160. package/md_cg/test_comment_gate.py +187 -0
  161. package/md_cg/test_cond_compose_anchors.py +76 -0
  162. package/md_cg/test_condition_anchor.py +82 -0
  163. package/md_cg/test_d_meta.py +412 -0
  164. package/md_cg/test_datapath_root.py +188 -0
  165. package/md_cg/test_gain_gate.py +47 -1
  166. package/md_cg/test_hot_cold.py +187 -0
  167. package/md_cg/test_hyperedge.py +245 -0
  168. package/md_cg/test_linkref.py +306 -0
  169. package/md_cg/test_md_access_parity.py +15 -3
  170. package/md_cg/test_mr_m1.py +108 -18
  171. package/md_cg/test_mr_m3.py +8 -1
  172. package/md_cg/test_p26_refindex.py +49 -20
  173. package/md_cg/test_p27_docindex.py +236 -2
  174. package/md_cg/test_p2_mcp.py +1 -1
  175. package/md_cg/test_p31_insight.py +24 -0
  176. package/md_cg/test_p44_md_whitebox.py +14 -1
  177. package/md_cg/test_protocol.py +243 -0
  178. package/md_cg/test_reach.py +378 -0
  179. package/md_cg/test_reach_keys.py +201 -0
  180. package/md_cg/test_reach_meta_exits.py +145 -0
  181. package/md_cg/test_read_clip.py +8 -4
  182. package/md_cg/test_retr_s1.py +340 -0
  183. package/md_cg/test_retr_s1b.py +209 -0
  184. package/md_cg/test_retr_s3.py +194 -0
  185. package/md_cg/test_retr_s4.py +163 -0
  186. package/md_cg/test_retr_s5.py +200 -0
  187. package/md_cg/test_retr_s6.py +157 -0
  188. package/md_cg/test_retr_s7.py +385 -0
  189. package/md_cg/test_retr_s8_time.py +316 -0
  190. package/md_cg/test_retr_s9_edges.py +286 -0
  191. package/md_cg/test_retr_s9_entity_ctx.py +175 -0
  192. package/md_cg/test_review_conformance.py +59 -2
  193. package/md_cg/test_role_views.py +354 -0
  194. package/md_cg/test_subproc_encoding.py +188 -0
  195. package/md_cg/test_trust.py +361 -0
  196. package/md_cg/test_units_poll.py +71 -0
  197. package/md_cg/test_v14_fixes.py +397 -0
  198. package/md_cg/test_validity_filter.py +280 -0
  199. package/md_cg/test_wisdom_md_store.py +7 -3
  200. package/md_cg/test_writepipe.py +5 -1
  201. package/md_cg/theory.py +16 -1
  202. package/md_cg/tokens.py +40 -8
  203. package/md_cg/tool_face.py +13 -2
  204. package/md_cg/trust.py +943 -0
  205. package/md_cg/twophase.py +12 -1
  206. package/md_cg/units.py +132 -10
  207. package/md_cg/vision_evidence.py +24 -1
  208. package/md_cg/weights.py +24 -1
  209. package/md_cg/whitebox.py +32 -1
  210. package/md_cg/whitebox_kb/data/verify_cache.json +21210 -365
  211. package/md_cg/whitebox_kb/data/verify_savings.jsonl +5078 -0
  212. package/md_cg/whitebox_kb/wisdom/audit_log/chain_heat.json +10 -10
  213. package/md_cg/whitebox_kb/wisdom/code_compose.py +113 -6
  214. package/md_cg/whitebox_kb/wisdom/code_solidified.json +1 -1
  215. package/md_cg/whitebox_kb/wisdom/verifier.py +340 -55
  216. package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db +0 -0
  217. package/md_cg/writelimit.py +18 -4
  218. package/md_cg/writepipe.py +178 -7
  219. package/package.json +2 -2
  220. package/skills/skills/designer-perspective/scripts/__pycache__/designer.cpython-310.pyc +0 -0
  221. package/skills/skills/designer-perspective/scripts/designer.py +17 -1
  222. package/skills/skills/designer-perspective/tests/selftest.py +3 -1
  223. package/src/hooks.ts +17 -21
  224. package/src/index.ts +33 -6
  225. package/src/lib/datapath.ts +211 -13
  226. package/src/lib/mdcg_client.ts +64 -25
  227. package/src/lib/mutual.ts +411 -411
  228. package/src/lib/token_store.ts +4 -5
  229. package/zcode/AGENTS.md +196 -195
  230. package/zcode/README.md +4 -0
  231. package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db-shm +0 -0
  232. package/md_cg/whitebox_kb/wisdom/wisdom-book-cloud.db-wal +0 -0
@@ -0,0 +1,372 @@
1
+ # -*- coding: utf-8 -*-
2
+ """md_cg · 记忆动词协议 v1(单一真源 · draft 期未冻结)
3
+
4
+ 目的(工作计划 §3.4):把 MCP 记忆工具面的**动词与 I/O 形状**冻结成可裁决的声明,
5
+ 使三端(本仓 MCP / DSH 内建基元 / 第三方客户端)能各自实现客户端而不必读源码;
6
+ 再由 `conformance.py` 的静态对账把「声明 ↔ 实现」钉死:
7
+
8
+ · 声明为 live 却在 MCP 面无分支 → FAIL(说了没做)
9
+ · reserved 动词在 MCP 面出现实现分支 → FAIL(预留位被静默实现,协议形同虚设)
10
+ · 协议外 op 分支 → 报告(扩展能力面,不是违例)
11
+
12
+ 范围(先行收窄):route / read / write / supersede / forget 五动词。
13
+
14
+ **协议面 ≠ MCP 面全量**(2026-09-19 实测):`_cg_dispatch` 现有 35 个 op 分支,
15
+ 其中 30 个(ccg / review / protect / verify / whitebox …)属**扩展能力面**——它们是能力,
16
+ 不是协议违例。把「协议覆盖范围」当成「MCP 面全量」会让协议每加一个 op 就永久红灯,
17
+ 故反向对账降级为 `extension_ops` 报告项(清单可见、不 FAIL);扩展面的文档一致性由
18
+ README 认知图 + `docs/mdcg/功能调用映射表` 的 cogmap 门禁承担(已在 CI)。
19
+
20
+ 三条纪律:
21
+ 1. **本文件是协议唯一真源**——文档 `docs/mdcg/灵枢记忆动词协议_v1.0-draft.md`
22
+ 与 `conformance.py` 的断言均从本文件取值,不另立第二份清单。
23
+ 2. **不冒充**——未实现的动词登记 `status="reserved"` 并给出 `map_to` 现状映射证据,
24
+ 不得写 live;live 的形状取**代码实测**(executor / 分支 return),不取设想。
25
+ 3. **draft 期(FROZEN=False)**——形状可破坏性调整;冻结是单向门,须三端实测收敛后
26
+ 由使用者拍板(工作计划 §9 风险 3)。
27
+
28
+ 用法:
29
+ python -m md_cg.protocol # 打印静态对账结论(只读,零写入)
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import ast
35
+ import inspect
36
+ import json
37
+ import textwrap
38
+
39
+ PROTOCOL_VERSION = 1
40
+ #: 冻结开关:True 后形状变更须走版本号递增(v1 → v2),不得原地改 v1 的形状
41
+ FROZEN = False
42
+ PROTOCOL_DOC = "docs/mdcg/灵枢记忆动词协议_v1.0-draft.md"
43
+ SURFACE_MODULE = "md_cg.mcp_server"
44
+ DISPATCH_FUNC = "_cg_dispatch"
45
+ CALL_FUNC = "_cg_call"
46
+
47
+ #: 协议声明的动词全集(顺序即文档呈现顺序)
48
+ VERBS = ("route", "read", "write", "supersede", "forget")
49
+
50
+ #: write 返回**铁律**:任一形态必含此三键——客户端据此判定「是否落盘」而非猜测。
51
+ #: 这是协议对三端客户端最有价值的一条:ok/committed 分离表达「闸门行为 ≠ 工具故障」。
52
+ WRITE_TRIO = ("ok", "id", "committed")
53
+
54
+ #: op 推导兜底(`_cg_call` wrapper,2026-09-13 防呆落地):op 漏传时按入参签名推导。
55
+ #: 协议侧只作**文档化声明**(供客户端理解兜底语义),不做静态对账——
56
+ #: 推导实现散落在 wrapper 分支里,强做正则对账会误报(宁可少断言,不可假绿灯)。
57
+ OP_DERIVE = (
58
+ {"when": "content", "op": "write"},
59
+ {"when": "query", "op": "read"},
60
+ {"when": "node_id", "op": "read"},
61
+ {"when": "intent", "op": "route"},
62
+ {"when": "(无签名)", "op": "read"},
63
+ )
64
+
65
+ #: op 推导发生时**追加透出**的键(实测):additive,不破坏各形态 required 子集判定。
66
+ #: 协议语义:客户端看到这些键即知道「本次 op 是猜的」——据此可要求调用方补显式 op。
67
+ DERIVE_EXTRA_KEYS = ("op", "op_derived", "hint")
68
+
69
+ #: 校验裁决(verdict)的字段集——写路径闸门短路时随返回透出(实测)。
70
+ #: state 取值 = ACCEPT / REJECT / DEFER / BLINDSPOT(四态资格裁决)。
71
+ VERDICT_FIELDS = ("state", "kind", "basis", "evidence", "detail")
72
+
73
+ VERB_SPECS = {
74
+ "route": {
75
+ "status": "live",
76
+ "mutating": False,
77
+ "impl": ("mcp_server", "_cg_dispatch"),
78
+ "requires_any": (("intent", "query"),),
79
+ "optional": ("k", "context"),
80
+ "shapes": {
81
+ "default": {
82
+ "when": "恒",
83
+ "required": ("knowledge", "meta"),
84
+ "optional": ("suggested_capabilities", "note"),
85
+ },
86
+ },
87
+ "semantics": "只给知识与建议能力名,不执行;由调用方决定下一步",
88
+ },
89
+ "read": {
90
+ "status": "live",
91
+ "mutating": False,
92
+ "impl": ("mcp_server", "_cg_dispatch"),
93
+ "requires_any": (("node_id",), ("query", "intent"), ("budget_tokens",)),
94
+ "optional": ("offset", "k", "context", "goal", "include_recent", "limit",
95
+ "session", "validity", "layer", "branch"),
96
+ "shapes": {
97
+ "node": {
98
+ "when": "node_id 非空且目标存在且可见",
99
+ "required": ("id", "path", "frontmatter", "content",
100
+ "verification_state"),
101
+ "optional": ("truncated", "content_lines", "content_bytes",
102
+ "offset", "next_offset", "note"),
103
+ },
104
+ "node_missing": {
105
+ "when": "node_id 非空但目标不存在 / 不可见 / 已软删",
106
+ "returns_null": True,
107
+ "required": (),
108
+ "optional": (),
109
+ "note": "**实测返回 null**(不是错误对象)——客户端须先判空再解析,"
110
+ "把 null 当异常会误报;把 null 当空内容会静默吞未知",
111
+ },
112
+ "list": {
113
+ "when": "budget_tokens 为空",
114
+ "required": ("meta", "results"),
115
+ "optional": (),
116
+ },
117
+ "pack": {
118
+ "when": "budget_tokens 非空(优先于 node_id 之外的 query 路径)",
119
+ "required": ("pack", "tokens_used", "budget", "skipped", "recent",
120
+ "meta"),
121
+ "optional": (),
122
+ },
123
+ },
124
+ "semantics": "读动词三分态:单节点视图 / 检索结果列表 / token 预算包",
125
+ },
126
+ "write": {
127
+ "status": "live",
128
+ "mutating": True,
129
+ "impl": ("writepipe", "default_pipeline"),
130
+ "requires_any": (("content",),),
131
+ "optional": ("content_kind", "layer", "tags", "importance",
132
+ "verification_basis", "condition_space",
133
+ "non_applicable_conditions", "depends_on", "derived_from",
134
+ "relation", "valid_from", "valid_until", "verification_state",
135
+ "consistency", "on_conflict", "gated", "override",
136
+ "importance_hint", "semantic", "node_id"),
137
+ "shapes": {
138
+ "committed": {
139
+ "when": "链尾执行器落盘",
140
+ "required": WRITE_TRIO,
141
+ "optional": ("verdict", "consistency", "propagation"),
142
+ },
143
+ "gate_short_circuit": {
144
+ "when": "任一 before 闸门短路(审核 REJECT / DEFER / 冲突)",
145
+ "required": WRITE_TRIO + ("moved_to", "verdict", "hint"),
146
+ "optional": ("pid", "dedup", "dup_of", "dup_status", "consistency"),
147
+ },
148
+ "gate_hard_reject": {
149
+ "when": "契约缺失硬拒(依赖声明闸 E050/E051)",
150
+ "required": WRITE_TRIO + ("gate", "error", "hint"),
151
+ "optional": ("missing", "verdict"),
152
+ },
153
+ "gate_gated": {
154
+ "when": "主动遗忘闸(gated=true)替代落盘路径",
155
+ "required": WRITE_TRIO + ("gate", "verdict"),
156
+ "optional": ("consistency", "moved_to", "propagation"),
157
+ },
158
+ },
159
+ "semantics": "写动词多形态:committed=已落盘;未 committed 时 moved_to/gate 说明去向,"
160
+ "hint 说明「闸门正常行为、不是工具故障、重试同样结果」",
161
+ },
162
+ "supersede": {
163
+ "status": "reserved",
164
+ "mutating": True,
165
+ "impl": None,
166
+ "requires_any": (("node_id",), ("superseded_by",)),
167
+ "optional": ("reason", "inherit_verification", "propagate"),
168
+ "shapes": {
169
+ "planned": {
170
+ "when": "(预留位,尚未实现)",
171
+ "required": ("ok", "id", "superseded_by"),
172
+ "optional": ("supersedes", "propagation", "verdict"),
173
+ },
174
+ },
175
+ "semantics": "以新节点取代旧节点:旧节点保留可审计但退出默认检索面,取代关系可追溯",
176
+ "map_to": (
177
+ {"verb": "write", "note": "新节点写入本身走 write(五动词不重复造写入通道)"},
178
+ {"verb": "review/verify", "note": "现有撤回体系由校验(verify 验伪)与审核"
179
+ "(review 的 delete/merge)承担,无独立取代动词"},
180
+ {"field": "nodefile.believed_at", "note": "取代语义的锚字段已就位(写侧注释),"
181
+ "缺的是动词入口与检索面过滤"},
182
+ ),
183
+ "reserved_reason": "取代会改变默认检索面(被取代节点是否可见),属行为变更,"
184
+ "须先冻结协议再落实现——避免三端各自发明可见性口径",
185
+ },
186
+ "forget": {
187
+ "status": "live",
188
+ "mutating": True,
189
+ "impl": ("mdcos", "MdCG.forget"),
190
+ "requires_any": (("node_id",),),
191
+ "optional": ("reason", "override", "action"),
192
+ "shapes": {
193
+ "forgotten": {
194
+ "when": "action 缺省或非 restore",
195
+ "required": ("ok", "id", "tombstone"),
196
+ "optional": (),
197
+ },
198
+ "restored": {
199
+ "when": "action == 'restore'",
200
+ "required": ("ok", "id", "forced"),
201
+ "optional": (),
202
+ },
203
+ "failed": {
204
+ "when": "目标不存在 / 已 tombstone(未 force)/ trash 无文件 / OSError",
205
+ "required": ("ok", "error"),
206
+ "optional": ("reason", "t", "action", "action_derived",
207
+ "hint_action"),
208
+ },
209
+ },
210
+ "semantics": "软删除与恢复:文件移入 trash/、写删除清单、摘索引;受保护节点需 override",
211
+ },
212
+ }
213
+
214
+
215
+ # 生效条件:node 为 ast 表达式节点;沿 Attribute/Call 递归剥到 Name,命中 Name("op") 返回 True,落到其它节点类型(含常量/字面量)返回 False;
216
+ def _is_op_expr(node) -> bool:
217
+ """判断 AST 表达式是否指向 `op`(兼容 `op.strip().lower()` 形态)。"""
218
+ cur = node
219
+ while True:
220
+ if isinstance(cur, ast.Name):
221
+ return cur.id == "op"
222
+ if isinstance(cur, ast.Attribute):
223
+ cur = cur.value
224
+ continue
225
+ if isinstance(cur, ast.Call):
226
+ cur = cur.func
227
+ continue
228
+ return False
229
+
230
+
231
+ # 生效条件:src 为字符串源码(缩进任意,内部先 dedent);ast.parse 成功返回按出现序去重的 op 字面量列表(识别 `op == "x"` 与 `op in ("x","y")` 两种形态,op 侧兼容 `op.strip().lower()`),解析失败(SyntaxError/TypeError/任意异常)返回空列表,不抛异常;
232
+ def _ops_from_source(src: str) -> list:
233
+ """从源码文本提取 op 分支名(dispatch_ops 与测试共用;测试可直接喂合成源码)。"""
234
+ try:
235
+ tree = ast.parse(textwrap.dedent(src or ""))
236
+ except Exception: # noqa: BLE001
237
+ return []
238
+ out = []
239
+ for node in ast.walk(tree):
240
+ if not isinstance(node, ast.Compare) or not _is_op_expr(node.left):
241
+ continue
242
+ for opnode, comp in zip(node.ops, node.comparators):
243
+ items = []
244
+ if isinstance(opnode, ast.Eq):
245
+ items = [comp]
246
+ elif isinstance(opnode, ast.In) and isinstance(
247
+ comp, (ast.Tuple, ast.List, ast.Set)):
248
+ items = list(comp.elts)
249
+ for it in items:
250
+ if isinstance(it, ast.Constant) and isinstance(it.value, str):
251
+ if it.value not in out:
252
+ out.append(it.value)
253
+ return out
254
+
255
+
256
+ # 生效条件:module 缺省取 SURFACE_MODULE、func 缺省取 DISPATCH_FUNC;导入模块 / 取属性 / getsource 任一抛异常,返回 {"ok": False, "error": "<类型>: <消息>", "ops": []};成功返回 {"ok": True, "module", "func", "ops": 按出现序去重的 op 字面量列表};
257
+ def dispatch_ops(module: str = None, func: str = None) -> dict:
258
+ """从分发函数源码用 **AST** 提取 op 分支(`if op == "x"` 与 `op in ("x","y")`)。
259
+
260
+ 为何用 AST 而非正则:正则对单引号/换行/`op.strip().lower()` 形态会静默漏提,
261
+ 而「漏提」在本协议里等于假绿灯(cogmap 已有同类教训)。AST 结构性识别不依赖写法。
262
+ """
263
+ mod_name = module or SURFACE_MODULE
264
+ fn_name = func or DISPATCH_FUNC
265
+ try:
266
+ m = __import__(mod_name, fromlist=[fn_name])
267
+ obj = getattr(m, fn_name)
268
+ src = inspect.getsource(obj)
269
+ except Exception as e: # noqa: BLE001
270
+ return {"ok": False, "error": f"{type(e).__name__}: {e}", "ops": []}
271
+ return {"ok": True, "module": mod_name, "func": fn_name,
272
+ "ops": _ops_from_source(src)}
273
+
274
+
275
+ # 生效条件:module/func 透传 dispatch_ops(默认面取模块常量);始终返回 dict,含 protocol_version/frozen/doc/live/reserved/declared/actual/has_impl/missing_impl/extension_ops/reserved_leaked/shape_errors/derive/errors/ok,任一静态对账项失败则 ok=False 且失败明细进 errors;
276
+ def audit(module: str = None, func: str = None) -> dict:
277
+ """静态对账:协议声明 ↔ MCP 面实现(不连库、不执行,纯源码事实)。"""
278
+ got = dispatch_ops(module, func)
279
+ actual = list(got.get("ops") or [])
280
+ declared = list(VERBS)
281
+ live = [v for v in declared if VERB_SPECS[v].get("status") == "live"]
282
+ reserved = [v for v in declared if VERB_SPECS[v].get("status") == "reserved"]
283
+ has_impl = [v for v in declared if v in actual]
284
+ missing_impl = [v for v in live if v not in actual]
285
+ # 协议 v1 只冻结五动词;MCP 面其余 op 属**扩展能力面**——它们是能力不是违例。
286
+ # 反向对账降级为报告项(extension_ops),理由见模块 docstring。
287
+ extension_ops = [v for v in actual if v not in declared]
288
+ reserved_leaked = [v for v in reserved if v in actual]
289
+ shape_errors = []
290
+ for v in declared:
291
+ spec = VERB_SPECS[v]
292
+ if spec.get("status") not in ("live", "reserved"):
293
+ shape_errors.append(f"{v}: status 取值非法 {spec.get('status')!r}")
294
+ shapes = spec.get("shapes") or {}
295
+ if not shapes:
296
+ shape_errors.append(f"{v}: 未声明任何形状")
297
+ for sname, sh in shapes.items():
298
+ if not sh.get("required") and not sh.get("returns_null"):
299
+ shape_errors.append(
300
+ f"{v}.{sname}: required 为空且未声明 returns_null")
301
+ if not sh.get("when"):
302
+ shape_errors.append(f"{v}.{sname}: 缺 when(何时走该形态)")
303
+ if spec.get("status") == "reserved" and not spec.get("map_to"):
304
+ shape_errors.append(f"{v}: reserved 但未声明 map_to 现状映射证据")
305
+ if spec.get("status") == "live" and not spec.get("impl"):
306
+ shape_errors.append(f"{v}: live 但未声明 impl 落点")
307
+ errors = []
308
+ if not got.get("ok"):
309
+ errors.append(f"源码提取失败:{got.get('error')}")
310
+ if missing_impl:
311
+ errors.append(f"声明为 live 但 MCP 面无分支:{missing_impl}")
312
+ if reserved_leaked:
313
+ errors.append(f"reserved 动词出现实现分支(实现了却未登记):{reserved_leaked}")
314
+ if shape_errors:
315
+ errors.append(f"形状声明不完整:{shape_errors}")
316
+ return {"protocol_version": PROTOCOL_VERSION, "frozen": FROZEN,
317
+ "doc": PROTOCOL_DOC, "declared": declared, "live": live,
318
+ "reserved": reserved, "actual": actual, "has_impl": has_impl,
319
+ "missing_impl": missing_impl, "extension_ops": extension_ops,
320
+ "reserved_leaked": reserved_leaked, "shape_errors": shape_errors,
321
+ "derive": list(OP_DERIVE), "errors": errors, "ok": not errors}
322
+
323
+
324
+ # 生效条件:verb 为 VERBS 成员时返回其 VERB_SPECS 规格 dict,非成员(含 None/空串)抛 KeyError;
325
+ def spec_of(verb: str) -> dict:
326
+ """取动词规格(非声明动词直接抛 KeyError——fail-closed,不返回空壳)。"""
327
+ return VERB_SPECS[verb]
328
+
329
+
330
+ # 生效条件:verb 已声明且 shape 为该动词 shapes 的键时返回该形态 dict;shape 缺省(None/空串)时返回其第一个形态;verb 未声明或 shape 不存在抛 KeyError;
331
+ def shape_of(verb: str, shape: str = None) -> dict:
332
+ """取某动词的形态声明(shape 缺省取第一个)。"""
333
+ shapes = VERB_SPECS[verb]["shapes"]
334
+ return shapes[shape] if shape else shapes[next(iter(shapes))]
335
+
336
+
337
+ # 生效条件:无入参;始终返回单行字符串(格式 "protocol v1 live=4/5 reserved=1 ops=4 ok=True"),不抛异常;
338
+ def summary() -> str:
339
+ """单行结论(供 sustain / 报告页眉引用)。"""
340
+ a = audit()
341
+ return (f"protocol v{PROTOCOL_VERSION} live={len(a['live'])}/{len(a['declared'])} "
342
+ f"reserved={len(a['reserved'])} ops={len(a['actual'])} "
343
+ f"ext={len(a['extension_ops'])} ok={a['ok']}")
344
+
345
+
346
+ # 生效条件:argv 为 None 时 argparse 取 sys.argv;--json 为真时打印缩进 JSON,否则打印人类可读多行;返回 0(ok)或 1(对账失败);
347
+ def main(argv=None) -> int:
348
+ p = argparse.ArgumentParser(prog="python -m md_cg.protocol",
349
+ description="记忆动词协议 v1 静态对账(只读,零写入)")
350
+ p.add_argument("--json", action="store_true", help="输出 JSON")
351
+ a = p.parse_args(argv)
352
+ rep = audit()
353
+ if a.json:
354
+ print(json.dumps(rep, ensure_ascii=False, indent=2))
355
+ else:
356
+ print(f"== {summary()} doc={rep['doc']} frozen={rep['frozen']}")
357
+ print(f" 声明 = {rep['declared']}")
358
+ print(f" MCP 实际 = {rep['actual']}")
359
+ print(f" 扩展能力面(不属协议 v1,共 {len(rep['extension_ops'])} 项)"
360
+ f"= {rep['extension_ops']}")
361
+ for v in rep["declared"]:
362
+ s = VERB_SPECS[v]
363
+ print(f" [{s['status']:8s}] {v}: "
364
+ f"{len(s['shapes'])} 形态 / requires_any={s['requires_any']}")
365
+ for e in rep["errors"]:
366
+ print(f" !! {e}")
367
+ return 0 if rep["ok"] else 1
368
+
369
+
370
+ if __name__ == "__main__":
371
+ import sys
372
+ sys.exit(main())