lingshu-skill 5.60.0 → 5.62.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 (207) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1 -1
  3. package/SKILL-lite.md +1 -1
  4. package/SKILL-tiny.md +1 -1
  5. package/SKILL.md +1 -1
  6. package/manifest.json +461 -0
  7. package/package.json +8 -2
  8. package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +10 -10
  9. package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +29 -0
  10. package/scripts/astrbot_plugin_lingshu/engine/README.md +1 -1
  11. package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +1 -1
  12. package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +1 -1
  13. package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +1 -1
  14. package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +58 -39
  15. package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +3 -4
  16. package/scripts/astrbot_plugin_lingshu/engine/scripts/make_dsh_tgz.py +20 -3
  17. package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +11 -2
  18. package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_build.py +13 -0
  19. package/scripts/core.py +58 -39
  20. package/scripts/growth.py +3 -4
  21. package/scripts/make_dsh_tgz.py +20 -3
  22. package/scripts/make_manifest.py +15 -10
  23. package/scripts/make_plugin_zip.py +7 -3
  24. package/scripts/memory.py +11 -2
  25. package/scripts/panel_build.py +13 -0
  26. package/scripts/_ci_env_probe.py +0 -81
  27. package/scripts/_panel_smoke_v299.py +0 -27
  28. package/scripts/_scratch/_tmp_backup_race.py +0 -70
  29. package/scripts/_scratch/_tmp_cleanup_move.py +0 -34
  30. package/scripts/_scratch/_tmp_count_kinds.py +0 -25
  31. package/scripts/_scratch/_tmp_diag_paths.py +0 -48
  32. package/scripts/_scratch/_tmp_facts.py +0 -63
  33. package/scripts/_scratch/_tmp_find_copies.py +0 -31
  34. package/scripts/_scratch/_tmp_find_pin.py +0 -29
  35. package/scripts/_scratch/_tmp_fix_pin.py +0 -36
  36. package/scripts/_scratch/_tmp_fold_fixture.py +0 -55
  37. package/scripts/_scratch/_tmp_fold_test.mjs +0 -81
  38. package/scripts/_scratch/_tmp_inject_secs.py +0 -30
  39. package/scripts/_scratch/_tmp_kb_balance.py +0 -159
  40. package/scripts/_scratch/_tmp_lines.py +0 -15
  41. package/scripts/_scratch/_tmp_market_probe.py +0 -13
  42. package/scripts/_scratch/_tmp_move_partial.py +0 -16
  43. package/scripts/_scratch/_tmp_patch_b3.py +0 -41
  44. package/scripts/_scratch/_tmp_patch_b5.py +0 -62
  45. package/scripts/_scratch/_tmp_patch_crash_excl.py +0 -24
  46. package/scripts/_scratch/_tmp_patch_handoff.py +0 -21
  47. package/scripts/_scratch/_tmp_patch_ps1.py +0 -25
  48. package/scripts/_scratch/_tmp_patch_stat.py +0 -27
  49. package/scripts/_scratch/_tmp_patch_todo.py +0 -25
  50. package/scripts/_scratch/_tmp_patch_todo2.py +0 -64
  51. package/scripts/_scratch/_tmp_probe_session.py +0 -51
  52. package/scripts/_scratch/_tmp_style_probe.py +0 -40
  53. package/scripts/_scratch/_tmp_write_note.py +0 -139
  54. package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +0 -1
  55. package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +0 -1044
  56. package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +0 -194
  57. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +0 -175
  58. package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +0 -97
  59. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +0 -47
  60. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +0 -40
  61. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +0 -37
  62. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +0 -9
  63. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +0 -36
  64. package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +0 -10
  65. package/scripts/_scratch/commit_msg_occ.txt +0 -16
  66. package/scripts/_scratch/commit_msg_struct.txt +0 -16
  67. package/scripts/_scratch/v5.34_changelog.txt +0 -36
  68. package/scripts/_smoke_v299.py +0 -31
  69. package/scripts/_sync_trae_cn.py +0 -102
  70. package/scripts/_tmp_add_s10.py +0 -54
  71. package/scripts/_tmp_add_s11.py +0 -61
  72. package/scripts/_tmp_add_s12.py +0 -66
  73. package/scripts/_tmp_add_s13.py +0 -69
  74. package/scripts/_tmp_add_s14.py +0 -80
  75. package/scripts/_tmp_add_s9.py +0 -68
  76. package/scripts/_tmp_cache_load.py +0 -82
  77. package/scripts/_tmp_clean_market.py +0 -40
  78. package/scripts/_tmp_clean_pruned.py +0 -81
  79. package/scripts/_tmp_cleanup_docs.py +0 -39
  80. package/scripts/_tmp_cmp_ranker.py +0 -17
  81. package/scripts/_tmp_dolater_note.py +0 -35
  82. package/scripts/_tmp_dust_why.py +0 -27
  83. package/scripts/_tmp_explicit_import.py +0 -40
  84. package/scripts/_tmp_extract_compaction.py +0 -35
  85. package/scripts/_tmp_extract_compaction2.py +0 -63
  86. package/scripts/_tmp_extract_compaction3.py +0 -51
  87. package/scripts/_tmp_extract_compaction4.py +0 -54
  88. package/scripts/_tmp_finalize_s14.py +0 -39
  89. package/scripts/_tmp_find_compaction.py +0 -43
  90. package/scripts/_tmp_fix_b4.py +0 -22
  91. package/scripts/_tmp_fix_cli76.py +0 -26
  92. package/scripts/_tmp_fix_docs.py +0 -38
  93. package/scripts/_tmp_fix_docs_b.py +0 -46
  94. package/scripts/_tmp_fix_docs_b2.py +0 -22
  95. package/scripts/_tmp_fix_i3.py +0 -23
  96. package/scripts/_tmp_fix_s10.py +0 -83
  97. package/scripts/_tmp_fix_s11.py +0 -14
  98. package/scripts/_tmp_fix_s9_status.py +0 -19
  99. package/scripts/_tmp_fix_shadow_sim.py +0 -37
  100. package/scripts/_tmp_fix_traits_value.py +0 -41
  101. package/scripts/_tmp_import_idem.py +0 -106
  102. package/scripts/_tmp_log_ack.py +0 -45
  103. package/scripts/_tmp_mark_batch.py +0 -28
  104. package/scripts/_tmp_mark_batch2.py +0 -32
  105. package/scripts/_tmp_mark_dolater.py +0 -26
  106. package/scripts/_tmp_mark_dolater2.py +0 -31
  107. package/scripts/_tmp_move_self.py +0 -16
  108. package/scripts/_tmp_occ_cli.py +0 -22
  109. package/scripts/_tmp_occ_link.py +0 -108
  110. package/scripts/_tmp_optimize_recall.py +0 -54
  111. package/scripts/_tmp_panel_audit.py +0 -26
  112. package/scripts/_tmp_patch_batch3.py +0 -65
  113. package/scripts/_tmp_patch_rrf.py +0 -46
  114. package/scripts/_tmp_patch_s2s3.py +0 -80
  115. package/scripts/_tmp_patch_s4.py +0 -39
  116. package/scripts/_tmp_patch_s7.py +0 -43
  117. package/scripts/_tmp_patch_s8.py +0 -91
  118. package/scripts/_tmp_patch_skill.py +0 -17
  119. package/scripts/_tmp_release_guard.py +0 -57
  120. package/scripts/_tmp_rerank_breaker.py +0 -62
  121. package/scripts/_tmp_s16.py +0 -41
  122. package/scripts/_tmp_scan_asar.py +0 -41
  123. package/scripts/_tmp_scan_asar2.py +0 -37
  124. package/scripts/_tmp_speed_survey.py +0 -49
  125. package/scripts/_tmp_struct_docs.py +0 -49
  126. package/scripts/_tmp_sum_fallback.py +0 -42
  127. package/scripts/_tmp_sweep.py +0 -81
  128. package/scripts/_tmp_sync_check.py +0 -69
  129. package/scripts/_tmp_sync_tail.py +0 -39
  130. package/scripts/_tmp_todo_clean.py +0 -67
  131. package/scripts/_tmp_verify_copy.py +0 -17
  132. package/scripts/_tmp_wire_extras.py +0 -93
  133. package/scripts/_tmp_wire_hsum.py +0 -34
  134. package/scripts/_tmp_wire_occ_b5.py +0 -40
  135. package/scripts/_tmp_wire_ranker.py +0 -13
  136. package/scripts/_tmp_wire_shadow_timeline.py +0 -45
  137. package/scripts/astrbot_plugin_lingshu/engine/scripts/_ci_env_probe.py +0 -81
  138. package/scripts/astrbot_plugin_lingshu/engine/scripts/_panel_smoke_v299.py +0 -27
  139. package/scripts/astrbot_plugin_lingshu/engine/scripts/_smoke_v299.py +0 -31
  140. package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +0 -102
  141. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +0 -54
  142. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +0 -61
  143. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +0 -66
  144. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +0 -69
  145. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +0 -80
  146. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +0 -68
  147. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +0 -82
  148. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +0 -40
  149. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +0 -81
  150. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +0 -39
  151. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +0 -17
  152. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +0 -35
  153. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +0 -27
  154. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +0 -40
  155. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +0 -35
  156. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +0 -63
  157. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +0 -51
  158. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +0 -54
  159. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +0 -39
  160. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +0 -43
  161. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +0 -22
  162. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +0 -26
  163. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +0 -38
  164. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +0 -46
  165. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +0 -22
  166. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +0 -23
  167. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +0 -83
  168. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +0 -14
  169. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +0 -19
  170. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +0 -37
  171. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +0 -41
  172. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +0 -106
  173. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +0 -45
  174. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +0 -28
  175. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +0 -32
  176. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +0 -26
  177. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +0 -31
  178. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +0 -16
  179. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +0 -22
  180. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +0 -108
  181. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +0 -54
  182. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +0 -26
  183. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +0 -65
  184. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +0 -46
  185. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +0 -80
  186. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +0 -39
  187. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +0 -43
  188. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +0 -91
  189. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +0 -17
  190. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +0 -57
  191. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +0 -62
  192. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +0 -41
  193. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +0 -41
  194. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +0 -37
  195. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_speed_survey.py +0 -49
  196. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +0 -49
  197. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +0 -42
  198. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +0 -81
  199. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +0 -69
  200. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +0 -39
  201. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +0 -67
  202. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +0 -17
  203. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +0 -93
  204. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +0 -34
  205. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +0 -40
  206. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +0 -13
  207. package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +0 -45
