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
package/scripts/memory.py CHANGED
@@ -20,7 +20,17 @@ from datetime import datetime
20
20
  from pathlib import Path
21
21
 
22
22
  from core import *
23
- import core # noqa: E402 # 教训库 lessons_file() 动态取 core.HOME,--home 切换后指向新目录
23
+ import core # noqa: E402
24
+ # 进程内记忆缓存(2026-11-30):避免单轮会话内重复读盘与重算哈希。
25
+ _load_cache = None
26
+ _load_cache_ts = 0
27
+ _load_cache_files = {} # 教训库 lessons_file() 动态取 core.HOME,--home 切换后指向新目录
28
+
29
+ # 冲突检测的实质重叠门槛:交集词数 + jaccard。太低会满屏误报(实测 4/4 全是误报),
30
+ # 太高会漏掉真正的改口(同一件事换说法)。
31
+ CONFLICT_MIN_OVERLAP = 4
32
+ CONFLICT_MIN_JACCARD = 0.18
33
+
24
34
 
25
35
  def detect_conflicts(limit: int = 50) -> list:
26
36
  """启发式扫描"可能矛盾的记忆"(如「我用 Windows」vs「我改用 Linux」)。
@@ -75,9 +85,18 @@ def detect_conflicts(limit: int = 50) -> list:
75
85
  a, b = members[i], members[j]
76
86
  if a["id"] == b["id"] or not _in_scope(a, b):
77
87
  continue
78
- inter = set(terms(a.get("text", ""))) & set(terms(b.get("text", "")))
88
+ ta, tb = terms(a.get("text", "")), terms(b.get("text", ""))
89
+ inter = ta & tb
79
90
  if len(inter) < 1:
80
91
  continue
92
+ # 实质重叠门槛(2026-11-30):原来只要共享 1 个词 + 一边带否定词就报冲突,
93
+ # 实测 4 条全是误报——"laneai 金额显示已修好" vs "laneai provider 现状"
94
+ # 共享的只是实体名,说的根本不是同一件事。
95
+ # 要求:交集 ≥4 个词且 jaccard ≥0.18,才可能是"同一件事的两种说法"。
96
+ _uni = ta | tb
97
+ _jac = (len(inter) / len(_uni)) if _uni else 0.0
98
+ if len(inter) < CONFLICT_MIN_OVERLAP or _jac < CONFLICT_MIN_JACCARD:
99
+ continue
81
100
  ca = any(c in a.get("text", "") for c in change_cues)
82
101
  cb = any(c in b.get("text", "") for c in change_cues)
83
102
  if ca != cb:
@@ -263,6 +282,43 @@ def set_memory_review(mid: str, status: str) -> dict:
263
282
  return target
264
283
 
265
284
 
285
+ def resolve_conflict_pair(winner_id: str, loser_id: str) -> dict:
286
+ """人工一键裁决冲突(FEAT-04):选定一条为胜出准则,另一条被其取代(superseded_by)。
287
+
288
+ 规则:
289
+ 1. loser 打上 superseded_by = winner_id(回忆默认跳过,但保留旧观念可回溯)
290
+ 2. 双向清理 conflicts 列表和 conflict_flag 标记
291
+ 3. winner 将 loser 加入 links(维持历史证据关联)
292
+ """
293
+ if READONLY:
294
+ raise PermissionError("记忆库当前只读,无法裁决冲突。")
295
+ with _locked(HOME / "hippocampus.jsonl"):
296
+ records = load_all()
297
+ w = next((m for m in records if m.get("id") == winner_id), None)
298
+ l = next((m for m in records if m.get("id") == loser_id), None)
299
+ if not w:
300
+ raise ValueError(f"找不到胜出记忆:{winner_id}")
301
+ if not l:
302
+ raise ValueError(f"找不到被取代记忆:{loser_id}")
303
+ l["superseded_by"] = winner_id
304
+ l["conflict_flag"] = False
305
+ if "conflicts" in l:
306
+ l["conflicts"] = [x for x in l.get("conflicts", []) if x != winner_id]
307
+ if not l["conflicts"]:
308
+ l.pop("conflicts", None)
309
+ w["conflict_flag"] = False
310
+ if "conflicts" in w:
311
+ w["conflicts"] = [x for x in w.get("conflicts", []) if x != loser_id]
312
+ if not w["conflicts"]:
313
+ w.pop("conflicts", None)
314
+ w.setdefault("links", [])
315
+ if loser_id not in w["links"]:
316
+ w["links"].append(loser_id)
317
+ save_all(records)
318
+ log_event("memory", f"冲突裁决:{winner_id} 取代 {loser_id}")
319
+ return {"ok": True, "winner": winner_id, "loser": loser_id}
320
+
321
+
266
322
  # ---------------------------------------------------------------- 意图层(dual-mem L7)
267
323
  # 目标/计划:用户说明的意图,跨会话保留,带状态与完成标记。与 work(12h 丢的
268
324
  # 会话暂存)不同,intent 是长期记忆(kind=intent),完成/取消只是改状态不删除。
@@ -532,8 +588,19 @@ def diagnose() -> dict:
532
588
  layer_counts[lc if lc in layer_counts else "hippo"] += 1
533
589
  layer_counts["archive"] = len(arch)
534
590
  bloat_warn = []
535
- if layer_counts["dust"] > layer_counts["hippo"] + layer_counts["cortex"] and layer_counts["dust"] > 200:
536
- bloat_warn.append(f"淡忘区 {layer_counts['dust']} 条已超过活跃层总和——考虑 fold 折叠或 archive 归档")
591
+ # ⚠ 口径:淡忘区里大量是 **verbatim 封存原文**(用户明确要保真),它们本来就不该被
592
+ # 折叠或归档。按原始 dust 数报警会把"设计如此"当成"膨胀"(实测 283 条里有 255 条
593
+ # 是 verbatim,真正可回收只有 28 条,doctor 却天天喊超量)。所以只看**可回收量**。
594
+ _dust_rows = [m for m in records if m.get("layer") == "dust"]
595
+ _dust_locked = sum(1 for m in _dust_rows
596
+ if m.get("verbatim") or m.get("pinned")
597
+ or m.get("kind") == "identity" or m.get("review") == "pending")
598
+ dust_reclaimable = max(0, len(_dust_rows) - _dust_locked)
599
+ active_total = layer_counts["hippo"] + layer_counts["cortex"]
600
+ if dust_reclaimable > active_total and dust_reclaimable > 200:
601
+ bloat_warn.append(
602
+ f"淡忘区可回收 {dust_reclaimable} 条已超过活跃层总和——考虑 fold 折叠或 archive 归档"
603
+ f"(另有 {_dust_locked} 条封存原文/受保护,不计入)")
537
604
  if total_bytes > 50 * 1024 * 1024:
538
605
  bloat_warn.append(f"数据总体积 {total_bytes // 1024 // 1024}MB 偏大,检查是否有超长记忆条")
539
606
  if long_rows:
@@ -678,17 +745,20 @@ def verify_integrity() -> dict:
678
745
 
679
746
 
680
747
  def load_all() -> list:
681
- """三层热层合并;缺 id 的 dict 记录**补一个稳定 id**,而不是丢弃。
748
+ """三层热层合并;缺 id 的 dict 记录**补一个稳定 id**,并带进程内缓存(2026-11-30)。"""
749
+ global _load_cache, _load_cache_ts, _load_cache_files
750
+ # 失效键 = (mtime_ns, size):审计 P2——同秒内跨进程追加时 mtime 粒度可能吞掉
751
+ # 变更,size 一起比就必然失效(追加必变大)。mtime_ns 比 float mtime 精度高。
752
+ _names = ("hippocampus.jsonl", "cortex.jsonl", "dust.jsonl")
753
+ try:
754
+ _cur_mtimes = {n: ((HOME / n).stat().st_mtime_ns, (HOME / n).stat().st_size)
755
+ for n in _names if (HOME / n).exists()}
756
+ except OSError:
757
+ _cur_mtimes = {}
682
758
 
