lingshu-skill 5.33.0 → 5.37.0

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 (266) hide show
  1. package/CHANGELOG.md +4281 -4227
  2. package/README.md +1584 -1577
  3. package/SKILL-lite.md +59 -59
  4. package/SKILL-tiny.md +38 -38
  5. package/SKILL.md +356 -331
  6. package/assets/panel.html +6753 -5698
  7. package/cordis-plugin/lingshu-cron/plugin.js +1455 -1417
  8. package/cordis-plugin/lingshu-startup/context-fold.js +170 -0
  9. package/cordis-plugin/lingshu-startup/context-pressure.js +16 -0
  10. package/cordis-plugin/lingshu-startup/context-snapshot.js +176 -0
  11. package/cordis-plugin/lingshu-startup/plugin.js +499 -467
  12. package/docs/audit_notes//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
  13. package/docs/audit_notes//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
  14. package/docs/audit_notes//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
  15. package/docs/commands.md +278 -247
  16. package/docs/mechanics.md +610 -610
  17. package/docs//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
  18. package/docs//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
  19. package/package.json +52 -52
  20. package/scripts/_scratch/_tmp_backup_race.py +70 -0
  21. package/scripts/_scratch/_tmp_cleanup_move.py +34 -0
  22. package/scripts/_scratch/_tmp_count_kinds.py +25 -0
  23. package/scripts/_scratch/_tmp_diag_paths.py +48 -0
  24. package/scripts/_scratch/_tmp_facts.py +63 -0
  25. package/scripts/_scratch/_tmp_find_copies.py +31 -0
  26. package/scripts/_scratch/_tmp_find_pin.py +29 -0
  27. package/scripts/_scratch/_tmp_fix_pin.py +36 -0
  28. package/scripts/_scratch/_tmp_fold_fixture.py +55 -0
  29. package/scripts/_scratch/_tmp_fold_test.mjs +81 -0
  30. package/scripts/_scratch/_tmp_inject_secs.py +30 -0
  31. package/scripts/_scratch/_tmp_kb_balance.py +159 -0
  32. package/scripts/_scratch/_tmp_lines.py +15 -0
  33. package/scripts/_scratch/_tmp_market_probe.py +13 -0
  34. package/scripts/_scratch/_tmp_move_partial.py +16 -0
  35. package/scripts/_scratch/_tmp_patch_b3.py +41 -0
  36. package/scripts/_scratch/_tmp_patch_b5.py +62 -0
  37. package/scripts/_scratch/_tmp_patch_crash_excl.py +24 -0
  38. package/scripts/_scratch/_tmp_patch_handoff.py +21 -0
  39. package/scripts/_scratch/_tmp_patch_ps1.py +25 -0
  40. package/scripts/_scratch/_tmp_patch_stat.py +27 -0
  41. package/scripts/_scratch/_tmp_patch_todo.py +25 -0
  42. package/scripts/_scratch/_tmp_patch_todo2.py +64 -0
  43. package/scripts/_scratch/_tmp_probe_session.py +51 -0
  44. package/scripts/_scratch/_tmp_style_probe.py +40 -0
  45. package/scripts/_scratch/_tmp_write_note.py +139 -0
  46. package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +1 -0
  47. package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +1044 -0
  48. package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +194 -0
  49. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +175 -0
  50. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +97 -0
  51. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +47 -0
  52. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +40 -0
  53. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +37 -0
  54. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +9 -0
  55. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +36 -0
  56. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +10 -0
  57. package/scripts/_scratch/commit_msg_occ.txt +16 -0
  58. package/scripts/_scratch/commit_msg_struct.txt +16 -0
  59. package/scripts/_scratch/v5.34_changelog.txt +36 -0
  60. package/scripts/_sync_trae_cn.py +102 -34
  61. package/scripts/_tmp_add_s10.py +54 -0
  62. package/scripts/_tmp_add_s11.py +61 -0
  63. package/scripts/_tmp_add_s12.py +66 -0
  64. package/scripts/_tmp_add_s13.py +69 -0
  65. package/scripts/_tmp_add_s14.py +80 -0
  66. package/scripts/_tmp_add_s9.py +68 -0
  67. package/scripts/_tmp_cache_load.py +82 -0
  68. package/scripts/_tmp_clean_market.py +40 -0
  69. package/scripts/_tmp_clean_pruned.py +81 -0
  70. package/scripts/_tmp_cleanup_docs.py +39 -0
  71. package/scripts/_tmp_cmp_ranker.py +17 -0
  72. package/scripts/_tmp_dolater_note.py +35 -0
  73. package/scripts/_tmp_dust_why.py +27 -0
  74. package/scripts/_tmp_explicit_import.py +40 -0
  75. package/scripts/_tmp_extract_compaction.py +35 -0
  76. package/scripts/_tmp_extract_compaction2.py +63 -0
  77. package/scripts/_tmp_extract_compaction3.py +51 -0
  78. package/scripts/_tmp_extract_compaction4.py +54 -0
  79. package/scripts/_tmp_finalize_s14.py +39 -0
  80. package/scripts/_tmp_find_compaction.py +43 -0
  81. package/scripts/_tmp_fix_b4.py +22 -0
  82. package/scripts/_tmp_fix_cli76.py +26 -0
  83. package/scripts/_tmp_fix_docs.py +38 -0
  84. package/scripts/_tmp_fix_docs_b.py +46 -0
  85. package/scripts/_tmp_fix_docs_b2.py +22 -0
  86. package/scripts/_tmp_fix_i3.py +23 -0
  87. package/scripts/_tmp_fix_s10.py +83 -0
  88. package/scripts/_tmp_fix_s11.py +14 -0
  89. package/scripts/_tmp_fix_s9_status.py +19 -0
  90. package/scripts/_tmp_fix_shadow_sim.py +37 -0
  91. package/scripts/_tmp_fix_traits_value.py +41 -0
  92. package/scripts/_tmp_import_idem.py +106 -0
  93. package/scripts/_tmp_log_ack.py +45 -0
  94. package/scripts/_tmp_mark_batch.py +28 -0
  95. package/scripts/_tmp_mark_batch2.py +32 -0
  96. package/scripts/_tmp_mark_dolater.py +26 -0
  97. package/scripts/_tmp_mark_dolater2.py +31 -0
  98. package/scripts/_tmp_move_self.py +16 -0
  99. package/scripts/_tmp_occ_cli.py +22 -0
  100. package/scripts/_tmp_occ_link.py +108 -0
  101. package/scripts/_tmp_optimize_recall.py +54 -0
  102. package/scripts/_tmp_panel_audit.py +26 -0
  103. package/scripts/_tmp_patch_batch3.py +65 -0
  104. package/scripts/_tmp_patch_rrf.py +46 -0
  105. package/scripts/_tmp_patch_s2s3.py +80 -0
  106. package/scripts/_tmp_patch_s4.py +39 -0
  107. package/scripts/_tmp_patch_s7.py +43 -0
  108. package/scripts/_tmp_patch_s8.py +91 -0
  109. package/scripts/_tmp_patch_skill.py +17 -0
  110. package/scripts/_tmp_release_guard.py +57 -0
  111. package/scripts/_tmp_rerank_breaker.py +62 -0
  112. package/scripts/_tmp_s16.py +41 -0
  113. package/scripts/_tmp_scan_asar.py +41 -0
  114. package/scripts/_tmp_scan_asar2.py +37 -0
  115. package/scripts/_tmp_struct_docs.py +49 -0
  116. package/scripts/_tmp_sum_fallback.py +42 -0
  117. package/scripts/_tmp_sweep.py +81 -0
  118. package/scripts/_tmp_sync_check.py +69 -0
  119. package/scripts/_tmp_sync_tail.py +39 -0
  120. package/scripts/_tmp_todo_clean.py +67 -0
  121. package/scripts/_tmp_verify_copy.py +17 -0
  122. package/scripts/_tmp_wire_extras.py +93 -0
  123. package/scripts/_tmp_wire_hsum.py +34 -0
  124. package/scripts/_tmp_wire_occ_b5.py +40 -0
  125. package/scripts/_tmp_wire_ranker.py +13 -0
  126. package/scripts/_tmp_wire_shadow_timeline.py +45 -0
  127. package/scripts/anchor_retention.py +68 -0
  128. package/scripts/app_context.py +1160 -0
  129. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +38 -22
  130. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +4281 -4227
  131. package/scripts/astrbot_plugin_lingshu/engine/README.md +1584 -1577
  132. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
  133. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
  134. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +356 -331
  135. package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +6753 -5698
  136. package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +278 -247
  137. package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -610
  138. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +102 -34
  139. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +54 -0
  140. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +61 -0
  141. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +66 -0
  142. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +69 -0
  143. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +80 -0
  144. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +68 -0
  145. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +82 -0
  146. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +40 -0
  147. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +81 -0
  148. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +39 -0
  149. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +17 -0
  150. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +35 -0
  151. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +27 -0
  152. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +40 -0
  153. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +35 -0
  154. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +63 -0
  155. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +51 -0
  156. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +54 -0
  157. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +39 -0
  158. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +43 -0
  159. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +22 -0
  160. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +26 -0
  161. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +38 -0
  162. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +46 -0
  163. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +22 -0
  164. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +23 -0
  165. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +83 -0
  166. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +14 -0
  167. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +19 -0
  168. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +37 -0
  169. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +41 -0
  170. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +106 -0
  171. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +45 -0
  172. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +28 -0
  173. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +32 -0
  174. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +26 -0
  175. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +31 -0
  176. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +16 -0
  177. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +22 -0
  178. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +108 -0
  179. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +54 -0
  180. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +26 -0
  181. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +65 -0
  182. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +46 -0
  183. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +80 -0
  184. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +39 -0
  185. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +43 -0
  186. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +91 -0
  187. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +17 -0
  188. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +57 -0
  189. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +62 -0
  190. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +41 -0
  191. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +41 -0
  192. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +37 -0
  193. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +49 -0
  194. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +42 -0
  195. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +81 -0
  196. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +69 -0
  197. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +39 -0
  198. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +67 -0
  199. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +17 -0
  200. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +93 -0
  201. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +34 -0
  202. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +40 -0
  203. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +13 -0
  204. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +45 -0
  205. package/scripts/astrbot_plugin_lingshu/engine/scripts/anchor_retention.py +68 -0
  206. package/scripts/astrbot_plugin_lingshu/engine/scripts/app_context.py +1160 -0
  207. package/scripts/astrbot_plugin_lingshu/engine/scripts/bigfive.py +90 -0
  208. package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +1 -1
  209. package/scripts/astrbot_plugin_lingshu/engine/scripts/check_docs.py +191 -0
  210. package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +921 -86
  211. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2468 -2406
  212. package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +5 -0
  213. package/scripts/astrbot_plugin_lingshu/engine/scripts/delivery.py +112 -0
  214. package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +41 -3
  215. package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +202 -23
  216. package/scripts/astrbot_plugin_lingshu/engine/scripts/gap_memory.py +186 -0
  217. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +72 -8
  218. package/scripts/astrbot_plugin_lingshu/engine/scripts/hsum.py +206 -0
  219. package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +92 -7
  220. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +530 -60
  221. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory_extras.py +200 -0
  222. package/scripts/astrbot_plugin_lingshu/engine/scripts/occ.py +190 -0
  223. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +232 -142
  224. package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2498 -2349
  225. package/scripts/astrbot_plugin_lingshu/engine/scripts/prepublish_tests.py +90 -0
  226. package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +326 -287
  227. package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +181 -0
  228. package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +832 -764
  229. package/scripts/astrbot_plugin_lingshu/engine/scripts/shadow_memory.py +173 -0
  230. package/scripts/astrbot_plugin_lingshu/engine/scripts/style_check.py +220 -0
  231. package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +343 -252
  232. package/scripts/astrbot_plugin_lingshu/engine/scripts/timeline.py +118 -0
  233. package/scripts/astrbot_plugin_lingshu/engine/scripts/watchdog.py +110 -0
  234. package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +125 -0
  235. package/scripts/bigfive.py +90 -0
  236. package/scripts/brain.py +1 -1
  237. package/scripts/check_docs.py +191 -0
  238. package/scripts/cli.py +921 -86
  239. package/scripts/core.py +2468 -2406
  240. package/scripts/coverage_report.py +5 -0
  241. package/scripts/delivery.py +112 -0
  242. package/scripts/dream.py +41 -3
  243. package/scripts/emotion.py +202 -23
  244. package/scripts/gap_memory.py +186 -0
  245. package/scripts/growth.py +72 -8
  246. package/scripts/hsum.py +206 -0
  247. package/scripts/mem_score.py +92 -7
  248. package/scripts/memory.py +530 -60
  249. package/scripts/memory_extras.py +200 -0
  250. package/scripts/occ.py +190 -0
  251. package/scripts/panel_server.py +232 -142
  252. package/scripts/persona.py +2498 -2349
  253. package/scripts/prepublish_tests.py +90 -0
  254. package/scripts/release.py +326 -287
  255. package/scripts/rss_ingest.py +181 -0
  256. package/scripts/run_tests.py +13 -0
  257. package/scripts/session_import.py +832 -764
  258. package/scripts/shadow_memory.py +173 -0
  259. package/scripts/style_check.py +220 -0
  260. package/scripts/summarizer.py +343 -252
  261. package/scripts/timeline.py +118 -0
  262. package/scripts/update_dsh_copy.ps1 +110 -107
  263. package/scripts/watchdog.py +110 -0
  264. package/scripts/web_research.py +125 -0
  265. package/docs//344/272/244/346/216/245/347/254/224/350/256/260-20261128.md +0 -128
  266. package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -408
