@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
@@ -2,21 +2,33 @@
2
2
  * datapath.ts · 灵枢数据根解析(记忆写入路径可配置)
3
3
  *
4
4
  * 与 Python 侧 `md_cg/datapath.py` **同口径**——两侧读同一份
5
- * `<插件仓>/data/paths.json`,避免大脑与脚本对「记忆真源在哪」各持一说。
5
+ * `<用户级状态根>/paths.json`(新位置;旧版 `<插件仓>/data/paths.json`
6
+ * 仍兼容读),避免大脑与脚本对「记忆真源在哪」各持一说。
7
+ *
8
+ * 为什么默认不再取「插件仓自身 data/」(issue #18 相邻问题,数据丢失级):
9
+ * DSH 插件按 hoisted 布局装在 `<profile>/node_modules/<pkg>`,`pnpm` 更新该包
10
+ * 会**整个替换包目录**——运行时数据落在包内(`<pkg>/data`)时,每次更新成功
11
+ * 即连目录一起删掉(贡献者实机实证:`data/` 54 文件 → 0,46 条记忆节点只能
12
+ * 靠人工备份回填);`paths.json` 同址,用户配置一并丢失。故默认数据根与配置
13
+ * 文件一律落**用户级状态根**(见 `stateRoot()`),与包目录彻底解耦。
6
14
  *
7
15
  * 优先级(高 → 低):
8
16
  * 1. 环境变量 `MDCG_DATA_ROOT`(数据根)/ `MDCG_ROOT`(认知图根)
9
- * 2. 用户可编辑配置 `<插件仓>/data/paths.json` 的 `data_root` / `root`
17
+ * 2. 用户可编辑配置 `paths.json` 的 `data_root` / `root`
18
+ * (位置:`<用户级状态根>/paths.json`;旧 `<插件仓>/data/paths.json` 兼容读)
10
19
  * 3. 插件配置项 `mdcg.root`(可为空=未指定)
11
- * 4. 默认 `<插件仓>/data/mdcg`(**自身仓库**,与进程 cwd 解耦)
20
+ * 4. 默认 `<用户级状态根>/data/mdcg`
12
21
  *
13
- * 为什么默认不再取「相对 cwd 的 data/mdcg」:
22
+ * 为什么默认不取「相对 cwd 的 data/mdcg」:
14
23
  * node 侧插件与 python 侧脚本的 cwd 不同,相对路径会漂移成
15
24
  * `<cwd>/data/mdcg`。历史事故:宿主 cwd 落在 AEIS 时,记忆真源
16
25
  * 分裂到 `AEIS/data/mdcg`,与插件仓 `data/` 变成互不可见的两处。
17
- * 锚定 `package.json` 所在目录后,默认值稳定且可预期。
26
+ *
27
+ * 旧数据接手:`migrateLegacyData()` 在默认数据根生效且旧包内位置仍有内容时
28
+ * 一次性**复制**(不删除、不覆盖)到用户级位置——见该函数注释。
18
29
  */
19
- import { existsSync, readFileSync } from 'node:fs'
30
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
31
+ import { homedir, tmpdir } from 'node:os'
20
32
  import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path'
21
33
  import { fileURLToPath } from 'node:url'
22
34
 
@@ -43,9 +55,56 @@ export function repoRoot(): string {
43
55
  return cachedRepoRoot
44
56
  }
45
57
 
46
- /** 用户可编辑的路径配置文件(固定在插件仓 data/,不受 dataRoot 取值影响)。 */
58
+ export const ENV_STATE_ROOT = 'MDCG_STATE_ROOT'
59
+
60
+ let cachedStateRoot: string | null = null
61
+
62
+ /**
63
+ * 用户级状态根(**插件包目录之外**):路径配置与默认数据根的落点。
64
+ * 优先级:`MDCG_STATE_ROOT` → `$DSH_HOME/.dsh-memory` → `~/.dsh/.dsh-memory`。
65
+ * `DSH_HOME` **未必**由宿主注入(本仓 `dsh/dsh-web-start.bat` 自行 set),
66
+ * 故家目录兜底;`~/.dsh` 是本插件既有约定(`bridge.ts` 调试日志同址)。
67
+ */
68
+ export function stateRoot(): string {
69
+ if (cachedStateRoot) return cachedStateRoot
70
+ const env = process.env[ENV_STATE_ROOT]
71
+ if (env) {
72
+ cachedStateRoot = resolve(env)
73
+ return cachedStateRoot
74
+ }
75
+ const dshHome = process.env['DSH_HOME']
76
+ cachedStateRoot = dshHome
77
+ ? join(resolve(dshHome), '.dsh-memory')
78
+ : join(homedir(), '.dsh', '.dsh-memory')
79
+ return cachedStateRoot
80
+ }
81
+
82
+ /** 旧版落点(插件包内 `data/`)——更新时会被整个替换,只作兼容读与迁移源。 */
83
+ export function legacyDataRoot(): string {
84
+ return join(repoRoot(), 'data')
85
+ }
86
+
87
+ function samePath(a: string, b: string): boolean {
88
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
89
+ }
90
+
91
+ /**
92
+ * 用户可编辑的路径配置文件:
93
+ * `<用户级状态根>/paths.json` → 不存在则回落**旧** `<插件仓>/data/paths.json`
94
+ * (兼容读)→ 都不存在返回新位置(首次写入时创建)。
95
+ * 不做自动复制:配置文件是「谁说了算」的唯一真源,悄悄复制会让旧件的后续编辑
96
+ * 静默失效——迁移只搬数据面,配置显式交给用户搬(或用 `set_user_root`)。
97
+ */
47
98
  export function pathsFile(): string {
48
- return join(repoRoot(), 'data', 'paths.json')
99
+ const current = join(stateRoot(), 'paths.json')
100
+ if (existsSync(current)) return current
101
+ const legacy = join(legacyDataRoot(), 'paths.json')
102
+ return existsSync(legacy) ? legacy : current
103
+ }
104
+
105
+ /** 生效中的 paths.json 位置来源:`user`=用户级 / `legacy`=旧包内(兼容读)。 */
106
+ export function pathsFileSource(): 'user' | 'legacy' {
107
+ return samePath(dirname(pathsFile()), stateRoot()) ? 'user' : 'legacy'
49
108
  }
50
109
 
51
110
  function readUserPaths(): Record<string, unknown> {
@@ -63,8 +122,141 @@ function anchor(p: string): string {
63
122
  return isAbsolute(p) ? p : resolve(repoRoot(), p)
64
123
  }
65
124
 
125
+ /** 默认数据根 = 用户级状态根下 `data/`(**插件包目录之外**,更新不触碰)。 */
66
126
  export function defaultDataRoot(): string {
67
- return join(repoRoot(), 'data')
127
+ return join(stateRoot(), 'data')
128
+ }
129
+
130
+ export interface LegacyMigration {
131
+ /** 是否真的搬了(false 时 `reason` 说明为何没搬)。 */
132
+ ran: boolean
133
+ reason: string
134
+ from: string
135
+ to: string
136
+ /** 复制成功的顶层条目数。 */
137
+ copied: number
138
+ /** 复制失败的顶层条目(权限/占用等,逐项吞掉不抛)。 */
139
+ failed: string[]
140
+ }
141
+
142
+ /** dst 为「空目录」时 true(不存在/非目录/有内容均为 false)。 */
143
+ function isEmptyDir(p: string): boolean {
144
+ try {
145
+ return readdirSync(p).length === 0
146
+ } catch {
147
+ return false
148
+ }
149
+ }
150
+
151
+ /**
152
+ * 一次性迁移:把旧版留在**插件包内** `data/` 的数据面复制到用户级默认数据根。
153
+ *
154
+ * 触发条件(三条同时满足,缺一不动):
155
+ * ① 数据根未被显式配置(env `MDCG_DATA_ROOT` / paths.json 的 `data_root` 都未设,
156
+ * 即 `dataRoot()` 恰为默认值)——显式配置是用户的决定,越权搬运等于改他的真源;
157
+ * ② 旧位置存在;
158
+ * ③ 目标顶层条目不存在或为空目录(**不覆盖、不合并**已有数据)。
159
+ *
160
+ * 只复制不删除(旧目录随后由 pnpm 更新自然移除);`paths.json` 不复制
161
+ * (配置走 `pathsFile()` 兼容读,复制会制造「哪个文件说了算」的两说)。
162
+ * 任何异常逐项吞掉并记入 `failed`——迁移是增益,不该成为启动失败源。
163
+ *
164
+ * 边界(如实):pnpm 更新是**先替换包目录再启动新代码**,故旧数据在升级瞬间
165
+ * 即已消失,本函数只能接手「旧位置那时仍在」的情形(手工安装、就地覆盖、
166
+ * 或包目录未被清理);已在升级中丢掉的数据无法由此恢复——发布说明须提示
167
+ * 0.4.8 及更早用户升级前备份 `<profile>/node_modules/<pkg>/data/`。
168
+ */
169
+ export function migrateLegacyData(): LegacyMigration {
170
+ const from = legacyDataRoot()
171
+ const to = defaultDataRoot()
172
+ const out: LegacyMigration = { ran: false, reason: '', from, to, copied: 0, failed: [] }
173
+ if (!samePath(dataRoot(), to)) {
174
+ out.reason = '数据根为显式配置(env/paths.json),不迁移'
175
+ return out
176
+ }
177
+ if (!existsSync(from)) {
178
+ out.reason = '旧位置不存在(多为更新时已随包目录被替换)'
179
+ return out
180
+ }
181
+ let entries: string[]
182
+ try {
183
+ entries = readdirSync(from)
184
+ } catch {
185
+ out.reason = '旧位置不可读'
186
+ return out
187
+ }
188
+ const names = entries.filter((n) => n !== 'paths.json')
189
+ if (!names.length) {
190
+ out.reason = '旧位置无数据'
191
+ return out
192
+ }
193
+ for (const name of names) {
194
+ const src = join(from, name)
195
+ const dst = join(to, name)
196
+ // 新位置已有实质内容 → 跳过(宁可少搬,不可覆盖)
197
+ if (existsSync(dst) && !isEmptyDir(dst)) continue
198
+ try {
199
+ mkdirSync(to, { recursive: true })
200
+ cpSync(src, dst, { recursive: true, force: false, errorOnExist: false })
201
+ out.copied += 1
202
+ } catch {
203
+ out.failed.push(name)
204
+ }
205
+ }
206
+ out.ran = out.copied > 0
207
+ if (!out.ran) out.reason = out.failed.length ? '目标不可写' : '新位置已有数据,未覆盖'
208
+ return out
209
+ }
210
+
211
+ export const ENV_CHILD_CWD = 'MDCG_CHILD_CWD'
212
+
213
+ let cachedRunRoot: string | null = null
214
+
215
+ /**
216
+ * 子进程的工作目录(**必须落在插件包目录之外**)。
217
+ *
218
+ * 为什么不能沿用 `repoRoot()`:Windows 不允许删除/改名「正被某进程当作 CWD」
219
+ * 的目录。DSH 的插件按 hoisted 布局安装在 `<profile>/node_modules/<pkg>`,
220
+ * 而 `pnpm` 每次更新该包都要先 `rmdir` 包目录 → 子进程一旦把包目录当 CWD,
221
+ * 更新必然 `ERR_PNPM_EBUSY: resource busy or locked`(含升级回滚一起失败,
222
+ * 应用内永远升不动这个插件)。注意落点也**不能**是 `<包>/data`——它仍在包内,
223
+ * 实测同样 `err=32`。
224
+ *
225
+ * 落点要求「稳定存在」:进程 cwd 指向已消失的目录会引出新的怪问题,故按稳定度
226
+ * 排候选目录,取**第一个能建成**的:
227
+ * 1. `MDCG_CHILD_CWD`(显式覆盖)
228
+ * 2. `$DSH_HOME/.dsh-memory/run`
229
+ * 3. `~/.dsh/.dsh-memory/run` —— 家目录兜底:`DSH_HOME` **未必**由宿主注入
230
+ * (本仓 `dsh/dsh-web-start.bat` 是自行 `set DSH_HOME=%USERPROFILE%\.dsh`),
231
+ * 而 `~/.dsh` 是本插件既有约定(`bridge.ts` 调试日志、`token_store` 密钥环同址)
232
+ * 4. 系统临时目录(可能被清理,故排最后)
233
+ * 全部建不成时不抛错,交给 spawn 报错——cwd 落点只是防呆,不该成为启动失败源。
234
+ *
235
+ * 安全性:`python -m` 的模块解析由 `pythonPathValue()` 的 PYTHONPATH 独立保证,
236
+ * 不依赖 cwd;已实测 cwd=包目录 与 cwd=包外 时,MCP initialize 握手与
237
+ * tools/list 工具面(33 个工具)完全一致。
238
+ */
239
+ export function runRoot(): string {
240
+ if (cachedRunRoot) return cachedRunRoot
241
+ const candidates: string[] = []
242
+ const override = process.env[ENV_CHILD_CWD]
243
+ if (override) candidates.push(resolve(override))
244
+ const dshHome = process.env['DSH_HOME']
245
+ if (dshHome) candidates.push(join(resolve(dshHome), '.dsh-memory', 'run'))
246
+ candidates.push(join(homedir(), '.dsh', '.dsh-memory', 'run'))
247
+ candidates.push(join(tmpdir(), 'dsh-memory-run'))
248
+ for (const dir of candidates) {
249
+ try {
250
+ mkdirSync(dir, { recursive: true })
251
+ cachedRunRoot = dir
252
+ return dir
253
+ } catch {
254
+ /* 该候选不可用(父目录只读等)→ 试下一个 */
255
+ }
256
+ }
257
+ const last = candidates[candidates.length - 1] ?? tmpdir()
258
+ cachedRunRoot = last
259
+ return last
68
260
  }
69
261
 
70
262
  /** 数据根(记忆/账本/运行态的父目录)。 */
@@ -110,18 +302,24 @@ export function describeDataPaths(configured?: string): Record<string, string |
110
302
  const dr = dataRoot()
111
303
  const mr = mdcgRoot(configured)
112
304
  const paths = readUserPaths()
113
- let source = 'default(插件仓自身 data/)'
305
+ const pfSource = pathsFileSource()
306
+ let source = 'default(用户级状态根 data/)'
114
307
  if (process.env[ENV_DATA_ROOT]) source = `env:${ENV_DATA_ROOT}`
115
308
  else if (process.env[ENV_MDCG_ROOT]) source = `env:${ENV_MDCG_ROOT}`
116
- else if (typeof paths['data_root'] === 'string' || typeof paths['root'] === 'string') source = 'paths.json'
117
- else if (configured && configured.trim()) source = 'config.mdcg.root'
309
+ else if (typeof paths['data_root'] === 'string' || typeof paths['root'] === 'string') {
310
+ source = pfSource === 'user' ? 'paths.json(用户级)' : 'paths.json(兼容读旧包内位置)'
311
+ } else if (configured && configured.trim()) source = 'config.mdcg.root'
118
312
  return {
119
313
  repoRoot: repoRoot(),
314
+ stateRoot: stateRoot(),
120
315
  dataRoot: dr,
121
316
  mdcgRoot: mr,
122
317
  source,
123
318
  pathsFile: pathsFile(),
124
- isDefault: dr === defaultDataRoot(),
319
+ pathsFileSource: pfSource,
320
+ isDefault: samePath(dr, defaultDataRoot()),
321
+ legacyDataRoot: legacyDataRoot(),
322
+ legacyDataExists: existsSync(legacyDataRoot()),
125
323
  dataRootExists: existsSync(dr),
126
324
  mdcgRootExists: existsSync(mr),
127
325
  }
@@ -37,7 +37,7 @@
37
37
 
38
38
  import { delimiter } from 'node:path'
39
39
  import { LingshuBridge, type McpCallResult } from '../bridge.js'
40
- import { pythonPathValue, repoRoot } from './datapath.js'
40
+ import { pythonPathValue, runRoot } from './datapath.js'
41
41
 
42
42
  /** md_cg 子进程与根目录配置。 */
43
43
  export interface MdcgOptions {
@@ -47,9 +47,12 @@ export interface MdcgOptions {
47
47
  args?: string[]
48
48
  /** 认知图根目录(MDCG_ROOT)。 */
49
49
  root: string
50
- /** Python 子进程工作目录,默认**插件仓根**(issue #12:Python 只把 cwd
51
- * 注入 sys.path,宿主在插件仓外启动时 `python -m md_cg.mcp_server`
52
- * 找不到随包 md_cg → 必然 ModuleNotFoundError → 静默降级只读 guest)。 */
50
+ /** Python 子进程工作目录,默认 `runRoot()`——**插件包目录之外**的稳定目录
51
+ * (issue #18:Windows 不允许删除/改名「正被某进程当作 cwd」的目录,
52
+ * cwd 落在包内会让 pnpm 更新本包必然 `ERR_PNPM_EBUSY` 且永不自愈)。
53
+ * 模块解析**不依赖 cwd**:`python -m` 靠 `PYTHONPATH`
54
+ * (见 `pythonPathValue()`)解析随包 md_cg,issue #12 口径不变。
55
+ * 显式传入本项时完全尊重原值。 */
53
56
  cwd?: string
54
57
  /** 调用主体标识(MDCG_ACTOR)。私有内容按 (tenant, actor) 派生 DEK,
55
58
  * 故与迁移脚本 --actor 必须一致,否则读不到已迁移节点。 */
@@ -75,6 +78,56 @@ export interface MdcgOptions {
75
78
 
76
79
  const DEFAULT_ARGS = ['-m', 'md_cg.mcp_server']
77
80
 
81
+ /** 子进程环境构造参数(`MdcgOptions` 中与环境相关的那半)。 */
82
+ export interface MdcgChildEnvOptions {
83
+ root: string
84
+ surface?: 'kernel' | 'full'
85
+ tenant?: string
86
+ clearance?: string
87
+ actor?: string
88
+ identity?: string
89
+ env?: Record<string, string>
90
+ }
91
+
92
+ /**
93
+ * MCP 子进程环境:**唯一构造点**(导出即为了让机械守卫能断言它——
94
+ * 见 `test/python-utf8-mode.test.ts`)。勿在别处另拼 env。
95
+ *
96
+ * ⚠️ 两条编码注入是**硬约束**,不是可选项:
97
+ *
98
+ * ① `PYTHONIOENCODING=utf-8`(子进程**自身** stdio):Windows 下 piped 子进程默认
99
+ * gbk + surrogateescape,Node 写出的 UTF-8 中文会被解成孤立代理字符(\udcXX),
100
+ * md_cg 在落盘 / 回写 stdout 时抛 UnicodeEncodeError——中文记忆(主场景)全失败。
101
+ *
102
+ * ② `PYTHONUTF8=1`(子进程**后代**的默认 text 编码,PEP 540):`PYTHONIOENCODING`
103
+ * 会被后代继承(后代于是往管道写 UTF-8),但**文本解码口径不被继承**——后代读
104
+ * `subprocess.run(..., text=True)` 时取的是 locale(本机 cp936),于是
105
+ * 「子进程写 UTF-8、父进程按 gbk 读」→ 读线程崩死、诊断静默丢失。
106
+ * 2026-09-20 实证现场(`npm test` 周期复现,来源为子进程的后代代码单元):
107
+ * Exception in thread Thread-N (_readerthread):
108
+ * UnicodeDecodeError: 'gbk' codec can't decode byte 0x82 in position 181
109
+ * UTF-8 模式把默认 text 编码改为 UTF-8,读写两侧同口径(且解码结果正确,
110
+ * 而非 `errors="replace"` 那种替换字符)。
111
+ *
112
+ * 确定性对照实验(P1 复现 / P3 消除)见 `test/python-utf8-mode.test.ts`。
113
+ * `opts.env` 最后展开——显式覆盖优先。
114
+ */
115
+ export function mdcgChildEnv(opts: MdcgChildEnvOptions): Record<string, string> {
116
+ return {
117
+ PYTHONIOENCODING: 'utf-8',
118
+ PYTHONUTF8: '1',
119
+ MDCG_ROOT: opts.root,
120
+ // 工具面必须是 full:写入通道 mdcg_remember 属细粒度工具(见 MdcgOptions.surface)。
121
+ MDCG_MCP_SURFACE: opts.surface ?? 'full',
122
+ MDCG_TENANT: opts.tenant ?? 'default',
123
+ MDCG_CLEARANCE: opts.clearance ?? 'private',
124
+ PYTHONPATH: pythonPathValue(),
125
+ ...(opts.actor ? { MDCG_ACTOR: opts.actor } : {}),
126
+ ...(opts.identity ? { MDCG_IDENTITY: opts.identity } : {}),
127
+ ...(opts.env ?? {}),
128
+ }
129
+ }
130
+
78
131
  /** 认知图依据强度:这些 basis 视为「强依据」,可支撑 pass。
79
132
  * 取值须在 md_cg.mdcg.VERIFICATION_BASIS 允许集内:
80
133
  * compiler | test | measurement | formal_proof | data | other(other 不算强依据)。 */
@@ -122,27 +175,13 @@ export class MdcgClient {
122
175
  readonly bridge: LingshuBridge
123
176
 
124
177
  constructor(opts: MdcgOptions) {
125
- // issue #12:cwd 与 PYTHONPATH 双保险锚定插件仓根——cwd 是 `python -m`
126
- // 解析随包包的主通道,PYTHONPATH 覆盖显式自定义 args 的场景。opts.env
127
- // 显式提供 PYTHONPATH 时完全接管(其展开在最后:显式配置原样尊重)。
128
- const cwd = opts.cwd ?? repoRoot()
129
- const env: Record<string, string> = {
130
- // ⚠️ 必须显式 utf-8:Windows 下 piped 子进程默认 gbk + surrogateescape,
131
- // Node 写出的 UTF-8 中文会被解成孤立代理字符(\udcXX),md_cg 在落盘 /
132
- // 回写 stdout 时抛 UnicodeEncodeError —— 中文记忆(本插件的主场景)全部失败。
133
- // md_cg 自带测试(test_p2_mcp.py)与 test/bridge.test.ts 均以
134
- // PYTHONIOENCODING=utf-8 启动子进程,此处对齐该约定;opts.env 可覆盖。
135
- PYTHONIOENCODING: 'utf-8',
136
- MDCG_ROOT: opts.root,
137
- // 工具面必须是 full:写入通道 mdcg_remember 属细粒度工具(见 MdcgOptions.surface)。
138
- MDCG_MCP_SURFACE: opts.surface ?? 'full',
139
- MDCG_TENANT: opts.tenant ?? 'default',
140
- MDCG_CLEARANCE: opts.clearance ?? 'private',
141
- PYTHONPATH: pythonPathValue(),
142
- ...(opts.actor ? { MDCG_ACTOR: opts.actor } : {}),
143
- ...(opts.identity ? { MDCG_IDENTITY: opts.identity } : {}),
144
- ...(opts.env ?? {}),
145
- }
178
+ // 子进程 cwd 必须落在插件包目录之外,否则 pnpm 更新本插件时
179
+ // rmdir 包目录会撞上 Windows 的「目录被当作 CWD」共享冲突 → ERR_PNPM_EBUSY。
180
+ // 模块解析不依赖 cwd:PYTHONPATH(pythonPathValue())已锚定随包 md_cg;
181
+ // opts.env 显式提供 PYTHONPATH 时完全接管(其展开在最后)。详见 datapath.runRoot()。
182
+ const cwd = opts.cwd ?? runRoot()
183
+ // 编码与模块解析口径见 mdcgChildEnv() 头注(含 2026-09-20 读线程崩溃现场)。
184
+ const env = mdcgChildEnv(opts)
146
185
  this.bridge = new LingshuBridge({
147
186
  python: opts.python,
148
187
  args: opts.args ?? DEFAULT_ARGS,