683
- 为什么不丢:`_locked_save_all` 专门保留 `no_id`、`dream.py:182` 也明确承诺
684
- "这些记录会原样保留在库,不会被 save_all 丢掉"。但早期版本在这里直接略过
685
- 它们 → 任何一次 `save_all(load_all())` 就把它们永远抹掉
686
- (审计 memory.py:686,承诺与实际相反)。
759
+ if _load_cache is not None and _cur_mtimes == _load_cache_files:
760
+ return [dict(m) for m in _load_cache] # 返回副本防外部修改污染缓存
687
761
 
688
- 现在按内容哈希补 id:同一条记录重复 load 得到同一个 id(幂等),于是它能
689
- 安全穿过 read-modify-write 而不蒸发,也不会每次 load 都长出重复副本。
690
- 仍然跳过非 dict 的记录(无法附加字段,也读不出 id)。
691
- """
692
762
  raw = (read_jsonl(HOME / "hippocampus.jsonl")
693
763
  + read_jsonl(HOME / "cortex.jsonl")
694
764
  + read_jsonl(HOME / "dust.jsonl"))
@@ -710,7 +780,11 @@ def load_all() -> list:
710
780
  "(不再丢弃,避免 save_all 抹掉它们)", level="warning")
711
781
  if bad:
712
782
  log_event("load", f"load_all 跳过 {bad} 条非 dict 畸形记录", level="warning")
713
- return good
783
+
784
+ _load_cache = good
785
+ _load_cache_files = _cur_mtimes
786
+ _load_cache_ts = time.time()
787
+ return [dict(m) for m in good]
714
788
 
715
789
 
716
790
  def count_recent(layer: str, floor_ts: float, predicate=None) -> int:
@@ -870,6 +944,69 @@ def _append_archive(new_rows: list) -> None:
870
944
  write_jsonl(HOME / "archive.jsonl", existing + add)
871
945
 
872
946
 
947
+ DUST_ARCHIVE_KEEP_DEFAULT = 200
948
+
949
+
950
+
951
+ def dust_archive(keep: int | None = None, dry_run: bool = False) -> dict:
952
+ """淡忘区超量自动归档(用户要求:做梦时把淡忘区自动归档)。
953
+
954
+ 为什么要单独一条:`_is_archivable` 只认 hippo/cortex,**淡忘区永远不会被常规归档
955
+ 选中**,于是 dust 只增不减(实测 283 条,长期超过活跃层总和,doctor 天天 WARN)。
956
+
957
+ 策略保守、可逆:
958
+ · 只把**超出 keep 的最旧那部分**移进 archive 层(原文保真,`archive restore` 可回热);
959
+ · 不碰 pinned / verbatim / identity / 待审(pending);
960
+ · keep 默认取 config `dust_archive_keep`,缺省 200。
961
+ """
962
+ if READONLY and not dry_run:
963
+ raise PermissionError("记忆库当前只读,无法归档。")
964
+ if keep is None:
965
+ try:
966
+ _cfg = load_config() or {}
967
+ keep = int(_num(_cfg.get("dust_archive_keep"), DUST_ARCHIVE_KEEP_DEFAULT))
968
+ except Exception:
969
+ keep = DUST_ARCHIVE_KEEP_DEFAULT
970
+ keep = max(0, int(keep))
971
+
972
+ now = now_ts()
973
+ with _locked(HOME / "hippocampus.jsonl"):
974
+ records = load_all()
975
+ dust = [m for m in records if m.get("layer") == "dust"]
976
+ empty = {"count": 0, "kept": len(dust), "keep": keep,
977
+ "dry_run": dry_run, "archived": []}
978
+ if len(dust) <= keep:
979
+ return empty
980
+ pool = [m for m in dust
981
+ if m.get("id") and not m.get("pinned") and not m.get("verbatim")
982
+ and m.get("kind") != "identity" and m.get("review") != "pending"]
983
+ excess = len(dust) - keep
984
+ if not pool or excess <= 0:
985
+ return empty
986
+ # 最旧、最不重要的先走(重要度相同按创建时间由远及近)
987
+ pool.sort(key=lambda m: (_num(m.get("importance"), 0.5),
988
+ _num(m.get("created"), 0)))
989
+ cand = pool[:min(excess, len(pool))]
990
+ arch = [{"id": m["id"],
991
+ "gist": m.get("gist") or heuristic_gist(m.get("text", ""))}
992
+ for m in cand]
993
+ if not dry_run:
994
+ for m in cand:
995
+ m["layer"] = ARCHIVE_LAYER
996
+ m["archived_at"] = now
997
+ m["archived_reason"] = "dust_auto_over_keep"
998
+ keep_ids = {m["id"] for m in cand}
999
+ _append_archive(cand) # 先写归档层,再从热层摘(顺序上防丢)
1000
+ save_all([m for m in records if m.get("id") not in keep_ids])
1001
+ try:
1002
+ audit_log("dream", "dust_archive", f"{len(cand)}条",
1003
+ f"淡忘区超量自动归档(keep={keep})")
1004
+ except Exception:
1005
+ pass
1006
+ return {"count": len(arch), "kept": len(dust) - len(cand), "keep": keep,
1007
+ "dry_run": dry_run, "archived": arch}
1008
+
1009
+
873
1010
  def archive_run(dry_run: bool = False) -> dict:
874
1011
  """手动触发归档:把沉眠记忆雪藏进 archive 层(原文保真,永不删)。