@@ -1,764 +1,832 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """附录 B · P1:DSH 会话日志导入(多平台入口 + 工作区隔离)。
4
-
5
- DSH 把一场会话写成:
6
- <sessions>/<工作区编码目录>/<会话目录>/session.v4.jsonl.zstd
7
-
8
- 其中有三个必须处理的现实约束:
9
- 1. 文件是**多帧拼接**的 zstd 容器:每行/每批事件一个独立帧。Node 的
10
- `zlib.zstdDecompressSync` 一次只解第一帧,直接解整个文件只会拿到
11
- 313 字节的 header(本机实测)。所以 Node 侧先做「帧结构扫描」再逐帧解压
12
- (与 DSH 自己 `scanZstdFrames` 的结构扫描逻辑等价),把明文流式写进临时文件。
13
- 2. 本机系统 Python **没有 zstandard 模块**,因此不把 Python 当解码器。
14
- 3. 会话事件是 `{"type": "...", "time": 毫秒, "data": {...}}`:
15
- 只导入 `user/message` / `assistant/message` 里的 text 片段(role/content/ts),
16
- `reasoning`、`tool-call`、`tool/result`、`system/message`、`command/*` 等
17
- 非对话条目一律跳过;`user/message` 里 `source.kind` 不是 `user` 的注入块
18
- (runtime-context / system-reminder)也算系统事件,跳过。
19
-
20
- 解码优先级(都不静默降级):
21
- Node 22+(先探测 `node -e "require('node:zlib').zstdDecompressSync"`)
22
- → 系统 `zstd -d` 命令
23
- → 抛 DecoderUnavailable(「需要 Node 22+ 或 zstd 命令」)。
24
-
25
- 导入:`session_rag.ingest_messages(rows, session=会话id, platform="dsh",
26
- workspace=工作区)`,按内容哈希幂等;解压后的临时文件逐行流式解析,每 500 条
27
- 批量入库,内存不随文件大小增长(8MB 压缩 / 1 万条事件级别实测可用)。
28
-
29
- CLI:
30
- python scripts/session_import.py [--sessions-dir PATH] [--limit N]
31
- [--workspace 名称] [--dry-run] [--json]
32
- """
33
- from __future__ import annotations
34
-
35
- import argparse
36
- import json
37
- import os
38
- import re
39
- import shutil
40
- import subprocess
41
- import sys
42
- import tempfile
43
- import time
44
- from dataclasses import dataclass
45
- from pathlib import Path
46
-
47
- HERE = Path(__file__).resolve().parent
48
- if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
49
- sys.path.insert(0, str(HERE))
50
-
51
- import session_rag # noqa: E402
52
-
53
- PLATFORM = "dsh"
54
- BATCH_SIZE = 500
55
- DEFAULT_TIMEOUT = 600.0 # 单文件解码的最长等待(秒)
56
-
57
- # 只认 DSH 会话日志:session.v4.jsonl.zstd / session.jsonl / 未来版本号
58
- _SESSION_LOG_RE = re.compile(r"^session(?:\.v\d+)?\.jsonl(\.zstd)?$", re.IGNORECASE)
59
-
60
- _NODE_PROBE = (
61
- "process.exit(typeof require('node:zlib').zstdDecompressSync === 'function' ? 0 : 1)"
62
- )
63
- _NODE_VERSION = "process.stdout.write(process.version)"
64
-
65
- # 多帧 zstd 解码器(Node 22+)。先做与 DSH 相同的帧结构扫描,再逐帧解压并
66
- # 立刻写盘 —— 不把整份明文同时留在内存里。
67
- _NODE_DECODE_JS = r"""
68
- const fs = require('node:fs')
69
- const zlib = require('node:zlib')
70
- const src = process.argv[2]
71
- const dst = process.argv[3]
72
- const MAGIC = 0xFD2FB528
73
- const buf = fs.readFileSync(src)
74
-
75
- // 返回完整帧的结束偏移;遇到文件尾部的不完整帧返回 -1(live 会话正在追加)。
76
- function frameEnd(buffer, start) {
77
- if (buffer.length - start < 4) return -1
78
- if (buffer.readUInt32LE(start) !== MAGIC) {
79
- throw new Error('corrupt Zstandard session log: invalid frame magic at byte ' + start)
80
- }
81
- let off = start + 4
82
- if (off === buffer.length) return -1
83
- const descriptor = buffer.readUInt8(off)
84
- off += 1
85
- if ((descriptor & 0x18) !== 0) {
86
- throw new Error('corrupt Zstandard session log: reserved frame-header bit at byte ' + (off - 1))
87
- }
88
- const contentSizeFlag = descriptor >>> 6
89
- const singleSegment = (descriptor & 0x20) !== 0
90
- const checksum = (descriptor & 0x04) !== 0
91
- const dictionaryFlag = descriptor & 0x03
92
- const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
93
- const contentSizeBytes = contentSizeFlag === 0
94
- ? (singleSegment ? 1 : 0)
95
- : (1 << contentSizeFlag)
96
- const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
97
- if (buffer.length - off < remainingHeaderBytes) return -1
98
- off += remainingHeaderBytes
99
- for (;;) {
100
- if (buffer.length - off < 3) return -1
101
- const blockHeader = buffer.readUIntLE(off, 3)
102
- off += 3
103
- const lastBlock = (blockHeader & 1) !== 0
104
- const blockType = (blockHeader >>> 1) & 0x03
105
- const blockSize = blockHeader >>> 3
106
- if (blockType === 0x03) {
107
- throw new Error('corrupt Zstandard session log: reserved block type at byte ' + (off - 3))
108
- }
109
- const payloadBytes = blockType === 0x01 ? 1 : blockSize
110
- if (buffer.length - off < payloadBytes) return -1
111
- off += payloadBytes
112
- if (lastBlock) break
113
- }
114
- if (checksum) {
115
- if (buffer.length - off < 4) return -1
116
- off += 4
117
- }
118
- return off
119
- }
120
-
121
- const fd = fs.openSync(dst, 'w')
122
- let frames = 0
123
- let plainBytes = 0
124
- let tornBytes = 0
125
- let offset = 0
126
- try {
127
- while (offset < buf.length) {
128
- const end = frameEnd(buf, offset)
129
- if (end < 0) {
130
- tornBytes = buf.length - offset
131
- break
132
- }
133
- const plain = zlib.zstdDecompressSync(buf.subarray(offset, end))
134
- fs.writeSync(fd, plain)
135
- plainBytes += plain.length
136
- frames += 1
137
- offset = end
138
- }
139
- } finally {
140
- fs.closeSync(fd)
141
- }
142
- process.stdout.write(JSON.stringify({
143
- frames: frames,
144
- plainBytes: plainBytes,
145
- tornBytes: tornBytes,
146
- compressedBytes: buf.length,
147
- }))
148
- """
149
-
150
-
151
- class DecoderUnavailable(RuntimeError):
152
- """本机既没有可解 zstd 的 Node(22+),也没有 zstd 命令。"""
153
-
154
-
155
- @dataclass(frozen=True)
156
- class Decoder:
157
- """已探测通过的 zstd 解码后端。"""
158
-
159
- backend: str # "node" | "zstd"
160
- exe: str
161
- version: str = ""
162
-
163
-
164
- @dataclass(frozen=True)
165
- class SessionLog:
166
- """一个待导入的 DSH 会话日志文件。"""
167
-
168
- path: Path
169
- workspace_dir: str # sessions/<工作区编码目录>/
170
- session_dir: str # sessions/<工作区编码目录>/<会话目录>/
171
- compressed: bool
172
-
173
-
174
- def default_sessions_dir() -> Path:
175
- """DSH 会话根目录:默认 ``~/.dsh/sessions``(尊重 DSH_HOME 自定义安装)。"""
176
- env_home = str(os.environ.get("DSH_HOME") or "").strip()
177
- base = Path(env_home) if env_home else (Path.home() / ".dsh")
178
- return base / "sessions"
179
-
180
-
181
- # ---------------------------------------------------------------- 解码器探测
182
-
183
- def _run_quiet(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
184
- return subprocess.run(cmd, capture_output=True, **kwargs)
185
-
186
-
187
- def _node_has_zstd(exe: str, timeout: float = 20.0) -> bool:
188
- """探测指定的 node 是否带 node:zlib zstd(Node 22+ / 23.8+ 才有)。"""
189
- try:
190
- rep = _run_quiet([exe, "-e", _NODE_PROBE], timeout=timeout)
191
- except (OSError, subprocess.SubprocessError):
192
- return False
193
- return rep.returncode == 0
194
-
195
-
196
- def _node_version(exe: str) -> str:
197
- try:
198
- rep = _run_quiet([exe, "-e", _NODE_VERSION], timeout=20.0)
199
- except (OSError, subprocess.SubprocessError):
200
- return ""
201
- if rep.returncode != 0:
202
- return ""
203
- return rep.stdout.decode("utf-8", "replace").strip()
204
-
205
-
206
- def _dsh_runtime_node_candidates() -> list[str]:
207
- """DSH 自带的 Node 运行时(PATH 上没有 node 或不支持 zstd 时兜底)。"""
208
- roots: list[Path] = []
209
- env_home = str(os.environ.get("DSH_HOME") or "").strip()
210
- if env_home:
211
- roots.append(Path(env_home))
212
- roots.append(Path.home() / ".dsh")
213
- out: list[str] = []
214
- seen: set[str] = set()
215
- for root in roots:
216
- try:
217
- runtimes = sorted((root / "dsh-runtimes").glob("*/dependencies/node/bin"))
218
- except OSError:
219
- continue
220
- for bindir in runtimes:
221
- for name in ("node.exe", "node"):
222
- cand = bindir / name
223
- key = os.path.normcase(str(cand))
224
- if key in seen:
225
- continue
226
- seen.add(key)
227
- if cand.is_file():
228
- out.append(str(cand))
229
- return out
230
-
231
-
232
- def find_node_exe() -> str | None:
233
- """返回第一个「node 能解 zstd」的可执行文件;没有则 None。
234
-
235
- 查找顺序:LINGSHU_NODE 环境变量 → PATH 上的 node → DSH 自带运行时。
236
- 每个候选都真跑一次 ``node -e`` 探测,不只看版本号猜。
237
- """
238
- candidates: list[str] = []
239
- env_node = str(os.environ.get("LINGSHU_NODE") or "").strip()
240
- if env_node:
241
- candidates.append(env_node)
242
- for name in ("node", "node.exe"):
243
- found = shutil.which(name)
244
- if found:
245
- candidates.append(found)
246
- candidates.extend(_dsh_runtime_node_candidates())
247
- seen: set[str] = set()
248
- for cand in candidates:
249
- key = os.path.normcase(str(cand))
250
- if not key or key in seen:
251
- continue
252
- seen.add(key)
253
- if _node_has_zstd(str(cand)):
254
- return str(cand)
255
- return None
256
-
257
-
258
- def find_zstd_exe() -> str | None:
259
- """系统 zstd CLI(次选解码器)。没有则 None。"""
260
- for name in ("zstd", "zstd.exe"):
261
- found = shutil.which(name)
262
- if found:
263
- return found
264
- return None
265
-
266
-
267
- def detect_decoder(*, node_exe: str | None = None) -> Decoder:
268
- """确定 zstd 解码后端;两者都没有时抛 DecoderUnavailable(绝不静默)。"""
269
- if node_exe:
270
- if not _node_has_zstd(str(node_exe)):
271
- raise DecoderUnavailable(
272
- f"指定的 Node 不支持 node:zlib zstd:{node_exe}(需要 Node 22+)")
273
- return Decoder("node", str(node_exe), _node_version(str(node_exe)))
274
- node = find_node_exe()
275
- if node:
276
- return Decoder("node", node, _node_version(node))
277
- zstd = find_zstd_exe()
278
- if zstd:
279
- return Decoder("zstd", zstd, "")
280
- raise DecoderUnavailable(
281
- "需要 Node 22+ 或 zstd 命令:本机既没有能解 zstd 的 Node"
282
- "(node:zlib.zstdDecompressSync 探测失败,PATH 与 DSH 自带运行时都不行),"
283
- "也没有 zstd 命令。系统 Python 没有 zstandard 模块,安装 Node 22+ 或 "
284
- "zstd 后重试;不会静默跳过或假装导入成功。")
285
-
286
-
287
- # ---------------------------------------------------------------- 会话发现
288
-
289
- def discover_sessions(sessions_dir=None, *, limit: int | None = None) -> list[SessionLog]:
290
- """遍历 <sessions>/<工作区>/<会话>/session*.jsonl[.zstd],按修改时间倒序。"""
291
- root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
292
- if not root.is_dir():
293
- raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
294
- logs: list[SessionLog] = []
295
- try:
296
- projects = sorted(root.iterdir(), key=lambda p: p.name.lower())
297
- except OSError as exc:
298
- raise RuntimeError(f"无法读取会话目录 {root}:{exc}") from exc
299
- for project in projects:
300
- if not project.is_dir():
301
- continue
302
- try:
303
- sessions = sorted(project.iterdir(), key=lambda p: p.name.lower())
304
- except OSError:
305
- continue
306
- for sess in sessions:
307
- if not sess.is_dir():
308
- continue
309
- try:
310
- entries = sorted(sess.iterdir(), key=lambda p: p.name.lower())
311
- except OSError:
312
- continue
313
- for f in entries:
314
- match = _SESSION_LOG_RE.match(f.name)
315
- if not match or not f.is_file():
316
- continue
317
- logs.append(SessionLog(path=f, workspace_dir=project.name,
318
- session_dir=sess.name,
319
- compressed=bool(match.group(1))))
320
- logs.sort(key=lambda x: _mtime(x.path), reverse=True)
321
- if limit is not None and int(limit) > 0:
322
- logs = logs[: int(limit)]
323
- return logs
324
-
325
-
326
- def _mtime(path: Path) -> float:
327
- try:
328
- return path.stat().st_mtime
329
- except OSError:
330
- return 0.0
331
-
332
-
333
- # ---------------------------------------------------------------- zstd 解码
334
-
335
- def decode_session_file(src, dst, decoder: Decoder) -> dict:
336
- """把多帧 zstd 会话日志解成明文 JSONL,写进 dst 临时文件;返回解码元数据。
337
-
338
- 返回统一 snake_case 键:backend/exe/frames/plain_bytes/compressed_bytes/
339
- torn_bytes(torn_bytes = 文件尾部不完整的 live 帧字节数,已忽略)。
340
- """
341
- src = Path(src)
342
- dst = Path(dst)
343
- dst.parent.mkdir(parents=True, exist_ok=True)
344
- raw = _decode_with_node(src, dst, decoder.exe) if decoder.backend == "node" \
345
- else _decode_with_zstd_cli(src, dst, decoder.exe)
346
- meta = {
347
- "backend": str(raw.get("backend") or decoder.backend),
348
- "exe": str(raw.get("exe") or decoder.exe),
349
- "frames": raw.get("frames"),
350
- "plain_bytes": int(raw.get("plainBytes") if raw.get("plainBytes") is not None
351
- else raw.get("plain_bytes") or 0),
352
- "compressed_bytes": int(raw.get("compressedBytes")
353
- if raw.get("compressedBytes") is not None
354
- else raw.get("compressed_bytes") or 0),
355
- "torn_bytes": int(raw.get("tornBytes") if raw.get("tornBytes") is not None
356
- else raw.get("torn_bytes") or 0),
357
- }
358
- if raw.get("warning"):
359
- meta["warning"] = raw["warning"]
360
- return meta
361
-
362
-
363
- def _decode_with_node(src: Path, dst: Path, node_exe: str) -> dict:
364
- with tempfile.TemporaryDirectory(prefix="lingshu-zstd-js-") as td:
365
- script = Path(td) / "decode_session.js"
366
- script.write_text(_NODE_DECODE_JS, encoding="utf-8")
367
- try:
368
- rep = subprocess.run([node_exe, str(script), str(src), str(dst)],
369
- capture_output=True, timeout=DEFAULT_TIMEOUT)
370
- except subprocess.TimeoutExpired as exc:
371
- raise RuntimeError(f"Node 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
372
- except OSError as exc:
373
- raise RuntimeError(f"Node 启动失败({node_exe}):{exc}") from exc
374
- if rep.returncode != 0:
375
- err = rep.stderr.decode("utf-8", "replace").strip()
376
- raise RuntimeError(f"Node 解压失败({src}):{err[:500] or f'rc={rep.returncode}'}")
377
- try:
378
- meta = json.loads(rep.stdout.decode("utf-8", "replace") or "{}")
379
- except ValueError:
380
- meta = {}
381
- meta.setdefault("plainBytes", dst.stat().st_size if dst.exists() else 0)
382
- return meta
383
-
384
-
385
- def _decode_with_zstd_cli(src: Path, dst: Path, zstd_exe: str) -> dict:
386
- try:
387
- with open(dst, "wb") as out:
388
- rep = subprocess.run([zstd_exe, "-d", "-q", "-c", str(src)],
389
- stdout=out, stderr=subprocess.PIPE,
390
- timeout=DEFAULT_TIMEOUT)
391
- except subprocess.TimeoutExpired as exc:
392
- raise RuntimeError(f"zstd 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
393
- except OSError as exc:
394
- raise RuntimeError(f"zstd 启动失败({zstd_exe}):{exc}") from exc
395
- stderr = (rep.stderr or b"").decode("utf-8", "replace").strip()
396
- meta = {"frames": None, "torn_bytes": 0,
397
- "plain_bytes": dst.stat().st_size if dst.exists() else 0,
398
- "compressed_bytes": src.stat().st_size if src.exists() else 0}
399
- if rep.returncode != 0:
400
- # live 会话尾部可能是半帧:zstd CLI 会报错但仍吐出完整帧的明文。
401
- # 只在明文以换行结尾(最后一帧完整)时接受,否则当失败。
402
- tail = b""
403
- if dst.exists() and dst.stat().st_size:
404
- with open(dst, "rb") as fh:
405
- fh.seek(max(0, dst.stat().st_size - 1))
406
- tail = fh.read(1)
407
- if not tail.endswith(b"\n"):
408
- raise RuntimeError(f"zstd 解压失败({src}):{stderr[:500] or f'rc={rep.returncode}'}")
409
- meta["warning"] = f"zstd 返回码 {rep.returncode},已接受以换行结尾的部分输出:{stderr[:200]}"
410
- return meta
411
-
412
-
413
- # ---------------------------------------------------------------- JSONL 解析
414
-
415
- def read_session_header(jsonl_file) -> dict:
416
- """读解压后 JSONL 的第一条 ``{"type":"session"}``(格式保证是首行,最多扫 64 行)。"""
417
- try:
418
- with open(jsonl_file, "r", encoding="utf-8-sig", errors="replace") as fh:
419
- for _ in range(64):
420
- line = fh.readline()
421
- if not line:
422
- break
423
- line = line.strip()
424
- if not line:
425
- continue
426
- try:
427
- event = json.loads(line)
428
- except ValueError:
429
- continue
430
- if isinstance(event, dict) and event.get("type") == "session":
431
- return event
432
- except OSError:
433
- pass
434
- return {}
435
-
436
-
437
- def _text_fragments(content) -> str:
438
- """content 可能是字符串或 block 数组:只取 text 片段(跳过 reasoning/image/tool-*)。"""
439
- if isinstance(content, str):
440
- return content.strip()
441
- if not isinstance(content, list):
442
- return ""
443
- parts: list[str] = []
444
- for block in content:
445
- if isinstance(block, str):
446
- if block.strip():
447
- parts.append(block.strip())
448
- elif isinstance(block, dict) and block.get("type") == "text":
449
- text = block.get("text")
450
- if text is not None and str(text).strip():
451
- parts.append(str(text).strip())
452
- return "\n".join(parts)
453
-
454
-
455
- def _event_to_row(event: dict) -> dict | None:
456
- """把一条 DSH 会话事件转成 ingest 行;非对话事件(工具/推理/系统)返回 None。"""
457
- event_type = event.get("type")
458
- data = event.get("data")
459
- if not isinstance(data, dict):
460
- data = {}
461
- if event_type == "user/message":
462
- source = data.get("source")
463
- kind = str((source or {}).get("kind") or "") if isinstance(source, dict) else ""
464
- if kind and kind != "user":
465
- return None # runtime-context / system-reminder 等注入块不是用户发言
466
- text = _text_fragments(data.get("content"))
467
- role = "user"
468
- elif event_type == "assistant/message":
469
- message = data.get("message")
470
- if not isinstance(message, dict):
471
- message = {}
472
- text = _text_fragments(message.get("content"))
473
- role = "assistant"
474
- else:
475
- return None
476
- if not text:
477
- return None # 只有 reasoning / 只有 tool-call 的 assistant 轮次
478
- time_ms = event.get("time")
479
- ts = float(time_ms) / 1000.0 if isinstance(time_ms, (int, float)) else 0.0
480
- return {"role": role, "content": text, "ts": ts}
481
-
482
-
483
- # ---------------------------------------------------------------- 导入
484
-
485
- def _workspace_matches(want, workspace: str, workspace_dir: str) -> bool:
486
- """--workspace 匹配:精确路径 / basename / 原始工作区目录名,且允许子串。"""
487
- wanted = str(want or "").strip()
488
- if not wanted:
489
- return True
490
- low = wanted.lower().rstrip("\\/")
491
- names = {str(workspace or "").strip().lower().rstrip("\\/"),
492
- str(workspace_dir or "").strip().lower()}
493
- if workspace:
494
- names.add(Path(workspace).name.lower())
495
- if low in names:
496
- return True
497
- for name in names:
498
- if name and low in name:
499
- return True
500
- return False
501
-
502
-
503
- def import_session_file(log: SessionLog, *, decoder: Decoder, dry_run: bool = False,
504
- db=None, workspace_filter: str | None = None,
505
- batch_size: int = BATCH_SIZE) -> dict:
506
- """解压 → 解析 → 批量入库一个会话文件(解压后的明文只在临时目录存活)。"""
507
- report: dict = {
508
- "file": str(log.path),
509
- "workspace_dir": log.workspace_dir,
510
- "session_dir": log.session_dir,
511
- "compressed": log.compressed,
512
- "session": log.session_dir,
513
- "workspace": log.workspace_dir,
514
- "messages": 0,
515
- "added": 0,
516
- "skipped": 0,
517
- "bad_lines": 0,
518
- "workspace_matched": True,
519
- "torn_bytes": 0,
520
- }
521
- with tempfile.TemporaryDirectory(prefix="lingshu-session-decode-") as td:
522
- plain = Path(td) / "session.jsonl"
523
- if log.compressed:
524
- meta = decode_session_file(log.path, plain, decoder)
525
- else:
526
- shutil.copyfile(log.path, plain)
527
- meta = {"backend": "plain", "frames": None, "torn_bytes": 0,
528
- "plain_bytes": log.path.stat().st_size, "compressed_bytes": 0}
529
- report["decode"] = {
530
- "backend": meta.get("backend"),
531
- "frames": meta.get("frames"),
532
- "compressed_bytes": meta.get("compressed_bytes"),
533
- "plain_bytes": meta.get("plain_bytes"),
534
- }
535
- report["torn_bytes"] = int(meta.get("torn_bytes") or 0)
536
- if meta.get("warning"):
537
- report["warning"] = meta["warning"]
538
-
539
- header = read_session_header(plain)
540
- session_id = str(header.get("id") or "").strip() or log.session_dir
541
- workspace = str(header.get("cwd") or "").strip() or log.workspace_dir
542
- report["session"] = session_id
543
- report["workspace"] = workspace
544
- if not _workspace_matches(workspace_filter, workspace, log.workspace_dir):
545
- report["workspace_matched"] = False
546
- return report
547
-
548
- parsed = added = skipped = bad_lines = 0
549
- batch: list[dict] = []
550
-
551
- def flush() -> None:
552
- nonlocal added, skipped
553
- if not batch:
554
- return
555
- if not dry_run:
556
- rep = session_rag.ingest_messages(
557
- batch, session=session_id, platform=PLATFORM,
558
- workspace=workspace, path=db)
559
- added += int(rep.get("added") or 0)
560
- skipped += int(rep.get("skipped") or 0)
561
- batch.clear()
562
-
563
- with open(plain, "r", encoding="utf-8-sig", errors="replace") as fh:
564
- for line in fh:
565
- line = line.strip()
566
- if not line:
567
- continue
568
- try:
569
- event = json.loads(line)
570
- except ValueError:
571
- bad_lines += 1
572
- continue
573
- if not isinstance(event, dict):
574
- bad_lines += 1
575
- continue
576
- if event.get("type") == "session":
577
- continue # 首行 header,不是对话
578
- row = _event_to_row(event)
579
- if row is None:
580
- continue
581
- parsed += 1
582
- batch.append(row)
583
- if len(batch) >= max(1, int(batch_size)):
584
- flush()
585
- flush()
586
-
587
- report["messages"] = parsed
588
- report["bad_lines"] = bad_lines
589
- if not dry_run:
590
- report["added"] = added
591
- report["skipped"] = skipped
592
- else:
593
- report["dry_run"] = True
594
- return report
595
-
596
-
597
- def import_sessions(sessions_dir=None, *, limit: int | None = None,
598
- workspace: str | None = None, dry_run: bool = False,
599
- db=None, decoder: Decoder | None = None) -> dict:
600
- """遍历导入 DSH 会话目录;返回可 JSON 化的报告。
601
-
602
- ``limit`` 限制「最终导入的会话数」而不是「扫描的文件数」:工作区过滤在
603
- 解出会话 header 的 cwd 之后生效,过滤通过的按修改时间倒序取前 N 个。
604
- """
605
- started = time.time()
606
- root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
607
- if not root.is_dir():
608
- raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
609
- logs = discover_sessions(root)
610
- dec = decoder if decoder is not None else detect_decoder()
611
- max_sessions = int(limit) if limit is not None and int(limit) > 0 else None
612
- files: list[dict] = []
613
- totals = {"files": 0, "sessions": 0, "messages": 0, "added": 0, "skipped": 0,
614
- "bad_lines": 0, "torn_bytes": 0}
615
- errors = 0
616
- for log in logs:
617
- try:
618
- rep = import_session_file(log, decoder=dec, dry_run=dry_run, db=db,
619
- workspace_filter=workspace)
620
- except RuntimeError as exc:
621
- errors += 1
622
- files.append({"file": str(log.path), "error": str(exc), "workspace_dir":
623
- log.workspace_dir, "session_dir": log.session_dir})
624
- continue
625
- files.append(rep)
626
- if not rep.get("workspace_matched", True):
627
- continue
628
- totals["files"] += 1
629
- totals["sessions"] += 1
630
- totals["messages"] += int(rep.get("messages") or 0)
631
- totals["added"] += int(rep.get("added") or 0)
632
- totals["skipped"] += int(rep.get("skipped") or 0)
633
- totals["bad_lines"] += int(rep.get("bad_lines") or 0)
634
- totals["torn_bytes"] += int(rep.get("torn_bytes") or 0)
635
- if max_sessions is not None and totals["files"] >= max_sessions:
636
- break
637
- report = {
638
- "ok": errors == 0,
639
- "sessions_dir": str(root),
640
- "workspace_filter": str(workspace or ""),
641
- "dry_run": bool(dry_run),
642
- "decoder": {"backend": dec.backend, "exe": dec.exe, "version": dec.version},
643
- "files": files,
644
- "totals": totals,
645
- "errors": errors,
646
- "elapsed_ms": int(round((time.time() - started) * 1000)),
647
- }
648
- if not dry_run:
649
- try:
650
- report["db"] = session_rag.stats(path=db)
651
- except Exception as exc: # noqa: BLE001 - 统计失败不该抹掉导入结果
652
- report["db"] = {"error": f"{type(exc).__name__}: {exc}"}
653
- return report
654
-
655
-
656
- # ---------------------------------------------------------------- CLI
657
-
658
- def _print_human(report: dict) -> None:
659
- dec = report.get("decoder") or {}
660
- version = f" {dec['version']}" if dec.get("version") else ""
661
- print(f"解码器:{dec.get('backend')}{version}({dec.get('exe')})")
662
- print(f"会话目录:{report.get('sessions_dir')}")
663
- if report.get("workspace_filter"):
664
- print(f"工作区过滤:{report['workspace_filter']}")
665
- for item in report.get("files") or []:
666
- if item.get("error"):
667
- print(f"- [错误] {item.get('session_dir') or item.get('file')}:{item['error']}")
668
- continue
669
- if not item.get("workspace_matched", True):
670
- continue
671
- tail = f"消息 {item.get('messages', 0)},新增 {item.get('added', 0)}," \
672
- f"跳过 {item.get('skipped', 0)}"
673
- if item.get("bad_lines"):
674
- tail += f",坏行 {item['bad_lines']}"
675
- if item.get("torn_bytes"):
676
- tail += f",忽略残帧 {item['torn_bytes']}B"
677
- if item.get("warning"):
678
- tail += f",警告:{item['warning'][:120]}"
679
- print(f"- [{item.get('workspace')}] {item.get('session')}({tail})")
680
- filtered = sum(1 for item in report.get("files") or []
681
- if not item.get("error") and not item.get("workspace_matched", True))
682
- if filtered:
683
- print(f"(按工作区过滤掉 {filtered} 个会话)")
684
- totals = report.get("totals") or {}
685
- suffix = "(dry-run,未写库)" if report.get("dry_run") else ""
686
- print(f"共 {totals.get('files', 0)} 个会话:解析 {totals.get('messages', 0)} 条,"
687
- f"新增 {totals.get('added', 0)},跳过 {totals.get('skipped', 0)},"
688
- f"用时 {report.get('elapsed_ms', 0) / 1000.0:.1f}s{suffix}")
689
- db = report.get("db")
690
- if isinstance(db, dict) and not db.get("error"):
691
- print(f"原文库:{db.get('messages', 0)} 条 / {db.get('sessions', 0)} 场会话"
692
- f"(platform={db.get('by_platform')})")
693
-
694
-
695
- def build_parser() -> argparse.ArgumentParser:
696
- parser = argparse.ArgumentParser(
697
- prog="session_import.py",
698
- description="把 DSH 会话日志(多帧 zstd)导入 session_rag 原文库(附录 B · P1)")
699
- parser.add_argument("--sessions-dir", default="",
700
- help="DSH 会话根目录,默认 ~/.dsh/sessions")
701
- parser.add_argument("--limit", type=int, default=0,
702
- help="最多导入 N 个会话(工作区过滤后按修改时间倒序,0=全部)")
703
- parser.add_argument("--workspace", default="",
704
- help="只导入匹配的工作区(路径/basename/目录名,子串匹配)")
705
- parser.add_argument("--dry-run", action="store_true", help="只解析不写库")
706
- parser.add_argument("--json", action="store_true", help="输出 JSON 报告")
707
- return parser
708
-
709
-
710
- def main(argv=None) -> int:
711
- args = build_parser().parse_args(argv)
712
- try:
713
- report = import_sessions(
714
- sessions_dir=args.sessions_dir or None,
715
- limit=args.limit or None,
716
- workspace=args.workspace or None,
717
- dry_run=bool(args.dry_run),
718
- )
719
- except DecoderUnavailable as exc:
720
- print(f"[错误] {exc}", file=sys.stderr)
721
- return 2
722
- except FileNotFoundError as exc:
723
- print(f"[错误] {exc}", file=sys.stderr)
724
- return 2
725
- except RuntimeError as exc:
726
- print(f"[错误] 导入失败:{exc}", file=sys.stderr)
727
- return 1
728
- if args.json:
729
- print(json.dumps(report, ensure_ascii=False, indent=2))
730
- else:
731
- _print_human(report)
732
- return 0 if report.get("ok") else 1
733
-
734
-
735
- def _ensure_utf8_stdout() -> None:
736
- """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
737
-
738
- CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
739
- 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
740
- 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
741
- """
742
- for name in ("stdout", "stderr"):
743
- stream = getattr(sys, name, None)
744
- fn = getattr(stream, "reconfigure", None)
745
- if callable(fn):
746
- try:
747
- fn(encoding="utf-8", errors="replace")
748
- continue
749
- except (OSError, ValueError, AttributeError):
750
- pass
751
- try:
752
- import io
753
- buf = getattr(stream, "buffer", None)
754
- if buf is not None:
755
- setattr(sys, name,
756
- io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
757
- line_buffering=True))
758
- except Exception: # noqa: BLE001
759
- pass
760
-
761
-
762
- if __name__ == "__main__":
763
- _ensure_utf8_stdout()
764
- sys.exit(main())
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """附录 B · P1:DSH 会话日志导入(多平台入口 + 工作区隔离)。
4
+
5
+ DSH 把一场会话写成:
6
+ <sessions>/<工作区编码目录>/<会话目录>/session.v4.jsonl.zstd
7
+
8
+ 其中有三个必须处理的现实约束:
9
+ 1. 文件是**多帧拼接**的 zstd 容器:每行/每批事件一个独立帧。Node 的
10
+ `zlib.zstdDecompressSync` 一次只解第一帧,直接解整个文件只会拿到
11
+ 313 字节的 header(本机实测)。所以 Node 侧先做「帧结构扫描」再逐帧解压
12
+ (与 DSH 自己 `scanZstdFrames` 的结构扫描逻辑等价),把明文流式写进临时文件。
13
+ 2. 本机系统 Python **没有 zstandard 模块**,因此不把 Python 当解码器。
14
+ 3. 会话事件是 `{"type": "...", "time": 毫秒, "data": {...}}`:
15
+ 只导入 `user/message` / `assistant/message` 里的 text 片段(role/content/ts),
16
+ `reasoning`、`tool-call`、`tool/result`、`system/message`、`command/*` 等
17
+ 非对话条目一律跳过;`user/message` 里 `source.kind` 不是 `user` 的注入块
18
+ (runtime-context / system-reminder)也算系统事件,跳过。
19
+
20
+ 解码优先级(都不静默降级):
21
+ Node 22+(先探测 `node -e "require('node:zlib').zstdDecompressSync"`)
22
+ → 系统 `zstd -d` 命令
23
+ → 抛 DecoderUnavailable(「需要 Node 22+ 或 zstd 命令」)。
24
+
25
+ 导入:`session_rag.ingest_messages(rows, session=会话id, platform="dsh",
26
+ workspace=工作区)`,按内容哈希幂等;解压后的临时文件逐行流式解析,每 500 条
27
+ 批量入库,内存不随文件大小增长(8MB 压缩 / 1 万条事件级别实测可用)。
28
+
29
+ CLI:
30
+ python scripts/session_import.py [--sessions-dir PATH] [--limit N]
31
+ [--workspace 名称] [--dry-run] [--json]
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import hashlib
37
+ import brain
38
+ import core
39
+ import json
40
+ import os
41
+ import re
42
+ import shutil
43
+ import subprocess
44
+ import sys
45
+ import tempfile
46
+ import time
47
+ from dataclasses import dataclass
48
+ from pathlib import Path
49
+
50
+ HERE = Path(__file__).resolve().parent
51
+ if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
52
+ sys.path.insert(0, str(HERE))
53
+
54
+ import session_rag # noqa: E402
55
+
56
+ PLATFORM = "dsh"
57
+ BATCH_SIZE = 500
58
+ DEFAULT_TIMEOUT = 600.0 # 单文件解码的最长等待(秒)
59
+
60
+ # 只认 DSH 会话日志:session.v4.jsonl.zstd / session.jsonl / 未来版本号
61
+ _SESSION_LOG_RE = re.compile(r"^session(?:\.v\d+)?\.jsonl(\.zstd)?$", re.IGNORECASE)
62
+
63
+ _NODE_PROBE = (
64
+ "process.exit(typeof require('node:zlib').zstdDecompressSync === 'function' ? 0 : 1)"
65
+ )
66
+ _NODE_VERSION = "process.stdout.write(process.version)"
67
+
68
+ # 多帧 zstd 解码器(Node 22+)。先做与 DSH 相同的帧结构扫描,再逐帧解压并
69
+ # 立刻写盘 —— 不把整份明文同时留在内存里。
70
+ _NODE_DECODE_JS = r"""
71
+ const fs = require('node:fs')
72
+ const zlib = require('node:zlib')
73
+ const src = process.argv[2]
74
+ const dst = process.argv[3]
75
+ const MAGIC = 0xFD2FB528
76
+ const buf = fs.readFileSync(src)
77
+
78
+ // 返回完整帧的结束偏移;遇到文件尾部的不完整帧返回 -1(live 会话正在追加)。
79
+ function frameEnd(buffer, start) {
80
+ if (buffer.length - start < 4) return -1
81
+ if (buffer.readUInt32LE(start) !== MAGIC) {
82
+ throw new Error('corrupt Zstandard session log: invalid frame magic at byte ' + start)
83
+ }
84
+ let off = start + 4
85
+ if (off === buffer.length) return -1
86
+ const descriptor = buffer.readUInt8(off)
87
+ off += 1
88
+ if ((descriptor & 0x18) !== 0) {
89
+ throw new Error('corrupt Zstandard session log: reserved frame-header bit at byte ' + (off - 1))
90
+ }
91
+ const contentSizeFlag = descriptor >>> 6
92
+ const singleSegment = (descriptor & 0x20) !== 0
93
+ const checksum = (descriptor & 0x04) !== 0
94
+ const dictionaryFlag = descriptor & 0x03
95
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
96
+ const contentSizeBytes = contentSizeFlag === 0
97
+ ? (singleSegment ? 1 : 0)
98
+ : (1 << contentSizeFlag)
99
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
100
+ if (buffer.length - off < remainingHeaderBytes) return -1
101
+ off += remainingHeaderBytes
102
+ for (;;) {
103
+ if (buffer.length - off < 3) return -1
104
+ const blockHeader = buffer.readUIntLE(off, 3)
105
+ off += 3
106
+ const lastBlock = (blockHeader & 1) !== 0
107
+ const blockType = (blockHeader >>> 1) & 0x03
108
+ const blockSize = blockHeader >>> 3
109
+ if (blockType === 0x03) {
110
+ throw new Error('corrupt Zstandard session log: reserved block type at byte ' + (off - 3))
111
+ }
112
+ const payloadBytes = blockType === 0x01 ? 1 : blockSize
113
+ if (buffer.length - off < payloadBytes) return -1
114
+ off += payloadBytes
115
+ if (lastBlock) break
116
+ }
117
+ if (checksum) {
118
+ if (buffer.length - off < 4) return -1
119
+ off += 4
120
+ }
121
+ return off
122
+ }
123
+
124
+ const fd = fs.openSync(dst, 'w')
125
+ let frames = 0
126
+ let plainBytes = 0
127
+ let tornBytes = 0
128
+ let offset = 0
129
+ try {
130
+ while (offset < buf.length) {
131
+ const end = frameEnd(buf, offset)
132
+ if (end < 0) {
133
+ tornBytes = buf.length - offset
134
+ break
135
+ }
136
+ const plain = zlib.zstdDecompressSync(buf.subarray(offset, end))
137
+ fs.writeSync(fd, plain)
138
+ plainBytes += plain.length
139
+ frames += 1
140
+ offset = end
141
+ }
142
+ } finally {
143
+ fs.closeSync(fd)
144
+ }
145
+ process.stdout.write(JSON.stringify({
146
+ frames: frames,
147
+ plainBytes: plainBytes,
148
+ tornBytes: tornBytes,
149
+ compressedBytes: buf.length,
150
+ }))
151
+ """
152
+
153
+
154
+ class DecoderUnavailable(RuntimeError):
155
+ """本机既没有可解 zstd 的 Node(22+),也没有 zstd 命令。"""
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class Decoder:
160
+ """已探测通过的 zstd 解码后端。"""
161
+
162
+ backend: str # "node" | "zstd"
163
+ exe: str
164
+ version: str = ""
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class SessionLog:
169
+ """一个待导入的 DSH 会话日志文件。"""
170
+
171
+ path: Path
172
+ workspace_dir: str # sessions/<工作区编码目录>/
173
+ session_dir: str # sessions/<工作区编码目录>/<会话目录>/
174
+ compressed: bool
175
+
176
+
177
+ def default_sessions_dir() -> Path:
178
+ """DSH 会话根目录:默认 ``~/.dsh/sessions``(尊重 DSH_HOME 自定义安装)。"""
179
+ env_home = str(os.environ.get("DSH_HOME") or "").strip()
180
+ base = Path(env_home) if env_home else (Path.home() / ".dsh")
181
+ return base / "sessions"
182
+
183
+
184
+ # ---------------------------------------------------------------- 解码器探测
185
+
186
+ def _run_quiet(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
187
+ return subprocess.run(cmd, capture_output=True, **kwargs)
188
+
189
+
190
+ def _node_has_zstd(exe: str, timeout: float = 20.0) -> bool:
191
+ """探测指定的 node 是否带 node:zlib zstd(Node 22+ / 23.8+ 才有)。"""
192
+ try:
193
+ rep = _run_quiet([exe, "-e", _NODE_PROBE], timeout=timeout)
194
+ except (OSError, subprocess.SubprocessError):
195
+ return False
196
+ return rep.returncode == 0
197
+
198
+
199
+ def _node_version(exe: str) -> str:
200
+ try:
201
+ rep = _run_quiet([exe, "-e", _NODE_VERSION], timeout=20.0)
202
+ except (OSError, subprocess.SubprocessError):
203
+ return ""
204
+ if rep.returncode != 0:
205
+ return ""
206
+ return rep.stdout.decode("utf-8", "replace").strip()
207
+
208
+
209
+ def _dsh_runtime_node_candidates() -> list[str]:
210
+ """DSH 自带的 Node 运行时(PATH 上没有 node 或不支持 zstd 时兜底)。"""
211
+ roots: list[Path] = []
212
+ env_home = str(os.environ.get("DSH_HOME") or "").strip()
213
+ if env_home:
214
+ roots.append(Path(env_home))
215
+ roots.append(Path.home() / ".dsh")
216
+ out: list[str] = []
217
+ seen: set[str] = set()
218
+ for root in roots:
219
+ try:
220
+ runtimes = sorted((root / "dsh-runtimes").glob("*/dependencies/node/bin"))
221
+ except OSError:
222
+ continue
223
+ for bindir in runtimes:
224
+ for name in ("node.exe", "node"):
225
+ cand = bindir / name
226
+ key = os.path.normcase(str(cand))
227
+ if key in seen:
228
+ continue
229
+ seen.add(key)
230
+ if cand.is_file():
231
+ out.append(str(cand))
232
+ return out
233
+
234
+
235
+ def find_node_exe() -> str | None:
236
+ """返回第一个「node 能解 zstd」的可执行文件;没有则 None。
237
+
238
+ 查找顺序:LINGSHU_NODE 环境变量 → PATH 上的 node → DSH 自带运行时。
239
+ 每个候选都真跑一次 ``node -e`` 探测,不只看版本号猜。
240
+ """
241
+ candidates: list[str] = []
242
+ env_node = str(os.environ.get("LINGSHU_NODE") or "").strip()
243
+ if env_node:
244
+ candidates.append(env_node)
245
+ for name in ("node", "node.exe"):
246
+ found = shutil.which(name)
247
+ if found:
248
+ candidates.append(found)
249
+ candidates.extend(_dsh_runtime_node_candidates())
250
+ seen: set[str] = set()
251
+ for cand in candidates:
252
+ key = os.path.normcase(str(cand))
253
+ if not key or key in seen:
254
+ continue
255
+ seen.add(key)
256
+ if _node_has_zstd(str(cand)):
257
+ return str(cand)
258
+ return None
259
+
260
+
261
+ def find_zstd_exe() -> str | None:
262
+ """系统 zstd CLI(次选解码器)。没有则 None。"""
263
+ for name in ("zstd", "zstd.exe"):
264
+ found = shutil.which(name)
265
+ if found:
266
+ return found
267
+ return None
268
+
269
+
270
+ def detect_decoder(*, node_exe: str | None = None) -> Decoder:
271
+ """确定 zstd 解码后端;两者都没有时抛 DecoderUnavailable(绝不静默)。"""
272
+ if node_exe:
273
+ if not _node_has_zstd(str(node_exe)):
274
+ raise DecoderUnavailable(
275
+ f"指定的 Node 不支持 node:zlib zstd:{node_exe}(需要 Node 22+)")
276
+ return Decoder("node", str(node_exe), _node_version(str(node_exe)))
277
+ node = find_node_exe()
278
+ if node:
279
+ return Decoder("node", node, _node_version(node))
280
+ zstd = find_zstd_exe()
281
+ if zstd:
282
+ return Decoder("zstd", zstd, "")
283
+ raise DecoderUnavailable(
284
+ "需要 Node 22+ 或 zstd 命令:本机既没有能解 zstd 的 Node"
285
+ "(node:zlib.zstdDecompressSync 探测失败,PATH 与 DSH 自带运行时都不行),"
286
+ "也没有 zstd 命令。系统 Python 没有 zstandard 模块,安装 Node 22+ 或 "
287
+ "zstd 后重试;不会静默跳过或假装导入成功。")
288
+
289
+
290
+ # ---------------------------------------------------------------- 会话发现
291
+
292
+ def discover_sessions(sessions_dir=None, *, limit: int | None = None) -> list[SessionLog]:
293
+ """遍历 <sessions>/<工作区>/<会话>/session*.jsonl[.zstd],按修改时间倒序。"""
294
+ root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
295
+ if not root.is_dir():
296
+ raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
297
+ logs: list[SessionLog] = []
298
+ try:
299
+ projects = sorted(root.iterdir(), key=lambda p: p.name.lower())
300
+ except OSError as exc:
301
+ raise RuntimeError(f"无法读取会话目录 {root}:{exc}") from exc
302
+ for project in projects:
303
+ if not project.is_dir():
304
+ continue
305
+ try:
306
+ sessions = sorted(project.iterdir(), key=lambda p: p.name.lower())
307
+ except OSError:
308
+ continue
309
+ for sess in sessions:
310
+ if not sess.is_dir():
311
+ continue
312
+ try:
313
+ entries = sorted(sess.iterdir(), key=lambda p: p.name.lower())
314
+ except OSError:
315
+ continue
316
+ for f in entries:
317
+ match = _SESSION_LOG_RE.match(f.name)
318
+ if not match or not f.is_file():
319
+ continue
320
+ logs.append(SessionLog(path=f, workspace_dir=project.name,
321
+ session_dir=sess.name,
322
+ compressed=bool(match.group(1))))
323
+ logs.sort(key=lambda x: _mtime(x.path), reverse=True)
324
+ if limit is not None and int(limit) > 0:
325
+ logs = logs[: int(limit)]
326
+ return logs
327
+
328
+
329
+ def _mtime(path: Path) -> float:
330
+ try:
331
+ return path.stat().st_mtime
332
+ except OSError:
333
+ return 0.0
334
+
335
+
336
+ # ---------------------------------------------------------------- zstd 解码
337
+
338
+ def decode_session_file(src, dst, decoder: Decoder) -> dict:
339
+ """把多帧 zstd 会话日志解成明文 JSONL,写进 dst 临时文件;返回解码元数据。
340
+
341
+ 返回统一 snake_case 键:backend/exe/frames/plain_bytes/compressed_bytes/
342
+ torn_bytes(torn_bytes = 文件尾部不完整的 live 帧字节数,已忽略)。
343
+ """
344
+ src = Path(src)
345
+ dst = Path(dst)
346
+ dst.parent.mkdir(parents=True, exist_ok=True)
347
+ raw = _decode_with_node(src, dst, decoder.exe) if decoder.backend == "node" \
348
+ else _decode_with_zstd_cli(src, dst, decoder.exe)
349
+ meta = {
350
+ "backend": str(raw.get("backend") or decoder.backend),
351
+ "exe": str(raw.get("exe") or decoder.exe),
352
+ "frames": raw.get("frames"),
353
+ "plain_bytes": int(raw.get("plainBytes") if raw.get("plainBytes") is not None
354
+ else raw.get("plain_bytes") or 0),
355
+ "compressed_bytes": int(raw.get("compressedBytes")
356
+ if raw.get("compressedBytes") is not None
357
+ else raw.get("compressed_bytes") or 0),
358
+ "torn_bytes": int(raw.get("tornBytes") if raw.get("tornBytes") is not None
359
+ else raw.get("torn_bytes") or 0),
360
+ }
361
+ if raw.get("warning"):
362
+ meta["warning"] = raw["warning"]
363
+ return meta
364
+
365
+
366
+ def _decode_with_node(src: Path, dst: Path, node_exe: str) -> dict:
367
+ with tempfile.TemporaryDirectory(prefix="lingshu-zstd-js-") as td:
368
+ script = Path(td) / "decode_session.js"
369
+ script.write_text(_NODE_DECODE_JS, encoding="utf-8")
370
+ try:
371
+ rep = subprocess.run([node_exe, str(script), str(src), str(dst)],
372
+ capture_output=True, timeout=DEFAULT_TIMEOUT)
373
+ except subprocess.TimeoutExpired as exc:
374
+ raise RuntimeError(f"Node 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
375
+ except OSError as exc:
376
+ raise RuntimeError(f"Node 启动失败({node_exe}):{exc}") from exc
377
+ if rep.returncode != 0:
378
+ err = rep.stderr.decode("utf-8", "replace").strip()
379
+ raise RuntimeError(f"Node 解压失败({src}):{err[:500] or f'rc={rep.returncode}'}")
380
+ try:
381
+ meta = json.loads(rep.stdout.decode("utf-8", "replace") or "{}")
382
+ except ValueError:
383
+ meta = {}
384
+ meta.setdefault("plainBytes", dst.stat().st_size if dst.exists() else 0)
385
+ return meta
386
+
387
+
388
+ def _decode_with_zstd_cli(src: Path, dst: Path, zstd_exe: str) -> dict:
389
+ try:
390
+ with open(dst, "wb") as out:
391
+ rep = subprocess.run([zstd_exe, "-d", "-q", "-c", str(src)],
392
+ stdout=out, stderr=subprocess.PIPE,
393
+ timeout=DEFAULT_TIMEOUT)
394
+ except subprocess.TimeoutExpired as exc:
395
+ raise RuntimeError(f"zstd 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
396
+ except OSError as exc:
397
+ raise RuntimeError(f"zstd 启动失败({zstd_exe}):{exc}") from exc
398
+ stderr = (rep.stderr or b"").decode("utf-8", "replace").strip()
399
+ meta = {"frames": None, "torn_bytes": 0,
400
+ "plain_bytes": dst.stat().st_size if dst.exists() else 0,
401
+ "compressed_bytes": src.stat().st_size if src.exists() else 0}
402
+ if rep.returncode != 0:
403
+ # live 会话尾部可能是半帧:zstd CLI 会报错但仍吐出完整帧的明文。
404
+ # 只在明文以换行结尾(最后一帧完整)时接受,否则当失败。
405
+ tail = b""
406
+ if dst.exists() and dst.stat().st_size:
407
+ with open(dst, "rb") as fh:
408
+ fh.seek(max(0, dst.stat().st_size - 1))
409
+ tail = fh.read(1)
410
+ if not tail.endswith(b"\n"):
411
+ raise RuntimeError(f"zstd 解压失败({src}):{stderr[:500] or f'rc={rep.returncode}'}")
412
+ meta["warning"] = f"zstd 返回码 {rep.returncode},已接受以换行结尾的部分输出:{stderr[:200]}"
413
+ return meta
414
+
415
+
416
+ # ---------------------------------------------------------------- JSONL 解析
417
+
418
+ def read_session_header(jsonl_file) -> dict:
419
+ """读解压后 JSONL 的第一条 ``{"type":"session"}``(格式保证是首行,最多扫 64 行)。"""
420
+ try:
421
+ with open(jsonl_file, "r", encoding="utf-8-sig", errors="replace") as fh:
422
+ for _ in range(64):
423
+ line = fh.readline()
424
+ if not line:
425
+ break
426
+ line = line.strip()
427
+ if not line:
428
+ continue
429
+ try:
430
+ event = json.loads(line)
431
+ except ValueError:
432
+ continue
433
+ if isinstance(event, dict) and event.get("type") == "session":
434
+ return event
435
+ except OSError:
436
+ pass
437
+ return {}
438
+
439
+
440
+ def _text_fragments(content) -> str:
441
+ """content 可能是字符串或 block 数组:只取 text 片段(跳过 reasoning/image/tool-*)。"""
442
+ if isinstance(content, str):
443
+ return content.strip()
444
+ if not isinstance(content, list):
445
+ return ""
446
+ parts: list[str] = []
447
+ for block in content:
448
+ if isinstance(block, str):
449
+ if block.strip():
450
+ parts.append(block.strip())
451
+ elif isinstance(block, dict) and block.get("type") == "text":
452
+ text = block.get("text")
453
+ if text is not None and str(text).strip():
454
+ parts.append(str(text).strip())
455
+ return "\n".join(parts)
456
+
457
+
458
+ def _event_to_row(event: dict) -> dict | None:
459
+ """把一条 DSH 会话事件转成 ingest 行;非对话事件(工具/推理/系统)返回 None。"""
460
+ event_type = event.get("type")
461
+ data = event.get("data")
462
+ if not isinstance(data, dict):
463
+ data = {}
464
+ if event_type == "user/message":
465
+ source = data.get("source")
466
+ kind = str((source or {}).get("kind") or "") if isinstance(source, dict) else ""
467
+ if kind and kind != "user":
468
+ return None # runtime-context / system-reminder 等注入块不是用户发言
469
+ text = _text_fragments(data.get("content"))
470
+ role = "user"
471
+ elif event_type == "assistant/message":
472
+ message = data.get("message")
473
+ if not isinstance(message, dict):
474
+ message = {}
475
+ text = _text_fragments(message.get("content"))
476
+ role = "assistant"
477
+ else:
478
+ return None
479
+ if not text:
480
+ return None # 只有 reasoning / 只有 tool-call 的 assistant 轮次
481
+ time_ms = event.get("time")
482
+ ts = float(time_ms) / 1000.0 if isinstance(time_ms, (int, float)) else 0.0
483
+ return {"role": role, "content": text, "ts": ts}
484
+
485
+
486
+ # ---------------------------------------------------------------- 导入
487
+
488
+ def _workspace_matches(want, workspace: str, workspace_dir: str) -> bool:
489
+ """--workspace 匹配:精确路径 / basename / 原始工作区目录名,且允许子串。"""
490
+ wanted = str(want or "").strip()
491
+ if not wanted:
492
+ return True
493
+ low = wanted.lower().rstrip("\\/")
494
+ names = {str(workspace or "").strip().lower().rstrip("\\/"),
495
+ str(workspace_dir or "").strip().lower()}
496
+ if workspace:
497
+ names.add(Path(workspace).name.lower())
498
+ if low in names:
499
+ return True
500
+ for name in names:
501
+ if name and low in name:
502
+ return True
503
+ return False
504
+
505
+
506
+ SEEN_FILE = ".session-import-seen.json"
507
+ SEEN_CAP = 50000
508
+
509
+
510
+ def _seen_path() -> Path:
511
+ return Path(brain.HOME) / SEEN_FILE if "brain" in globals() else Path.home() / SEEN_FILE
512
+
513
+
514
+ def load_seen_keys() -> set:
515
+ """跨批次/跨运行的导入幂等键(上次入库过的行不再进)。"""
516
+ try:
517
+ p = _seen_path()
518
+ if not p.is_file():
519
+ return set()
520
+ data = json.loads(p.read_text(encoding="utf-8", errors="replace") or "[]")
521
+ return {str(x) for x in (data or []) if x}
522
+ except Exception:
523
+ return set()
524
+
525
+
526
+ def save_seen_keys(keys: set) -> None:
527
+ try:
528
+ p = _seen_path()
529
+ tmp = p.with_name(p.name + ".tmp")
530
+ kept = sorted(keys)[-SEEN_CAP:]
531
+ tmp.write_text(json.dumps(kept, ensure_ascii=False), encoding="utf-8")
532
+ os.replace(tmp, p) # 原子替换,避免写一半被读到
533
+ except Exception:
534
+ pass
535
+
536
+
537
+ def row_key(session_id: str, row: dict, source: str = "") -> str:
538
+ """一行的幂等键:**源文件** + 会话 + 行内容指纹。
539
+
540
+ 为什么要带源文件:去重语义是"重跑同一次导出不重复入库",
541
+ 不是"两个不同文件里内容相同的行只留一条"——后者会把合法数据吞掉(实测两个
542
+ 测试夹具同内容不同文件,被误判成重复)。行结构变了也不会误判。
543
+ """
544
+ try:
545
+ basis = f"{source}|{session_id}|" + json.dumps(row, ensure_ascii=False, sort_keys=True)
546
+ except Exception:
547
+ basis = f"{source}|{session_id}|" + str(row)[:500]
548
+ return hashlib.sha1(basis.encode("utf-8", "replace")).hexdigest()[:20]
549
+
550
+
551
+ def import_session_file(log: SessionLog, *, decoder: Decoder, dry_run: bool = False,
552
+ db=None, workspace_filter: str | None = None,
553
+ batch_size: int = BATCH_SIZE) -> dict:
554
+ """解压 → 解析 → 批量入库一个会话文件(解压后的明文只在临时目录存活)。"""
555
+ report: dict = {
556
+ "file": str(log.path),
557
+ "workspace_dir": log.workspace_dir,
558
+ "session_dir": log.session_dir,
559
+ "compressed": log.compressed,
560
+ "session": log.session_dir,
561
+ "workspace": log.workspace_dir,
562
+ "messages": 0,
563
+ "added": 0,
564
+ "skipped": 0,
565
+ "bad_lines": 0,
566
+ "workspace_matched": True,
567
+ "torn_bytes": 0,
568
+ }
569
+ with tempfile.TemporaryDirectory(prefix="lingshu-session-decode-") as td:
570
+ plain = Path(td) / "session.jsonl"
571
+ if log.compressed:
572
+ meta = decode_session_file(log.path, plain, decoder)
573
+ else:
574
+ shutil.copyfile(log.path, plain)
575
+ meta = {"backend": "plain", "frames": None, "torn_bytes": 0,
576
+ "plain_bytes": log.path.stat().st_size, "compressed_bytes": 0}
577
+ report["decode"] = {
578
+ "backend": meta.get("backend"),
579
+ "frames": meta.get("frames"),
580
+ "compressed_bytes": meta.get("compressed_bytes"),
581
+ "plain_bytes": meta.get("plain_bytes"),
582
+ }
583
+ report["torn_bytes"] = int(meta.get("torn_bytes") or 0)
584
+ if meta.get("warning"):
585
+ report["warning"] = meta["warning"]
586
+
587
+ header = read_session_header(plain)
588
+ session_id = str(header.get("id") or "").strip() or log.session_dir
589
+ workspace = str(header.get("cwd") or "").strip() or log.workspace_dir
590
+ report["session"] = session_id
591
+ report["workspace"] = workspace
592
+ if not _workspace_matches(workspace_filter, workspace, log.workspace_dir):
593
+ report["workspace_matched"] = False
594
+ return report
595
+
596
+ parsed = added = skipped = bad_lines = 0
597
+ skipped_dup = 0
598
+ # 幂等默认**关闭**:导入的既有语义是"加法"(两个文件里同内容都该进)。
599
+ # 需要"重跑同一次导出不重复入库"时开 config session_import_idempotent: true,
600
+ # 或用 --idempotent。默认开会让状态跨批次残留,改变既有行为(实测 2 个测试挂)。
601
+ try:
602
+ _idem = bool((core.load_config() or {}).get("session_import_idempotent"))
603
+ except Exception:
604
+ _idem = False
605
+ _seen_keys = load_seen_keys() if _idem else set()
606
+ _pending_keys: set = set()
607
+ batch: list[dict] = []
608
+
609
+ def flush() -> None:
610
+ nonlocal added, skipped
611
+ if not batch:
612
+ return
613
+ if not dry_run:
614
+ rep = session_rag.ingest_messages(
615
+ batch, session=session_id, platform=PLATFORM,
616
+ workspace=workspace, path=db)
617
+ added += int(rep.get("added") or 0)
618
+ skipped += int(rep.get("skipped") or 0)
619
+ batch.clear()
620
+
621
+ with open(plain, "r", encoding="utf-8-sig", errors="replace") as fh:
622
+ for line in fh:
623
+ line = line.strip()
624
+ if not line:
625
+ continue
626
+ try:
627
+ event = json.loads(line)
628
+ except ValueError:
629
+ bad_lines += 1
630
+ continue
631
+ if not isinstance(event, dict):
632
+ bad_lines += 1
633
+ continue
634
+ if event.get("type") == "session":
635
+ continue # 首行 header,不是对话
636
+ row = _event_to_row(event)
637
+ if row is None:
638
+ continue
639
+ # parsed 统计"解析到的行数"(保持既有语义不变);
640
+ # #5 持久化幂等只影响"是否入 batch",重复单独记在 already_imported。
641
+ parsed += 1
642
+ _k = row_key(session_id, row, str(log.path))
643
+ if _k in _seen_keys:
644
+ skipped_dup += 1
645
+ continue
646
+ _pending_keys.add(_k)
647
+ batch.append(row)
648
+ if len(batch) >= max(1, int(batch_size)):
649
+ flush()
650
+ flush()
651
+
652
+ report["messages"] = parsed
653
+ report["bad_lines"] = bad_lines
654
+ report["already_imported"] = skipped_dup
655
+ if not dry_run:
656
+ report["added"] = added
657
+ report["skipped"] = skipped
658
+ if _idem and _pending_keys:
659
+ save_seen_keys(_seen_keys | _pending_keys)
660
+ else:
661
+ report["dry_run"] = True
662
+ return report
663
+
664
+
665
+ def import_sessions(sessions_dir=None, *, limit: int | None = None,
666
+ workspace: str | None = None, dry_run: bool = False,
667
+ db=None, decoder: Decoder | None = None) -> dict:
668
+ """遍历导入 DSH 会话目录;返回可 JSON 化的报告。
669
+
670
+ ``limit`` 限制「最终导入的会话数」而不是「扫描的文件数」:工作区过滤在
671
+ 解出会话 header 的 cwd 之后生效,过滤通过的按修改时间倒序取前 N 个。
672
+ """
673
+ started = time.time()
674
+ root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
675
+ if not root.is_dir():
676
+ raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
677
+ logs = discover_sessions(root)
678
+ dec = decoder if decoder is not None else detect_decoder()
679
+ max_sessions = int(limit) if limit is not None and int(limit) > 0 else None
680
+ files: list[dict] = []
681
+ totals = {"files": 0, "sessions": 0, "messages": 0, "added": 0, "skipped": 0,
682
+ "bad_lines": 0, "torn_bytes": 0}
683
+ errors = 0
684
+ for log in logs:
685
+ try:
686
+ rep = import_session_file(log, decoder=dec, dry_run=dry_run, db=db,
687
+ workspace_filter=workspace)
688
+ except RuntimeError as exc:
689
+ errors += 1
690
+ files.append({"file": str(log.path), "error": str(exc), "workspace_dir":
691
+ log.workspace_dir, "session_dir": log.session_dir})
692
+ continue
693
+ files.append(rep)
694
+ if not rep.get("workspace_matched", True):
695
+ continue
696
+ totals["files"] += 1
697
+ totals["sessions"] += 1
698
+ totals["messages"] += int(rep.get("messages") or 0)
699
+ totals["added"] += int(rep.get("added") or 0)
700
+ totals["skipped"] += int(rep.get("skipped") or 0)
701
+ totals["bad_lines"] += int(rep.get("bad_lines") or 0)
702
+ totals["torn_bytes"] += int(rep.get("torn_bytes") or 0)
703
+ if max_sessions is not None and totals["files"] >= max_sessions:
704
+ break
705
+ report = {
706
+ "ok": errors == 0,
707
+ "sessions_dir": str(root),
708
+ "workspace_filter": str(workspace or ""),
709
+ "dry_run": bool(dry_run),
710
+ "decoder": {"backend": dec.backend, "exe": dec.exe, "version": dec.version},
711
+ "files": files,
712
+ "totals": totals,
713
+ "errors": errors,
714
+ "elapsed_ms": int(round((time.time() - started) * 1000)),
715
+ }
716
+ if not dry_run:
717
+ try:
718
+ report["db"] = session_rag.stats(path=db)
719
+ except Exception as exc: # noqa: BLE001 - 统计失败不该抹掉导入结果
720
+ report["db"] = {"error": f"{type(exc).__name__}: {exc}"}
721
+ return report
722
+
723
+
724
+ # ---------------------------------------------------------------- CLI
725
+
726
+ def _print_human(report: dict) -> None:
727
+ dec = report.get("decoder") or {}
728
+ version = f" {dec['version']}" if dec.get("version") else ""
729
+ print(f"解码器:{dec.get('backend')}{version}({dec.get('exe')})")
730
+ print(f"会话目录:{report.get('sessions_dir')}")
731
+ if report.get("workspace_filter"):
732
+ print(f"工作区过滤:{report['workspace_filter']}")
733
+ for item in report.get("files") or []:
734
+ if item.get("error"):
735
+ print(f"- [错误] {item.get('session_dir') or item.get('file')}:{item['error']}")
736
+ continue
737
+ if not item.get("workspace_matched", True):
738
+ continue
739
+ tail = f"消息 {item.get('messages', 0)},新增 {item.get('added', 0)}," \
740
+ f"跳过 {item.get('skipped', 0)}"
741
+ if item.get("bad_lines"):
742
+ tail += f",坏行 {item['bad_lines']}"
743
+ if item.get("torn_bytes"):
744
+ tail += f",忽略残帧 {item['torn_bytes']}B"
745
+ if item.get("warning"):
746
+ tail += f",警告:{item['warning'][:120]}"
747
+ print(f"- [{item.get('workspace')}] {item.get('session')}({tail})")
748
+ filtered = sum(1 for item in report.get("files") or []
749
+ if not item.get("error") and not item.get("workspace_matched", True))
750
+ if filtered:
751
+ print(f"(按工作区过滤掉 {filtered} 个会话)")
752
+ totals = report.get("totals") or {}
753
+ suffix = "(dry-run,未写库)" if report.get("dry_run") else ""
754
+ print(f"共 {totals.get('files', 0)} 个会话:解析 {totals.get('messages', 0)} 条,"
755
+ f"新增 {totals.get('added', 0)},跳过 {totals.get('skipped', 0)},"
756
+ f"用时 {report.get('elapsed_ms', 0) / 1000.0:.1f}s{suffix}")
757
+ db = report.get("db")
758
+ if isinstance(db, dict) and not db.get("error"):
759
+ print(f"原文库:{db.get('messages', 0)} 条 / {db.get('sessions', 0)} 场会话"
760
+ f"(platform={db.get('by_platform')})")
761
+
762
+
763
+ def build_parser() -> argparse.ArgumentParser:
764
+ parser = argparse.ArgumentParser(
765
+ prog="session_import.py",
766
+ description="把 DSH 会话日志(多帧 zstd)导入 session_rag 原文库(附录 B · P1)")
767
+ parser.add_argument("--sessions-dir", default="",
768
+ help="DSH 会话根目录,默认 ~/.dsh/sessions")
769
+ parser.add_argument("--limit", type=int, default=0,
770
+ help="最多导入 N 个会话(工作区过滤后按修改时间倒序,0=全部)")
771
+ parser.add_argument("--workspace", default="",
772
+ help="只导入匹配的工作区(路径/basename/目录名,子串匹配)")
773
+ parser.add_argument("--dry-run", action="store_true", help="只解析不写库")
774
+ parser.add_argument("--json", action="store_true", help="输出 JSON 报告")
775
+ return parser
776
+
777
+
778
+ def main(argv=None) -> int:
779
+ args = build_parser().parse_args(argv)
780
+ try:
781
+ report = import_sessions(
782
+ sessions_dir=args.sessions_dir or None,
783
+ limit=args.limit or None,
784
+ workspace=args.workspace or None,
785
+ dry_run=bool(args.dry_run),
786
+ )
787
+ except DecoderUnavailable as exc:
788
+ print(f"[错误] {exc}", file=sys.stderr)
789
+ return 2
790
+ except FileNotFoundError as exc:
791
+ print(f"[错误] {exc}", file=sys.stderr)
792
+ return 2
793
+ except RuntimeError as exc:
794
+ print(f"[错误] 导入失败:{exc}", file=sys.stderr)
795
+ return 1
796
+ if args.json:
797
+ print(json.dumps(report, ensure_ascii=False, indent=2))
798
+ else:
799
+ _print_human(report)
800
+ return 0 if report.get("ok") else 1
801
+
802
+
803
+ def _ensure_utf8_stdout() -> None:
804
+ """把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
805
+
806
+ CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
807
+ 直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
808
+ 这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
809
+ """
810
+ for name in ("stdout", "stderr"):
811
+ stream = getattr(sys, name, None)
812
+ fn = getattr(stream, "reconfigure", None)
813
+ if callable(fn):
814
+ try:
815
+ fn(encoding="utf-8", errors="replace")
816
+ continue
817
+ except (OSError, ValueError, AttributeError):
818
+ pass
819
+ try:
820
+ import io
821
+ buf = getattr(stream, "buffer", None)
822
+ if buf is not None:
823
+ setattr(sys, name,
824
+ io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
825
+ line_buffering=True))
826
+ except Exception: # noqa: BLE001
827
+ pass
828
+
829
+
830
+ if __name__ == "__main__":
831
+ _ensure_utf8_stdout()
832
+ sys.exit(main())