@@ -2,7 +2,7 @@
2
2
 
3
3
  > 名字取自《黄帝内经》:**算力给思考,人格给灵魂,记忆给生命。**
4
4
 
5
- > 当前版本 **v5.60**(变更见 [CHANGELOG.md](CHANGELOG.md))
5
+ > 当前版本 **v5.62**(变更见 [CHANGELOG.md](CHANGELOG.md))
6
6
 
7
7
  > 🔁 **双仓库镜像**:GitHub(主)与 Gitee(镜像)保持同步——[gitee.com/htmcwy_0/lingshu-skill](https://gitee.com/htmcwy_0/lingshu-skill)。灵枢的更新检查会探测两边最新提交,**谁更新就自动从谁拉取**;任一边不可达(Gitee 匿名风控 / GitHub 限额)时走另一边兜底。
8
8
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: lingshu-lite
3
3
  title: 灵枢-lite
4
- version: 5.60
4
+ version: 5.62
5
5
  description: 灵枢记忆系统的精简版说明书,给 3B 以下本地小模型或第一次用的人。只保留最有用的核心:分层记忆(含冷热自动归档)、模糊回忆、工作记忆、人格初识;砍掉高风险自动能力(自动做梦合并、自动情绪评估、自动提炼知识库)——小模型做这些容易把幻觉固化落盘。当用户提到"记住这个""你还记得吗""你记得什么""上下文快满了"且宿主是小模型时使用。
6
6
  ---
7
7
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: lingshu-tiny
3
3
  title: 灵枢-tiny
4
- version: 5.60
4
+ version: 5.62
5
5
  description: 灵枢记忆系统的最小试用版说明书。只剩三件事:startup 带回上次的记忆、remember 记下值得记的、recall 想不起来时捞回来。给第一次接触灵枢的人或最小模型:先跑通这三条拿到真实收益,再决定要不要升级完整版。当用户提到"记住这个""你还记得吗"且你不想背整套机制时使用。
6
6
  ---
7
7
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: lingshu
3
3
  title: 灵枢
4
- version: 5.60
4
+ version: 5.62
5
5
  description: 类脑持久记忆/人格/成长。跨会话记住事情、长出人格、上下文将满时做梦整理。用户提记忆/记住/上次/人格/设定/性格/知识库/笔记/日志/成长/自我进化/工作记忆,或新会话需恢复关系上下文时用。纯本地零依赖。
6
6
  ---
7
7
 
@@ -1622,12 +1622,22 @@ def read_jsonl(path: Path) -> list:
1622
1622
  continue
1623
1623
  except Exception:
1624
1624
  pass
1625
- # 单行解析失败:可能是多行格式化 JSON。按括号配对把整块累积起来再试,
1626
- # 避免把一条跨行合法记录当成坏行丢掉。
1625
+ # LS-018(v5.61):防止残缺 JSONL 块吞掉后续合法记录!
1626
+ # 若单行解析失败,尝试多行聚合时,如果后续某一行本身就是独立的合法 JSON,绝不能被吞进坏块!
1627
1627
  block = [lines[i]]
1628
1628
  depth = _brace_balance(lines[i])
1629
1629
  i += 1
1630
- while i < n and depth > 0 and len(block) < 200:
1630
+ while i < n and depth > 0 and len(block) < 50:
1631
+ next_line = lines[i].strip()
1632
+ # 探测:若下一行本身已经能独立解析为完整合法 JSON 对象,说明上一行只是残缺坏行,不是跨行对象!
1633
+ if next_line.startswith("{") and next_line.endswith("}"):
1634
+ try:
1635
+ maybe_valid = json.loads(next_line)
1636
+ if isinstance(maybe_valid, dict):
1637
+ # 发现独立合法行,终止当前坏块累积,让外部循环正常处理该行
1638
+ break
1639
+ except Exception:
1640
+ pass
1631
1641
  block.append(lines[i])
1632
1642
  depth += _brace_balance(lines[i])
1633
1643
  i += 1
@@ -1834,27 +1844,18 @@ def _locked(path: Path, timeout: float = 10.0):
1834
1844
  # (_held() 已为 False 才会走到这里)→ 这是我们自己遗留的锁,立刻接管。
1835
1845
  # 否则会等满 timeout 才失败,实测能把同进程的 remember 循环卡死。
1836
1846
  try:
1837
- _owner = _lock_owner(lock)
1847
+ _owner, _host = _lock_owner_info(lock)
1838
1848
  _age = time.time() - lock.stat().st_mtime
1839
- # ⚠ 本进程的锁**绝不能只按 pid 判孤儿**:面板是 ThreadingHTTPServer,
1840
- # 多个线程会写同一批 jsonl。A 线程持锁超过宽限期时(全量重写上万条、
1841
- # _replace_retry 退避都可能 >1s),B 线程会读到 owner pid == 自己进程
1842
- # 而误判"遗留孤儿锁",把 A 的活锁删掉 → 两线程同时读-改-写 → 静默丢记忆。
1843
- # 正确判据是"**本线程是否真持有**"(_held 里有 (锁路径, 线程id))。
1844
1849
  _held_by_me = _held_any_thread(lock)
1845
- _same_proc = (_owner == os.getpid())
1846
- # 通道 A:空锁文件(O_CREAT 与写 pid 之间的窗口)。
1847
- # 活着的进程不会把锁空着超过宽限期,所以可接管;
1848
- # 但若本线程正持有(重入已在函数开头 return),这里不涉及。
1849
- # 空锁文件:本进程没人持有它,且已过宽限期 → 是遗留孤儿,可接管。
1850
- # 若本进程有线程正持有(刚 create、还没写 pid 的一瞬)→ 是活锁,别动。
1850
+ _same_host = (not _host or _host == _HOSTNAME)
1851
+ _same_proc = (_same_host and _owner == os.getpid())
1851
1852
  _orphan_empty = (_owner is None and not _held_by_me)
1852
- # 通道 B:**持锁进程已死**。与时间无关(只要过了宽限),
1853
- # 否则会撞上"STALE_LOCK_SECONDS(30) > timeout(10)"的死角。
1854
- _owner_dead = (_owner is not None and not _same_proc
1853
+ # LS-006(v5.61):修复共享盘远程锁误判!
1854
+ # 远程机器持有的活锁,其 PID 在本机探活时大概率返回 Dead(ProcessLookupError),
1855
+ # 旧逻辑仅根据 `not _pid_alive` 就会误将远程活锁当作孤儿锁 unlink 抢占,导致双机并发破坏数据。
1856
+ # 规定:只有确认是【同一主机】且 PID 已死,才允许按进程死亡接管孤儿锁!
1857
+ _owner_dead = (_owner is not None and _same_host and not _same_proc
1855
1858
  and not _pid_alive(_owner))
1856
- # 本进程 + **没有线程持有** = 真孤儿(守卫已在上面排除"有线程持有"),
1857
- # 可以安全接管:否则崩溃/异常后同进程后续写入会一直超时。
1858
1859
  _owner_self_orphan = _same_proc and not _held_by_me
1859
1860
  if _age > ORPHAN_LOCK_GRACE and (
1860
1861
  _orphan_empty or _owner_dead or _owner_self_orphan):
@@ -1865,21 +1866,24 @@ def _locked(path: Path, timeout: float = 10.0):
1865
1866
  continue
1866
1867
  except OSError:
1867
1868
  pass
1868
- # ② 陈旧锁(持锁进程已死):久到不可能是正常写盘(正常持锁 <2s)才接管。
1869
- # 阈值别设太小:dream 整理记忆时持锁会久一点,抢早了就是两个进程同时写。
1869
+ # ② 陈旧锁:超过 STALE_LOCK_SECONDS。
1870
+ # 对本机锁进行 PID 探活;对远程锁(_host != _HOSTNAME),仅当极度超时且无更新才清理
1870
1871
  try:
1871
1872
  if time.time() - lock.stat().st_mtime > STALE_LOCK_SECONDS:
1872
- # 再加一道 pid 探活:持锁进程还活着就别抢(work_flush/dream 可能持锁较久)。
1873
- # 同进程(含本进程其它线程)持有的锁一律视为"活着",绝不接管。
1874
- owner = _lock_owner(lock)
1875
- if owner is not None and _pid_alive(owner):
1876
- pass # 活着的持锁者:继续等,不接管
1877
- else:
1878
- try:
1879
- lock.unlink()
1880
- except OSError:
1881
- pass
1882
- continue
1873
+ owner, host = _lock_owner_info(lock)
1874
+ same_host = (not host or host == _HOSTNAME)
1875
+ if owner is not None:
1876
+ if same_host and _pid_alive(owner):
1877
+ pass # 本机存活持锁者:不抢
1878
+ elif not same_host:
1879
+ # LS-006: 远程主机持锁:非本机不能拿本地 PID 判断生死
1880
+ pass # 远程锁在超时窗口内严格保持等待,防止跨主机冲突
1881
+ else:
1882
+ try:
1883
+ lock.unlink()
1884
+ except OSError:
1885
+ pass
1886
+ continue
1883
1887
  except OSError:
1884
1888
  pass
1885
1889
  if time.time() > deadline:
@@ -1956,13 +1960,23 @@ def _pid_alive(pid: int) -> bool:
1956
1960
  return True
1957
1961
 
1958
1962
 
1959
- def _lock_owner(lock: Path) -> int | None:
1960
- """读锁文件里记录的持有者 pid;读不到/格式不对返回 None。"""
1963
+ def _lock_owner_info(lock: Path) -> tuple[int | None, str]:
1964
+ """LS-006(v5.61):读锁持有者 (pid, host)。读不到返回 (None, '')。"""
1961
1965
  try:
1962
- raw = lock.read_text(encoding="utf-8", errors="ignore").strip()
1963
- return int(raw.split()[0]) if raw else None
1966
+ raw = lock.read_text(encoding="utf-8", errors="ignore").strip().lstrip("\ufeff")
1967
+ if not raw:
1968
+ return None, ""
1969
+ parts = raw.split()
1970
+ pid = int(parts[0]) if parts else None
1971
+ host = parts[1] if len(parts) > 1 else ""
1972
+ return pid, host
1964
1973
  except (OSError, ValueError, IndexError):
1965
- return None
1974
+ return None, ""
1975
+
1976
+
1977
+ def _lock_owner(lock: Path) -> int | None:
1978
+ """读锁文件里记录的持有者 pid;读不到/格式不对返回 None。"""
1979
+ return _lock_owner_info(lock)[0]
1966
1980
 
1967
1981
 
1968
1982
  def lock_writers() -> list[dict]:
@@ -2013,7 +2027,12 @@ def _persona_txn(fn):
2013
2027
 
2014
2028
  def _locked_save_all(records: list) -> None:
2015
2029
  """save_all 的加锁版:并发写记忆不丢更新。"""
2016
- with _locked(HOME / "hippocampus.jsonl"):
2030
+ # LS-007(v5.61):统一强化与定向补丁的锁口径!
2031
+ # 之前仅持 hippocampus.jsonl 单锁,却跨层改写了 cortex 和 dust,导致与持 cortex 锁的补丁并发互踩丢失字段。
2032
+ # 固定按三层层级顺序持有锁:
2033
+ with _locked(HOME / "hippocampus.jsonl"), \
2034
+ _locked(HOME / "cortex.jsonl"), \
2035
+ _locked(HOME / "dust.jsonl"):
2017
2036
  existing = load_all()
2018
2037
  by_id = {}
2019
2038
  no_id = [] # 缺 id 的畸形记录也原样保留,不能因为无法索引就悄悄丢掉
@@ -1688,12 +1688,11 @@ def apply_update(src_dir: Path, dst_dir: Path,
1688
1688
  + ", ".join(sorted(_missing)[:8])
1689
1689
  + (f" 等 {len(_missing)} 个" if len(_missing) > 8 else ""))
1690
1690
  def _norm_sha(p: Path) -> str:
1691
+ # LS-121(v5.62):二进制文件(png, ico等)不执行文本换行归一化,直接取原始字节 SHA
1692
+ if p.suffix.lower() in {".png", ".ico", ".jpg", ".jpeg", ".webp", ".gif", ".pdf", ".woff", ".woff2", ".ttf"}:
1693
+ return _sha256_file(p)
1691
1694
  # 规范形态哈希:与 make_manifest.py 生成侧完全一致——
1692
1695
  # CRLF→LF 归一化(autocrlf/git clone 的换行符差异)+ 剥 UTF-8 BOM
1693
- # (raw 下载/记事本保存可能带 BOM)。字节形态不同但内容没变的文件
1694
- # 放行,内容真被篡改仍然拦得住。
1695
- # 注意分块方式:\r 必须暂存到下一块拼回来再 replace——否则恰好在
1696
- # 64KB 边界被切成 \r|\n 的换行符会漏归一化,大文件哈希对不上。
1697
1696
  h = hashlib.sha256()
1698
1697
  first = True
1699
1698
  tail = b""
@@ -33,9 +33,26 @@ EXCLUDE_NAMES = {"panel-token.txt", ".env", "LINGSHU_PANEL_TOKEN", "config.json"
33
33
 
34
34
  def collect() -> list[Path]:
35
35
  """manifest 发布文件 + engine/ 全目录(都要先 sync 生成)。"""
36
- # manifest.json 里的发布文件(git 跟踪的核心文件)
37
- manifest = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8"))
38
- files = [ROOT / rel for rel in manifest["files"]]
36
+ manifest_p = ROOT / "manifest.json"
37
+ if not manifest_p.is_file():
38
+ raise SystemExit("[错误] 找不到 manifest.json,拒绝打包")
39
+ manifest = json.loads(manifest_p.read_text(encoding="utf-8"))
40
+
41
+ # LS-119(v5.62):DSH 打包遇到清单缺文件必须失败非零退出!
42
+ missing = []
43
+ files = []
44
+ for rel in manifest.get("files", {}):
45
+ p = ROOT / rel
46
+ if not p.is_file():
47
+ missing.append(rel)
48
+ else:
49
+ files.append(p)
50
+ if missing:
51
+ raise SystemExit(f"[错误] DSH 打包失败:manifest 中有 {len(missing)} 个文件在本地缺失!\n 缺失示例: {', '.join(missing[:5])}")
52
+
53
+ # LS-120(v5.62):将 manifest.json 本身加入 DSH tgz 的根目录,保证安装后能做完整哈希校验
54
+ files.append(manifest_p)
55
+
39
56
  # engine/ 派生副本(打包时生成,不入库)
40
57
  engine = ROOT / "scripts" / "astrbot_plugin_lingshu" / "engine"
41
58
  if engine.is_dir():
@@ -294,6 +294,10 @@ def resolve_conflict_pair(winner_id: str, loser_id: str) -> dict:
294
294
  raise PermissionError("记忆库当前只读,无法裁决冲突。")
295
295
  with _locked(HOME / "hippocampus.jsonl"):
296
296
  records = load_all()
297
+ # LS-024(v5.61):禁止记录与自身进行冲突裁决!
298
+ # 否则会生成 superseded_by=自身 的自环,或自身指向自身的死循环链接并导致记忆从回忆中消失。
299
+ if str(winner_id).strip() == str(loser_id).strip():
300
+ raise ValueError(f"冲突裁决的胜出记忆与被取代记忆不能是同一条记录:{winner_id}")
297
301
  w = next((m for m in records if m.get("id") == winner_id), None)
298
302
  l = next((m for m in records if m.get("id") == loser_id), None)
299
303
  if not w:
@@ -757,7 +761,8 @@ def load_all() -> list:
757
761
  _cur_mtimes = {}
758
762
 
759
763
  if _load_cache is not None and _cur_mtimes == _load_cache_files:
760
- return [dict(m) for m in _load_cache] # 返回副本防外部修改污染缓存
764
+ # LS-022(v5.61):深拷贝防止嵌套列表/对象(tags、links、entities)被外部原地修改污染进程内缓存
765
+ return [json.loads(json.dumps(m, ensure_ascii=False)) for m in _load_cache]
761
766
 
762
767
  raw = (read_jsonl(HOME / "hippocampus.jsonl")
763
768
  + read_jsonl(HOME / "cortex.jsonl")
@@ -784,7 +789,7 @@ def load_all() -> list:
784
789
  _load_cache = good
785
790
  _load_cache_files = _cur_mtimes
786
791
  _load_cache_ts = time.time()
787
- return [dict(m) for m in good]
792
+ return [json.loads(json.dumps(m, ensure_ascii=False)) for m in good]
788
793
 
789
794
 
790
795
  def count_recent(layer: str, floor_ts: float, predicate=None) -> int:
@@ -1589,6 +1594,10 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1589
1594
  fras: dict | None = None,
1590
1595
  source_file: str | None = None,
1591
1596
  avoid: bool = False) -> tuple:
1597
+ # LS-008(v5.61):公共 remember 入口必须在只读模式下立即拒绝写盘!
1598
+ # 覆盖 --ro、环境只读降级与 readonly_scope()。
1599
+ if READONLY:
1600
+ raise PermissionError("记忆库当前只读,无法写入新记忆。")
1592
1601
  ensure_home()
1593
1602
  text = (text or "").strip()
1594
1603
  if not text:
@@ -82,11 +82,24 @@ def build(src: Path = SRC, out: Path | None = OUT) -> bytes:
82
82
  """拼装产物;out=None 时只返回字节、不落盘(--check 用,检查不该改文件)。"""
83
83
  shell = (src / "index.html").read_bytes()
84
84
  meta = json.loads((src / "blocks.json").read_text(encoding="utf-8"))
85
+ consumed = 0
85
86
  for i, blk in enumerate(meta):
86
87
  token = f"<!--@@BLOCK:{i}@@-->".encode()
88
+ if token not in shell:
89
+ raise ValueError(f"LS-123 缺失占位符:index.html 中未找到 {token.decode()} 无法嵌入块 {blk['file']}")
87
90
  body = (src / blk["file"]).read_bytes()
88
91
  close = b"</style>" if blk["kind"] == "style" else b"</script>"
89
92
  shell = shell.replace(token, blk["open"].encode() + body + close, 1)
93
+ consumed += 1
94
+
95
+ # LS-123(v5.62):面板构建校验所有占位符和块均被消费!
96
+ # 检查产物中是否仍残留未被替换的 <!--@@BLOCK:*@@--> 占位符
97
+ leftover = re.findall(rb"<!--@@BLOCK:\d+@@-->", shell)
98
+ if leftover:
99
+ raise ValueError(f"LS-123 构建产物中残留未消费的占位符:{[x.decode() for x in leftover]}")
100
+ if consumed != len(meta):
101
+ raise ValueError(f"LS-123 ���消费不全:定义了 {len(meta)} 个块,实际消费 {consumed} 个")
102
+
90
103
  if out is not None:
91
104
  out.parent.mkdir(parents=True, exist_ok=True)
92
105
  out.write_bytes(shell)
package/scripts/core.py CHANGED
@@ -1622,12 +1622,22 @@ def read_jsonl(path: Path) -> list:
1622
1622
  continue
1623
1623
  except Exception:
1624
1624
  pass
1625
- # 单行解析失败:可能是多行格式化 JSON。按括号配对把整块累积起来再试,
1626
- # 避免把一条跨行合法记录当成坏行丢掉。
1625
+ # LS-018(v5.61):防止残缺 JSONL 块吞掉后续合法记录!
1626
+ # 若单行解析失败,尝试多行聚合时,如果后续某一行本身就是独立的合法 JSON,绝不能被吞进坏块!
1627
1627
  block = [lines[i]]
1628
1628
  depth = _brace_balance(lines[i])
1629
1629
  i += 1
1630
- while i < n and depth > 0 and len(block) < 200:
1630
+ while i < n and depth > 0 and len(block) < 50:
1631
+ next_line = lines[i].strip()
1632
+ # 探测:若下一行本身已经能独立解析为完整合法 JSON 对象,说明上一行只是残缺坏行,不是跨行对象!
1633
+ if next_line.startswith("{") and next_line.endswith("}"):
1634
+ try:
1635
+ maybe_valid = json.loads(next_line)
1636
+ if isinstance(maybe_valid, dict):
1637
+ # 发现独立合法行,终止当前坏块累积,让外部循环正常处理该行
1638
+ break
1639
+ except Exception:
1640
+ pass
1631
1641
  block.append(lines[i])
1632
1642
  depth += _brace_balance(lines[i])
1633
1643
  i += 1
@@ -1834,27 +1844,18 @@ def _locked(path: Path, timeout: float = 10.0):
1834
1844
  # (_held() 已为 False 才会走到这里)→ 这是我们自己遗留的锁,立刻接管。
1835
1845
  # 否则会等满 timeout 才失败,实测能把同进程的 remember 循环卡死。
1836
1846
  try:
1837
- _owner = _lock_owner(lock)
1847
+ _owner, _host = _lock_owner_info(lock)
1838
1848
  _age = time.time() - lock.stat().st_mtime
1839
- # ⚠ 本进程的锁**绝不能只按 pid 判孤儿**:面板是 ThreadingHTTPServer,
1840
- # 多个线程会写同一批 jsonl。A 线程持锁超过宽限期时(全量重写上万条、
1841
- # _replace_retry 退避都可能 >1s),B 线程会读到 owner pid == 自己进程
1842
- # 而误判"遗留孤儿锁",把 A 的活锁删掉 → 两线程同时读-改-写 → 静默丢记忆。
1843
- # 正确判据是"**本线程是否真持有**"(_held 里有 (锁路径, 线程id))。
1844
1849
  _held_by_me = _held_any_thread(lock)
1845
- _same_proc = (_owner == os.getpid())
1846
- # 通道 A:空锁文件(O_CREAT 与写 pid 之间的窗口)。
1847
- # 活着的进程不会把锁空着超过宽限期,所以可接管;
1848
- # 但若本线程正持有(重入已在函数开头 return),这里不涉及。
1849
- # 空锁文件:本进程没人持有它,且已过宽限期 → 是遗留孤儿,可接管。
1850
- # 若本进程有线程正持有(刚 create、还没写 pid 的一瞬)→ 是活锁,别动。
1850
+ _same_host = (not _host or _host == _HOSTNAME)
1851
+ _same_proc = (_same_host and _owner == os.getpid())
1851
1852
  _orphan_empty = (_owner is None and not _held_by_me)
1852
- # 通道 B:**持锁进程已死**。与时间无关(只要过了宽限),
1853
- # 否则会撞上"STALE_LOCK_SECONDS(30) > timeout(10)"的死角。
1854
- _owner_dead = (_owner is not None and not _same_proc
1853
+ # LS-006(v5.61):修复共享盘远程锁误判!
1854
+ # 远程机器持有的活锁,其 PID 在本机探活时大概率返回 Dead(ProcessLookupError),
1855
+ # 旧逻辑仅根据 `not _pid_alive` 就会误将远程活锁当作孤儿锁 unlink 抢占,导致双机并发破坏数据。
1856
+ # 规定:只有确认是【同一主机】且 PID 已死,才允许按进程死亡接管孤儿锁!
1857
+ _owner_dead = (_owner is not None and _same_host and not _same_proc
1855
1858
  and not _pid_alive(_owner))
1856
- # 本进程 + **没有线程持有** = 真孤儿(守卫已在上面排除"有线程持有"),
1857
- # 可以安全接管:否则崩溃/异常后同进程后续写入会一直超时。
1858
1859
  _owner_self_orphan = _same_proc and not _held_by_me
1859
1860
  if _age > ORPHAN_LOCK_GRACE and (
1860
1861
  _orphan_empty or _owner_dead or _owner_self_orphan):
@@ -1865,21 +1866,24 @@ def _locked(path: Path, timeout: float = 10.0):
1865
1866
  continue
1866
1867
  except OSError:
1867
1868
  pass
1868
- # ② 陈旧锁(持锁进程已死):久到不可能是正常写盘(正常持锁 <2s)才接管。
1869
- # 阈值别设太小:dream 整理记忆时持锁会久一点,抢早了就是两个进程同时写。
1869
+ # ② 陈旧锁:超过 STALE_LOCK_SECONDS。
1870
+ # 对本机锁进行 PID 探活;对远程锁(_host != _HOSTNAME),仅当极度超时且无更新才清理
1870
1871
  try:
1871
1872
  if time.time() - lock.stat().st_mtime > STALE_LOCK_SECONDS:
1872
- # 再加一道 pid 探活:持锁进程还活着就别抢(work_flush/dream 可能持锁较久)。
1873
- # 同进程(含本进程其它线程)持有的锁一律视为"活着",绝不接管。
1874
- owner = _lock_owner(lock)
1875
- if owner is not None and _pid_alive(owner):
1876
- pass # 活着的持锁者:继续等,不接管
1877
- else:
1878
- try:
1879
- lock.unlink()
1880
- except OSError:
1881
- pass
1882
- continue
1873
+ owner, host = _lock_owner_info(lock)
1874
+ same_host = (not host or host == _HOSTNAME)
1875
+ if owner is not None:
1876
+ if same_host and _pid_alive(owner):
1877
+ pass # 本机存活持锁者:不抢
1878
+ elif not same_host:
1879
+ # LS-006: 远程主机持锁:非本机不能拿本地 PID 判断生死
1880
+ pass # 远程锁在超时窗口内严格保持等待,防止跨主机冲突
1881
+ else:
1882
+ try:
1883
+ lock.unlink()
1884
+ except OSError:
1885
+ pass
1886
+ continue
1883
1887
  except OSError:
1884
1888
  pass
1885
1889
  if time.time() > deadline:
@@ -1956,13 +1960,23 @@ def _pid_alive(pid: int) -> bool:
1956
1960
  return True
1957
1961
 
1958
1962
 
1959
- def _lock_owner(lock: Path) -> int | None:
1960
- """读锁文件里记录的持有者 pid;读不到/格式不对返回 None。"""
1963
+ def _lock_owner_info(lock: Path) -> tuple[int | None, str]:
1964
+ """LS-006(v5.61):读锁持有者 (pid, host)。读不到返回 (None, '')。"""
1961
1965
  try:
1962
- raw = lock.read_text(encoding="utf-8", errors="ignore").strip()
1963
- return int(raw.split()[0]) if raw else None
1966
+ raw = lock.read_text(encoding="utf-8", errors="ignore").strip().lstrip("\ufeff")
1967
+ if not raw:
1968
+ return None, ""
1969
+ parts = raw.split()
1970
+ pid = int(parts[0]) if parts else None
1971
+ host = parts[1] if len(parts) > 1 else ""
1972
+ return pid, host
1964
1973
  except (OSError, ValueError, IndexError):
1965
- return None
1974
+ return None, ""
1975
+
1976
+
1977
+ def _lock_owner(lock: Path) -> int | None:
1978
+ """读锁文件里记录的持有者 pid;读不到/格式不对返回 None。"""
1979
+ return _lock_owner_info(lock)[0]
1966
1980
 
1967
1981
 
1968
1982
  def lock_writers() -> list[dict]:
@@ -2013,7 +2027,12 @@ def _persona_txn(fn):
2013
2027
 
2014
2028
  def _locked_save_all(records: list) -> None:
2015
2029
  """save_all 的加锁版:并发写记忆不丢更新。"""
2016
- with _locked(HOME / "hippocampus.jsonl"):
2030
+ # LS-007(v5.61):统一强化与定向补丁的锁口径!
2031
+ # 之前仅持 hippocampus.jsonl 单锁,却跨层改写了 cortex 和 dust,导致与持 cortex 锁的补丁并发互踩丢失字段。
2032
+ # 固定按三层层级顺序持有锁:
2033
+ with _locked(HOME / "hippocampus.jsonl"), \
2034
+ _locked(HOME / "cortex.jsonl"), \
2035
+ _locked(HOME / "dust.jsonl"):
2017
2036
  existing = load_all()
2018
2037
  by_id = {}
2019
2038
  no_id = [] # 缺 id 的畸形记录也原样保留,不能因为无法索引就悄悄丢掉
package/scripts/growth.py CHANGED
@@ -1688,12 +1688,11 @@ def apply_update(src_dir: Path, dst_dir: Path,
1688
1688
  + ", ".join(sorted(_missing)[:8])
1689
1689
  + (f" 等 {len(_missing)} 个" if len(_missing) > 8 else ""))
1690
1690
  def _norm_sha(p: Path) -> str:
1691
+ # LS-121(v5.62):二进制文件(png, ico等)不执行文本换行归一化,直接取原始字节 SHA
1692
+ if p.suffix.lower() in {".png", ".ico", ".jpg", ".jpeg", ".webp", ".gif", ".pdf", ".woff", ".woff2", ".ttf"}:
1693
+ return _sha256_file(p)
1691
1694
  # 规范形态哈希:与 make_manifest.py 生成侧完全一致——
1692
1695
  # CRLF→LF 归一化(autocrlf/git clone 的换行符差异)+ 剥 UTF-8 BOM
1693
- # (raw 下载/记事本保存可能带 BOM)。字节形态不同但内容没变的文件
1694
- # 放行,内容真被篡改仍然拦得住。
1695
- # 注意分块方式:\r 必须暂存到下一块拼回来再 replace——否则恰好在
1696
- # 64KB 边界被切成 \r|\n 的换行符会漏归一化,大文件哈希对不上。
1697
1696
  h = hashlib.sha256()
1698
1697
  first = True
1699
1698
  tail = b""
@@ -33,9 +33,26 @@ EXCLUDE_NAMES = {"panel-token.txt", ".env", "LINGSHU_PANEL_TOKEN", "config.json"
33
33
 
34
34
  def collect() -> list[Path]:
35
35
  """manifest 发布文件 + engine/ 全目录(都要先 sync 生成)。"""
36
- # manifest.json 里的发布文件(git 跟踪的核心文件)
37
- manifest = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8"))
38
- files = [ROOT / rel for rel in manifest["files"]]
36
+ manifest_p = ROOT / "manifest.json"
37
+ if not manifest_p.is_file():
38
+ raise SystemExit("[错误] 找不到 manifest.json,拒绝打包")
39
+ manifest = json.loads(manifest_p.read_text(encoding="utf-8"))
40
+
41
+ # LS-119(v5.62):DSH 打包遇到清单缺文件必须失败非零退出!
42
+ missing = []
43
+ files = []
44
+ for rel in manifest.get("files", {}):
45
+ p = ROOT / rel
46
+ if not p.is_file():
47
+ missing.append(rel)
48
+ else:
49
+ files.append(p)
50
+ if missing:
51
+ raise SystemExit(f"[错误] DSH 打包失败:manifest 中有 {len(missing)} 个文件在本地缺失!\n 缺失示例: {', '.join(missing[:5])}")
52
+
53
+ # LS-120(v5.62):将 manifest.json 本身加入 DSH tgz 的根目录,保证安装后能做完整哈希校验
54
+ files.append(manifest_p)
55
+
39
56
  # engine/ 派生副本(打包时生成,不入库)
40
57
  engine = ROOT / "scripts" / "astrbot_plugin_lingshu" / "engine"
41
58
  if engine.is_dir():
@@ -54,19 +54,24 @@ def _excluded(rel: str, name: str) -> bool:
54
54
  return name.startswith("test_") and name.endswith(".py")
55
55
 
56
56
 
57
- def sha256_file(p: Path) -> tuple[str, int]:
58
- """规范形态哈希:CRLF→LF 归一化 + 去 UTF-8 BOM 后再算,返回 (sha256, size)。
57
+ # 二进制扩展名白名单(图片、图标、音频等):绝不执行换行符归一化
58
+ BINARY_EXTS = {".png", ".ico", ".jpg", ".jpeg", ".webp", ".gif", ".pdf", ".woff", ".woff2", ".ttf"}
59
59
 
60
- manifest 是发布契约——它必须对应"发布内容的规范形态",而不是作者本机的
61
- 磁盘形态。作者机器 core.autocrlf=true + 记事本存盘会把工作区文件写成
62
- CRLF+带 BOM,逐字节哈希记录的就是这套形态;用户按 raw / zip 拿到的是
63
- LF+无 BOM,逐字节比对永远失败(v2.52 只修了比对侧,没修生成侧)。
64
- 换行符与 BOM 都不改变内容语义,归一化后哈希才与发布内容对齐;
65
- 真正的内容篡改仍拦得住。
66
60
 
67
- 分块注意:\r 若恰好落在 64KB 块尾必须暂存到下一块拼回来再替换——否则
68
- 边界处的 CRLF 被切成 \r|\n 两段各自漏掉,大文件哈希漂移(与比对侧同一坑)。
61
+ def sha256_file(p: Path) -> tuple[str, int]:
62
+ """计算文件的 SHA256 与大小。
63
+ LS-121(v5.62):仅对文本文件执行换行符归一化(CRLF→LF + 剥 BOM);
64
+ 二进制文件(如 png, ico)按原始字节计算哈希与大小,绝不能当作文本替换字节破坏文件哈希!
69
65
  """
66
+ if p.suffix.lower() in BINARY_EXTS:
67
+ h = hashlib.sha256()
68
+ size = 0
69
+ with open(p, "rb") as f:
70
+ for chunk in iter(lambda: f.read(1 << 16), b""):
71
+ h.update(chunk)
72
+ size += len(chunk)
73
+ return h.hexdigest(), size
74
+
70
75
  h = hashlib.sha256()
71
76
  size = 0
72
77
  first = True
@@ -25,8 +25,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
25
25
 
26
26
  REPO = Path(__file__).resolve().parent.parent
27
27
  SRC = REPO / "scripts" / "astrbot_plugin_lingshu"
28
- EXCLUDE_DIRS = {"__pycache__"}
29
- EXCLUDE_SUFFIX = {".pyc", ".pyo", ".log", ".zip"}
28
+ EXCLUDE_DIRS = {"__pycache__", "_scratch", "垃圾桶", "_ui_probe", "tests"}
29
+ EXCLUDE_SUFFIX = {".pyc", ".pyo", ".log", ".zip", ".tmp"}
30
30
  EXCLUDE_NAMES = {"panel-token.txt", ".home", "consent.json",
31
31
  "hippocampus.jsonl", "persona.json", "emotions.jsonl"}
32
32
 
@@ -36,7 +36,11 @@ def collect() -> list[Path]:
36
36
  for p in sorted(SRC.rglob("*")):
37
37
  if p.is_dir():
38
38
  continue
39
- if any(part in EXCLUDE_DIRS for part in p.relative_to(SRC).parts):
39
+ rel_parts = p.relative_to(SRC).parts
40
+ if any(part in EXCLUDE_DIRS for part in rel_parts):
41
+ continue
42
+ # LS-118(v5.62):排除开发探针、临时脚本和冒烟代码
43
+ if p.name.startswith(("_tmp", "_ci_env_probe", "_panel_smoke")):
40
44
  continue
41
45
  if p.suffix.lower() in EXCLUDE_SUFFIX or p.name in EXCLUDE_NAMES:
42
46
  continue
package/scripts/memory.py CHANGED
@@ -294,6 +294,10 @@ def resolve_conflict_pair(winner_id: str, loser_id: str) -> dict:
294
294
  raise PermissionError("记忆库当前只读,无法裁决冲突。")
295
295
  with _locked(HOME / "hippocampus.jsonl"):
296
296
  records = load_all()
297
+ # LS-024(v5.61):禁止记录与自身进行冲突裁决!
298
+ # 否则会生成 superseded_by=自身 的自环,或自身指向自身的死循环链接并导致记忆从回忆中消失。
299
+ if str(winner_id).strip() == str(loser_id).strip():
300
+ raise ValueError(f"冲突裁决的胜出记忆与被取代记忆不能是同一条记录:{winner_id}")
297
301
  w = next((m for m in records if m.get("id") == winner_id), None)
298
302
  l = next((m for m in records if m.get("id") == loser_id), None)
299
303
  if not w:
@@ -757,7 +761,8 @@ def load_all() -> list:
757
761
  _cur_mtimes = {}
758
762
 
759
763
  if _load_cache is not None and _cur_mtimes == _load_cache_files:
760
- return [dict(m) for m in _load_cache] # 返回副本防外部修改污染缓存
764
+ # LS-022(v5.61):深拷贝防止嵌套列表/对象(tags、links、entities)被外部原地修改污染进程内缓存
765
+ return [json.loads(json.dumps(m, ensure_ascii=False)) for m in _load_cache]
761
766
 
762
767
  raw = (read_jsonl(HOME / "hippocampus.jsonl")
763
768
  + read_jsonl(HOME / "cortex.jsonl")
@@ -784,7 +789,7 @@ def load_all() -> list:
784
789
  _load_cache = good
785
790
  _load_cache_files = _cur_mtimes
786
791
  _load_cache_ts = time.time()
787
- return [dict(m) for m in good]
792
+ return [json.loads(json.dumps(m, ensure_ascii=False)) for m in good]
788
793
 
789
794
 
790
795
  def count_recent(layer: str, floor_ts: float, predicate=None) -> int:
@@ -1589,6 +1594,10 @@ def remember(text: str, kind: str = "fact", importance: float | None = None,
1589
1594
  fras: dict | None = None,
1590
1595
  source_file: str | None = None,
1591
1596
  avoid: bool = False) -> tuple:
1597
+ # LS-008(v5.61):公共 remember 入口必须在只读模式下立即拒绝写盘!
1598
+ # 覆盖 --ro、环境只读降级与 readonly_scope()。
1599
+ if READONLY:
1600
+ raise PermissionError("记忆库当前只读,无法写入新记忆。")
1592
1601
  ensure_home()
1593
1602
  text = (text or "").strip()
1594
1603
  if not text:
@@ -82,11 +82,24 @@ def build(src: Path = SRC, out: Path | None = OUT) -> bytes:
82
82
  """拼装产物;out=None 时只返回字节、不落盘(--check 用,检查不该改文件)。"""
83
83
  shell = (src / "index.html").read_bytes()
84
84
  meta = json.loads((src / "blocks.json").read_text(encoding="utf-8"))
85
+ consumed = 0
85
86
  for i, blk in enumerate(meta):
86
87
  token = f"<!--@@BLOCK:{i}@@-->".encode()
88
+ if token not in shell:
89
+ raise ValueError(f"LS-123 缺失占位符:index.html 中未找到 {token.decode()} 无法嵌入块 {blk['file']}")
87
90
  body = (src / blk["file"]).read_bytes()
88
91
  close = b"</style>" if blk["kind"] == "style" else b"</script>"
89
92
  shell = shell.replace(token, blk["open"].encode() + body + close, 1)
93
+ consumed += 1
94
+
95
+ # LS-123(v5.62):面板构建校验所有占位符和块均被消费!
96
+ # 检查产物中是否仍残留未被替换的 <!--@@BLOCK:*@@--> 占位符
97
+ leftover = re.findall(rb"<!--@@BLOCK:\d+@@-->", shell)
98
+ if leftover:
99
+ raise ValueError(f"LS-123 构建产物中残留未消费的占位符:{[x.decode() for x in leftover]}")
100
+ if consumed != len(meta):
101
+ raise ValueError(f"LS-123 ���消费不全:定义了 {len(meta)} 个块,实际消费 {consumed} 个")
102
+
90
103
  if out is not None:
91
104
  out.parent.mkdir(parents=True, exist_ok=True)
92
105
  out.write_bytes(shell)