875
1012
 
@@ -1201,6 +1338,17 @@ def make_record(text: str, kind: str = "fact", importance: float | None = None,
1201
1338
  "consolidated": False,
1202
1339
  "pinned": False,
1203
1340
  }
1341
+ # #50 寄生钩子:写 mistake/insight 时预埋"未来触发器"(词法近似)。
1342
+ # 只在这类记忆上有意义——它们最容易"换个说法又踩一次"。
1343
+ # 默认关(config delivery_hooks),避免给整个库凭空加字段。
1344
+ try:
1345
+ if (load_config() or {}).get("delivery_hooks") and str(kind) in ("mistake", "insight"):
1346
+ import delivery as _dlv_w
1347
+ _hk = _dlv_w.attach_hooks(text, str(kind))
1348
+ if _hk:
1349
+ rec["hooks"] = _hk
1350
+ except Exception:
1351
+ pass
1204
1352
  # P5 #20 方案 A(v3.80):用户亲口说的(source="user")本就是事实——直接标
1205
1353
  # review=confirmed,让 auto_archive 能把它们沉淀进知识库。AI 产出(默认
1206
1354
  # "ai"/dream/work-flush 等)一律不标,继续走 pending/审核闸防幻觉固化。
@@ -2321,6 +2469,7 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2321
2469
  idf = build_idf(list(all_terms.values())) if q_terms else {}
2322
2470
 
2323
2471
  scored = []
2472
+ _dropped_persona = 0
2324
2473
  # —— persona core 关键词:永久规则加权——
2325
2474
  # persona.traits 里每条 trait 的 name(如"专注"、"耐心")+ drives 的 key,
2326
2475
  # 形成一个"核心规则关键词集"。记忆 tags/entities/kind 命中这些关键词时,
@@ -2348,16 +2497,91 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2348
2497
 
2349
2498
  # 首因效应:同一片记忆里最早留下的印象占权更高(第一次的印象比后来补的更深)
2350
2499
  oldest = max((now - _num(m.get("created"), now) for m in records), default=0)
2500
+ # §2 do-now #3(BM25):长度归一要用到平均文档长度——取本次候选集的词数均值。
2501
+ # 拿不到具体数时传 None,relevance 会自动退回按单文档长度归一(不报错)。
2502
+ try:
2503
+ _lens = [len(t) for t in all_terms.values() if t]
2504
+ _avgdl = (sum(_lens) / len(_lens)) if _lens else None
2505
+ except Exception:
2506
+ _avgdl = None
2507
+ # §2 do-later #1(RRF):配了 embed 之后,两路分数量纲不可比(cosine 0.7~0.9 vs
2508
+ # 词法 0.1~0.4)。原来 `rel = max(rel, dense)` 让向量单方面压过词法,**精确关键词命中
2509
+ # 被语义近邻淹没**。有向量分时改用**名次融合**(Reciprocal Rank Fusion, k=60):
2510
+ # 只看两路各自的名次、不看绝对分,量纲问题自然消失。
2511
+ # 没有向量分(未配 embed)时保持原词法余弦,行为完全不变。
2512
+ _rrf_k = 60.0
2513
+ _lex_rank: dict = {}
2514
+ _dense_rank: dict = {}
2515
+ _rrf_max = 1.0
2516
+ _use_rrf = bool(dense_scores) and bool(cfg.get("rrf_fusion"))
2517
+ if _use_rrf:
2518
+ _lex_scored = {}
2519
+ for m in records:
2520
+ try:
2521
+ _lr = relevance(q_terms, all_terms[m["id"]], idf, _avgdl) if q_terms else 0.0
2522
+ except Exception:
2523
+ _lr = 0.0
2524
+ if _lr > 0:
2525
+ _lex_scored[m["id"]] = _lr
2526
+ for i, (mid, _v) in enumerate(sorted(_lex_scored.items(), key=lambda kv: -kv[1])):
2527
+ _lex_rank[mid] = i
2528
+ for i, (mid, _v) in enumerate(sorted(dense_scores.items(), key=lambda kv: -kv[1])):
2529
+ if _v and _v > 0:
2530
+ _dense_rank[mid] = i
2531
+ _rrf_max = (1.0 / (_rrf_k + 0.0)) * (1.0 + (1.0 if _dense_rank else 0.0))
2532
+
2533
+ def _fuse_rel(mid: str, lex_rel: float) -> float:
2534
+ if not _use_rrf:
2535
+ return lex_rel
2536
+ if mid not in _lex_rank and mid not in _dense_rank:
2537
+ return 0.0
2538
+ _r = 0.0
2539
+ if mid in _lex_rank:
2540
+ _r += 1.0 / (_rrf_k + _lex_rank[mid])
2541
+ if mid in _dense_rank:
2542
+ _r += 1.0 / (_rrf_k + _dense_rank[mid])
2543
+ return min(1.0, _r / _rrf_max) if _rrf_max else 0.0
2544
+
2545
+ # §2 do-later #48(亲和度漂移,opt-in):人格变了,检索排序自然跟着变。
2546
+ # 近似做法:记忆的 tags/entities 命中当前人格 traits 越多的,给一点亲和加成。
2547
+ # 默认关闭——它改的是召回秩序,属调优项(和 RRF/MMR 同一理由)。
2548
+ _aff_on = bool(cfg.get("affinity_drift"))
2549
+ _ptraits = set()
2550
+ if _aff_on:
2551
+ try:
2552
+ _ptraits = {str(k) for k in ((load_persona() or {}).get("traits") or {})}
2553
+ except Exception:
2554
+ _ptraits = set()
2555
+
2351
2556
  for m in records:
