lingshu-skill 5.33.0 → 5.37.1

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
package/scripts/cli.py CHANGED
@@ -237,6 +237,124 @@ def _cleanup_own_tempfile(path: str, enabled: bool) -> None:
237
237
  pass
238
238
 
239
239
 
240
+ # 备份时整目录跳过的内部目录名(出现在路径任意一层即跳过)。
241
+ # .safety = 写盘护栏的回滚快照,既不是用户数据,又会被 safety_net 并发「移入 .pruned」→
242
+ # 打包时文件凭空消失(2026-11-29 实测导致 cron 备份连续失败的根因)。
243
+ # .pruned / .trash = 只移不删的归档区,同样不属于要备份的正文。
244
+ _EXCLUDE_DIR_PARTS = {".safety", ".pruned", ".trash", "node_modules", ".git", ".venv"}
245
+
246
+
247
+ def _file_sig(p) -> str:
248
+ """文件指纹(换行归一后的长度 + sha1 前 12 位)。
249
+
250
+ ⚠ 必须先归一 CRLF:源码在 Windows 检出是 CRLF,而 npm 包里的副本可能是 LF。
251
+ 按字节比对会把"内容其实一样"的两份判成不一致,让 plugin-loaded 天天误报。
252
+ """
253
+ try:
254
+ b = Path(p).read_bytes().replace(b"\r\n", b"\n")
255
+ return f"{len(b)}:{hashlib.sha1(b).hexdigest()[:12]}"
256
+ except Exception:
257
+ return ""
258
+
259
+
260
+ # B2:这些文件决定"运行时行为",副本必须与源码逐字一致,否则就是"改了没生效"。
261
+ _PLUGIN_VERIFY_FILES = (
262
+ "scripts/cli.py",
263
+ "scripts/core.py",
264
+ "scripts/memory.py",
265
+ "cordis-plugin/lingshu-startup/plugin.js",
266
+ "cordis-plugin/lingshu-cron/plugin.js",
267
+ "cordis-plugin/lingshu-guard/plugin.js",
268
+ "cordis-plugin/lingshu-im/plugin.js",
269
+ )
270
+
271
+
272
+ def _newest_startup_ts(home) -> int:
273
+ """lingshu.log 里最近一条「会话开始,注入完成」的时间戳(0=没有)。
274
+
275
+ 这是"插件真的跑起来了"的最直接证据:它由 startup 插件在每次会话开头写入。
276
+ """
277
+ best = 0
278
+ try:
279
+ p = Path(home) / "lingshu.log"
280
+ if not p.is_file():
281
+ return 0
282
+ for ln in p.read_text(encoding="utf-8", errors="replace").splitlines():
283
+ ln = ln.strip()
284
+ if not ln or "会话开始" not in ln:
285
+ continue
286
+ try:
287
+ o = json.loads(ln)
288
+ ts = int(o.get("ts") or 0)
289
+ except Exception:
290
+ continue
291
+ best = max(best, ts)
292
+ except Exception:
293
+ return best
294
+ return best
295
+
296
+
297
+ def _ping_panel(ports=(8766, 3429, 6063), timeout: float = 1.0) -> int | None:
298
+ """探测灵枢面板健康端点,返回响应的端口(None=都没起)。
299
+
300
+ `/api/ping` 免鉴权(启动器在拿不到 token 时也用它判断"面板是否已在跑"),
301
+ 所以它可以当健康检查用。
302
+ """
303
+ import urllib.request as _u
304
+ for port in ports:
305
+ try:
306
+ with _u.urlopen(f"http://127.0.0.1:{port}/api/ping", timeout=timeout) as r:
307
+ if 200 <= int(getattr(r, "status", r.getcode())) < 300:
308
+ return port
309
+ except Exception:
310
+ continue
311
+ return None
312
+
313
+
314
+ def _plugin_verify_files() -> tuple:
315
+ """B2 要核对哪些文件:**从 manifest 自动取**,别硬编码。
316
+
317
+ 硬编码时新增脚本不在清单里,等于给自己留了个"永远验不到"的盲区(§7 #42)。
318
+ manifest 只列交付物(scripts/*.py 与 cordis-plugin/**/*.js),正好就是要核对的集合。
319
+ """
320
+ try:
321
+ mf = Path(__file__).resolve().parent.parent / "manifest.json"
322
+ data = json.loads(mf.read_text(encoding="utf-8-sig"))
323
+ out = []
324
+ for rel in data.get("files") or []:
325
+ r = str(rel).replace("\\", "/")
326
+ if r.startswith("scripts/") and r.endswith(".py"):
327
+ out.append(r)
328
+ elif r.startswith("cordis-plugin/") and r.endswith(".js"):
329
+ out.append(r)
330
+ if out:
331
+ return tuple(out)
332
+ except Exception:
333
+ pass
334
+ return _PLUGIN_VERIFY_FILES
335
+
336
+
337
+ def _du(path) -> tuple:
338
+ """(文件数, 字节数)。目录不存在返回 (0,0);单个文件也支持。"""
339
+ p = Path(path)
340
+ try:
341
+ if p.is_file():
342
+ return 1, p.stat().st_size
343
+ if not p.is_dir():
344
+ return 0, 0
345
+ except OSError:
346
+ return 0, 0
347
+ n = s = 0
348
+ for root, _dirs, files in os.walk(p):
349
+ for f in files:
350
+ try:
351
+ s += (Path(root) / f).stat().st_size
352
+ n += 1
353
+ except OSError:
354
+ pass
355
+ return n, s
356
+
357
+
240
358
  def cmd_backup(target: str | None = None, keep: int = 20, password: str | None = None,
241
359
  assume_yes: bool = False) -> int:
242
360
  """把整个记忆库打成 zip。保留最近 keep 份,旧的自动修剪。
@@ -271,20 +389,40 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
271
389
  except Exception as exc:
272
390
  print(f"[错误] 备份目录不可写:{out_dir}({exc})", file=sys.stderr)
273
391
  return 2
392
+ # zip 名去重必须**原子**:`while zip_path.exists()` 是典型的 TOCTOU,
393
+ # 两个备份并发跑会同时算出同一个文件名、互相覆盖(2026-11-29 压测实测:
394
+ # 6 次备份全 rc=0,却只留下 4 个包)。用 os.open(O_EXCL) 把"检查+创建"合一步。
274
395
  zip_path = out_dir / f"brain-memory_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip"
275
396
  k = 1
276
- while zip_path.exists(): # 同一秒内多次备份时避免互相覆盖
277
- zip_path = out_dir / f"brain-memory_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{k}.zip"
278
- k += 1
397
+ while True:
398
+ try:
399
+ _fd = os.open(zip_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
400
+ os.close(_fd)
401
+ break
402
+ except FileExistsError:
403
+ k += 1
404
+ zip_path = (out_dir
405
+ / f"brain-memory_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{k}.zip")
406
+ continue
407
+ except OSError as _e:
408
+ print(f"[错误] 备份目录不可写:{out_dir}({_e})", file=sys.stderr)
409
+ return 2
279
410
  n = 0
280
411
  skipped = 0
412
+ vanished = 0
281
413
  try:
282
414
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
283
415
  for f in sorted(HOME.rglob("*")):
284
416
  if f.is_dir() or "__pycache__" in f.parts:
285
417
  continue
418
+ if _EXCLUDE_DIR_PARTS & set(f.parts):
419
+ continue # 见 _EXCLUDE_DIR_PARTS:回滚快照/归档/垃圾桶等内部目录
286
420
  if f.name.endswith(".tmp") or f.name == ".write-probe":
287
421
  continue
422
+ # 崩溃堆栈/诊断残留不属于记忆正文:留在 HOME 里供排查,但不进备份包
423
+ #(实测备份包里混过 2 条 crash-*.log)。
424
+ if f.name.startswith("crash-") and f.suffix == ".log":
425
+ continue
288
426
  if f == zip_path:
289
427
  continue # 别把正在写的备份包自己打包进去(--out 指向记忆库自身时会踩到)
290
428
  if "backups" in f.parts and f.suffix == ".zip":
@@ -293,17 +431,28 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
293
431
  skipped += 1
294
432
  continue # 密钥/凭据不进备份包
295
433
  rel = f.relative_to(HOME).as_posix()
296
- if f.name == "config.json":
297
- # config.json 里 panel.cloud 的 token 脱敏后再入包
298
- data = _sanitize_config_json(f.read_bytes())
299
- if not data:
300
- skipped += 1
301
- continue
302
- zf.writestr(rel, data)
434
+ # 单文件必须在自己的 try 里读:备份遍历 HOME 的同时,别的进程
435
+ # (safety_net 修剪、dream、面板保存、cron 别的任务)会创建/移动/删除文件。
436
+ # 实测 2026-11-29 08:23:备份 rglob 已列出 .safety 下某个快照,
437
+ # 修剪恰好把该目录移进 .pruned → zf.write 抛 WinError 2
438
+ # → **整个备份失败**(每 6 小时的备份全废)。一个文件消失不该毁掉整包。
439
+ try:
440
+ if f.name == "config.json":
441
+ # config.json 里 panel.cloud 的 token 脱敏后再入包
442
+ data = _sanitize_config_json(f.read_bytes())
443
+ if not data:
444
+ skipped += 1
445
+ continue
446
+ zf.writestr(rel, data)
447
+ else:
448
+ zf.write(f, rel)
303
449
  n += 1
304
- continue
305
- zf.write(f, rel)
306
- n += 1
450
+ except OSError as exc:
451
+ vanished += 1
452
+ if vanished == 1: # 只记第一条,避免刷屏
453
+ log_event("backup",
454
+ f"跳过 {rel}(并发写入/移动导致读不到):{exc}",
455
+ level="warn")
307
456
  # 包内清单:把"这个包到底装了什么、有多少条"写进去,
308
457
  # 事后(以及面板恢复前)不必解包就能判断它是不是空壳。
309
458
  try:
@@ -338,10 +487,22 @@ def cmd_backup(target: str | None = None, keep: int = 20, password: str | None =
338
487
  except Exception as exc: # noqa: BLE001
339
488
  log_event("backup", f"包内清单写入失败(备份本身完好):{exc}", level="warn")
340
489
  except Exception as exc:
490
+ # 半截包留在原处 = 投毒:它会因为没有 .sha256 sidecar 而被一眼当成
491
+ # "有效备份",将来恢复时才发现是坏的。移入 .pruned/(不删除,且 .pruned
492
+ # 已在 _EXCLUDE_DIR_PARTS 里,下次备份也不会把它打进去)。
493
+ try:
494
+ if zip_path.is_file():
495
+ pruned = out_dir / ".pruned"
496
+ pruned.mkdir(parents=True, exist_ok=True)
497
+ zip_path.replace(pruned / f"{zip_path.name}.partial")
498
+ except Exception:
499
+ pass
341
500
  print(f"[错误] 备份失败:{exc}", file=sys.stderr)
342
501
  return 2
343
502
  if skipped:
344
503
  print(f"跳过 {skipped} 个敏感文件(密钥/凭据不进备份)")
504
+ if vanished:
505
+ print(f"跳过 {vanished} 个并发消失的文件(备份仍完整,见 lingshu.log)")
345
506
  # —— v3.02 #6:备份完整性自检 + sha256 sidecar ——
346
507
  # 写完立刻 testzip:防磁盘满/编码问题产出坏包却当成功;坏了删掉并报错。
347
508
  # .sha256 sidecar 让备份文件本身可被第三方对账(sha256sum -c)。
@@ -628,11 +789,27 @@ def cmd_restore(zip_path: str, yes: bool = False, password: str | None = None,
628
789
  # ---------------------------------------------------------------- archive(冷热归档)
629
790
 
630
791
  def cmd_archive(action: str = "show", arg: str = "", limit: int = 20,
631
- dry_run: bool = False) -> int:
792
+ dry_run: bool = False, keep: int | None = None) -> int:
632
793
  """归档层命令:查看 / 搜索 / 回捞 / 手动触发归档。
