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
@@ -0,0 +1,1160 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """灵枢 · APP 实时上下文视图(v5.34,替代插件快照方案)
4
+
5
+ 为什么换:原来靠插件在 agent/pre-step 抓 decision.messages 写快照,必须先
6
+ 重载插件才生效,而且只能看到"那一刻"。APP 宿主本身把**整场会话的事件流**
7
+ 实时落盘到:
8
+
9
+ ~/.app/sessions/<项目目录>/<session-id>/session.v4.jsonl.zstd
10
+
11
+ 本模块直接读它——不用插件、不用重载、随事件实时更新,而且字段比快照全
12
+ (system/user/assistant/tool、注入、错误、重试、审批、目标、todo)。
13
+
14
+ brain.py context status [--session ID] 实时水位 + 构成 + 健康(一屏)
15
+ brain.py context messages [--role R] 重建出的实时消息列表
16
+ brain.py context tools 工具调用/失败统计
17
+ brain.py context errors 本次会话的错误 / 重试 / 失败工具
18
+ brain.py context plan 建议折叠区间(只建议,不动手)
19
+ brain.py context sessions 列出所有会话(最近的在前)
20
+
21
+ 只读:本模块绝不写会话文件、不改注入、不动任何消息。
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import glob
26
+ import json
27
+ import os
28
+ import time
29
+ from pathlib import Path
30
+
31
+ import core
32
+
33
+ APP_HOME = Path.home() / ".dsh"
34
+ SESSIONS_ROOT = APP_HOME / "sessions"
35
+ WORKSPACE_INDEX = APP_HOME / "storages" / "workspace.json"
36
+ SESSION_FILE = "session.v4.jsonl.zstd"
37
+ PRESSURE = ".context-pressure.json"
38
+ FOLDS = "context-folds.json"
39
+
40
+ FOLD_MIN_RUN = 4 # 连续可折叠 >=4 条才算一段
41
+ KEEP_RECENT = 6 # 末尾这几条不建议折叠
42
+ MSG_CAP = 600 # messages 命令默认最多列多少条
43
+
44
+ # 已知的「宿主/灵枢自己注入」来源:摘对话时要剔掉,否则人格块会被当成用户原话。
45
+ INJECTED_KINDS = {
46
+ "skill-invocation", "time-context", "runtime-context", "skill-catalog",
47
+ "goal", "user-approval", "tool-jobs",
48
+ }
49
+
50
+
51
+ # ---------------------------------------------------------------- 定位会话
52
+
53
+ def _load_json(path: Path):
54
+ try:
55
+ if path.is_file():
56
+ return json.loads(path.read_text(encoding="utf-8", errors="replace") or "null")
57
+ except Exception:
58
+ pass
59
+ return None
60
+
61
+
62
+ def _encode_part(part: str) -> str:
63
+ """APP 的目录名转义:ASCII 保留字母数字与 ._-,其余 ASCII 变 '-',非 ASCII 变 ~XXXX。
64
+
65
+ 实测 `E:\\丁厚同\\文档\\程序` → `--E-~4E01~539A~540C-~6587~6863-~7A0B~5E8F--`。
66
+ """
67
+ out = []
68
+ for ch in part:
69
+ if ch.isascii() and (ch.isalnum() or ch in "._-"):
70
+ out.append(ch)
71
+ elif ch.isascii():
72
+ out.append("-")
73
+ else:
74
+ out.append("~%04X" % ord(ch))
75
+ return "".join(out)
76
+
77
+
78
+ def session_dir_name(cwd: str) -> str:
79
+ """把工作目录路径编码成 APP 的会话项目目录名(不依赖列目录,可直连)。"""
80
+ p = Path(cwd)
81
+ parts = [p.drive.rstrip(":")] + list(p.parts[1:])
82
+ return "--" + "-".join(_encode_part(x) for x in parts if x) + "--"
83
+
84
+
85
+ def _constructed_session(cwd: str | None, session_id: str) -> Path | None:
86
+ """不走列目录,直接按编码规则拼出会话文件路径。"""
87
+ if not session_id:
88
+ return None
89
+ base = cwd or os.getcwd()
90
+ cand = SESSIONS_ROOT / session_dir_name(base) / session_id / SESSION_FILE
91
+ return cand if cand.is_file() else None
92
+
93
+
94
+ def _find_workspace(cwd: str | None = None):
95
+ """找包含当前目录的工作区条目(取最长前缀)。返回 (path, sessionIds) 或 (None, [])。"""
96
+ idx = _load_json(WORKSPACE_INDEX)
97
+ if not isinstance(idx, dict):
98
+ return None, []
99
+ ws = ((idx.get("tables") or {}).get("workspaces") or {})
100
+ if not isinstance(ws, dict):
101
+ return None, []
102
+ want = os.path.normcase(os.path.abspath(cwd or os.getcwd()))
103
+
104
+ def _norm(p: str) -> str:
105
+ return os.path.normcase(os.path.abspath(p))
106
+
107
+ best, best_len = None, -1
108
+ for _wid, w in ws.items():
109
+ if not isinstance(w, dict):
110
+ continue
111
+ p = w.get("path")
112
+ if not isinstance(p, str) or not p:
113
+ continue
114
+ try:
115
+ wp = _norm(p)
116
+ except Exception:
117
+ continue
118
+ if want == wp or want.startswith(wp + os.sep):
119
+ if len(wp) > best_len:
120
+ best, best_len = w, len(wp)
121
+ if best is None:
122
+ return None, []
123
+ ids = best.get("sessionIds")
124
+ return best.get("path"), ([str(x) for x in ids] if isinstance(ids, list) else [])
125
+
126
+
127
+ def _workspace_session_ids(cwd: str | None = None) -> list[str]:
128
+ return _find_workspace(cwd)[1]
129
+
130
+
131
+ def _glob_session(session_id: str) -> Path | None:
132
+ if not session_id:
133
+ return None
134
+ hits = glob.glob(str(SESSIONS_ROOT / "*" / session_id / SESSION_FILE))
135
+ return Path(hits[0]) if hits else None
136
+
137
+
138
+ def list_sessions() -> list[dict]:
139
+ """所有会话,按文件 mtime 倒序。"""
140
+ out = []
141
+ for p in glob.glob(str(SESSIONS_ROOT / "*" / "*" / SESSION_FILE)):
142
+ try:
143
+ st = os.stat(p)
144
+ except OSError:
145
+ continue
146
+ out.append({
147
+ "session": Path(p).parent.name,
148
+ "project": Path(p).parent.parent.name,
149
+ "path": p,
150
+ "mtime": int(st.st_mtime),
151
+ "bytes": st.st_size,
152
+ })
153
+ out.sort(key=lambda x: x["mtime"], reverse=True)
154
+ return out
155
+
156
+
157
+ def find_session(session: str | None = None, cwd: str | None = None) -> Path | None:
158
+ """定位要读的会话文件。
159
+
160
+ 优先用「编码规则直拼路径」而不列目录——实测 Python 枚举该目录在某些
161
+ 环境下会返回空,但按确定路径直接 open 是可靠的。
162
+ """
163
+ if session:
164
+ # 显式 id:先按当前 cwd 拼,再试列目录
165
+ p = _constructed_session(cwd, session)
166
+ if p:
167
+ return p
168
+ p = _glob_session(session)
169
+ if p:
170
+ return p
171
+ hits = glob.glob(str(SESSIONS_ROOT / "*" / f"*{session}*" / SESSION_FILE))
172
+ return Path(hits[0]) if hits else None
173
+ ws_path, ids = _find_workspace(cwd)
174
+ base = ws_path or cwd
175
+ for sid in ids:
176
+ p = _constructed_session(base, sid) or _glob_session(sid)
177
+ if p:
178
+ return p
179
+ # 兜底:全局最新
180
+ alls = list_sessions()
181
+ return Path(alls[0]["path"]) if alls else None
182
+
183
+
184
+ # ---------------------------------------------------------------- 读事件
185
+
186
+ def read_events(path: Path) -> list[dict]:
187
+ """解压并逐行解析。容忍:文件正在被写(末行可能撕裂)、zstd 被拒。"""
188
+ try:
189
+ import zstandard
190
+ except Exception:
191
+ return []
192
+ try:
193
+ with zstandard.ZstdDecompressor().stream_reader(path.read_bytes()) as r:
194
+ text = r.read().decode("utf-8", errors="replace")
195
+ except Exception:
196
+ # 正在写导致读失败:再试一次
197
+ try:
198
+ time.sleep(0.05)
199
+ with zstandard.ZstdDecompressor().stream_reader(path.read_bytes()) as r:
200
+ text = r.read().decode("utf-8", errors="replace")
201
+ except Exception:
202
+ return []
203
+ out = []
204
+ for ln in text.splitlines():
205
+ ln = ln.strip()
206
+ if not ln:
207
+ continue
208
+ try:
209
+ o = json.loads(ln)
210
+ except Exception:
211
+ continue # 撕裂的末行直接跳过
212
+ if isinstance(o, dict):
213
+ out.append(o)
214
+ return out
215
+
216
+
217
+ def _msg_of(ev: dict) -> dict | None:
218
+ """取出事件里的消息体。
219
+
220
+ ⚠ 两种形态都要认(2026-11-28 实测踩过):
221
+ · assistant/message、tool/result、system/message → data = {turn, step, message:{...}}
222
+ · user/message → **data 本身就是消息**(有 role/content,没有 message 键)
223
+ 只认前一种会把**所有用户消息整条丢掉**(症状:摘要里"没读到用户消息"、
224
+ user 计数偏少)。
225
+ """
226
+ d = ev.get("data") or {}
227
+ m = d.get("message")
228
+ if isinstance(m, dict):
229
+ return m
230
+ if isinstance(d.get("role"), str) and "content" in d:
231
+ return d
232
+ return None
233
+
234
+
235
+ def _turn_starts(events: list[dict]) -> list:
236
+ """[(seq, turn)],按 seq 升序。"""
237
+ starts = []
238
+ for ev in events:
239
+ if ev.get("type") != "turn/start":
240
+ continue
241
+ t = (ev.get("data") or {}).get("turn")
242
+ s = ev.get("seq")
243
+ if isinstance(t, int) and isinstance(s, int):
244
+ starts.append((s, t))
245
+ starts.sort()
246
+ return starts
247
+
248
+
249
+ def _turn_for_seq(starts: list, seq) -> int | None:
250
+ """消息归属哪一轮:取 seq <= 消息 seq 的最后一个 turn/start;
251
+ 若消息出现在第一个 turn/start 之前(如首条 inbox 注入),归给紧接着的那一轮。"""
252
+ if not isinstance(seq, int):
253
+ return None
254
+ prev = None
255
+ for s, t in starts:
256
+ if s <= seq:
257
+ prev = t
258
+ else:
259
+ return prev if prev is not None else t
260
+ return prev
261
+
262
+
263
+ def _text_len(m: dict) -> tuple[int, int]:
264
+ """(text 字符, reasoning 字符)。"""
265
+ t = r = 0
266
+ c = m.get("content")
267
+ if isinstance(c, str):
268
+ return len(c), 0
269
+ for part in (c or []):
270
+ if not isinstance(part, dict):
271
+ continue
272
+ if part.get("type") == "text":
273
+ t += len(str(part.get("text") or ""))
274
+ elif part.get("type") == "reasoning":
275
+ r += len(str(part.get("text") or ""))
276
+ return t, r
277
+
278
+
279
+ def _first_text(m: dict, n: int = 80) -> str:
280
+ c = m.get("content")
281
+ if isinstance(c, str):
282
+ return c[:n]
283
+ for part in (c or []):
284
+ if isinstance(part, dict) and part.get("type") == "text":
285
+ return str(part.get("text") or "")[:n]
286
+ return ""
287
+
288
+
289
+ def reconstruct_messages(events: list[dict]) -> list[dict]:
290
+ """把事件流重建成消息序列(按 id 去重,保持首次出现顺序)。"""
291
+ seen = {}
292
+ order = []
293
+ def add(seq, m, turn=None, step=None):
294
+ if not isinstance(m, dict):
295
+ return
296
+ mid = m.get("id") or f"seq:{seq}"
297
+ if mid in seen:
298
+ return
299
+ t, r = _text_len(m)
300
+ seen[mid] = {
301
+ "seq": seq,
302
+ "id": mid,
303
+ "role": m.get("role") or "unknown",
304
+ "source": (m.get("source") or {}).get("kind") or "",
305
+ # §54:宿主 compaction 的 checkpoint(summary 替代片段)——已压过,别再压
306
+ "is_checkpoint": ((m.get("source") or {}).get("kind") == "compact-checkpoint"),
307
+ "chars": t,
308
+ "reasoning": r,
309
+ "tool_call_id": m.get("toolCallId") or "",
310
+ "tool_call_ids": [
311
+ str(p.get("id"))
312
+ for p in (m.get("content") or [])
313
+ if isinstance(p, dict) and p.get("type") == "tool-call" and p.get("id")
314
+ ],
315
+ "has_tool_call": any(
316
+ isinstance(p, dict) and p.get("type") == "tool-call"
317
+ for p in (m.get("content") or [])
318
+ ) if not isinstance(m.get("content"), str) else False,
319
+ "is_error": bool(m.get("isError")),
320
+ "turn": turn,
321
+ "step": step,
322
+ "preview": _first_text(m),
323
+ }
324
+ order.append(mid)
325
+
326
+ starts = _turn_starts(events)
327
+ for ev in events:
328
+ t = ev.get("type")
329
+ seq = ev.get("seq", 0)
330
+ d = ev.get("data") or {}
331
+ turn, step = d.get("turn"), d.get("step")
332
+ if turn is None:
333
+ # user/message 等不带 turn:按 turn/start 的 seq 推归属
334
+ turn = _turn_for_seq(starts, seq)
335
+ if t in ("system/message", "user/message", "assistant/message", "tool/result"):
336
+ add(seq, _msg_of(ev), turn, step)
337
+ elif t == "agent/inbox/spliced":
338
+ for m in (d.get("inserted") or []):
339
+ add(seq, m, turn, step)
340
+ return [seen[k] for k in order]
341
+
342
+
343
+ def completed_turns(events: list[dict]) -> tuple[set, int]:
344
+ """(已结束的 turn 集合, 最大 turn 号)。未结束的轮(正在进行)绝不折叠。"""
345
+ done, mx = set(), 0
346
+ for ev in events:
347
+ d = ev.get("data") or {}
348
+ t = d.get("turn")
349
+ if isinstance(t, int):
350
+ mx = max(mx, t)
351
+ if ev.get("type") == "turn/end" and isinstance(t, int):
352
+ done.add(t)
353
+ return done, mx
354
+
355
+
356
+ # ---------------------------------------------------------------- 分析
357
+
358
+ def analyze(path: Path) -> dict:
359
+ events = read_events(path)
360
+ msgs = reconstruct_messages(events)
361
+
362
+ by_role, by_source = {}, {}
363
+ text_chars = reasoning_chars = 0
364
+ for m in msgs:
365
+ by_role[m["role"]] = by_role.get(m["role"], 0) + 1
366
+ src = m["source"] or "host"
367
+ by_source[src] = by_source.get(src, 0) + 1
368
+ text_chars += m["chars"]
369
+ reasoning_chars += m["reasoning"]
370
+
371
+ tools = {}
372
+ tool_errors = []
373
+ turns = []
374
+ errors = []
375
+ retries = []
376
+ approvals = []
377
+ goals = []
378
+ todos = None
379
+ meta = {}
380
+ context_window = None
381
+
382
+ for ev in events:
383
+ t = ev.get("type")
384
+ d = ev.get("data") or {}
385
+ if t == "session":
386
+ meta = {"session": ev.get("id"), "cwd": ev.get("cwd"),
387
+ "preset": ev.get("agentPreset"), "created": ev.get("createdAt")}
388
+ elif t == "request/context":
389
+ context_window = d.get("contextWindow")
390
+ meta.setdefault("provider", d.get("provider"))
391
+ meta.setdefault("model", d.get("model"))
392
+ elif t == "turn/start":
393
+ turns.append(d.get("turn"))
394
+ elif t == "turn/end":
395
+ reason = d.get("reason") or {}
396
+ if reason.get("kind") == "error":
397
+ err = reason.get("error") or {}
398
+ errors.append({"turn": d.get("turn"), "message": err.get("message"),
399
+ "code": err.get("code")})
400
+ elif reason.get("kind") and reason.get("kind") != "completed":
401
+ errors.append({"turn": d.get("turn"), "message": f"turn 结束:{reason.get('kind')}",
402
+ "code": reason.get("kind")})
403
+ elif t == "tool/call":
404
+ name = d.get("name") or "?"
405
+ tools[name] = tools.get(name, 0) + 1
406
+ elif t == "tool/result":
407
+ m = _msg_of(ev) or {}
408
+ if m.get("isError"):
409
+ tool_errors.append({"tool": m.get("source", {}).get("kind"),
410
+ "text": _first_text(m, 120)})
411
+ elif t == "llm/retry":
412
+ f = d.get("failure") or {}
413
+ retries.append({"turn": d.get("turn"), "step": d.get("step"),
414
+ "retry": d.get("retry"), "code": f.get("code"),
415
+ "message": f.get("message")})
416
+ elif t == "approval/decided":
417
+ approvals.append({"id": d.get("id"), "outcome": d.get("outcome")})
418
+ elif t == "goal/change":
419
+ g = d.get("goal") or {}
420
+ goals.append({"op": d.get("operation"), "id": g.get("id"),
421
+ "phase": g.get("phase")})
422
+ elif t == "todo/write":
423
+ todos = d.get("todos")
424
+
425
+ press = _load_json(core.HOME / PRESSURE) if hasattr(core, "HOME") else None
426
+ press = press if isinstance(press, dict) else {}
427
+ completed, max_turn = completed_turns(events)
428
+ plans = plan_turns(msgs, completed, max_turn)
429
+
430
+ # 「宿主口径」与「折叠后口径」并列:APP 的水位是**宿主自己的 tokenMeter**,
431
+ # 它按会话历史算;灵枢的折叠只改**本次请求发出去的 messages**(插件 contextFold 开才生效)。
432
+ # 所以会出现"灵枢压了、APP 显示没降"——把两个数一起给出来,才不至于误判成没生效。
433
+ _eff = simulate_folds(msgs, load_folds())
434
+ _win = (press.get("context_window") or context_window) or 0
435
+ _eff_pct = round(_eff["tokens_after"] / _win * 100, 1) if _win else None
436
+
437
+ return {
438
+ "session_file": str(path),
439
+ "meta": meta,
440
+ "context_window": context_window,
441
+ "pressure": {
442
+ "pct": press.get("pct"),
443
+ "tokens": press.get("pressure_tokens"),
444
+ "window": press.get("context_window") or context_window,
445
+ "source": press.get("source"),
446
+ "age_sec": (int(time.time()) - int(press.get("ts") or 0)) if press.get("ts") else None,
447
+ },
448
+ "totals": {
449
+ "messages": len(msgs),
450
+ "text_chars": text_chars,
451
+ "reasoning_chars": reasoning_chars,
452
+ "by_role": by_role,
453
+ "by_source": by_source,
454
+ "turns": len(turns),
455
+ },
456
+ "tools": tools,
457
+ "tool_errors": tool_errors,
458
+ "errors": errors,
459
+ "retries": retries,
460
+ "approvals": approvals,
461
+ "goals": goals,
462
+ "todos": todos,
463
+ "plan": plans,
464
+ "effective": {
465
+ "tokens_before": _eff["tokens_before"],
466
+ "tokens_after": _eff["tokens_after"],
467
+ "pct": _eff_pct,
468
+ "saved_pct": _eff["saved_pct"],
469
+ "folded_turns": _eff["folded_turns"],
470
+ },
471
+ "_messages": msgs,
472
+ "_events": len(events),
473
+ }
474
+
475
+
476
+ # ---------------------------------------------------------------- 折叠建议
477
+
478
+ def plan_ranges(msgs: list[dict]) -> list[dict]:
479
+ """建议折叠区间:只挑「纯文本、非工具、非 system」的连续段。
480
+
481
+ 保守:>=FOLD_MIN_RUN 条;末尾 KEEP_RECENT 条一律保留。
482
+ """
483
+ if not msgs:
484
+ return []
485
+ keep_from = len(msgs) - KEEP_RECENT
486
+ out = []
487
+ cur = []
488
+ def flush():
489
+ if len(cur) >= FOLD_MIN_RUN:
490
+ out.append({
491
+ "from": cur[0]["seq"], "to": cur[-1]["seq"],
492
+ "messages": len(cur),
493
+ "characters": sum(x["chars"] for x in cur),
494
+ "message_ids": [x["id"] for x in cur],
495
+ })
496
+ cur.clear()
497
+ for idx, m in enumerate(msgs):
498
+ ok = (m["role"] in ("user", "assistant")
499
+ and not m["tool_call_id"] and m["chars"] > 0 and idx < keep_from)
500
+ if ok:
501
+ cur.append(m)
502
+ else:
503
+ flush()
504
+ flush()
505
+ return out
506
+
507
+
508
+ # ---------------------------------------------------------------- 折叠账本
509
+
510
+ def folds_path() -> Path:
511
+ return Path(core.HOME) / FOLDS
512
+
513
+
514
+ def _fold_enabled() -> bool:
515
+ """插件侧 contextFold 是否已打开(决定折叠是否真的作用于请求)。"""
516
+ try:
517
+ cfg = _load_json(Path(core.HOME) / "config.json") or {}
518
+ return bool(cfg.get("contextFold"))
519
+ except Exception:
520
+ return False
521
+
522
+
523
+ def load_folds() -> dict:
524
+ d = _load_json(folds_path())
525
+ if not isinstance(d, dict) or not isinstance(d.get("folds"), list):
526
+ return {"version": 1, "folds": []}
527
+ return d
528
+
529
+
530
+ def save_folds(doc: dict) -> None:
531
+ p = folds_path()
532
+ p.parent.mkdir(parents=True, exist_ok=True)
533
+ p.write_text(json.dumps(doc, ensure_ascii=False, indent=2), encoding="utf-8")
534
+
535
+
536
+ def _full_text(m: dict) -> str:
537
+ c = m.get("content")
538
+ if isinstance(c, str):
539
+ return c
540
+ out = []
541
+ for p in (c or []):
542
+ if isinstance(p, dict) and p.get("type") == "text":
543
+ out.append(str(p.get("text") or ""))
544
+ return "\n".join(out)
545
+
546
+
547
+ def turn_cost(msgs: list[dict], turn: int) -> dict:
548
+ """一整轮的**真实上下文成本**:正文 + 推理,以及条数。
549
+
550
+ 为什么不能只算对话正文:实测 turn1 的对话正文只有 352 字,而整轮占 4 万字符——
551
+ 绝大部分是 reasoning 与工具输出。只按正文报"压缩比"会严重低估真实收益。
552
+ """
553
+ g = [m for m in msgs if m.get("turn") == turn]
554
+ return {
555
+ "messages": len(g),
556
+ "text_chars": sum(m["chars"] for m in g),
557
+ "reasoning_chars": sum(m["reasoning"] for m in g),
558
+ "total_chars": sum(m["chars"] + m["reasoning"] for m in g),
559
+ "tool_results": sum(1 for m in g if m.get("tool_call_id")),
560
+ }
561
+
562
+
563
+ def turn_tool_digest(events: list[dict], turn: int) -> str:
564
+ """该轮的工具活动摘要(谁调了几次、失败几次)——折叠后别把"做过什么"一起丢掉。"""
565
+ counts: dict[str, int] = {}
566
+ errs = 0
567
+ starts = _turn_starts(events)
568
+ for ev in events:
569
+ t = (ev.get("data") or {}).get("turn")
570
+ if t is None:
571
+ t = _turn_for_seq(starts, ev.get("seq"))
572
+ if t != turn:
573
+ continue
574
+ if ev.get("type") == "tool/call":
575
+ name = (ev.get("data") or {}).get("name") or "?"
576
+ counts[name] = counts.get(name, 0) + 1
577
+ elif ev.get("type") == "tool/result":
578
+ m = _msg_of(ev) or {}
579
+ if m.get("isError"):
580
+ errs += 1
581
+ if not counts:
582
+ return ""
583
+ parts = [f"{k}×{v}" for k, v in sorted(counts.items(), key=lambda x: -x[1])]
584
+ tail = f"(失败 {errs} 次)" if errs else ""
585
+ return "、".join(parts) + tail
586
+
587
+
588
+ def turn_turns(events: list[dict], turn: int) -> list[dict]:
589
+ """取某一轮的真实**对话**文本(给摘要器用)。
590
+
591
+ 只收真正的人机对话:
592
+ · user/message 且 source.kind == 'user'(**排除灵枢自己的注入块**
593
+ skill-invocation,以及 time-context/runtime-context/skill-catalog/goal 等宿主上下文——
594
+ 实测这些块含"必须/不要/别"等词,会被摘要器当成"约束/未决/原话"三段同时抽中,
595
+ 把整份人格注入塞进摘要);
596
+ · assistant/message 且 source.kind == 'model';
597
+ · 跳过 role=tool(工具输出是噪音,不是对话)。
598
+ 单条截到 2000 字,避免某个大块独占摘要。
599
+ """
600
+ seen = set()
601
+ out = []
602
+ starts = _turn_starts(events)
603
+ for ev in events:
604
+ m = _msg_of(ev)
605
+ if not isinstance(m, dict):
606
+ continue
607
+ t = (ev.get("data") or {}).get("turn")
608
+ if t is None:
609
+ t = _turn_for_seq(starts, ev.get("seq"))
610
+ if t != turn:
611
+ continue
612
+ role = m.get("role")
613
+ if role not in ("user", "assistant"):
614
+ continue
615
+ kind = ((m.get("source") or {}).get("kind") or "")
616
+ # 用**排除表**而不是白名单:未知但真实的来源要保留,已知的注入/上下文才剔掉。
617
+ if kind in INJECTED_KINDS:
618
+ continue
619
+ mid = m.get("id")
620
+ if mid and mid in seen:
621
+ continue
622
+ if mid:
623
+ seen.add(mid)
624
+ txt = _full_text(m).strip()
625
+ if not txt:
626
+ continue
627
+ out.append({"role": role, "text": txt[:2000]})
628
+ return out
629
+
630
+
631
+ def plan_turns(msgs: list[dict], completed: set, max_turn: int, keep_turns: int = 2) -> list[dict]:
632
+ """按轮出折叠建议:只挑**已结束**的轮,且不碰最近 keep_turns 轮。"""
633
+ groups: dict[int, list] = {}
634
+ for m in msgs:
635
+ t = m.get("turn")
636
+ if isinstance(t, int):
637
+ groups.setdefault(t, []).append(m)
638
+ out = []
639
+ for t in sorted(groups):
640
+ if t not in completed or t > max_turn - keep_turns:
641
+ continue
642
+ g = groups[t]
643
+ # §54:这一轮里已经有宿主 checkpoint(summary 替代过),不再折叠——避免重复压缩。
644
+ if any(x.get('is_checkpoint') for x in g):
645
+ continue
646
+ out.append({
647
+ "turn": t,
648
+ "messages": len(g),
649
+ "characters": sum(x["chars"] for x in g),
650
+ "has_tool": any(x.get("has_tool_call") or x.get("tool_call_id") for x in g),
651
+ "message_ids": [x["id"] for x in g],
652
+ })
653
+ return out
654
+
655
+
656
+ def create_fold(turn: int, path: Path, max_chars: int = 1200,
657
+ keep_turns: int = 2, force: bool = False,
658
+ replace: bool = False) -> dict:
659
+ """把一整轮压成一条五段式摘要,记进账本(不直接改上下文,改由插件应用)。"""
660
+ import uuid
661
+
662
+ from summarizer import normalize_turns, summarize
663
+
664
+ events = read_events(path)
665
+ msgs = reconstruct_messages(events)
666
+ completed, max_turn = completed_turns(events)
667
+
668
+ if turn not in completed and not force:
669
+ raise ValueError(f"turn {turn} 还没结束(已结束:{sorted(completed)});确需折叠加 --force")
670
+ if turn > max_turn - keep_turns and not force:
671
+ raise ValueError(f"turn {turn} 落在最近 {keep_turns} 轮保留区内(最大轮 {max_turn});确需折叠加 --force")
672
+
673
+ group = [m for m in msgs if m.get("turn") == turn]
674
+ if not group:
675
+ raise ValueError(f"turn {turn} 没有可折叠的消息")
676
+
677
+ turns = turn_turns(events, turn)
678
+ if not turns:
679
+ raise ValueError(f"turn {turn} 没有正文文本(全是工具调用?)")
680
+
681
+ cost = turn_cost(msgs, turn)
682
+ chars_before = cost["total_chars"] or sum(len(t["text"]) for t in turns)
683
+ digest = turn_tool_digest(events, turn)
684
+ res = summarize(normalize_turns(turns), max_chars=max_chars)
685
+ summary = str(res.get("text") or "").strip()
686
+ if not summary:
687
+ raise ValueError("摘要生成失败(空结果)")
688
+
689
+ doc = load_folds()
690
+ entry = {
691
+ "id": "f_" + uuid.uuid4().hex[:10],
692
+ "session": (path.parent.name),
693
+ "turn": turn,
694
+ "message_ids": [m["id"] for m in group],
695
+ "seq_from": min(m["seq"] for m in group),
696
+ "seq_to": max(m["seq"] for m in group),
697
+ "chars_before": chars_before,
698
+ "chars_after": len(summary),
699
+ "summary": summary,
700
+ "tool_digest": digest,
701
+ "cost": cost,
702
+ "source": res.get("source"),
703
+ "warnings": res.get("warnings") or [],
704
+ "created": int(time.time()),
705
+ "applied": False,
706
+ "restored": False,
707
+ }
708
+ if replace:
709
+ # 同一会话同一轮已有折叠时,把旧的标成已还原并由新条目取代(保留审计痕迹)
710
+ for f in doc["folds"]:
711
+ if (isinstance(f, dict) and f.get("turn") == turn
712
+ and f.get("session") == entry["session"]
713
+ and not f.get("restored")):
714
+ f["restored"] = True
715
+ f["superseded_by"] = entry["id"]
716
+ doc["folds"].append(entry)
717
+ save_folds(doc)
718
+ return entry
719
+
720
+
721
+ def restore_fold(fold_id: str) -> dict:
722
+ doc = load_folds()
723
+ for f in doc["folds"]:
724
+ if isinstance(f, dict) and f.get("id") == fold_id:
725
+ f["restored"] = True
726
+ save_folds(doc)
727
+ return f
728
+ raise ValueError(f"没有这个折叠:{fold_id}")
729
+
730
+
731
+ def search_folds(kw: str) -> list[dict]:
732
+ kw = (kw or "").strip().lower()
733
+ if not kw:
734
+ return []
735
+ return [f for f in load_folds()["folds"]
736
+ if isinstance(f, dict) and not f.get("restored")
737
+ and kw in str(f.get("summary") or "").lower()]
738
+
739
+
740
+ def render_folds(doc: dict) -> list[str]:
741
+ items = [f for f in doc.get("folds", []) if isinstance(f, dict)]
742
+ if not items:
743
+ return ["(还没有折叠记录。用 `context fold --turn N` 折一整轮)"]
744
+ out = []
745
+ for f in items:
746
+ state = ("已还原" if f.get("restored") else
747
+ ("生效中" if f.get("applied") else "待应用"))
748
+ out.append(f"{f.get('id')} turn{f.get('turn')} {f.get('chars_before', 0)}→"
749
+ f"{f.get('chars_after', 0)} 字 [{state}] {f.get('source')}")
750
+ if f.get("tool_digest"):
751
+ out.append(f" 工具:{f['tool_digest']}")
752
+ out.append("(待应用=账本已记,等插件在 agent/pre-step 落地)")
753
+ return out
754
+
755
+
756
+ def render_plan_turns(plans: list[dict]) -> list[str]:
757
+ if not plans:
758
+ return ["暂无建议(没有已结束且不在保留区的轮)。"]
759
+ out = []
760
+ for p in plans:
761
+ flag = "含工具" if p.get("has_tool") else "纯文本"
762
+ out.append(f"turn {p['turn']}:{p['messages']} 条 / {p['characters']} 字符({flag})")
763
+ return out
764
+
765
+
766
+ def simulate_folds(msgs: list[dict], doc: dict, max_chars: int = 1600) -> dict:
767
+ """**只读模拟**:把账本里生效中的折叠套到消息序列上,算出真实收益。
768
+
769
+ 这是给"要不要打开 contextFold"用的验收工具——行为和插件侧
770
+ `context-fold.js` 对齐(同样按 id 匹配、同样做工具配对保护),
771
+ 但它不写任何东西、也绝不改宿主。
772
+ """
773
+ active = [f for f in (doc.get("folds") or [])
774
+ if isinstance(f, dict) and not f.get("restored")
775
+ and f.get("summary") and f.get("message_ids")]
776
+
777
+ by_id = {}
778
+ for f in active:
779
+ for mid in f["message_ids"]:
780
+ by_id[str(mid)] = f
781
+
782
+ # 工具配对保护:被折叠消息声明的 tool-call id,若仍被保留消息引用 → 该折叠跳过
783
+ dropped_calls = {}
784
+ for m in msgs:
785
+ f = by_id.get(str(m.get("id")))
786
+ if not f:
787
+ continue
788
+ for cid in (m.get("tool_call_ids") or []):
789
+ dropped_calls[cid] = f["id"]
790
+ broken = set()
791
+ for m in msgs:
792
+ if str(m.get("id")) in by_id:
793
+ continue
794
+ cid = m.get("tool_call_id") or ""
795
+ if cid and cid in dropped_calls:
796
+ broken.add(dropped_calls[cid])
797
+
798
+ usable = [f for f in active if f["id"] not in broken]
799
+ out, emitted, folded = [], set(), 0
800
+ for m in msgs:
801
+ f = by_id.get(str(m.get("id")))
802
+ if not f or f["id"] in broken:
803
+ out.append(m)
804
+ continue
805
+ if f["id"] not in emitted:
806
+ emitted.add(f["id"])
807
+ text = str(f.get("summary") or "")[:max(120, max_chars)]
808
+ digest = str(f.get("tool_digest") or "")
809
+ body = f"{text}\n工具:{digest}" if digest else text
810
+ out.append({
811
+ "id": f"fold-{f['id']}", "role": "user", "source": "lingshu-fold",
812
+ "chars": len(body), "reasoning": 0,
813
+ "tool_call_id": "", "tool_call_ids": [], "has_tool_call": False,
814
+ "is_error": False, "turn": f.get("turn"), "seq": f.get("seq_from", 0),
815
+ "preview": body[:80],
816
+ })
817
+ folded += 1
818
+
819
+ def cost(xs):
820
+ return sum(x.get("chars", 0) + x.get("reasoning", 0) for x in xs)
821
+
822
+ before, after = cost(msgs), cost(out)
823
+ return {
824
+ "messages_before": len(msgs),
825
+ "messages_after": len(out),
826
+ "chars_before": before,
827
+ "chars_after": after,
828
+ "tokens_before": int(before / 2),
829
+ "tokens_after": int(after / 2),
830
+ "saved_chars": before - after,
831
+ "saved_pct": round((before - after) / before * 100, 1) if before else 0.0,
832
+ "folded_turns": folded,
833
+ "skipped": sorted(broken),
834
+ "messages": out,
835
+ }
836
+
837
+
838
+ def render_preview(st: dict) -> list[str]:
839
+ lines = [
840
+ f"折叠后:{st['messages_before']} → {st['messages_after']} 条消息"
841
+ f"(折了 {st['folded_turns']} 轮)",
842
+ f"字符:{st['chars_before']} → {st['chars_after']}"
843
+ f"(省 {st['saved_chars']},约 {st['saved_pct']}%)",
844
+ f"估算 token:{st['tokens_before']} → {st['tokens_after']}(chars/2 口径)",
845
+ ]
846
+ if st["skipped"]:
847
+ lines.append(f"⚠ 因工具配对保护跳过 {len(st['skipped'])} 段:{', '.join(st['skipped'])}")
848
+ if not st["folded_turns"]:
849
+ lines.append("(当前没有生效中的折叠,先 `context fold --turn N`)")
850
+ return lines
851
+
852
+
853
+ def autofold(min_pct: float = 60.0, max_turns: int = 3, dry_run: bool = False) -> dict:
854
+ """水位超过阈值时**自动**把可折叠的整轮压成摘要并记账(APP 上下文压缩的自动化入口)。
855
+
856
+ 分工:本函数只负责"生成摘要 + 记账";真正把 `decision.messages` 换掉的是插件
857
+ (`context-fold.js`,需 `contextFold: true`)。两边都开启才算"自动压缩"。
858
+ """
859
+ path = find_session()
860
+ if not path:
861
+ return {"ok": False, "reason": "找不到会话文件"}
862
+ d = analyze(path)
863
+ pct = float((d.get("pressure") or {}).get("pct") or 0.0)
864
+ plan = d.get("plan") or []
865
+ if pct < min_pct:
866
+ return {"ok": True, "skipped": "water_low", "pct": pct, "eligible": len(plan),
867
+ "created": [], "min_pct": min_pct}
868
+ if not plan:
869
+ return {"ok": True, "skipped": "no_eligible_turns", "pct": pct,
870
+ "eligible": 0, "created": [], "min_pct": min_pct}
871
+
872
+ doc = load_folds()
873
+ active_turns = {f.get("turn") for f in doc.get("folds", [])
874
+ if isinstance(f, dict) and not f.get("restored")}
875
+ created = []
876
+ for p in plan:
877
+ if len(created) >= max(1, int(max_turns)):
878
+ break
879
+ t = p.get("turn")
880
+ if t in active_turns:
881
+ continue
882
+ if dry_run:
883
+ created.append({"turn": t, "dry_run": True, "chars": p.get("characters")})
884
+ continue
885
+ try:
886
+ e = create_fold(int(t), path, keep_turns=0, force=True)
887
+ created.append({"turn": t, "id": e["id"], "chars_before": e["chars_before"],
888
+ "chars_after": e["chars_after"]})
889
+ active_turns.add(t)
890
+ except Exception as exc: # noqa: BLE001
891
+ created.append({"turn": t, "error": str(exc)[:120]})
892
+ return {"ok": True, "pct": pct, "eligible": len(plan), "created": created,
893
+ "min_pct": min_pct, "dry_run": dry_run}
894
+
895
+
896
+ def render_autofold(r: dict) -> list[str]:
897
+ if not r.get("ok"):
898
+ return [f"自动折叠失败:{r.get('reason')}"]
899
+ if r.get("skipped") == "water_low":
900
+ return [f"水位 {r.get('pct')}% < 阈值 {r.get('min_pct')}% —— 不折叠"
901
+ f"(可折叠轮 {r.get('eligible')} 个待命)"]
902
+ if r.get("skipped") == "no_eligible_turns":
903
+ return [f"水位 {r.get('pct')}% 已过阈值,但没有可折叠的轮(保留区/未结束)"]
904
+ lines = [f"水位 {r.get('pct')}%,可折叠 {r.get('eligible')} 轮;本次处理 {len(r.get('created') or [])} 个:"]
905
+ for c in r.get("created") or []:
906
+ if c.get("error"):
907
+ lines.append(f" turn{c['turn']} 失败:{c['error']}")
908
+ elif c.get("dry_run"):
909
+ lines.append(f" turn{c['turn']}(干跑,{c.get('chars')} 字符)")
910
+ else:
911
+ lines.append(f" turn{c['turn']} → {c['id']}:{c['chars_before']}→{c['chars_after']} 字")
912
+ return lines
913
+
914
+
915
+ # ---------------------------------------------------------------- 渲染
916
+
917
+ def render_status(d: dict) -> list[str]:
918
+ meta = d.get("meta") or {}
919
+ p = d.get("pressure") or {}
920
+ t = d.get("totals") or {}
921
+ lines = []
922
+ lines.append(f"会话:{meta.get('session') or '?'} ({(meta.get('cwd') or '')})")
923
+ if meta.get("model"):
924
+ lines.append(f"模型:{meta.get('provider')} / {meta.get('model')}")
925
+ if p.get("pct") is not None:
926
+ lines.append(f"水位:{p.get('pct')}%({p.get('tokens')} / {p.get('window')} token,源 {p.get('source')})")
927
+ eff = d.get("effective") or {}
928
+ if eff.get("folded_turns"):
929
+ _flag = "" if _fold_enabled() else "(⚠ 插件 contextFold 未开,请求尚未用上)"
930
+ lines.append(
931
+ f"折叠后:{eff.get('pct')}%(省 {eff.get('saved_pct')}%,折了 {eff.get('folded_turns')} 轮){_flag}")
932
+ else:
933
+ lines.append(f"水位:未知(窗口 {p.get('window') or d.get('context_window')},无实时压力)")
934
+ roles = t.get("by_role", {})
935
+ role_s = "、".join(f"{k} {v}" for k, v in roles.items()) or "—"
936
+ lines.append(f"上下文:{t.get('messages', 0)} 条 / {t.get('turns', 0)} 轮({role_s})")
937
+ lines.append(f"字符:正文 {t.get('text_chars', 0)} + 推理 {t.get('reasoning_chars', 0)}")
938
+ src = t.get("by_source", {})
939
+ if src:
940
+ lines.append("来源:" + "、".join(f"{k} {v}" for k, v in src.items()))
941
+ tools = d.get("tools") or {}
942
+ if tools:
943
+ lines.append("工具:" + "、".join(f"{k}×{v}" for k, v in sorted(tools.items(), key=lambda x: -x[1])))
944
+ bad_err = len(d.get("errors") or [])
945
+ bad_retry = len(d.get("retries") or [])
946
+ bad_tool = len(d.get("tool_errors") or [])
947
+ if bad_err or bad_retry or bad_tool:
948
+ lines.append(f"健康:错误 {bad_err} · 重试 {bad_retry} · 工具失败 {bad_tool}(`context errors` 看明细)")
949
+ plans = d.get("plan") or []
950
+ if plans:
951
+ lines.append(f"可折叠 {len(plans)} 轮:" + ";".join(
952
+ f"turn{x['turn']}({x['messages']} 条/{x['characters']} 字)" for x in plans))
953
+ else:
954
+ lines.append("可折叠:暂无(没有已结束且不在保留区的轮)")
955
+ return lines
956
+
957
+
958
+ def render_messages(d: dict, limit: int = MSG_CAP, role: str | None = None) -> list[str]:
959
+ msgs = d.get("_messages") or []
960
+ if role:
961
+ msgs = [m for m in msgs if m["role"] == role]
962
+ total = len(msgs)
963
+ msgs = msgs[-limit:]
964
+ out = []
965
+ for m in msgs:
966
+ flag = "✗" if m["is_error"] else " "
967
+ rc = f" +推理{m['reasoning']}" if m["reasoning"] else ""
968
+ prev = (m["preview"] or "").replace("\n", " ")
969
+ out.append(f"{flag} seq{m['seq']:<4} [{m['role']:<9}] {m['chars']:>6}字{rc:<10} {prev}".rstrip())
970
+ out.append(f"(共 {total} 条,显示末 {len(msgs)} 条)")
971
+ return out
972
+
973
+
974
+ def render_tools(d: dict) -> list[str]:
975
+ tools = d.get("tools") or {}
976
+ if not tools:
977
+ return ["(本次会话没有工具调用)"]
978
+ total = sum(tools.values())
979
+ out = [f"工具调用共 {total} 次:"]
980
+ for k, v in sorted(tools.items(), key=lambda x: -x[1]):
981
+ out.append(f" {k:<16} ×{v}")
982
+ te = d.get("tool_errors") or []
983
+ if te:
984
+ out.append(f"失败 {len(te)} 次:")
985
+ for e in te[:10]:
986
+ out.append(f" ✗ {e['text']}")
987
+ return out
988
+
989
+
990
+ def render_errors(d: dict) -> list[str]:
991
+ out = []
992
+ errs = d.get("errors") or []
993
+ retries = d.get("retries") or []
994
+ tool_errors = d.get("tool_errors") or []
995
+ if not (errs or retries or tool_errors):
996
+ return ["(本次会话没有错误)"]
997
+ if errs:
998
+ out.append(f"轮次错误 {len(errs)} 条:")
999
+ for e in errs:
1000
+ out.append(f" turn {e['turn']}:{e['message']} [{e['code']}]")
1001
+ if retries:
1002
+ out.append(f"模型重试 {len(retries)} 次:")
1003
+ for r in retries:
1004
+ out.append(f" turn {r['turn']} step {r['step']} retry{r['retry']}:{r['code']} {r['message']}")
1005
+ if tool_errors:
1006
+ out.append(f"工具失败 {len(tool_errors)} 次:")
1007
+ for e in tool_errors[:15]:
1008
+ out.append(f" ✗ {e['text']}")
1009
+ return out
1010
+
1011
+
1012
+ # ---------------------------------------------------------------- CLI
1013
+
1014
+ def run(args) -> int:
1015
+ cmd = getattr(args, "ctx_cmd", None) or "status"
1016
+ as_json = bool(getattr(args, "json", False))
1017
+ session = getattr(args, "session", None)
1018
+
1019
+ if cmd == "sessions":
1020
+ rows = list_sessions()
1021
+ if as_json:
1022
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
1023
+ else:
1024
+ for r in rows[:30]:
1025
+ when = time.strftime("%m-%d %H:%M", time.localtime(r["mtime"]))
1026
+ print(f"{r['session']:<44} {when} {r['bytes'] // 1024:>5}KB {r['project']}")
1027
+ return 0
1028
+
1029
+ path = find_session(session)
1030
+ if path is None:
1031
+ print("找不到会话文件(~/.dsh/sessions 下没有 session.v4.jsonl.zstd)。"
1032
+ "如果 APP 版本不同,可能改了存储格式。", file=__import__("sys").stderr)
1033
+ return 2
1034
+
1035
+ d = analyze(path)
1036
+
1037
+ if cmd == "status":
1038
+ if as_json:
1039
+ print(json.dumps({k: v for k, v in d.items() if not k.startswith("_")},
1040
+ ensure_ascii=False, indent=2))
1041
+ else:
1042
+ for line in render_status(d):
1043
+ print(line)
1044
+ return 0
1045
+
1046
+ if cmd == "messages":
1047
+ if as_json:
1048
+ print(json.dumps(d.get("_messages") or [], ensure_ascii=False, indent=2))
1049
+ else:
1050
+ for line in render_messages(d, getattr(args, "limit", MSG_CAP), getattr(args, "role", None)):
1051
+ print(line)
1052
+ return 0
1053
+
1054
+ if cmd == "tools":
1055
+ if as_json:
1056
+ print(json.dumps({"tools": d.get("tools"), "errors": d.get("tool_errors")},
1057
+ ensure_ascii=False, indent=2))
1058
+ else:
1059
+ for line in render_tools(d):
1060
+ print(line)
1061
+ return 0
1062
+
1063
+ if cmd == "errors":
1064
+ if as_json:
1065
+ print(json.dumps({"errors": d.get("errors"), "retries": d.get("retries"),
1066
+ "tool_errors": d.get("tool_errors")}, ensure_ascii=False, indent=2))
1067
+ else:
1068
+ for line in render_errors(d):
1069
+ print(line)
1070
+ return 0
1071
+
1072
+ if cmd == "plan":
1073
+ plans = d.get("plan") or []
1074
+ if as_json:
1075
+ print(json.dumps({"plan": plans}, ensure_ascii=False, indent=2))
1076
+ else:
1077
+ for line in render_plan_turns(plans):
1078
+ print(line)
1079
+ if plans:
1080
+ print("\n折叠某一轮:brain.py context fold --turn <N>")
1081
+ return 0
1082
+
1083
+ if cmd == "autofold":
1084
+ r = autofold(min_pct=float(getattr(args, "min_pct", 60)),
1085
+ max_turns=int(getattr(args, "max_turns", 3)),
1086
+ dry_run=bool(getattr(args, "dry_run", False)))
1087
+ if as_json:
1088
+ print(json.dumps(r, ensure_ascii=False, indent=2))
1089
+ else:
1090
+ for line in render_autofold(r):
1091
+ print(line)
1092
+ return 0
1093
+
1094
+ if cmd == "preview":
1095
+ st = simulate_folds(d.get("_messages") or [], load_folds(),
1096
+ int(getattr(args, "max_chars", 1600)))
1097
+ if as_json:
1098
+ print(json.dumps({k: v for k, v in st.items() if k != "messages"},
1099
+ ensure_ascii=False, indent=2))
1100
+ else:
1101
+ for line in render_preview(st):
1102
+ print(line)
1103
+ show = int(getattr(args, "limit", 0) or 0)
1104
+ if show:
1105
+ print("\n折叠后的消息尾部:")
1106
+ for line in render_messages({"_messages": st["messages"]}, show):
1107
+ print(line)
1108
+ return 0
1109
+
1110
+ if cmd == "fold":
1111
+ try:
1112
+ entry = create_fold(int(args.turn), path,
1113
+ max_chars=int(getattr(args, "max_chars", 1200)),
1114
+ keep_turns=int(getattr(args, "keep_turns", 2)),
1115
+ force=bool(getattr(args, "force", False)),
1116
+ replace=bool(getattr(args, "replace", False)))
1117
+ except ValueError as exc:
1118
+ print(f"[错误] {exc}", file=__import__("sys").stderr)
1119
+ return 1
1120
+ if as_json:
1121
+ print(json.dumps(entry, ensure_ascii=False, indent=2))
1122
+ else:
1123
+ print(f"已记账:{entry['id']} turn{entry['turn']} "
1124
+ f"{entry['chars_before']}→{entry['chars_after']} 字(源 {entry['source']})")
1125
+ print("等插件在 agent/pre-step 应用后生效;`context folds` 看状态。")
1126
+ return 0
1127
+
1128
+ if cmd == "unfold":
1129
+ try:
1130
+ f = restore_fold(args.id)
1131
+ except ValueError as exc:
1132
+ print(f"[错误] {exc}", file=__import__("sys").stderr)
1133
+ return 1
1134
+ print(f"已还原:{f['id']}(turn{f.get('turn')}),之后不再折叠该轮。")
1135
+ return 0
1136
+
1137
+ if cmd == "folds":
1138
+ doc = load_folds()
1139
+ if as_json:
1140
+ print(json.dumps(doc, ensure_ascii=False, indent=2))
1141
+ else:
1142
+ for line in render_folds(doc):
1143
+ print(line)
1144
+ return 0
1145
+
1146
+ if cmd == "search":
1147
+ kw = " ".join(getattr(args, "query", []) or []).strip()
1148
+ hits = search_folds(kw)
1149
+ if as_json:
1150
+ print(json.dumps(hits, ensure_ascii=False, indent=2))
1151
+ else:
1152
+ if not hits:
1153
+ print(f"(没有折叠摘要命中「{kw}」)")
1154
+ for f in hits:
1155
+ print(f"— {f.get('id')} turn{f.get('turn')}(原文 {f.get('chars_before')} 字)")
1156
+ print(f.get("summary") or "")
1157
+ return 0
1158
+
1159
+ print(f"未知的 context 子命令:{cmd}", file=__import__("sys").stderr)
1160
+ return 1