2352
- rel = relevance(q_terms, all_terms[m["id"]], idf) if q_terms else 0.0
2353
- # Dense 语义分托底:向量说"像"但词面没重叠(rel=0)时用语义分当 relevance;
2354
- # 词面已命中时取两者较大值,语义只增不减。
2355
- _ds = dense_scores.get(m["id"]) if dense_scores else None
2356
- if _ds is not None and _ds > rel:
2357
- rel = _ds
2557
+ rel = relevance(q_terms, all_terms[m["id"]], idf, _avgdl) if q_terms else 0.0
2558
+ # 有向量分时用 RRF 名次融合(替代原来的 max 抢占);否则保持纯词法分
2559
+ if _use_rrf:
2560
+ rel = _fuse_rel(m["id"], rel)
2561
+ else:
2562
+ _ds = dense_scores.get(m["id"]) if dense_scores else None
2563
+ if _ds is not None and _ds > rel:
2564
+ rel = _ds
2358
2565
  rec = retention(m, now)
2359
2566
  imp = _num(m.get("importance"), 0.5)
2360
2567
  score = w["relevance"] * rel + w["recency"] * rec + w["importance"] * imp
2568
+ if _aff_on and _ptraits:
2569
+ try:
2570
+ _hit = {str(t) for t in (m.get("tags") or [])} | {str(e) for e in (m.get("entities") or [])}
2571
+ _aff = len(_hit & _ptraits) / max(1, len(_ptraits))
2572
+ if _aff:
2573
+ score *= (1.0 + 0.15 * _aff) # 最多 +15%,属"轻微偏好",不抢相关性
2574
+ except Exception:
2575
+ pass
2576
+ # §2 do-later(ACT-R 基础激活):让**频次**参与决策,但权重刻意很小——
2577
+ # 它的作用是"同样相关、同样新鲜时,想过 5 次的比想过 1 次的略靠前",
2578
+ # 不是让高频记忆霸榜(那会把注入包塞满老生常谈)。
2579
+ try:
2580
+ _act = actr_base_level(m, now)
2581
+ if _act:
2582
+ score += min(0.08, 0.05 * _act)
2583
+ except Exception:
2584
+ pass
2361
2585
  # 首因:最早创建的那批(年龄接近最大)给一点额外权重
2362
2586
  age = now - _num(m.get("created"), now)
2363
2587
  if oldest > 0 and age >= oldest * 0.85:
@@ -2390,6 +2614,24 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2390
2614
  if m_kind in ("identity", "preference") or hits_core:
2391
2615
  boost = 1.0 + (w.get("core_bias", 0.20) * (1.5 if m_kind == "identity" else 1.0))
2392
2616
  score *= boost
2617
+ # —— 模块4:独立感情状态机 (A/T/C) 记忆索引加权 ——
2618
+ # 亲和高(A)优先调取正向经历与情感记忆;冲突态(C=1)优先调取过往共识与确凿事实,避免激化
2619
+ try:
2620
+ import emotion as _emo
2621
+ _aff = _emo.affection_state(now)
2622
+ _c = _aff.get("conflict", False)
2623
+ _a = _aff.get("affinity", 60.0)
2624
+ if _c:
2625
+ # 冲突态:加权共识事实与规则,降权主观猜测
2626
+ if m.get("kind") in ("fact", "preference", "rule") or not m.get("emotion"):
2627
+ score *= 1.15
2628
+ elif _a >= 75:
2629
+ # 高亲和态:加权共鸣记忆与带正面情绪的记忆
2630
+ if m.get("emotion") or m.get("kind") in ("episode", "insight"):
2631
+ score *= 1.10
2632
+ except Exception:
2633
+ pass
2634
+
2393
2635
  # —— 永久记忆:不再做"时间半衰"压分——
2394
2636
  # 原 score *= max(0.5, 0.5 ** (age_days / 30.0)) 让 3 个月前的核心偏好被压到
2395
2637
  # 50%,每月衰减、没有底板。永久记忆的"这件事本身过去多久"不该直接压分:
@@ -2413,6 +2655,19 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2413
2655
  "age_boost": 1.0}
2414
2656
  if _ds is not None:
2415
2657
  _parts["dense"] = round(_ds, 3) # 透明化:这条是向量语义捞回来的
2658
+ # 记忆投递策略(#44/#47/#50):人格池默认不进任务上下文;触发/钩子命中才加权。
2659
+ # 只读判断、纯函数;出任何问题都放行(fail-open),绝不因为策略把召回搞崩。
2660
+ try:
2661
+ import delivery as _dlv
2662
+ _keep, _fac, _why = _dlv.decide(m, set(q_terms or ()), query, cfg)
2663
+ if not _keep:
2664
+ _dropped_persona += 1
2665
+ continue
2666
+ if _fac != 1.0:
2667
+ score *= _fac
2668
+ _parts['delivery'] = _why
2669
+ except Exception:
2670
+ pass
2416
2671
  scored.append([m, score, _parts])
2417
2672
 
2418
2673
  # 情绪一致性提取(mood-congruent recall):心情会偏向勾起同调性的记忆
@@ -2447,17 +2702,20 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2447
2702
  # 显式联想:记忆之间已有的关联边把邻居也带起来("提到 A 就想起 B")
2448
2703
  # mode=fast 跳过关联扩散:低延迟模式只认词面直接命中(#27)。
2449
2704
  if (not READONLY or _assoc_file().exists()) and eff_mode != "fast":
2705
+ # 优化(2026-11-30):load_assoc 提到循环外,且把待加分项索引化
2706
+ # 避免在 assoc 循环里套 O(n) 的 ID 查找。
2707
+ _rest_map = {x[0]["id"]: x for x in scored[len(top):]}
2450
2708
  for r in load_assoc():
2451
- if r["src"] in top_ids and r["dst"] not in top_ids:
2452
- w = _num(r.get("weight"), 1)
2453
- for item in scored[len(top):]:
2454
- if item[0]["id"] == r["dst"]:
2455
- item[1] += min(0.12, 0.04 * w)
2456
- elif r["dst"] in top_ids and r["src"] not in top_ids:
2709
+ sid, did = r.get("src"), r.get("dst")
2710
+ target_id = None
2711
+ if sid in top_ids and did in _rest_map:
2712
+ target_id = did
2713
+ elif did in top_ids and sid in _rest_map:
2714
+ target_id = sid
2715
+
2716
+ if target_id:
2457
2717
  w = _num(r.get("weight"), 1)