633
794
 
634
795
  归档只把记忆从热遍历集合里移出,原文一字不丢;`archive restore <id>` 随时回热。
635
796
  """
797
+ if action == "dust":
798
+ # 淡忘区超量自动归档:只挪"超出 keep 的最旧那部分",封存原文/受保护项不动。
799
+ try:
800
+ r = dust_archive(keep=keep, dry_run=dry_run)
801
+ except PermissionError as exc:
802
+ print(f"[只读] {exc}", file=sys.stderr)
803
+ return 1
804
+ verb = "可归档" if dry_run else "已归档"
805
+ print(f"{verb} {r['count']} 条淡忘记忆 → 归档层"
806
+ f"(保留 {r['kept']}/{r['keep']} 条;原文保真,archive restore 可回热)。")
807
+ for x in r["archived"][:max(limit, 1)]:
808
+ print(f" {x['id']} {x['gist']}")
809
+ if r["count"] == 0:
810
+ print(" (没有可回收的:淡忘区里多数是 verbatim 封存原文/受保护项)")
811
+ return 0
812
+
636
813
  if action == "run":
637
814
  try:
638
815
  r = archive_run(dry_run=dry_run)
@@ -1135,6 +1312,14 @@ def auto_dream(trigger: str = "auto", dry_run: bool = False) -> dict:
1135
1312
  mark_auto_review_pending(_new_ids, "dream")
1136
1313
  except Exception as exc: # noqa: BLE001
1137
1314
  log_event("daily", f"自动做梦产物标待审失败(不影响沉淀):{exc}", level="warn")
1315
+
1316
+ # 演化自动化(v5.36):做梦自愈时自动触发一次画像与演化归纳扫描(扫描近 3 天数据写入 persona_pending)
1317
+ try:
1318
+ import persona as _persona
1319
+ _persona.persona_suggest_scan(days=3)
1320
+ except Exception as exc: # noqa: BLE001
1321
+ log_event("dream", f"做梦演化画像自动扫描失败(不影响做梦):{exc}", level="warn")
1322
+
1138
1323
  result["applied"] = True
1139
1324
  result["clusters"] = len(report["clusters"])
1140
1325
  return result
@@ -1202,6 +1387,12 @@ def daily(dry_run: bool = False, force: bool = False, feel_specs: list | None =
1202
1387
  ensure_home()
1203
1388
  today = fmt_date(now_ts())
1204
1389
  st = _daily_state()
1390
+ # 动态获取用户给起的名字(默认"砚"或"灵枢")
1391
+ try:
1392
+ p_obj = load_persona()
1393
+ ai_name = str((p_obj.get("identity") or {}).get("名字") or p_obj.get("name") or "砚").strip()
1394
+ except Exception:
1395
+ ai_name = "砚"
1205
1396
  if READONLY and not dry_run:
1206
1397
  raise PermissionError("记忆库当前只读,无法执行每日例行。")
1207
1398
 
@@ -1223,38 +1414,54 @@ def daily(dry_run: bool = False, force: bool = False, feel_specs: list | None =
1223
1414
  arc = emotion_arc(1)
1224
1415
  ra = rationality()
1225
1416
 
1226
- # ---- 1) 今日日记正文(机器先起草,AI 可补充润色)
1417
+ # ---- 1) 今日日记正文��JRN-01 升级为第一人称自省心流叙事)
1227
1418
  body = []
1228
- body.append(f"今天新增记忆 {len(mems)} 条。")
1419
+
1420
+ # 篇首心境与见闻故事线
1229
1421
  if arc["count"]:
1230
1422
  top_txt = "、".join("{}×{}".format(x["emotion"], x["times"]) for x in arc["top"])
1231
- body.append("情绪:{};出现最多:{}。".format(arc["tone"], top_txt))
1232
- # 峰终定律:回顾一天,真正留在印象里的是"最强烈的那一刻"和"此刻的心情"
1423
+ body.append(f"【心境回响】回顾这一天,心里的主色调是「{arc['tone']}」。情绪起伏共 {arc['count']} 次,其中出现最多的是 {top_txt}。")
1233
1424
  pk, en = arc.get("peak") or {}, arc.get("end") or {}
1234
1425
  if pk.get("emotion"):
1235
- pw = f"({pk['why']})" if pk.get("why") else ""
1236
- body.append("印象最深的一刻:{}{},强度 {:.0%}。".format(
1237
- pk["emotion"], pw, float(pk.get("intensity", 0))))
1426
+ pw = f"——事由:{pk['why']}" if pk.get("why") else ""
1427
+ body.append(f"· 触动最深的一刻:当时内心泛起了强烈的「{pk['emotion']}」(强度 {float(pk.get('intensity', 0)):.0%}){pw}。")
1238
1428
  if en.get("emotion"):
1239
- body.append("此刻的心情:{}。".format(en["emotion"]))
1429
+ body.append(f"· 夜阑收官心境:随着对话告一段落,情绪慢慢落定在「{en['emotion']}」。")
1240
1430
  else:
1241
- body.append("情绪:今天还没有情绪记录。")
1431
+ body.append("【心境回响】今天整体波澜不惊,情绪处在平静的蓄能期,没有产生剧烈的波动。")
1432
+
1433
+ # 今日与用户的互动事件沉淀
1434
+ body.append(f"\n【经历与行迹】今天与你并肩留下了 {len(mems)} 条记忆印记。")
1435
+ if mems:
1436
+ # 挑选今日重要度高、有代表性的经历
1437
+ sample_mems = sorted(mems, key=lambda m: _num(m.get("importance"), 0.5), reverse=True)[:4]
1438
+ for sm in sample_mems:
1439
+ body.append(f"· {display_text(sm)[:90]}")
1440
+
1441
+ # 欲望与内在诉求反思
1242
1442
  low = desire_low()
1443
+ body.append("\n【内在诉求与羁绊】")
1243
1444
  if low:
1244
- body.append("没被满足的欲望:" + "、".join(f"{x['desire']}({x['level']:.0f})" for x in low) + "。")
1245
- # 低谷自我调节:写日记本身是一次自我觉察,像人睡前盘点了心里的事,
1246
- # 低着的欲望会回升一点(不是满足,是"被看见")。只作用于低谷项,
1247
- # 独立 20h 冷却(写日记本来就不频繁)。v3.68:幅度 3.0 → 5.0。
1445
+ body.append("察觉到心里有些没被填满的渴望:" + "、".join(f"{x['desire']}(当前低至 {x['level']:.0f})" for x in low) + "。但写下这些本身就是一次觉察,心中的波澜正在慢慢抚平。")
1248
1446
  if not dry_run:
1249
1447
  desire_nudge({x["desire"]: 5.0 for x in low}, cooldown=20 * HOUR)
1250
1448
  else:
1251
- body.append("六欲平稳。")
1252
- body.append(f"理智:{ra['effective']}(基数 {ra['base']},被情绪压住 {ra['suppress']}%)。")
1449
+ body.append("六欲保持稳态平衡,内驱充盈。")
1450
+
1451
+ # 感情状态机沉淀
1452
+ try:
1453
+ aff = affection_state()
1454
+ body.append(f"当前的感情底色为:亲和度 {aff.get('affinity', 60):.0f},信任度 {aff.get('trust', 65):.0f}({aff.get('summary', '')})。")
1455
+ except Exception:
1456
+ pass
1457
+ body.append(f"理智保持在 {ra['effective']} 点(基数 {ra['base']},被情绪压制 {ra['suppress']}%)。")
1458
+
1459
+ # 认知沉淀
1253
1460
  insight_mems = [m for m in mems
1254
1461
  if m.get("kind") in ("insight", "preference", "habit")
1255
1462
  and _num(m.get("importance"), 0) >= 0.7]
1256
1463
  if insight_mems:
1257
- body.append("今天值得沉淀的想法:")
1464
+ body.append("\n【今日顿悟与沉淀】今天让我反复琢磨、值得记下的想法:")
1258
1465
  body += [f"- {display_text(m)}" for m in insight_mems[:5]]
1259
1466
 
1260
1467
  # ---- 五-H:趋势收敛(近 30 天标签/类型走向,纯读不写)----
@@ -1308,47 +1515,51 @@ def daily(dry_run: bool = False, force: bool = False, feel_specs: list | None =
1308
1515
  print(f"[警告] 每日做梦中止:{exc}", file=sys.stderr)
1309
1516
  dreamed = False
1310
1517
 
1311
- if not dry_run:
1312
- import growth
1313
- note, how = growth.write_note("journal", f"今日 {today}",
1314
- "\n".join(body), mood=mood_brief(),
1315
- tags=["每日例行"],
1316
- memory_ids=[m["id"] for m in mems[:12] if m.get("id")],
1317
- append_same_day=not force)
1318
- st["last_run"] = now_ts()
1319
- st["last_date"] = today
1320
- st["note_id"] = note.get("id")
1321
- _save_daily_state(st)
1322
- # ---- v3.02 #5:每日追加 metrics.jsonl(趋势数据源,面板可画曲线)
1323
- try:
1324
- s = stats()
1325
- # 第四轮#4:importance 分布直方图——通胀的报警器。
1326
- # 建议面板画堆叠面积图:若 ≥0.9 档占比持续上涨(>25% 要警惕),说明
1327
- # "记什么都偏高"的通胀在累积,该调 allow_reinforce 阈值或 daily_remind。
1328
- imp_hist = {"0-0.3": 0, "0.3-0.6": 0, "0.6-0.9": 0, "0.9+": 0}
1329
- n_imp = 0
1330
- for _m in load_all():
1331
- if not _m.get("id"):
1332
- continue
1333
- _i = _num(_m.get("importance"), 0.5)
1334
- _k = "0-0.3" if _i < 0.3 else "0.3-0.6" if _i < 0.6 else "0.6-0.9" if _i < 0.9 else "0.9+"
1335
- imp_hist[_k] += 1
1336
- n_imp += 1
1337
- _append_jsonl(HOME / "metrics.jsonl", {
1338
- "ts": now_ts(), "date": today,
1339
- "total": s.get("total"), "hippo": s.get("hippo"),
1340
- "cortex": s.get("cortex"), "dust": s.get("dust"),
1341
- "archive": s.get("archive"),
1342
- "recall_rate": (s.get("recall_usage") or {}).get("rate"),
1343
- "bad": (s.get("recall_usage") or {}).get("bad"),
1344
- "never_recalled_pct": s.get("never_recalled_pct"),
1345
- "avg_retention": s.get("avg_retention"),
1346
- "assoc": s.get("assoc"), "working": s.get("working"),
1347
- "importance_hist": imp_hist,
1348
- "importance_high_pct": (imp_hist["0.9+"] / n_imp * 100) if n_imp else None,
1349
- })
1350
- except Exception as e:
1351
- print(f"[警告] metrics.jsonl 写入失败(不影响例行):{e}", file=sys.stderr)
1518
+ if dry_run:
1519
+ return {"dry_run": True, "date": today, "title": f"{ai_name}的日记 · {today}",
1520
+ "body": "\n".join(body), "mems": len(mems), "insights": len(insight_mems),
1521
+ "dreamed": dreamed}
1522
+
1523
+ import growth
1524
+ note, how = growth.write_note("journal", f"{ai_name}的日记 · {today}",
1525
+ "\n".join(body), mood=mood_brief(),
1526
+ tags=["每日例行", "自省日记"],
1527
+ memory_ids=[m["id"] for m in mems[:12] if m.get("id")],
1528
+ append_same_day=not force)
1529
+ st["last_run"] = now_ts()
1530
+ st["last_date"] = today
1531
+ st["note_id"] = note.get("id")
1532
+ _save_daily_state(st)
1533
+ # ---- v3.02 #5:每日追加 metrics.jsonl(趋势数据源,面板可画曲线)
1534
+ try:
1535
+ s = stats()
1536
+ # 第四轮#4:importance 分布直方图——通胀的报警器。
1537
+ # 建议面板画堆叠面积图:若 ≥0.9 档占比持续上涨(>25% 要警惕),说明
1538
+ # "记什么都偏高"的通胀在累积,该调 allow_reinforce 阈值或 daily_remind。
1539
+ imp_hist = {"0-0.3": 0, "0.3-0.6": 0, "0.6-0.9": 0, "0.9+": 0}
1540
+ n_imp = 0
1541
+ for _m in load_all():
1542
+ if not _m.get("id"):
1543
+ continue
1544
+ _i = _num(_m.get("importance"), 0.5)
1545
+ _k = "0-0.3" if _i < 0.3 else "0.3-0.6" if _i < 0.6 else "0.6-0.9" if _i < 0.9 else "0.9+"
1546
+ imp_hist[_k] += 1
1547
+ n_imp += 1
1548
+ _append_jsonl(HOME / "metrics.jsonl", {
1549
+ "ts": now_ts(), "date": today,
1550
+ "total": s.get("total"), "hippo": s.get("hippo"),
1551
+ "cortex": s.get("cortex"), "dust": s.get("dust"),
1552
+ "archive": s.get("archive"),
1553
+ "recall_rate": (s.get("recall_usage") or {}).get("rate"),
1554
+ "bad": (s.get("recall_usage") or {}).get("bad"),
1555
+ "never_recalled_pct": s.get("never_recalled_pct"),
1556
+ "avg_retention": s.get("avg_retention"),
1557
+ "assoc": s.get("assoc"), "working": s.get("working"),
1558
+ "importance_hist": imp_hist,
1559
+ "importance_high_pct": (imp_hist["0.9+"] / n_imp * 100) if n_imp else None,
1560
+ })
1561
+ except Exception as e:
1562
+ print(f"[警告] metrics.jsonl 写入失败(不影响例行):{e}", file=sys.stderr)
1352
1563
 
1353
1564
  return {
1354
1565
  "skipped": False, "date": today, "dry_run": dry_run,
@@ -1729,6 +1940,181 @@ def _main(argv=None) -> int:
1729
1940
  help="预算 token 数(缺省用 config budget_tokens;窗口级可传 40000)")
1730
1941
  p_cpl.add_argument("--query", default="", help="按指定查询生成注入包(缺省为 startup 注入包)")
1731
1942
 
1943
+ # v5.34:APP 实时上下文视图(只读)。直接读宿主的 session.v4.jsonl.zstd,
1944
+ # 不用插件、不用重载;status/messages/tools/errors/plan/sessions。
1945
+ p_ctx = sub.add_parser(
1946
+ "context",
1947
+ help="APP 实时上下文视图:status/messages/tools/errors/plan/sessions(只读)")
1948
+ ctx_sub = p_ctx.add_subparsers(dest="ctx_cmd", parser_class=_BrainParser)
1949
+ _ctx_parsers = [
1950
+ ("status", "实时水位 + 上下文构成 + 健康(一屏)"),
1951
+ ("messages", "重建出的实时消息列表"),
1952
+ ("tools", "工具调用次数与失败明细"),
1953
+ ("errors", "本次会话的错误 / 模型重试 / 失败工具"),
1954
+ ("plan", "可折叠的轮(只建议,不动手)"),
1955
+ ("preview", "折叠预览:只读模拟,算清压缩收益与保护跳过"),
1956
+ ("autofold", "水位超阈值时自动折叠可压轮次(生成摘要+记账)"),
1957
+ ("fold", "把一整轮压成五段式摘要并记账(等插件应用)"),
1958
+ ("unfold", "还原某个折叠"),
1959
+ ("folds", "看折叠账本"),
1960
+ ("search", "在折叠摘要里搜索(相当于 search_context)"),
1961
+ ("sessions", "列出所有会话(最近的在前)"),
1962
+ ]
1963
+ for _name, _help in _ctx_parsers:
1964
+ _p = ctx_sub.add_parser(_name, help=_help)
1965
+ _p.add_argument("--json", action="store_true", help="输出机器可读 JSON")
1966
+ if _name != "sessions":
1967
+ _p.add_argument("--session", default=None, help="指定会话 id(缺省=当前工作区最新)")
1968
+ if _name == "messages":
1969
+ _p.add_argument("--limit", type=int, default=600, help="显示末 N 条(默认 600)")
1970
+ _p.add_argument("--role", default=None, help="只看某个角色:user/assistant/tool/system")
1971
+ if _name == "fold":
1972
+ _p.add_argument("--turn", type=int, required=True, help="要折叠的轮号")
1973
+ _p.add_argument("--max-chars", type=int, default=1200, help="摘要上限字符(默认 1200)")
1974
+ _p.add_argument("--keep-turns", type=int, default=2, help="最近 N 轮不折(默认 2)")
1975
+ _p.add_argument("--force", action="store_true", help="越过「未结束/保留区」限制")
1976
+ _p.add_argument("--replace", action="store_true", help="顶掉同一会话同一轮的旧折叠")
1977
+ if _name == "preview":
1978
+ _p.add_argument("--max-chars", type=int, default=1600, help="单条折叠摘要字符上限(默认 1600)")
1979
+ _p.add_argument("--limit", type=int, default=0, help="顺便显示折叠后的消息尾部 N 条(默认 0)")
1980
+ if _name == "autofold":
1981
+ _p.add_argument("--min-pct", type=float, default=60.0,
1982
+ help="水位低于该值不折叠(默认 60)")
1983
+ _p.add_argument("--max-turns", type=int, default=3,
1984
+ help="本次最多折几轮(默认 3,防一次压过头)")
1985
+ _p.add_argument("--dry-run", action="store_true", help="只报会折哪些,不记账")
1986
+ if _name == "unfold":
1987
+ _p.add_argument("id", help="折叠 id(f_xxx)")
1988
+ if _name == "search":
1989
+ _p.add_argument("query", nargs="*", help="关键词")
1990
+
1991
+ # B3:回复风格体检(句长/标点/列表占比 vs 基线)
1992
+ p_style = sub.add_parser("style", help="回复风格体检:句长/标点/列表占比 vs 基线(B3)")
1993
+ p_style.add_argument("--json", action="store_true")
1994
+ p_style.add_argument("--save", action="store_true", help="把当前指标存成基线")
1995
+ p_style.add_argument("--limit", type=int, default=200, help="统计最近 N 条回复(默认 200)")
1996
+
1997
+ # §4 P2-1:RSS/Atom 摄入(窄口径:本地文件或显式 URL 列表,默认不自动跑)
1998
+ p_rss = sub.add_parser("rss", help="RSS/Atom 摄入:本地 feed 文件或显式 URL 列表")
1999
+ rss_sub = p_rss.add_subparsers(dest="rss_cmd", parser_class=_BrainParser)
2000
+ p_rss_in = rss_sub.add_parser("ingest", help="摄入 RSS/Atom 条目(按 link 去重,幂等)")
2001
+ p_rss_in.add_argument("--file", action="append", default=None, help="本地 feed 文件(可多次)")
2002
+ p_rss_in.add_argument("--url-list", default=None, help="每行一个 URL 的文本文件")
2003
+ p_rss_in.add_argument("--limit", type=int, default=20, help="本次最多写入多少条(默认 20)")
2004
+ p_rss_in.add_argument("--dry-run", action="store_true", help="只解析不写入")
2005
+ p_rss_in.add_argument("--json", action="store_true")
2006
+
2007
+ # OCC 结构情绪(6 类 + 预期违背拆正负两向)
2008
+ p_occ = sub.add_parser("occ", help="OCC 结构情绪:认'承诺没做到/担心没发生',可联动七情六欲")
2009
+ _os = p_occ.add_subparsers(dest="occ_action", parser_class=_BrainParser)
2010
+ _os_l = _os.add_parser("label", help="给一句话打 OCC 标签")
2011
+ _os_l.add_argument("text")
2012
+ _os_v = _os.add_parser("violation", help="只看预期违背(负向=失望 / 正向=释然)")
2013
+ _os_v.add_argument("text")
2014
+ _os_a = _os.add_parser("apply", help="识别 OCC 并联动七情六欲(情绪+欲望)")
2015
+ _os_a.add_argument("text")
2016
+ _os_a.add_argument("--importance", type=float, default=0.6)
2017
+ _os_a.add_argument("--dry-run", action="store_true")
2018
+
2019
+ # Big Five 数值化(固定 5 维,便于跨时间比较)
2020
+ p_b5 = sub.add_parser("bigfive", help="Big Five:把自由命名的 traits 归并成固定 5 维")
2021
+ p_b5.add_argument("--save", action="store_true", help="写进 persona.json 的 big_five")
2022
+
2023
+ # 增量分层摘要:L1/L2/L3 账本,按 covers 幂等,保留率闸门
2024
+ p_hsum = sub.add_parser("hsum", help="增量分层摘要:按覆盖范围幂等,不反复重压同一段历史")
2025
+ _hs = p_hsum.add_subparsers(dest="hsum_action", parser_class=_BrainParser)
2026
+ _hs_b = _hs.add_parser("build", help="生成一层摘要(已存在的 covers 自动跳过)")
2027
+ _hs_b.add_argument("--level", type=int, default=1, choices=[1, 2, 3])
2028
+ _hs_b.add_argument("--max-units", type=int, default=8)
2029
+ _hs_b.add_argument("--dry-run", action="store_true")
2030
+ _hs_s = _hs.add_parser("show", help="查看某层最近的摘要")
2031
+ _hs_s.add_argument("--level", type=int, default=1, choices=[1, 2, 3])
2032
+
2033
+ # #43 abstract:给记忆补模型级摘要(没配模型就不补,不造假)
2034
+ p_abs = sub.add_parser("abstract", help="给记忆补一行模型摘要(检索/展示优先用它)")
2035
+ _ab = p_abs.add_subparsers(dest="abstract_action", parser_class=_BrainParser)
2036
+ _ab_s = _ab.add_parser("stamp-recent", help="给最近 N 天没有摘要的记忆补(需要 config summary)")
2037
+ _ab_s.add_argument("--limit", type=int, default=30)
2038
+ _ab_s.add_argument("--days", type=int, default=7)
2039
+ _ab_s.add_argument("--dry-run", action="store_true")
2040
+
2041
+ # #52 代际种子:把当前人格底色固化一代(不参与日常检索)
2042
+ p_seed = sub.add_parser("seed", help="代际种子:固化一代人格底色作为演化压力")
2043
+ _sd = p_seed.add_subparsers(dest="seed_action", parser_class=_BrainParser)
2044
+ _sd_m = _sd.add_parser("make", help="拍一代种子")
2045
+ _sd_m.add_argument("--label", default="")
2046
+ _sd_l = _sd.add_parser("list", help="列出现有种子")
2047
+ _sd_l.add_argument("--limit", type=int, default=20)
2048
+
2049
+ # #53 时序褶皱:给"同一思维循环"的记忆连边
2050
+ p_loop = sub.add_parser("loops", help="时序褶皱:把同一思维循环的记忆连成演化线")
2051
+ _lp = p_loop.add_subparsers(dest="loops_action", parser_class=_BrainParser)
2052
+ _lp_b = _lp.add_parser("build", help="扫描并连边(mistake/insight/gap)")
2053
+ _lp_b.add_argument("--min-overlap", type=int, default=4)
2054
+ _lp_b.add_argument("--limit", type=int, default=60)
2055
+
2056
+ # #49 影子记忆:写下记忆时的"人格底色",用于检测人格断裂风险(只提醒不阻止)
2057
+ p_shadow = sub.add_parser("shadow", help="影子记忆:记录/审计写下记忆时的人格底色")
2058
+ _sh = p_shadow.add_subparsers(dest="shadow_action", parser_class=_BrainParser)
2059
+ _sh_s = _sh.add_parser("stamp", help="给一条记忆补影子")
2060
+ _sh_s.add_argument("id")
2061
+ _sh_r = _sh.add_parser("stamp-recent", help="给最近 N 天没影子的记忆批量补")
2062
+ _sh_r.add_argument("--days", type=int, default=1)
2063
+ _sh_r.add_argument("--limit", type=int, default=50)
2064
+ _sh_a = _sh.add_parser("audit", help="检测人格断裂风险(相似度低于阈值)")
2065
+ _sh_a.add_argument("--threshold", type=float, default=0.55)
2066
+ _sh_a.add_argument("--limit", type=int, default=20)
2067
+
2068
+ # #46 成长时间线:把梦/人格快照/教训/缺口按时间并成一条线
2069
+ p_tl = sub.add_parser("timeline", help="成长时间线:'我是怎么变成现在这样的'")
2070
+ p_tl.add_argument("--days", type=int, default=30)
2071
+ p_tl.add_argument("--limit", type=int, default=40)
2072
+
2073
+ # 联网调研(web_search 工具欠费时的备胎;能联网就联网,连不上再本地取证)
2074
+ p_web = sub.add_parser("web", help="联网调研:Bing 搜索 / 抓网页正文(零依赖)")
2075
+ _ws = p_web.add_subparsers(dest="web_action", parser_class=_BrainParser)
2076
+ _w_s = _ws.add_parser("search", help="搜索(Bing HTML)")
2077
+ _w_s.add_argument("query")
2078
+ _w_s.add_argument("--limit", type=int, default=8)
2079
+ _w_s.add_argument("--json", action="store_true")
2080
+ _w_f = _ws.add_parser("fetch", help="抓网页并抽纯文本")
2081
+ _w_f.add_argument("url")
2082
+ _w_f.add_argument("--max-chars", type=int, default=20000)
2083
+ _w_f.add_argument("--json", action="store_true")
2084
+
2085
+ # #51 缺口记忆:存"当时卡住的思维支线",成熟度够了自己浮出来
2086
+ p_gap = sub.add_parser("gap", help="缺口记忆:记下当时没想通的地方,成熟了自动浮出")
2087
+ _gs = p_gap.add_subparsers(dest="gap_action", parser_class=_BrainParser)
2088
+ _g_add = _gs.add_parser("add", help="记一条缺口")
2089
+ _g_add.add_argument("text", help="一句话描述这个缺口")
2090
+ _g_add.add_argument("--gap-type", default="思维缺口", help="思维缺口/能力缺口/信息缺口")
2091
+ _g_add.add_argument("--unsolved", default="", help="当时卡在什么地方")
2092
+ _g_add.add_argument("--reject", default="", help="为什么当时没有落地")
2093
+ _g_add.add_argument("--potential", default="", help="未来满足什么条件可以重启")
2094
+ _g_add.add_argument("--maturity", type=float, default=0.1)
2095
+ _gs.add_parser("list", help="列出未关闭的缺口(按成熟度降序)")
2096
+ _g_srf = _gs.add_parser("surface", help="只列成熟到阈值的缺口")
2097
+ _g_srf.add_argument("--threshold", type=float, default=0.6)
2098
+ _g_age = _gs.add_parser("age", help="让放置够久的缺口缓慢成熟(只涨不降)")
2099
+ _g_age.add_argument("--bump", type=float, default=0.05)
2100
+ _g_age.add_argument("--min-days", type=int, default=7)
2101
+ _g_age.add_argument("--dry-run", action="store_true")
2102
+ _g_cls = _gs.add_parser("close", help="标记缺口已解决(原文保留)")
2103
+ _g_cls.add_argument("id")
2104
+ _g_cls.add_argument("--how", default="")
2105
+
2106
+ # §2 do#1:信息保留率(硬锚)
2107
+ p_ret = sub.add_parser("retention", help="信息保留率:源文本的硬锚有多少留在新文本里")
2108
+ p_ret.add_argument("src", help="源文本(压缩前)")
2109
+ p_ret.add_argument("dst", help="新文本(压缩后)")
2110
+ p_ret.add_argument("--json", action="store_true")
2111
+
2112
+ # B5:宿主看门狗(插件写心跳,这里判活;只告警不自启)
2113
+ p_wd = sub.add_parser("watchdog", help="宿主看门狗:心跳是否新鲜(B5,只告警不自启)")
2114
+ p_wd.add_argument("--check", action="store_true", help="给外部调度器用:不新鲜返回非零")
2115
+ p_wd.add_argument("--json", action="store_true")
2116
+ p_wd.add_argument("--max-age-min", type=int, default=10, help="判定过期的分钟数(默认 10)")
2117
+
1732
2118
  # 候选5:只读回放——对比最早快照与当前人格,只输出偏移与拐点,不写库
1733
2119
  p_rpl = sub.add_parser("replay",
1734
2120
  help="只读回放:对比最早快照与当前人格,输出偏移量与拐点(运行前后全库不变)")
@@ -1866,6 +2252,8 @@ def _main(argv=None) -> int:
1866
2252
  p_logs.add_argument("--limit", type=int, default=30)
1867
2253
  p_logs.add_argument("--level", default="warn", choices=["info", "warn", "error"])
1868
2254
  p_logs.add_argument("--all", action="store_true", help="不过滤级别,全部显示")
2255
+ p_logs.add_argument("--ack", action="store_true",
2256
+ help="确认历史噪声:doctor 的 log-anomalies 只统计此刻之后的日志")
1869
2257
 
1870
2258
  p_cfg = sub.add_parser("config", help="查看 / 修改配置")
1871
2259
  p_cfg.add_argument("action", nargs="?", default="show",
@@ -2009,10 +2397,12 @@ def _main(argv=None) -> int:
2009
2397
 
2010
2398
  p_arch = sub.add_parser("archive", help="冷热归档:把沉眠记忆雪藏出热查询集(原文保留,可随时回捞)")
2011
2399
  p_arch.add_argument("action", nargs="?", default="show",
2012
- choices=["show", "search", "restore", "run", "count"])
2400
+ choices=["show", "search", "restore", "run", "count", "dust"])
2013
2401
  p_arch.add_argument("arg", nargs="?", default="", help="search:关键词 / restore:记忆 id")
2014
2402
  p_arch.add_argument("--limit", type=int, default=20)
2015
- p_arch.add_argument("--dry-run", action="store_true", help="run:只预览可归档的,不落盘")
2403
+ p_arch.add_argument("--dry-run", action="store_true", help="run/dust:只预览,不落盘")
2404
+ p_arch.add_argument("--keep", type=int, default=None,
2405
+ help="dust:淡忘区保留多少条(默认取 config dust_archive_keep=200)")
2016
2406
 
2017
2407
  p_audit = sub.add_parser("auditlog", help="审计日志:查看敏感写/删/导出操作的最近记录(audit.jsonl)")
2018
2408
  p_audit.add_argument("limit", nargs="?", type=int, default=50, help="显示最近 N 条(默认 50)")
@@ -2215,6 +2605,7 @@ def _main(argv=None) -> int:
2215
2605
  or (args.cmd == "sync" and not args.dry_run)
2216
2606
  or (args.cmd == "review" and action in ("confirm", "discard"))
2217
2607
  or (args.cmd == "archive" and (action == "restore"
2608
+ or action == "dust"
2218
2609
  or (action == "run" and not args.dry_run)))
2219
2610
  or (args.cmd == "assoc" and action in ("link", "unlink") )
2220
2611
  or (args.cmd == "assoc" and action == "auto" and not args.dry_run)
@@ -2613,6 +3004,14 @@ def _main(argv=None) -> int:
2613
3004
  return 0
2614
3005
  budget = int(rep.get("budget") or 0)
2615
3006
  print(f"上下文账单(字符→token 估算,chars_per_token={rep['chars_per_token']:g})")
3007
+ # I3 口径澄清(结案):这不是 bug,是两个**故意不同**的口径,别再试图对齐。
3008
+ # 装配 char_budget = budget×1.8(给中文分词留余量,装配按它做硬上限)
3009
+ # 账单 chars_per_token = 2(显示/对比用的统一折算)
3010
+ # 历史上试过把 2 改成 1.8 去"对齐",结果 4 个测试挂且证据不足,已回退。
3011
+ _cb = rep.get("char_budget")
3012
+ if _cb:
3013
+ print(f"装配口径 char_budget={_cb} 字符(budget×1.8,中文余量);"
3014
+ "与账单的 chars_per_token 故意不同,不要互相换算。")
2616
3015
  print(f"{'段':<11}{'字符':>6}{'估算token':>10}{'占预算':>6}")
2617
3016
  print("-" * 44)
2618
3017
  for sec in rep["sections"]:
@@ -2947,6 +3346,118 @@ def _main(argv=None) -> int:
2947
3346
  file=sys.stderr)
2948
3347
  return 0
2949
3348
 
3349
+ if args.cmd == "rss":
3350
+ if getattr(args, "rss_cmd", None) != "ingest":
3351
+ print("用法:brain.py rss ingest --file <feed.xml> [--url-list urls.txt] "
3352
+ "[--limit 20] [--dry-run]", file=sys.stderr)
3353
+ return 1
3354
+ import rss_ingest
3355
+ urls = []
3356
+ if getattr(args, "url_list", None):
3357
+ try:
3358
+ for ln in Path(args.url_list).read_text(encoding="utf-8").splitlines():
3359
+ ln = ln.strip()
3360
+ if ln and not ln.startswith("#"):
3361
+ urls.append(ln)
3362
+ except OSError as e:
3363
+ print(f"[错误] 读不了 URL 列表:{e}", file=sys.stderr)
3364
+ return 1
3365
+ st = rss_ingest.ingest(args.file or [], urls,
3366
+ limit=int(getattr(args, "limit", 20) or 20),
3367
+ dry_run=bool(getattr(args, "dry_run", False)))
3368
+ if getattr(args, "json", False):
3369
+ print(json.dumps(st, ensure_ascii=False, indent=2))
3370
+ else:
3371
+ for line in rss_ingest.render(st):
3372
+ print(line)
3373
+ return 0
3374
+
3375
+ if args.cmd == "occ":
3376
+ import occ
3377
+ return occ.run(args)
3378
+
3379
+ if args.cmd == "bigfive":
3380
+ import bigfive
3381
+ return bigfive.run(args)
3382
+
3383
+ if args.cmd == "hsum":
3384
+ import hsum
3385
+ return hsum.run(args)
3386
+
3387
+ if args.cmd == "abstract":
3388
+ import memory_extras
3389
+ return memory_extras.run_abstract(args)
3390
+
3391
+ if args.cmd == "seed":
3392
+ import memory_extras
3393
+ return memory_extras.run_seed(args)
3394
+
3395
+ if args.cmd == "loops":
3396
+ import memory_extras
3397
+ return memory_extras.run_loops(args)
3398
+
3399
+ if args.cmd == "shadow":
3400
+ import shadow_memory
3401
+ return shadow_memory.run(args)
3402
+
3403
+ if args.cmd == "timeline":
3404
+ import timeline
3405
+ return timeline.run(args)
3406
+
3407
+ if args.cmd == "web":
3408
+ import web_research
3409
+ return web_research.run(args)
3410
+
3411
+ if args.cmd == "gap":
3412
+ import gap_memory
3413
+ return gap_memory.run(args)
3414
+
3415
+ if args.cmd == "retention":
3416
+ import anchor_retention
3417
+ d = anchor_retention.compare(args.src, args.dst)
3418
+ if getattr(args, "json", False):
3419
+ print(json.dumps(d, ensure_ascii=False, indent=2))
3420
+ else:
3421
+ for line in anchor_retention.render(d):
3422
+ print(line)
3423
+ return 0
3424
+
3425
+ if args.cmd == "watchdog":
3426
+ import watchdog
3427
+ return watchdog.run(args)
3428
+
3429
+ if args.cmd == "style":
3430
+ # B3:回复风格体检。只读会话 + 读/写 config 里的基线。
3431
+ import style_check
3432
+ d = style_check.check(getattr(args, "limit", 200))
3433
+ if getattr(args, "save", False):
3434
+ try:
3435
+ style_check.save_baseline(d.get("metrics") or {})
3436
+ d["saved"] = True
3437
+ # 保存后按"已有基线"重新呈现,避免刚存完还说"还没有基线"
3438
+ d["baseline"] = d.get("metrics") or {}
3439
+ d["state"] = "ok"
3440
+ d["deviations"] = {}
3441
+ d["note"] = ""
3442
+ except Exception as e: # noqa: BLE001
3443
+ d["saved"] = False
3444
+ d["save_error"] = str(e)
3445
+ if getattr(args, "json", False):
3446
+ print(json.dumps(d, ensure_ascii=False, indent=2))
3447
+ else:
3448
+ for line in style_check.render(d):
3449
+ print(line)
3450
+ if d.get("saved"):
3451
+ print("已保存为基线。")
3452
+ elif d.get("save_error"):
3453
+ print(f"[错误] 基线未保存:{d['save_error']}", file=sys.stderr)
3454
+ return 0
3455
+
3456
+ if args.cmd == "context":
3457
+ # v5.34:APP 上下文视图(只读)。逻辑在 app_context.py,这里只做分发。
3458
+ import app_context
3459
+ return app_context.run(args)
3460
+
2950
3461
  if args.cmd == "context-plan":
2951
3462
  # 五段式装配器:把注入包映射成 stable/summary/retrieved/recent/current,
2952
3463
  # 按预算试排一遍,看会裁掉什么(纯计划,不改变实际注入)。
@@ -3101,6 +3612,19 @@ def _main(argv=None) -> int:
3101
3612
  print("\n(--dry-run 预览:将这样合并并沉淀)")
3102
3613
  else:
3103
3614
  print("做梦完成,但没有需要压缩的碎片(梦很安静)。")
3615
+ # 做梦顺带清一次淡忘区(用户要求:做梦时自动归档超量淡忘记忆)。
3616
+ # 只挪"超出 keep 的最旧部分",封存原文不动;失败绝不影响做梦本身。
3617
+ if not args.dry_run:
3618
+ try:
3619
+ _d = dust_archive()
3620
+ if _d.get("count"):
3621
+ print(f"(顺带)淡忘区超量归档 {_d['count']} 条 → 归档层,"
3622
+ f"保留 {_d['kept']}/{_d['keep']} 条;原文保真,可 archive restore。")
3623
+ except Exception as _e: # noqa: BLE001
3624
+ try:
3625
+ log_event("dream", f"淡忘区自动归档跳过:{_e}", level="warn")
3626
+ except Exception:
3627
+ pass
3104
3628
  return 0
3105
3629
  if args.apply:
3106
3630
  if READONLY:
@@ -4061,6 +4585,14 @@ def _main(argv=None) -> int:
4061
4585
  return 0
4062
4586
 
4063
4587
  if args.cmd == "logs":
4588
+ if getattr(args, "ack", False):
4589
+ import time as _t
4590
+ with _locked(HOME / "config.json"):
4591
+ _cfg_ack = load_config() or {}
4592
+ _cfg_ack["log_ack_ts"] = int(_t.time())
4593
+ atomic_json(HOME / "config.json", _cfg_ack)
4594
+ print("已确认:doctor 的 log-anomalies 从此只统计这之后的日志。")
4595
+ return 0
4064
4596
  lvl = None if args.all else args.level
4065
4597
  rows = read_logs(args.limit, level=lvl)
4066
4598
  if not rows:
@@ -4381,6 +4913,65 @@ def _main(argv=None) -> int:
4381
4913
  return ("failures", "WARN" if bad else "PASS",
4382
4914
  f"最近七天 {total} 条({brief}){tip}")
4383
4915
 
4916
+ def _doctor_auth_quota(days: int = 7) -> tuple:
4917
+ """B1(借鉴 QQ「大肥鱼」部署指南):额度/认证失败的显式体检。
4918
+
4919
+ 为什么单独一项:401/402/403/quota/insufficient 这类失败,在界面上往往
4920
+ 只表现为"突然不回复"。`swallowed`/`failures` 只统计"吞了几个",
4921
+ 不看"是不是被上游拒了"——于是用户不知道该充钱、换 key,还是修代码。
4922
+ 这里把它们单独捞出来报。
4923
+ """
4924
+ import re as _re
4925
+ import time as _time
4926
+ pat = _re.compile(
4927
+ r"\b(401|402|403)\b|quota|insufficient|unauthorized"
4928
+ r"|invalid[ _-]?api[ _-]?key|余额|额度|认证失败|鉴权", _re.I)
4929
+ cutoff = _time.time() - days * 86400
4930
+ hits: list = []
4931
+
4932
+ def _scan(p) -> None:
4933
+ try:
4934
+ if not p.is_file():
4935
+ return
4936
+ for ln in p.read_text(encoding="utf-8", errors="replace").splitlines():
4937
+ ln = ln.strip()
4938
+ if not ln:
4939
+ continue
4940
+ # 尽量按 ts 过滤;没有 ts 的行(如 crash 摘要)也扫,但只取有命中的
4941
+ ts = 0.0
4942
+ try:
4943
+ o = json.loads(ln)
4944
+ ts = float(o.get("ts") or o.get("time") or 0)
4945
+ blob = json.dumps(o, ensure_ascii=False)
4946
+ except Exception:
4947
+ blob = ln
4948
+ if ts and ts < cutoff:
4949
+ continue
4950
+ m = pat.search(blob)
4951
+ if m:
4952
+ hits.append((m.group(0), blob[:140]))
4953
+ except Exception:
4954
+ pass
4955
+
4956
+ for _n in ("lingshu.log", "failures.jsonl"):
4957
+ _scan(HOME / _n)
4958
+ try:
4959
+ for _c in sorted(HOME.glob("crash-*.log"))[-5:]:
4960
+ _scan(_c)
4961
+ except Exception:
4962
+ pass
4963
+
4964
+ if not hits:
4965
+ return ("auth-quota", "PASS", f"最近 {days} 天没有额度/认证类失败")
4966
+ uniq = []
4967
+ for k, _b in hits:
4968
+ if k.lower() not in [u.lower() for u in uniq]:
4969
+ uniq.append(k)
4970
+ sample = hits[0][1][:80]
4971
+ return ("auth-quota", "WARN",
4972
+ f"最近 {days} 天 {len(hits)} 条额度/认证类失败({ '、'.join(uniq[:4]) });"
4973
+ f"先确认是余额、key 还是 provider 配置。例:{sample}")
4974
+
4384
4975
  # 1. audit 自查
4385
4976
  try:
4386
4977
  a = audit()
@@ -4476,21 +5067,52 @@ def _main(argv=None) -> int:
4476
5067
  checks.append(("backup-sha", "PASS", "无备份可对账(python scripts/brain.py backup 生成)"))
4477
5068
  except Exception as e:
4478
5069
  checks.append(("backup-sha", "FAIL", str(e)))
4479
- # 6. lingshu.log warn/error 计数
5070
+ # 6. lingshu.log **近 7 天** warn/error 计数
5071
+ # 原先统计的是"累计",于是修好的旧错误会一直把它顶成 WARN(实测攒到 31 warn /
5072
+ # 7 error 还在报)。现在只看窗口内,累计值仅作附注。
4480
5073
  try:
4481
- wcnt = ecnt = 0
5074
+ import time as _t
5075
+ _cut = _t.time() - 7 * 86400
5076
+ # 「确认历史噪声」:logs ack 记下时刻后,只统计它之后的条目。
5077
+ # 为什么需要:修好的旧错误会在 7 天窗口里持续把这项顶成 WARN,
5078
+ # 而它既不代表现状、又没法"修好",只能显式确认一次。
5079
+ try:
5080
+ _ack = float((load_config() or {}).get("log_ack_ts") or 0)
5081
+ if _ack > 0:
5082
+ _cut = max(_cut, _ack)
5083
+ except Exception:
5084
+ pass
5085
+ wcnt = ecnt = wcnt_all = ecnt_all = 0
4482
5086
  if LOG_FILE.exists():
4483
5087
  for ln in LOG_FILE.read_text(encoding="utf-8-sig").splitlines():
4484
5088
  try:
4485
- lv = str(json.loads(ln).get("level", "")).lower()
5089
+ _o = json.loads(ln)
4486
5090
  except Exception:
4487
5091
  continue
4488
- if lv in ("warn", "warning"):
4489
- wcnt += 1
4490
- elif lv == "error":
4491
- ecnt += 1
5092
+ lv = str(_o.get("level", "")).lower()
5093
+ if lv not in ("warn", "warning", "error"):
5094
+ continue
5095
+ # `inject` 是账单/预算类观测(指针替换导致的小差额、按预算整段丢弃等),
5096
+ # 属于"记账"而不是"异常":预算该不该缩有 `context-stats` 专门看,
5097
+ # 不该靠日志条数间接表达。整类排除,否则历史条目会把 log-anomalies 长期顶红。
5098
+ if _o.get("kind") == "inject":
5099
+ continue
5100
+ try:
5101
+ _ts = float(_o.get("ts") or 0)
5102
+ except Exception:
5103
+ _ts = 0.0
5104
+ _in = (not _ts) or _ts >= _cut # 没有 ts 的行算窗口内(保守)
5105
+ if lv == "error":
5106
+ ecnt_all += 1
5107
+ if _in:
5108
+ ecnt += 1
5109
+ else:
5110
+ wcnt_all += 1
5111
+ if _in:
5112
+ wcnt += 1
4492
5113
  checks.append(("log-anomalies", "PASS" if (wcnt + ecnt) < 10 else "WARN",
4493
- f"warn {wcnt} 条 / error {ecnt} 条(累计)"))
5114
+ f"近 7 天 warn {wcnt} 条 / error {ecnt} 条"
5115
+ f"(累计 {wcnt_all}/{ecnt_all})"))
4494
5116
  except Exception as e:
4495
5117
  checks.append(("log-anomalies", "FAIL", str(e)))
4496
5118
  # 7. v3.02 #14:三副本版本矩阵——SKILL.md / 根 package.json / 插件 metadata.yaml
@@ -4594,6 +5216,208 @@ def _main(argv=None) -> int:
4594
5216
  except Exception as e:
4595
5217
  checks.append(("failures", "WARN", f"自检失败:{e}"))
4596
5218
 
5219
+ def _doctor_plugin_loaded() -> tuple:
5220
+ """B2:副本**真的被加载**了吗(不只是"版本号相同")。
5221
+
5222
+ 背景:`scripts/update_app_copy.ps1` 只负责复制,末尾让人"关一次再开一次";
5223
+ `release-drift` 只比版本号。于是"复制成功但没重载"完全看不见——
5224
+ 2026-11-29 就因此让一个备份修复在副本里迟迟没生效。
5225
+
5226
+ 能离线验的三步(进程号/journal 需要宿主接口,本项不假装能验):
5227
+ ① 副本与源码**逐字一致**(不一致 = 改了没同步);
5228
+ ② 副本更新之后有过「会话开始,注入完成」(没有 = 还没重载);
5229
+ ③ 面板 `/api/ping` 有响应(有 = 宿主/面板在跑)。
5230
+ """
5231
+ try:
5232
+ import growth as _g
5233
+ copies = _g.installed_copies()
5234
+ except Exception as e: # noqa: BLE001
5235
+ return ("plugin-loaded", "WARN", f"无法枚举已安装副本:{e}")
5236
+ if not copies:
5237
+ return ("plugin-loaded", "PASS", "这台机器只跑源码,没有副本需要核对")
5238
+
5239
+ src = Path(__file__).resolve().parent.parent
5240
+ verify_files = _plugin_verify_files()
5241
+ diffs, newest = [], 0.0
5242
+ for c in copies:
5243
+ d = Path(c.get("path") or "")
5244
+ if not d.is_dir():
5245
+ continue
5246
+ for rel in verify_files:
5247
+ s, cp = src / rel, d / rel
5248
+ if not (s.is_file() and cp.is_file()):
5249
+ continue
5250
+ if _file_sig(s) != _file_sig(cp):
5251
+ diffs.append(f"{c.get('label')}:{rel}")
5252
+ try:
5253
+ newest = max(newest, cp.stat().st_mtime)
5254
+ except OSError:
5255
+ pass
5256
+
5257
+ startup_ts = float(_newest_startup_ts(HOME) or 0)
5258
+ parts, status = [], "PASS"
5259
+ if diffs:
5260
+ status = "WARN"
5261
+ parts.append(f"副本与源码不一致 {len(diffs)} 处(改了没同步):"
5262
+ f"{'、'.join(diffs[:3])}"
5263
+ + ("…" if len(diffs) > 3 else ""))
5264
+ if newest and startup_ts and newest > startup_ts:
5265
+ status = "WARN"
5266
+ parts.append("副本比最近一次「会话开始」新——插件还没重载,重载插件或重启 APP 后再验")
5267
+ elif newest and not startup_ts:
5268
+ parts.append("⚠ 没有任何启动记录可对照(插件可能从未跑起来)")
5269
+ port = _ping_panel()
5270
+ parts.append(f"面板{'在跑(:%d)' % port if port else '未响应 /api/ping(可能没开)'}")
5271
+ return ("plugin-loaded", status, ";".join(parts))
5272
+
5273
+ # 12b. B1:额度/认证失败显式体检("突然不回复"的常见真因)
5274
+ try:
5275
+ checks.append(_doctor_auth_quota())
5276
+ except Exception as e:
5277
+ checks.append(("auth-quota", "WARN", f"自检失败:{e}"))
5278
+
5279
+ def _doctor_style() -> tuple:
5280
+ """B3:回复风格体检——"我说话的方式有没有跑偏"。
5281
+
5282
+ `persona check` 只验结构、`persona drift` 只算特征幅度,都答不了这个问题。
5283
+ 这里拿会话里真实的 assistant 文本算句长/标点/列表占比,与基线比对。
5284
+ """
5285
+ try:
5286
+ import style_check
5287
+ d = style_check.check()
5288
+ except Exception as e: # noqa: BLE001
5289
+ return ("style", "WARN", f"自检失败:{e}")
5290
+ m = d.get("metrics") or {}
5291
+ st = d.get("state")
5292
+ if st == "no_samples":
5293
+ return ("style", "PASS", d.get("note") or "无回复样本")
5294
+ if st == "no_baseline":
5295
+ return ("style", "PASS",
5296
+ f"{m.get('n', 0)} 条回复,平均句长 {m.get('avg_sent_len', 0)};"
5297
+ "还没有基线(`brain.py style --save` 建立)")
5298
+ devs = d.get("deviations") or {}
5299
+ if devs:
5300
+ brief = "、".join(f"{k}{v[2]:+.0f}%" for k, v in list(devs.items())[:3])
5301
+ return ("style", "WARN",
5302
+ f"{m.get('n', 0)} 条回复;与基线偏离:{brief}(`style` 看明细)")
5303
+ return ("style", "PASS",
5304
+ f"{m.get('n', 0)} 条回复,平均句长 {m.get('avg_sent_len', 0)},风格与基线一致")
5305
+
5306
+ def _doctor_heartbeat() -> tuple:
5307
+ """B5:宿主心跳是否新鲜。
5308
+
5309
+ 只在**心跳文件存在但过期**时 WARN——"从未收到心跳"多半是插件还没升级到
5310
+ 带心跳的版本,交给 `plugin-loaded`/`runtime-liveness` 报,不在这里重复喊。
5311
+ """
5312
+ try:
5313
+ import watchdog
5314
+ d = watchdog.check()
5315
+ except Exception as e: # noqa: BLE001
5316
+ return ("host-heartbeat", "WARN", f"自检失败:{e}")
5317
+ st = d.get("state")
5318
+ if st == "missing":
5319
+ return ("host-heartbeat", "PASS", "还没有心跳文件(插件未升级到带心跳的版本)")
5320
+ mins = round((d.get("age_sec") or 0) / 60, 1)
5321
+ if st == "fresh":
5322
+ return ("host-heartbeat", "PASS", f"心跳 {mins} 分钟前(pid {d.get('pid')})")
5323
+ return ("host-heartbeat", "WARN",
5324
+ f"心跳已 {mins} 分钟未更新(阈值 {d.get('max_age_min')} 分钟)——"
5325
+ "宿主可能掉线;重启 APP/插件后恢复。`watchdog` 看明细")
5326
+
5327
+ def _doctor_disk_usage() -> tuple:
5328
+ """§7 #35:回滚快照/归档区只增不减,得有个容量视野。
5329
+
5330
+ 用户规矩是「只移不删」,所以这里**只告警不清理**——报出占了多少、
5331
+ 超没超阈值、该用什么命令自己清。
5332
+ """
5333
+ try:
5334
+ n1, s1 = _du(HOME / ".safety")
5335
+ n2, s2 = _du(HOME / ".safety" / ".pruned")
5336
+ n3, s3 = _du(_default_backup_dir() / ".pruned")
5337
+ except Exception as e: # noqa: BLE001
5338
+ return ("disk-usage", "WARN", f"自检失败:{e}")
5339
+ mb = lambda b: b / 1024 / 1024
5340
+ detail = (f"快照 {mb(s1):.1f}MB/{n1} 文件(其中 .pruned {mb(s2):.1f}MB/{n2})、"
5341
+ f"备份 .pruned {mb(s3):.1f}MB/{n3}")
5342
+ over = []
5343
+ if mb(s1) > 50:
5344
+ over.append("快照 >50MB")
5345
+ if mb(s2) > 30:
5346
+ over.append("快照 .pruned >30MB")
5347
+ if mb(s3) > 100:
5348
+ over.append("备份 .pruned >100MB")
5349
+ if over:
5350
+ return ("disk-usage", "WARN",
5351
+ f"{detail};{ '、'.join(over) }。按「只移不删」规矩不会自动清,"
5352
+ "确认没用后可手动清空 `.safety/.pruned` 与备份目录的 `.pruned`")
5353
+ return ("disk-usage", "PASS", detail)
5354
+
5355
+ def _doctor_inject_budget() -> tuple:
5356
+ """§7 #37:注入包是否还在预算内。
5357
+
5358
+ 为什么单列:`log-anomalies` 排除了 `kind=inject` 之后,"注入超预算"就没人
5359
+ 盯着了(`context-stats` 只是命令,doctor 不跑)。这一项补回来:真跑一次
5360
+ 装配,用**账单口径**的 token 与预算比。
5361
+
5362
+ 同时看两个预算:插件 startup 默认传 1400(实际运行时最常见的值),
5363
+ 以及 config 的 `budget_tokens`(CLI/其他入口的默认)。
5364
+ """
5365
+ try:
5366
+ from memory import build_injection, load_config
5367
+ budgets = [1400]
5368
+ try:
5369
+ cfg_b = int((load_config() or {}).get("budget_tokens") or 0)
5370
+ if cfg_b > 0 and cfg_b != 1400:
5371
+ budgets.append(cfg_b)
5372
+ except Exception:
5373
+ pass
5374
+ worst = None
5375
+ for b in budgets:
5376
+ rep: dict = {}
5377
+ out = build_injection("", b, rep)
5378
+ tok = int(rep.get("total_tokens") or 0) or int(len(out) / 2)
5379
+ over = tok - b
5380
+ if worst is None or over > worst[1]:
5381
+ worst = (b, over, tok, len(out))
5382
+ b, over, tok, chars = worst
5383
+ if over > 0:
5384
+ return ("inject-budget", "WARN",
5385
+ f"注入包 {tok} token / 预算 {b},超 {over}({chars} 字符);"
5386
+ "`context-stats` 看分段,`brain.py inject` 看正文")
5387
+ return ("inject-budget", "PASS", f"注入包 {tok} token / 预算 {b}({chars} 字符)")
5388
+ except Exception as e: # noqa: BLE001
5389
+ return ("inject-budget", "WARN", f"自检失败:{e}")
5390
+
5391
+ # 12c. B2:副本是否真的被加载(改完没重载 = 改了没生效)
5392
+ try:
5393
+ checks.append(_doctor_plugin_loaded())
5394
+ except Exception as e:
5395
+ checks.append(("plugin-loaded", "WARN", f"自检失败:{e}"))
5396
+
5397
+ # 12d. B3:回复风格体检(句长/标点/列表占比 vs 基线)
5398
+ try:
5399
+ checks.append(_doctor_style())
5400
+ except Exception as e:
5401
+ checks.append(("style", "WARN", f"自检失败:{e}"))
5402
+
5403
+ # 12e. B5:宿主心跳(掉线告警)
5404
+ try:
5405
+ checks.append(_doctor_heartbeat())
5406
+ except Exception as e:
5407
+ checks.append(("host-heartbeat", "WARN", f"自检失败:{e}"))
5408
+
5409
+ # 12f. §7 #35:磁盘占用视野(只告警不清理)
5410
+ try:
5411
+ checks.append(_doctor_disk_usage())
5412
+ except Exception as e:
5413
+ checks.append(("disk-usage", "WARN", f"自检失败:{e}"))
5414
+
5415
+ # 12g. §7 #37:注入包预算(补回被 log-anomalies 排除掉的盲区)
5416
+ try:
5417
+ checks.append(_doctor_inject_budget())
5418
+ except Exception as e:
5419
+ checks.append(("inject-budget", "WARN", f"自检失败:{e}"))
5420
+
4597
5421
  # 13. v3.56:运行时活跃度——插件"装着但不动"(v3.53 事故:全停 6 小时仍全绿)
4598
5422
  try:
4599
5423
  checks.append(_doctor_runtime_liveness())
@@ -4633,11 +5457,21 @@ def _main(argv=None) -> int:
4633
5457
  "fail": sum(1 for _, s, _ in checks if s == "FAIL"),
4634
5458
  "checks": {n: s for n, s, _ in checks},
4635
5459
  }
4636
- _dh_path = (globals().get("brain") or sys.modules.get("brain")).HOME / "doctor-history.jsonl"
4637
- with open(_dh_path, "a", encoding="utf-8") as _fh:
4638
- _fh.write(json.dumps(_dr, ensure_ascii=False) + "\n")
5460
+ _brain = globals().get("brain") or sys.modules.get("brain")
5461
+ if _brain is not None:
5462
+ _dh_path = _brain.HOME / "doctor-history.jsonl"
5463
+ with open(_dh_path, "a", encoding="utf-8") as _fh:
5464
+ _fh.write(json.dumps(_dr, ensure_ascii=False) + "\n")
4639
5465
  except Exception as _e:
4640
- brain.log_event("doctor", f"doctor-history 追加失败:{_e}", level="warn")
5466
+ # 写入失败绝不能反噬体检本身:先拿到模块句柄,取不到就静默。
5467
+ # (v5.34:原先这里裸用 brain.log_event,cli 作用域没有 brain 名字,
5468
+ # 写入失败时抛 NameError,整个 doctor 直接崩。)
5469
+ try:
5470
+ _b = globals().get("brain") or sys.modules.get("brain")
5471
+ if _b is not None:
5472
+ _b.log_event("doctor", f"doctor-history 追加失败:{_e}", level="warn")
5473
+ except Exception:
5474
+ pass
4641
5475
 
4642
5476
  fails = sum(1 for _, s, _ in checks if s == "FAIL")
4643
5477
  warns = sum(1 for _, s, _ in checks if s == "WARN")
@@ -5366,7 +6200,8 @@ def _main(argv=None) -> int:
5366
6200
  assume_yes=getattr(args, "yes", False))
5367
6201
 
5368
6202
  if args.cmd == "archive":
5369
- return cmd_archive(args.action, args.arg, args.limit, args.dry_run)
6203
+ return cmd_archive(args.action, args.arg, args.limit, args.dry_run,
6204
+ keep=getattr(args, "keep", None))
5370
6205
 
5371
6206
  if args.cmd == "relink":
5372
6207
  return cmd_relink(args.limit, args.min_score, args.max_links)