2458
- for item in scored[len(top):]:
2459
- if item[0]["id"] == r["src"]:
2460
- item[1] += min(0.12, 0.04 * w)
2718
+ _rest_map[target_id][1] += min(0.12, 0.04 * w)
2461
2719
 
2462
2720
  scored.sort(key=lambda x: x[1], reverse=True)
2463
2721
 
@@ -2548,6 +2806,33 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2548
2806
  kept_texts.append(txt)
2549
2807
  result = kept
2550
2808
 
2809
+ # §2 do-later #2(MMR):侧抑制只砍 jaccard≥0.85 的近重复;**0.6~0.85 的
2810
+ # "同一件事换个说法"仍会占满 800 token 注入预算**。这里对已选结果做一次
2811
+ # 最大边际相关重排:MMR = λ·score归一 − (1−λ)·与已选的最大 jaccard。
2812
+ # λ 取 config `mmr_lambda`(默认 0.75:偏相关性,但明显罚重复)。
2813
+ if len(result) > 2 and q_terms and cfg.get("mmr_diversity"):
2814
+ try:
2815
+ _lam = _cfg_num(cfg, "mmr_lambda", 0.75, float)
2816
+ _lam = min(1.0, max(0.0, _lam if _lam is not None else 0.75))
2817
+ _smax = max((x[1] for x in result), default=0.0) or 1.0
2818
+ _tmap = {m["id"]: (all_terms.get(m["id"]) or terms(m.get("text", "")))
2819
+ for m, _s, _p in result}
2820
+ _pool, _picked = list(result), []
2821
+ while _pool:
2822
+ _best, _best_v = None, None
2823
+ for _it in _pool:
2824
+ _t = _tmap[_it[0]["id"]]
2825
+ _sim = max((jaccard(_t, _tmap[p[0]["id"]]) for p in _picked),
2826
+ default=0.0)
2827
+ _v = _lam * (_it[1] / _smax) - (1.0 - _lam) * _sim
2828
+ if _best_v is None or _v > _best_v:
2829
+ _best, _best_v = _it, _v
2830
+ _pool.remove(_best)
2831
+ _picked.append(_best)
2832
+ result = _picked
2833
+ except Exception:
2834
+ pass
2835
+
2551
2836
  # 错卦(v5.1):标注"查询方向"与"记忆极性"的冲突。
2552
2837
  # 只在**方向相反**时打标(查询肯定↔记忆禁止,或反之),一致时不打扰。
2553
2838
  try:
@@ -2570,10 +2855,26 @@ def recall(query: str, k: int = 8, layers: tuple = ("cortex", "hippo"),
2570
2855
  # 首次提取巩固更强:头一回想起来的事,印记打得比反复想起更深
2571
2856
  # (首因效应 + 首次测试效应:第一次回忆本身就是一次强巩固)
2572
2857
  # linked 项是"顺带想起",巩固倍率低一档(1.2 / 1.1)
2858
+ #
2859
+ # §2 do-now #2:倍率不再固定,按 **retrievability** 缩放(FSRS 式)。
2860
+ # 原来固定 ×2.6/×1.8,连刷 10 次和隔 30 天想起一次奖励相同——间隔效应被抹平,
2861
+ # Ebbinghaus 曲线只用了后半条:编码期反复触碰的过度加固(挤占注入),
2862
+ # 久别重逢的得不到强化。改成 mult = base × (1 + g·(1-R)):
2863
+ # R→1(刚见过)只按基础倍率;R→0(快忘了)加成最大。
2864
+ _R = 0.0
2865
+ try:
2866
+ _R = float(retention(m, now))
2867
+ except Exception:
2868
+ _R = 0.0
2869
+ _R = min(1.0, max(0.0, _R))
2573
2870
  if m.get("linked"):
2574
- mult = 1.2 if first else 1.1
2871
+ _base = 1.2 if first else 1.1
2872
+ _g = STRENGTHEN_GAIN_LINKED
2575
2873
  else:
2576
- mult = 2.6 if first else 1.8
2874
+ _base = 2.6 if first else 1.8
2875
+ _g = STRENGTHEN_GAIN_FIRST if first else STRENGTHEN_GAIN_REPEAT
2876
+ mult = _base * (1.0 + _g * (1.0 - _R))
2877
+ mult = min(STRENGTHEN_MULT_MAX, max(1.0, mult))
2577
2878
  m["stability"] = min(MAX_STABILITY, _num(m.get("stability"), DEFAULT_STABILITY) * mult + 4 * HOUR)
2578
2879
  m["last_access"] = now
2579
2880
  # detail 的落盘交给 _strengthen_write 在锁内以盘上现值重算巩固
@@ -4409,10 +4710,11 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4409
4710
  if not hit:
4410
4711
  continue
4411
4712
  # 共享稀有词越多越优先;同分时偏好重要度高、非归档的邻居
4713
+ # (v5.36:重要性查 id 索引,别在 sort key 里线性扫全表)
4714
+ _imp_idx = {m["id"]: _num(m.get("importance"), 0.5) for m in nodes}
4412
4715
  scored = sorted(
4413
4716
  hit.items(),
4414
- key=lambda kv: (-kv[1], -_num(
4415
- next((m for m in nodes if m["id"] == kv[0]), {}).get("importance"), 0.5)),
4717
+ key=lambda kv: (-kv[1], -_imp_idx.get(kv[0], 0.5)),
4416
4718
  )
4417
4719
  for other, cnt in scored[:2]: # 留 2 条候选
4418
4720
  w = BOOT_WEIGHT if cnt >= 2 else BOOT_WEIGHT * 0.7
@@ -4480,6 +4782,18 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4480
4782
  merged = 0
4481
4783
  try:
4482
4784
  import fallback_embed as _fe2
4785
+ # v5.36 性能:这段原来在双层循环里用 `next((m for m in nodes if m["id"]==mid))`
4786
+ # 线性扫全表找节点——实测 73,526 次生成器调用、占 assoc_graph 一半耗时。
4787
+ # 改为一次性建 id 索引 + 一次性预分词,复杂度从 O(轮 × 分量 × 主图 × 节点)
4788
+ # 降到 O(节点)。
4789
+ _by_id = {m["id"]: m for m in nodes}
4790
+ _imp_of = {mid: _num((_by_id.get(mid) or {}).get("importance"), 0.5) for mid in _by_id}
4791
+ _toks_of: dict = {}
4792
+ for mid, m in _by_id.items():
4793
+ try:
4794
+ _toks_of[mid] = set(_fe2.tokenize(m.get("text") or m.get("gist") or ""))
4795
+ except Exception:
4796
+ _toks_of[mid] = set()
4483
4797
  for _ in range(4): # 最多四轮,正常一轮就收敛
4484
4798
  comps = _components()
4485
4799
  main = next((c for c in comps if persona_id in c), [persona_id])
@@ -4489,17 +4803,11 @@ def assoc_graph(limit: int = 300, generic_ratio: float | None = None,
4489
4803
  break
4490
4804
  for comp in others:
4491
4805
  # 分量里最该代表它的节点:重要度最高的
4492
- head = max(comp, key=lambda mid: _num(
4493
- next((m for m in nodes if m["id"] == mid), {}).get("importance"), 0.5))
4494
- toks_head = set(_fe2.tokenize(
4495
- next((m.get("text") or m.get("gist") or "" for m in nodes
4496
- if m["id"] == head), "")))
4806
+ head = max(comp, key=lambda mid: _imp_of.get(mid, 0.5))
4807
+ toks_head = _toks_of.get(head) or set()
4497
4808
  best, best_cnt = None, 0
4498
4809
  for mid in main_set:
4499
- toks = set(_fe2.tokenize(
4500
- next((m.get("text") or m.get("gist") or "" for m in nodes
4501
- if m["id"] == mid), "")))
4502
- cnt = len(toks_head & toks)
4810
+ cnt = len(toks_head & (_toks_of.get(mid) or set()))
4503
4811
  if cnt > best_cnt:
4504
4812
  best, best_cnt = mid, cnt
4505
4813
  target = best if (best and best_cnt >= 2) else persona_id
@@ -4891,6 +5199,9 @@ _INJECT_CACHE_FILES = ("hippocampus.jsonl", "cortex.jsonl", "archive.jsonl",
4891
5199
  # config.json 的 mtime 故意不入键——cmd_startup 每轮都写 last_startup/wake_count,
4892
5200
  # 会把缓存打穿;改为哈希全部非易失配置,通道许可等变化仍会立即失效。
4893
5201
  _INJECT_CACHE_CONFIG_IGNORE = {"last_startup", "wake_count"}
5202
+ # 装配算法版本,参与注入缓存键。改 build_injection 的装配逻辑(截断、分段、兜底等)
5203
+ # 必须同步升这个值,否则旧缓存会被原样读回、新逻辑形同未做。
5204
+ _INJECT_CACHE_SCHEMA = "v5.34-cap1"
4894
5205
 
4895
5206
 
4896
5207
  def _inject_file_sig(path) -> str:
@@ -4918,10 +5229,17 @@ def _inject_cache_key(query: str, budget: int, cfg: dict, pressure_tier: str = "
4918
5229
 
4919
5230
  `pressure_tier`(v3.57)参与哈希:高压档位下的注入体更短,若不进键,
4920
5231
  低压时写入的全文缓存会被高压请求命中,降档形同未做。
5232
+
5233
+ `_INJECT_CACHE_SCHEMA`(v5.34)**必须**进键:装配算法改了(比如加了总量兜底),
5234
+ 键不变的话旧缓存会被原样读回,新逻辑等于没生效——实测 2026-11-29 就踩到:
5235
+ budget=1400 时 startup 返回的是旧算法算出的 3949 字符,而不是兜底后的 1993。
5236
+ 改装配请同步升这个常量。
4921
5237
  """
5238
+ schema = _INJECT_CACHE_SCHEMA
4922
5239
  try:
4923
5240
  cfg_key = {k: v for k, v in cfg.items() if k not in _INJECT_CACHE_CONFIG_IGNORE}
4924
5241
  parts = [str(query or ""), str(budget), str(pressure_tier or "full"),
5242
+ f"schema:{schema}",
4925
5243
  json.dumps(cfg_key, ensure_ascii=False, sort_keys=True,
4926
5244
  separators=(",", ":"), default=str)]
4927
5245
  for name in _INJECT_CACHE_FILES:
@@ -5066,9 +5384,12 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5066
5384
  session_mode = resolve_mode(query)
5067
5385
 
5068
5386
  brief = persona_brief(p, mood=(session_mode != "work"))
5069
- # 注入包两段容器:report 模式用记账 list(每行记所属段名),否则普通 list。
5070
- out = _SectionList() if report is not None else []
5071
- dyn = _SectionList() if report is not None else []
5387
+ # 注入包两段容器:两块都必须记账(每行记所属段名)。
5388
+ # ⚠ v5.34:`dyn` 原先在 report=None(**运行时默认走这条**)时是普通 list,
5389
+ # 末尾那一大块实时状态于是全被标成 other → other 独大、可丢段丢光也压不下来,
5390
+ # 总量兜底等于失灵(实测 startup 仍 3984 字符 / 约 1972 token)。
5391
+ out = _SectionList()
5392
+ dyn = _SectionList()
5072
5393
  # 包头两句是骨架文案归 other;「我是谁」+ 人格简介归 persona。
5073
5394
  _bill["sec"] = "other"
5074
5395
  out.append("===== 长期记忆注入(灵枢)=====")
@@ -5738,15 +6059,33 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5738
6059
  _bill["sec"] = "skills"
5739
6060
  try:
5740
6061
  import growth
5741
- avail = [r for r in growth.skill_roots() if r.get("exists") and r.get("count")]
6062
+ # v5.36:只注入**已启用**的技能——面板开关关掉后,这里就不再让 AI 看见它。
6063
+ # 计数与清单都按 enabled 过滤,别让"已关闭"的技能占预算、也别让目录计数虚高。
6064
+ all_sk = growth.scan_skills()
6065
+ enabled_sk = [s for s in all_sk if s.get("enabled", True)]
6066
+ by_root: dict = {}
6067
+ for s in enabled_sk:
6068
+ by_root[s["root"]] = by_root.get(s["root"], 0) + 1
6069
+ avail = [{"label": r["label"], "path": r["path"], "count": by_root.get(r["path"], 0)}
6070
+ for r in growth.skill_roots() if by_root.get(r["path"])]
5742
6071
  # v3.57 高压档整段省略:技能库是"锦上添花"的可选块(实测 ~139 tokens),
5743
6072
  # 上下文快满时它最不值得花;需要时 `skill scan` 随时能查。
5744
6073
  if avail and _p_tier != "minimal":
5745
- out.append("\n## 技能库(跨宿主,可直接用)")
6074
+ out.append("\n## 技能库(已启用且跨宿主可用)")
5746
6075
  out.append("这些目录里有现成技能,都是本地文件,读出来照做即可,不必先安装:")
5747
- for r in avail[:8]:
5748
- out.append(f"- [{r['label']}] {r['path']}({r['count']} 个)")
5749
- out.append("列全部:`python scripts/brain.py skill scan`;照做某个:`skill use <名字>`"
6076
+ # OPS-01: 惰性加载模式——只注入名称和一句话功能定位,模型按需通过 skill use 读取完整内容
6077
+ sk_descs = []
6078
+ for s in enabled_sk[:10]:
6079
+ d_short = (s.get("description") or "").strip().replace("\n", " ")
6080
+ if len(d_short) > 36:
6081
+ d_short = d_short[:36].rstrip() + "…"
6082
+ sk_descs.append(f"- {s['name']}" + (f":{d_short}" if d_short else ""))
6083
+ if sk_descs:
6084
+ out.append("已激活能力清单(按需调用,全文按需加载):")
6085
+ out.extend(sk_descs)
6086
+ for r in avail[:5]:
6087
+ out.append(f"[{r['label']}] {r['path']}({r['count']} 个)")
6088
+ out.append("列全部:`python scripts/brain.py skill scan`;查看/调用某个:`skill use <名字>`"
5750
6089
  "(`--root <宿主名或目录>` 限定来源);变成自己的版本:`skill borrow <名字>`。")
5751
6090
  except Exception:
5752
6091
  pass
@@ -5780,15 +6119,106 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5780
6119
  + ";".join(_parts) + "。语气与判断与它保持一致,别越聊越走样。")
5781
6120
  except Exception:
5782
6121
  pass
6122
+ # B4(借鉴 QQ「大肥鱼」):周期性语气提示——从**近期对话**提炼,每 6 小时一次。
6123
+ # 默认关闭:它往注入包加内容,属于主链路改动,需 config `style_hint: true` 才生效。
6124
+ if cfg.get("style_hint"):
6125
+ try:
6126
+ import style_check
6127
+ _hint = style_check.hint()
6128
+ if _hint:
6129
+ _bill["sec"] = "rules"
6130
+ out.append("\n" + _hint)
6131
+ except Exception:
6132
+ pass
5783
6133
  # 五-A:稳定前缀在前、实时状态在后。分界线本身也是常量,便于 inject-drift 自检定位。
5784
6134
  _bill["sec"] = "other"
5785
6135
  out.append("\n" + INJECT_DYN_MARKER)
5786
- if report is not None:
5787
- out.extend(dyn, secs=dyn.secs)
5788
- else:
5789
- out.extend(dyn)
6136
+ out.extend(dyn, secs=dyn.secs)
5790
6137
  out.append("===== 注入结束:请自然地使用这些记忆,不要逐条复述 =====")
5791
6138
  out.append("")
6139
+ # ---- P0.8 总量兜底 ----
6140
+ # 各段有自己的 cap_frac(_soft_block)与 mem_cap(0.4/0.5 倍),这些比例是**各自独立**的,
6141
+ # 加总当然可以超 100%(实测注入包 190.3%:2664 token / 预算 1400)。调 char_budget 系数
6142
+ # 只挪参考线,不改这个事实。所以在这里按**段优先级整段丢弃**,直到不超 char_budget。
6143
+ def _sec_of(i: int) -> str:
6144
+ return out.secs[i] if i < len(out.secs) else "other"
6145
+
6146
+ def _size() -> int:
6147
+ return sum(len(p) for p in out)
6148
+
6149
+ # 低→高,先丢:dynamic(兜底分类)最先,persona/water/other 永不丢。
6150
+ _DROP_PRIORITY = ("dynamic", "skills", "topics", "relationships", "related",
6151
+ "recent", "mistakes", "rules")
6152
+ _before = _size()
6153
+ # 提示行本身也占字符:预留它的上限,否则"刚好达标"再补一行又超预算。
6154
+ _NOTICE_MAX = 160
6155
+ _target = max(0, char_budget - _NOTICE_MAX)
6156
+ if _before > char_budget:
6157
+ # ⚠ 必须**累计递减**:之前写成循环里反复问 _size(),而 out 在循环里没变,
6158
+ # 结果每个可丢段都被判"还超"→ 全丢光(实测 mistakes/recent/rules 一起清空,
6159
+ # 注入只剩 persona+water,比超预算更糟)。
6160
+ _sec_sizes: dict = {}
6161
+ for i in range(len(out)):
6162
+ _s = _sec_of(i)
6163
+ _sec_sizes[_s] = _sec_sizes.get(_s, 0) + len(out[i])
6164
+ _budget_left = _before
6165
+ _drop = set()
6166
+ for sec in _DROP_PRIORITY:
6167
+ if _budget_left <= _target:
6168
+ break
6169
+ _sz = _sec_sizes.get(sec, 0)
6170
+ if _sz:
6171
+ _budget_left -= _sz
6172
+ _drop.add(sec)
6173
+ # 丢光**也**压不下来 → 大头在不可丢段(persona/water/other),此时丢弃纯属白丢:
6174
+ # 内容没了、预算照样超。这种情况一律不丢。
6175
+ # 降噪:高压 minimal 档(如水位 >= 90% 封存期)预算极度收缩(仅 45%),不可丢段超预算属常态,
6176
+ # 不属于程序 bug,记录 info 避免反复刷屏产生假警报。
6177
+ if _drop and _budget_left > _target:
6178
+ try:
6179
+ _lv = "info" if _p_tier == "minimal" else "warn"
6180
+ log_event("inject",
6181
+ f"注入包超 char_budget({_before}>{char_budget}),但丢光可丢段"
6182
+ f"仍会超({_budget_left}>{_target})——主体在不可丢段,本次不丢",
6183
+ level=_lv)
6184
+ except Exception:
6185
+ pass
6186
+ _drop = set()
6187
+ if _drop:
6188
+ _parts, _secs = [], []
6189
+ for i in range(len(out)):
6190
+ if _sec_of(i) in _drop:
6191
+ continue
6192
+ _parts.append(out[i])
6193
+ _secs.append(_sec_of(i))
6194
+ out = _SectionList()
6195
+ for _p, _s in zip(_parts, _secs):
6196
+ out.append(_p, _s)
6197
+ # 静默省略比超预算更糟:让 AI 知道自己"少看到了什么",
6198
+ # 需要时能主动 recall。放在分割线前,不打断人格前缀。
6199
+ try:
6200
+ _names = {"dynamic": "实时状态", "skills": "技能库", "topics": "话题栈",
6201
+ "relationships": "人际关系", "related": "相关记忆",
6202
+ "recent": "最近的记忆", "mistakes": "我犯过的错", "rules": "规则"}
6203
+ _txt = "、".join(_names.get(_s, _s) for _s in sorted(_drop))
6204
+ out.append(f"※ 本次预算紧张,已省略以下段落(需要时用 recall/deref 现取):{_txt}")
6205
+ except Exception:
6206
+ pass
6207
+ try:
6208
+ log_event("inject",
6209
+ f"注入包超 char_budget({_before}>{char_budget}),按优先级整段丢弃:"
6210
+ f"{'、'.join(sorted(_drop))}(省 {_before - _size()} 字符)",
6211
+ level="info")
6212
+ except Exception:
6213
+ pass
6214
+ if _size() > char_budget:
6215
+ try:
6216
+ _lv = "info" if _p_tier == "minimal" else "warn"
6217
+ log_event("inject",
6218
+ f"丢弃可丢段后仍超 char_budget({_size()}>{char_budget})"
6219
+ "——persona/water/other 属不可丢段", level=_lv)
6220
+ except Exception:
6221
+ pass
5792
6222
  _result = "\n".join(out)
5793
6223
  # 指针短 id 的最终形态(统一在此决定,覆盖「相关/最近记忆」与「刚刚发生」两条渲染路径):
5794
6224
  # · 段头已有"指针条目"提示 → 紧凑形(去掉哨兵,只留 8 位短号)
@@ -5844,14 +6274,16 @@ def build_injection(query: str = "", budget_tokens: int | None = None,
5844
6274
  total_chars = len(_result)
5845
6275
  total_tokens = sum(_s["tokens"] for _s in sections)
5846
6276
  try:
5847
- log_event("inject",
5848
- f"注入账单字符数与实际不符(已按实际校正 {_delta:+d}):"
5849
- "通常是指针标记替换改变了长度", level="warn")
5850
- except Exception: # noqa: BLE001
6277
+ _lv = "info" if abs(int(_delta)) <= 40 else "warn"
6278
+ log_event("inject", f"注入账单字符数已按实际校正 ({_delta:+d})", level=_lv)
6279
+ except Exception:
5851
6280
  pass
5852
6281
  report.update({"sections": sections, "total_chars": total_chars,
5853
6282
  "total_tokens": total_tokens, "budget": budget,
5854
- "chars_per_token": ratio})
6283
+ "chars_per_token": ratio,
6284
+ # §7/§2 I3 澄清:装配用的字符预算(budget×1.8,给中文分词留余量)
6285
+ # 与账单用的 chars_per_token **故意不同**,别互相换算/对齐。
6286
+ "char_budget": char_budget})
5855
6287
  # P4 灰度记账接线(本轮只记账、不切换装配):report 刚汇总完,用它的分段账单
5856
6288
  # 试排一次五段式计划,按采样率落一条 metrics.jsonl。默认 enabled=false 时
5857
6289
  # 只做一次开关判断就返回——连 plan 都不算,零写盘;enabled 才 import/试排,
@@ -5992,9 +6424,45 @@ def stats() -> dict:
5992
6424
  "never_used_pct": round(never_used / n_active, 3),
5993
6425
  "archive_hint": old_never,
5994
6426
  "home": str(HOME),
6427
+ # IDEA-02: 记忆衰减分布热力图数据源
6428
+ "decay_heatmap": memory_decay_heatmap(now),
5995
6429
  }
5996
6430
 
5997
6431
 
6432
+ def memory_decay_heatmap(at: float | None = None) -> dict:
6433
+ """按层级与创建时间跨度聚合计算艾宾浩斯记忆保留率 R(t) 热力分布图。"""
6434
+ records = load_all() + load_archive()
6435
+ now = at or now_ts()
6436
+ layers = ["hippo", "cortex", "dust", "archive"]
6437
+ res = {}
6438
+ for l in layers:
6439
+ res[l] = {"count": 0, "ret_sum": 0.0, "0_3d": 0, "3_7d": 0, "7_30d": 0, "30d_plus": 0}
6440
+
6441
+ for r in records:
6442
+ l = r.get("layer", "hippo")
6443
+ if l not in res:
6444
+ l = "hippo"
6445
+ created = _num(r.get("created"), now)
6446
+ age_days = max(0.0, (now - created) / DAY)
6447
+ ret = float(retention(r, now))
6448
+ res[l]["count"] += 1
6449
+ res[l]["ret_sum"] += ret
6450
+ if age_days <= 3:
6451
+ res[l]["0_3d"] += 1
6452
+ elif age_days <= 7:
6453
+ res[l]["3_7d"] += 1
6454
+ elif age_days <= 30:
6455
+ res[l]["7_30d"] += 1
6456
+ else:
6457
+ res[l]["30d_plus"] += 1
6458
+
6459
+ for l in layers:
6460
+ cnt = res[l]["count"]
6461
+ res[l]["avg_retention"] = round(res[l]["ret_sum"] / cnt, 3) if cnt else 0.0
6462
+ res[l].pop("ret_sum", None)
6463
+ return res
6464
+
6465
+
5998
6466
  def list_memories(limit: int = 30, layer: str | None = None) -> list:
5999
6467
  records = load_all()
6000
6468
  if layer:
@@ -6017,7 +6485,9 @@ from mem_dialogue import * # noqa: E402,F401,F403
6017
6485
 
6018
6486
 
6019
6487
  # 评分/保留度纯函数已拆到 mem_score.py(v3.40)
6020
- from mem_score import * # noqa: E402,F401,F403
6488
+ from mem_score import (terms, jaccard, build_idf, relevance, _num, heuristic_importance,
6489
+ _imp_key_safe, retention, activation, ACTIVATION_FORGET_THRESHOLD, activation_forget,
6490
+ _KIND_STABILITY_FACTOR, _cosine_sim) # noqa: E402,F401 # noqa: E402,F401 # noqa: E402,F401
6021
6491
 
6022
6492
 
6023
6493
  # 会话话题栈已拆到 mem_topic.py(v3.69)