dsh-qqbot-plus 0.0.0-stage → 0.1.2

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 (301) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/CHANGELOG_EN.md +188 -0
  3. package/LICENSE +21 -0
  4. package/README.md +281 -2
  5. package/README_EN.md +248 -0
  6. package/cordis.patch.yml +163 -0
  7. package/cordis.yml +112 -0
  8. package/install.sh +108 -0
  9. package/lib/alarms.js +371 -0
  10. package/lib/client.js +2411 -0
  11. package/lib/commands/auth.d.ts +18 -0
  12. package/lib/commands/auth.d.ts.map +1 -0
  13. package/lib/commands/auth.js +15 -0
  14. package/lib/commands/auth.js.map +1 -0
  15. package/lib/commands/help.d.ts +10 -0
  16. package/lib/commands/help.d.ts.map +1 -0
  17. package/lib/commands/help.js +39 -0
  18. package/lib/commands/help.js.map +1 -0
  19. package/lib/commands/index.d.ts +15 -0
  20. package/lib/commands/index.d.ts.map +1 -0
  21. package/lib/commands/index.js +30 -0
  22. package/lib/commands/index.js.map +1 -0
  23. package/lib/commands/misc.d.ts +21 -0
  24. package/lib/commands/misc.d.ts.map +1 -0
  25. package/lib/commands/misc.js +93 -0
  26. package/lib/commands/misc.js.map +1 -0
  27. package/lib/commands/model.d.ts +6 -0
  28. package/lib/commands/model.d.ts.map +1 -0
  29. package/lib/commands/model.js +63 -0
  30. package/lib/commands/model.js.map +1 -0
  31. package/lib/commands/new.js +17 -0
  32. package/lib/commands/preset.d.ts +8 -0
  33. package/lib/commands/preset.d.ts.map +1 -0
  34. package/lib/commands/preset.js +56 -0
  35. package/lib/commands/preset.js.map +1 -0
  36. package/lib/commands/session.d.ts +14 -0
  37. package/lib/commands/session.d.ts.map +1 -0
  38. package/lib/commands/session.js +34 -0
  39. package/lib/commands/session.js.map +1 -0
  40. package/lib/commands/status.d.ts +7 -0
  41. package/lib/commands/status.d.ts.map +1 -0
  42. package/lib/commands/status.js +26 -0
  43. package/lib/commands/status.js.map +1 -0
  44. package/lib/commands/types.d.ts +21 -0
  45. package/lib/commands/types.d.ts.map +1 -0
  46. package/lib/commands/types.js +2 -0
  47. package/lib/commands/types.js.map +1 -0
  48. package/lib/config.d.ts +95 -0
  49. package/lib/config.js +88 -0
  50. package/lib/features/answer-parser.d.ts +9 -0
  51. package/lib/features/answer-parser.d.ts.map +1 -0
  52. package/lib/features/answer-parser.js +23 -0
  53. package/lib/features/answer-parser.js.map +1 -0
  54. package/lib/features/approval-channel.d.ts +94 -0
  55. package/lib/features/approval-channel.d.ts.map +1 -0
  56. package/lib/features/approval-channel.js +158 -0
  57. package/lib/features/approval-channel.js.map +1 -0
  58. package/lib/features/approval-renderer.d.ts +18 -0
  59. package/lib/features/approval-renderer.d.ts.map +1 -0
  60. package/lib/features/approval-renderer.js +52 -0
  61. package/lib/features/approval-renderer.js.map +1 -0
  62. package/lib/features/button-utils.d.ts +34 -0
  63. package/lib/features/button-utils.d.ts.map +1 -0
  64. package/lib/features/button-utils.js +27 -0
  65. package/lib/features/button-utils.js.map +1 -0
  66. package/lib/features/history-store.d.ts +8 -0
  67. package/lib/features/history-store.d.ts.map +1 -0
  68. package/lib/features/history-store.js +23 -0
  69. package/lib/features/history-store.js.map +1 -0
  70. package/lib/features/question-channel.d.ts +96 -0
  71. package/lib/features/question-channel.d.ts.map +1 -0
  72. package/lib/features/question-channel.js +234 -0
  73. package/lib/features/question-channel.js.map +1 -0
  74. package/lib/features/question-renderer.d.ts +20 -0
  75. package/lib/features/question-renderer.d.ts.map +1 -0
  76. package/lib/features/question-renderer.js +70 -0
  77. package/lib/features/question-renderer.js.map +1 -0
  78. package/lib/fishcheck/measure.js +230 -0
  79. package/lib/fishcheck/rules.js +99 -0
  80. package/lib/fishmeme/plugin.js +605 -0
  81. package/lib/fishmeme/routes.js +141 -0
  82. package/lib/fishmemory/plugin.js +1052 -0
  83. package/lib/gateway/bootstrap.d.ts +12 -0
  84. package/lib/gateway/bootstrap.d.ts.map +1 -0
  85. package/lib/gateway/bootstrap.js +200 -0
  86. package/lib/gateway/bootstrap.js.map +1 -0
  87. package/lib/gateway/index.d.ts +3 -0
  88. package/lib/gateway/index.d.ts.map +1 -0
  89. package/lib/gateway/index.js +3 -0
  90. package/lib/gateway/index.js.map +1 -0
  91. package/lib/gateway/middleware-setup.d.ts +12 -0
  92. package/lib/gateway/middleware-setup.d.ts.map +1 -0
  93. package/lib/gateway/middleware-setup.js +82 -0
  94. package/lib/gateway/middleware-setup.js.map +1 -0
  95. package/lib/host/adapter.d.ts +48 -0
  96. package/lib/host/adapter.d.ts.map +1 -0
  97. package/lib/host/adapter.js +127 -0
  98. package/lib/host/adapter.js.map +1 -0
  99. package/lib/humanlike/ENV_PROMPT.md +28 -0
  100. package/lib/humanlike/affinity.js +316 -0
  101. package/lib/humanlike/learn.js +343 -0
  102. package/lib/humanlike/life.js +899 -0
  103. package/lib/humanlike/mind.js +323 -0
  104. package/lib/humanlike/plugin.js +587 -0
  105. package/lib/humanlike/reach.js +119 -0
  106. package/lib/humanlike/real.js +276 -0
  107. package/lib/humanlike/rules.js +67 -0
  108. package/lib/humanlike/settings-api.js +159 -0
  109. package/lib/humanlike/settings.js +370 -0
  110. package/lib/humanlike/together.js +251 -0
  111. package/lib/identity/paths.js +27 -0
  112. package/lib/identity/persona.js +75 -0
  113. package/lib/identity/portrait.js +25 -0
  114. package/lib/identity/runtime.js +78 -0
  115. package/lib/index.d.ts +15 -0
  116. package/lib/index.js +117 -0
  117. package/lib/media/draft-tool.js +442 -0
  118. package/lib/media/draft-tool.js.bak-to-182027 +389 -0
  119. package/lib/media/media-cleaner.d.ts +19 -0
  120. package/lib/media/media-cleaner.d.ts.map +1 -0
  121. package/lib/media/media-cleaner.js +81 -0
  122. package/lib/media/media-cleaner.js.map +1 -0
  123. package/lib/media/say-tool.js +72 -0
  124. package/lib/media/send-file-tool.d.ts +12 -0
  125. package/lib/media/send-file-tool.d.ts.map +1 -0
  126. package/lib/media/send-file-tool.js +122 -0
  127. package/lib/media/send-file-tool.js.map +1 -0
  128. package/lib/media/send-media.d.ts +61 -0
  129. package/lib/media/send-media.d.ts.map +1 -0
  130. package/lib/media/send-media.js +104 -0
  131. package/lib/media/send-media.js.map +1 -0
  132. package/lib/media/vision-tool.d.ts +22 -0
  133. package/lib/media/vision-tool.d.ts.map +1 -0
  134. package/lib/media/vision-tool.js +288 -0
  135. package/lib/media/vision-tool.js.map +1 -0
  136. package/lib/middleware/attachment.d.ts +11 -0
  137. package/lib/middleware/attachment.d.ts.map +1 -0
  138. package/lib/middleware/attachment.js +30 -0
  139. package/lib/middleware/attachment.js.map +1 -0
  140. package/lib/middleware/question-answer.d.ts +10 -0
  141. package/lib/middleware/question-answer.d.ts.map +1 -0
  142. package/lib/middleware/question-answer.js +19 -0
  143. package/lib/middleware/question-answer.js.map +1 -0
  144. package/lib/model/index.d.ts +10 -0
  145. package/lib/model/index.d.ts.map +1 -0
  146. package/lib/model/index.js +9 -0
  147. package/lib/model/index.js.map +1 -0
  148. package/lib/model/model-resolver.d.ts +102 -0
  149. package/lib/model/model-resolver.d.ts.map +1 -0
  150. package/lib/model/model-resolver.js +206 -0
  151. package/lib/model/model-resolver.js.map +1 -0
  152. package/lib/model/prefs-store.d.ts +50 -0
  153. package/lib/model/prefs-store.d.ts.map +1 -0
  154. package/lib/model/prefs-store.js +215 -0
  155. package/lib/model/prefs-store.js.map +1 -0
  156. package/lib/model/settings-reader.d.ts +19 -0
  157. package/lib/model/settings-reader.d.ts.map +1 -0
  158. package/lib/model/settings-reader.js +76 -0
  159. package/lib/model/settings-reader.js.map +1 -0
  160. package/lib/model/types.d.ts +15 -0
  161. package/lib/model/types.d.ts.map +1 -0
  162. package/lib/model/types.js +5 -0
  163. package/lib/model/types.js.map +1 -0
  164. package/lib/resume-check.js +122 -0
  165. package/lib/resume-tool.js +29 -0
  166. package/lib/rules.js +57 -0
  167. package/lib/session/idle-evictor.d.ts +18 -0
  168. package/lib/session/idle-evictor.d.ts.map +1 -0
  169. package/lib/session/idle-evictor.js +31 -0
  170. package/lib/session/idle-evictor.js.map +1 -0
  171. package/lib/session/index.d.ts +9 -0
  172. package/lib/session/index.d.ts.map +1 -0
  173. package/lib/session/index.js +8 -0
  174. package/lib/session/index.js.map +1 -0
  175. package/lib/session/pick-agent.js +116 -0
  176. package/lib/session/session-id.d.ts +5 -0
  177. package/lib/session/session-id.d.ts.map +1 -0
  178. package/lib/session/session-id.js +15 -0
  179. package/lib/session/session-id.js.map +1 -0
  180. package/lib/session/session-manager.d.ts +138 -0
  181. package/lib/session/session-manager.d.ts.map +1 -0
  182. package/lib/session/session-manager.js +1157 -0
  183. package/lib/session/session-manager.js.bak-target +1081 -0
  184. package/lib/session/session-manager.js.bak-title-20261118 +1119 -0
  185. package/lib/session/session-manager.js.map +1 -0
  186. package/lib/session/types.d.ts +162 -0
  187. package/lib/session/types.d.ts.map +1 -0
  188. package/lib/session/types.js +2 -0
  189. package/lib/session/types.js.map +1 -0
  190. package/lib/setup/bind-routes.d.ts +78 -0
  191. package/lib/setup/bind-routes.d.ts.map +1 -0
  192. package/lib/setup/bind-routes.js +588 -0
  193. package/lib/setup/bind-routes.js.bak-join-163944 +761 -0
  194. package/lib/setup/bind-routes.js.map +1 -0
  195. package/lib/setup/binding-service.d.ts +86 -0
  196. package/lib/setup/binding-service.d.ts.map +1 -0
  197. package/lib/setup/binding-service.js +175 -0
  198. package/lib/setup/binding-service.js.map +1 -0
  199. package/lib/setup/index.d.ts +50 -0
  200. package/lib/setup/index.d.ts.map +1 -0
  201. package/lib/setup/index.js +163 -0
  202. package/lib/setup/index.js.map +1 -0
  203. package/lib/setup/persist.d.ts +42 -0
  204. package/lib/setup/persist.d.ts.map +1 -0
  205. package/lib/setup/persist.js +344 -0
  206. package/lib/setup/persist.js.map +1 -0
  207. package/lib/setup/presenters.d.ts +40 -0
  208. package/lib/setup/presenters.d.ts.map +1 -0
  209. package/lib/setup/presenters.js +84 -0
  210. package/lib/setup/presenters.js.map +1 -0
  211. package/lib/setup/qr-svg.d.ts +9 -0
  212. package/lib/setup/qr-svg.d.ts.map +1 -0
  213. package/lib/setup/qr-svg.js +33 -0
  214. package/lib/setup/qr-svg.js.map +1 -0
  215. package/lib/shared/bind-protocol.d.ts +42 -0
  216. package/lib/shared/bind-protocol.d.ts.map +1 -0
  217. package/lib/shared/bind-protocol.js +33 -0
  218. package/lib/shared/bind-protocol.js.map +1 -0
  219. package/lib/shared/dirs.d.ts +10 -0
  220. package/lib/shared/dirs.d.ts.map +1 -0
  221. package/lib/shared/dirs.js +20 -0
  222. package/lib/shared/dirs.js.map +1 -0
  223. package/lib/shared/http-body.js +43 -0
  224. package/lib/shared/index.d.ts +8 -0
  225. package/lib/shared/index.d.ts.map +1 -0
  226. package/lib/shared/index.js +8 -0
  227. package/lib/shared/index.js.map +1 -0
  228. package/lib/shared/json-file.js +34 -0
  229. package/lib/shared/orders.js +26 -0
  230. package/lib/shared/scope.d.ts +14 -0
  231. package/lib/shared/scope.d.ts.map +1 -0
  232. package/lib/shared/scope.js +12 -0
  233. package/lib/shared/scope.js.map +1 -0
  234. package/lib/shared/send-helper.d.ts +11 -0
  235. package/lib/shared/send-helper.d.ts.map +1 -0
  236. package/lib/shared/send-helper.js +13 -0
  237. package/lib/shared/send-helper.js.map +1 -0
  238. package/lib/shared/utils.d.ts +31 -0
  239. package/lib/shared/utils.d.ts.map +1 -0
  240. package/lib/shared/utils.js +228 -0
  241. package/lib/shared/utils.js.map +1 -0
  242. package/lib/tool-guard.js +74 -0
  243. package/lib/transport/attachment.d.ts +41 -0
  244. package/lib/transport/attachment.d.ts.map +1 -0
  245. package/lib/transport/attachment.js +191 -0
  246. package/lib/transport/attachment.js.map +1 -0
  247. package/lib/transport/chunker.d.ts +14 -0
  248. package/lib/transport/chunker.d.ts.map +1 -0
  249. package/lib/transport/chunker.js +78 -0
  250. package/lib/transport/chunker.js.map +1 -0
  251. package/lib/transport/deliverables.d.ts +20 -0
  252. package/lib/transport/deliverables.d.ts.map +1 -0
  253. package/lib/transport/deliverables.js +72 -0
  254. package/lib/transport/deliverables.js.map +1 -0
  255. package/lib/transport/events.d.ts +117 -0
  256. package/lib/transport/events.d.ts.map +1 -0
  257. package/lib/transport/events.js +112 -0
  258. package/lib/transport/events.js.map +1 -0
  259. package/lib/transport/inbound.d.ts +11 -0
  260. package/lib/transport/inbound.d.ts.map +1 -0
  261. package/lib/transport/inbound.js +511 -0
  262. package/lib/transport/inbound.js.map +1 -0
  263. package/lib/transport/index.d.ts +10 -0
  264. package/lib/transport/index.d.ts.map +1 -0
  265. package/lib/transport/index.js +10 -0
  266. package/lib/transport/index.js.map +1 -0
  267. package/lib/transport/msgid-cache.d.ts +23 -0
  268. package/lib/transport/msgid-cache.d.ts.map +1 -0
  269. package/lib/transport/msgid-cache.js +57 -0
  270. package/lib/transport/msgid-cache.js.map +1 -0
  271. package/lib/transport/notify.js +147 -0
  272. package/lib/transport/outbound-buffer.d.ts +42 -0
  273. package/lib/transport/outbound-buffer.d.ts.map +1 -0
  274. package/lib/transport/outbound-buffer.js +68 -0
  275. package/lib/transport/outbound-buffer.js.map +1 -0
  276. package/lib/transport/outbound.d.ts +42 -0
  277. package/lib/transport/outbound.d.ts.map +1 -0
  278. package/lib/transport/outbound.js +183 -0
  279. package/lib/transport/outbound.js.map +1 -0
  280. package/lib/transport/reply-limiter.d.ts +31 -0
  281. package/lib/transport/reply-limiter.d.ts.map +1 -0
  282. package/lib/transport/reply-limiter.js +50 -0
  283. package/lib/transport/reply-limiter.js.map +1 -0
  284. package/lib/transport/reply-target.d.ts +32 -0
  285. package/lib/transport/reply-target.d.ts.map +1 -0
  286. package/lib/transport/reply-target.js +64 -0
  287. package/lib/transport/reply-target.js.map +1 -0
  288. package/lib/transport/streaming-writer.d.ts +55 -0
  289. package/lib/transport/streaming-writer.d.ts.map +1 -0
  290. package/lib/transport/streaming-writer.js +122 -0
  291. package/lib/transport/streaming-writer.js.map +1 -0
  292. package/lib/transport/tool-presenter.d.ts +37 -0
  293. package/lib/transport/tool-presenter.d.ts.map +1 -0
  294. package/lib/transport/tool-presenter.js +116 -0
  295. package/lib/transport/tool-presenter.js.map +1 -0
  296. package/lib/turn-check.js +85 -0
  297. package/lib/types.d.ts +39 -0
  298. package/lib/types.js +5 -0
  299. package/locale/en.json +6 -0
  300. package/locale/zh.json +6 -0
  301. package/package.json +127 -4
@@ -0,0 +1,1052 @@
1
+ /**
2
+ * dsh-fishmemory:大肥鱼的记忆插件(从 dsh-qqbot-plus 里搬出来的那一半)。
3
+ *
4
+ * 分层照 Anthropic「components of agent memory」那篇:
5
+ *
6
+ * 转录 journal/<日期>.jsonl —— 每句话都记,原样可查(双方)
7
+ * 笔记 notes/<id>.md —— 值得长期留下的,一条一个 Markdown 文件
8
+ * 索引 index.md —— 笔记的目录,每行一条指针;每轮注入的就是它
9
+ * 做梦 dream.json —— 离线整理过的痕迹(什么时候、动了什么)
10
+ *
11
+ * 三条硬规矩:
12
+ * 1. 注入层只有索引,且只由「做梦」改写。它一变就掀掉整条前缀缓存,
13
+ * 所以它必须小(≤2400 字)且稳;细节一律留给 memory_search 现查。
14
+ * 2. 笔记是纯 Markdown + 极简 frontmatter,人可读、diff 得出、改得动。
15
+ * 3. 记忆是「人」的,不是某个屋子的:这里直接听 session 事件,
16
+ * 不绑定 QQ、Web 或任何渠道。
17
+ */
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import os from 'node:os'
21
+ import crypto from 'node:crypto'
22
+ import child from 'node:child_process'
23
+
24
+ import { PLUGIN_HOME } from '../shared/dirs.js'
25
+ import { ORDER } from '../shared/orders.js'
26
+
27
+
28
+ const HOME = os.homedir()
29
+ const DATA = path.join(PLUGIN_HOME, 'memory')
30
+ const NOTES = path.join(DATA, 'notes')
31
+ const JOURNAL = path.join(DATA, 'journal')
32
+ const INDEX = path.join(DATA, 'index.md')
33
+ const DREAM = path.join(DATA, 'dream.json')
34
+
35
+ const KINDS = new Set(['rule', 'fact', 'person', 'task', 'lesson', 'event'])
36
+ const INDEX_MAX_NOTES = 500 // 标题一行 128 条也只有 4K 多字,不再按条数卡
37
+ // 两本账分开算:行为类带摘要,事实/经过只列标题。混在一起算,事实一多就把
38
+ // 规矩/教训挤成空标题,或者反过来只剩规矩、六十条事实一条都看不见。
39
+ const INDEX_MAX_CHARS = 20000
40
+ const INDEX_TITLE_CHARS = 20000
41
+ const INDEX_EXCERPT_KINDS = new Set() // 索引只放标题认路;正文靠每轮现捞的三条(recallSection)
42
+ // 每类各留一份额度:共用一本账时,「人」和「待办」排在教训后面,教训一长
43
+ // 这两类就整组消失——而待办恰恰是最该看见的。
44
+ const INDEX_KIND_CHARS = { rule: 1100, lesson: 900, person: 150, task: 250, event: 700 }
45
+ // 事实和经过共用一本 3000 字的大账:它们条数最多,单独开口子会把别的类挤没。
46
+ const INDEX_SHARED_CHARS = 2000
47
+ // 「经过」以前和「事实」共用一张 3000 字的账,事实先写满就把经过全挤掉——
48
+ // 索引里永远看不到经过。分开算,各自有额度。
49
+ const INDEX_SHARED_KINDS = new Set(['fact'])
50
+ // 分配算法一改,旧 index.md 就该当场重排;只比 mtime 的话,磁盘上那份
51
+ // 老格式会一直被读下去(上一轮就这么白等了一次重启)。
52
+ const INDEX_VERSION = 4
53
+
54
+ // ────────────────────────────── 分词与打分 ──────────────────────────────
55
+ const STOPWORDS = new Set([
56
+ '的', '了', '着', '过', '是', '在', '有', '和', '与', '就', '都', '也', '还', '又', '再', '才',
57
+ '只', '很', '太', '更', '最', '没', '不', '别', '被', '把', '给', '让', '对', '从', '到',
58
+ '我', '你', '他', '她', '它', '这', '那', '个', '什么', '怎么', '为什么', '现在', '今天',
59
+ '明天', '昨天', '刚刚', '刚才', '还是', '但是', '而且', '所以', '因为', '如果', '可以',
60
+ '应该', '需要', '就是', '然后', '已经', '一下', '这个', '那个', '时候', '东西', '事情',
61
+ 'the', 'and', 'you', 'are', 'for', 'with', 'that', 'this', 'have', 'what', 'just',
62
+ 'can', 'not', 'but', 'from', 'they', 'will', 'your', 'about', 'was', 'were', 'has',
63
+ ])
64
+
65
+ function tokenize(text) {
66
+ const out = new Set()
67
+ if (typeof text !== 'string') return out
68
+ const lower = text.toLowerCase()
69
+ for (const m of lower.matchAll(/[a-z0-9_]{2,}/g)) out.add(m[0])
70
+ const cjk = lower.replace(/[^\u4e00-\u9fff]+/g, ' ')
71
+ for (const run of cjk.split(/\s+/)) {
72
+ if (run === '') continue
73
+ if (run.length === 1) out.add(run)
74
+ for (let i = 0; i + 1 < run.length; i += 1) out.add(run.slice(i, i + 2))
75
+ }
76
+ for (const token of STOPWORDS) out.delete(token)
77
+ return out
78
+ }
79
+
80
+ function scoreDocs(query, docs) {
81
+ const q = String(query ?? '').trim()
82
+ if (q === '' || docs.length === 0) return []
83
+ const queryTokens = tokenize(q)
84
+ const queryChars = [...new Set([...q].filter((ch) => ch >= '\u4e00' && ch <= '\u9fff'))]
85
+ const df = new Map()
86
+ const tokensById = docs.map((doc) => {
87
+ const tokens = tokenize(doc.text)
88
+ for (const token of tokens) df.set(token, (df.get(token) ?? 0) + 1)
89
+ return tokens
90
+ })
91
+ const N = Math.max(docs.length, 16)
92
+ const ceiling = Math.log(N + 2) || 1
93
+ const out = []
94
+ docs.forEach((doc, i) => {
95
+ const tokens = tokensById[i]
96
+ let s = 0
97
+ for (const token of queryTokens) {
98
+ if (!tokens.has(token)) continue
99
+ s += Math.max(0, Math.log((N + 2) / ((df.get(token) ?? 0) + 1)) / ceiling)
100
+ }
101
+ if (queryChars.length > 0) {
102
+ let hit = 0
103
+ for (const ch of queryChars) if (doc.text.includes(ch)) hit += 1
104
+ s += 0.35 * (hit / queryChars.length)
105
+ }
106
+ if (s <= 0) return
107
+ const c = s / (s + 1.1)
108
+ out.push({ ...doc, score: Number((c * (0.7 + 0.2 * (doc.importance ?? 0.5) + (doc.type === 'note' ? 0.1 : 0))).toFixed(4)) })
109
+ })
110
+ out.sort((a, b) => b.score - a.score)
111
+ return out
112
+ }
113
+
114
+ // ────────────────────────────── 文件与笔记 ──────────────────────────────
115
+ /** 记忆目录的 git 版本:只跟踪 notes/ 和 index.md。
116
+ * 写一条就提交一次,作者标 model;主人自己改的会以 operator 落进来。
117
+ * 失败一律静默——git 不在、仓库坏掉,都不能把写笔记这条路堵死。 */
118
+ function git(args, extraEnv) {
119
+ try {
120
+ return child.spawnSync('git', args, {
121
+ cwd: DATA,
122
+ encoding: 'utf8',
123
+ timeout: 5000,
124
+ env: { ...process.env, ...(extraEnv ?? {}) },
125
+ })
126
+ } catch {
127
+ return null
128
+ }
129
+ }
130
+
131
+ function ensureGit() {
132
+ try {
133
+ if (!fs.existsSync(DATA)) return false
134
+ if (fs.existsSync(path.join(DATA, '.git'))) {
135
+ if (!fs.existsSync(path.join(DATA, '.gitignore'))) {
136
+ fs.writeFileSync(path.join(DATA, '.gitignore'), 'journal/\nevents.log\nmessages.log\ndream.json\nboot.log\n*.lock\n', 'utf8')
137
+ }
138
+ return true
139
+ }
140
+ const init = git(['init', '-q'])
141
+ if (!init || init.status !== 0) return false
142
+ fs.writeFileSync(path.join(DATA, '.gitignore'), 'journal/\nevents.log\nmessages.log\ndream.json\nboot.log\n*.lock\n', 'utf8')
143
+ git(['add', '-A'])
144
+ git(['commit', '-q', '-m', 'init: 记忆第一次进版本'], {
145
+ GIT_AUTHOR_NAME: '大肥鱼', GIT_AUTHOR_EMAIL: 'fish@local',
146
+ GIT_COMMITTER_NAME: '大肥鱼', GIT_COMMITTER_EMAIL: 'fish@local',
147
+ })
148
+ return true
149
+ } catch {
150
+ return false
151
+ }
152
+ }
153
+
154
+ /** 提交一次。message 里带动作与 id,翻历史时一眼看得懂改了什么。 */
155
+ function commitNotes(message, who = 'model') {
156
+ try {
157
+ if (!ensureGit()) return
158
+ git(['add', 'notes', 'index.md'])
159
+ const name = who === 'operator' ? '主人' : '大肥鱼'
160
+ git(['commit', '-q', '-m', message], {
161
+ GIT_AUTHOR_NAME: name, GIT_AUTHOR_EMAIL: 'fish@local',
162
+ GIT_COMMITTER_NAME: name, GIT_COMMITTER_EMAIL: 'fish@local',
163
+ })
164
+ } catch {
165
+ // 静默
166
+ }
167
+ }
168
+
169
+ /** 前缀里那一小段清单:条数 + 分类计数 + 最近改过的 5 份。
170
+ * 按笔记目录 mtime 缓存,目录没变就返回同一段字符串(前缀逐字相同,缓存不炸)。 */
171
+ let __listingCache = { key: '', text: '' }
172
+ function memoryListing() {
173
+ try {
174
+ let key = ''
175
+ try {
176
+ const st = fs.statSync(NOTES)
177
+ key = `${st.mtimeMs}:${st.size}`
178
+ } catch {
179
+ return ''
180
+ }
181
+ if (__listingCache.key === key && __listingCache.text !== '') return __listingCache.text
182
+ const notes = listNotes()
183
+ if (notes.length === 0) return ''
184
+ const counts = {}
185
+ for (const n of notes) counts[n.kind] = (counts[n.kind] ?? 0) + 1
186
+ const label = { rule: '规矩', lesson: '教训', fact: '事实', person: '人', task: '待办', event: '经过' }
187
+ const parts = Object.entries(counts)
188
+ .sort((a, b) => b[1] - a[1])
189
+ .map(([k, v]) => `${label[k] ?? k} ${v}`)
190
+ .join(' · ')
191
+ const recent = notes.slice(0, 5).map((n) => `${n.id} ${n.title}`).join(' / ')
192
+ const text = [
193
+ `### 记忆清单(每轮现读,不是摘要)`,
194
+ `notes/ 共 ${notes.length} 份:${parts}`,
195
+ `最近改过:${recent}`,
196
+ `要具体内容就 memory_search 或直接读 notes/<id>.md;不要凭印象说「我记得」。`,
197
+ ].join('\n')
198
+ __listingCache = { key, text }
199
+ return text
200
+ } catch {
201
+ return ''
202
+ }
203
+ }
204
+
205
+ function ensureDir(dir) {
206
+ fs.mkdirSync(dir, { recursive: true })
207
+ }
208
+
209
+ function stamp(at) {
210
+ const d = at ? new Date(at) : new Date()
211
+ const pad = (n) => String(n).padStart(2, '0')
212
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
213
+ }
214
+
215
+ function deriveTitle(body) {
216
+ const first = String(body ?? '').trim().split(/[\n。!?!?]/)[0] ?? ''
217
+ const clean = first.replace(/^[-*\s#]+/, '').trim()
218
+ if (clean === '') return '未命名'
219
+ return clean.length > 24 ? `${clean.slice(0, 24)}…` : clean
220
+ }
221
+
222
+ function noteId(title, body) {
223
+ return crypto.createHash('sha1').update(`${title}\u0000${String(body ?? '').slice(0, 200)}`).digest('hex').slice(0, 10)
224
+ }
225
+
226
+ function parseNoteFile(file) {
227
+ const raw = fs.readFileSync(file, 'utf8')
228
+ const meta = {}
229
+ let body = raw
230
+ if (raw.startsWith('---')) {
231
+ const end = raw.indexOf('\n---', 3)
232
+ if (end >= 0) {
233
+ const head = raw.slice(3, end).trim()
234
+ body = raw.slice(end + 4).replace(/^\n/, '')
235
+ for (const line of head.split('\n')) {
236
+ const at = line.indexOf(':')
237
+ if (at < 0) continue
238
+ const key = line.slice(0, at).trim()
239
+ let value = line.slice(at + 1).trim()
240
+ if (value.startsWith('[') && value.endsWith(']')) {
241
+ value = value.slice(1, -1).split(',').map((item) => item.trim()).filter(Boolean)
242
+ }
243
+ meta[key] = value
244
+ }
245
+ }
246
+ }
247
+ return { meta, body }
248
+ }
249
+
250
+ function serializeNote(meta, body) {
251
+ const lines = ['---']
252
+ for (const key of ['id', 'title', 'kind', 'tags', 'importance', 'source', 'created', 'updated', 'verified']) {
253
+ const value = meta[key]
254
+ if (value === undefined || value === '' || (Array.isArray(value) && value.length === 0)) continue
255
+ lines.push(`${key}: ${Array.isArray(value) ? `[${value.join(', ')}]` : value}`)
256
+ }
257
+ lines.push('---', '', String(body ?? '').trim(), '')
258
+ return lines.join('\n')
259
+ }
260
+
261
+ function listNotes() {
262
+ let files = []
263
+ try {
264
+ files = fs.readdirSync(NOTES).filter((f) => f.endsWith('.md'))
265
+ } catch {
266
+ return []
267
+ }
268
+ const out = []
269
+ for (const file of files) {
270
+ try {
271
+ const full = path.join(NOTES, file)
272
+ const { meta, body } = parseNoteFile(full)
273
+ out.push({
274
+ id: meta.id ?? file.replace(/\.md$/, ''),
275
+ file: full,
276
+ title: meta.title ?? deriveTitle(body),
277
+ kind: KINDS.has(meta.kind) ? meta.kind : 'fact',
278
+ tags: Array.isArray(meta.tags) ? meta.tags : [],
279
+ importance: Number(meta.importance ?? 0.6) || 0.6,
280
+ created: meta.created ?? '',
281
+ updated: meta.updated ?? '',
282
+ verified: meta.verified ?? '',
283
+ body,
284
+ })
285
+ } catch {
286
+ // 坏文件忽略
287
+ }
288
+ }
289
+ out.sort((a, b) => String(b.updated || b.created).localeCompare(String(a.updated || a.created)))
290
+ return out
291
+ }
292
+
293
+ function findNote(id) {
294
+ return listNotes().find((note) => note.id === id) ?? null
295
+ }
296
+
297
+ /** tags 到这儿有时是数组、有时是逗号串(工具层会做一次序列化),两种都收。
298
+ * 以前写死 (tags ?? []).map() 会把整次 memory_write 直接搞挂。 */
299
+ function normalizeTags(value) {
300
+ const list = Array.isArray(value)
301
+ ? value
302
+ : (typeof value === 'string' ? value.split(/[,,、\s]+/) : [])
303
+ return [...new Set(list.map((t) => String(t).trim()).filter(Boolean))]
304
+ }
305
+
306
+ function upsertNote(input) {
307
+ const text = String(input?.text ?? '').trim()
308
+ if (text === '') throw new Error('memory_write: 正文不能为空')
309
+ const title = String(input?.title ?? '').trim() || deriveTitle(text)
310
+ const id = String(input?.id ?? '').trim() || noteId(title, text)
311
+ const previous = findNote(id)
312
+ const now = stamp()
313
+ const meta = {
314
+ id,
315
+ title,
316
+ kind: KINDS.has(input?.kind) ? input.kind : 'fact',
317
+ tags: normalizeTags(input?.tags),
318
+ importance: Math.min(1, Math.max(0, Number(input?.importance ?? 0.6) || 0.6)),
319
+ source: input?.source ?? 'model',
320
+ created: previous?.created || now,
321
+ updated: now,
322
+ verified: input?.verified ?? previous?.verified ?? '',
323
+ }
324
+ ensureDir(NOTES)
325
+ const file = path.join(NOTES, `${id}.md`)
326
+ fs.writeFileSync(file, serializeNote(meta, text), 'utf8')
327
+ return { id, file, title, created: meta.created, updated: now }
328
+ }
329
+
330
+ function rebuildIndex() {
331
+ const notes = listNotes()
332
+ // 行为类的排前面:规矩/教训/人 先占位置,事实再多也不许把它们挤掉。
333
+ const groups = [['rule', '规矩'], ['lesson', '教训'], ['person', '人'], ['task', '待办'], ['fact', '事实'], ['event', '经过']]
334
+ const lines = ['# 记忆索引', `<!-- fishmemory-index v${INDEX_VERSION} -->`, '']
335
+ if (notes.length === 0) lines.push('(还是一条都没有)')
336
+ const used = new Set()
337
+ let sharedChars = 0
338
+ for (const [kind, label] of groups) {
339
+ const bucket = notes
340
+ .filter((note) => note.kind === kind)
341
+ .sort((a, b) => (b.importance - a.importance) || String(b.updated).localeCompare(String(a.updated)))
342
+ if (bucket.length === 0) continue
343
+ const shared = INDEX_SHARED_KINDS.has(kind)
344
+ const kindCap = INDEX_KIND_CHARS[kind] ?? INDEX_MAX_CHARS
345
+ const body = []
346
+ let kindChars = 0
347
+ for (const note of bucket) {
348
+ // 每一类各留一份额度:规矩/教训先占满,事实和经过共用大账排最后。
349
+ const room = shared
350
+ ? sharedChars < INDEX_SHARED_CHARS
351
+ : kindChars < kindCap
352
+ if (!room) break
353
+ if (used.size >= INDEX_MAX_NOTES) break
354
+ const line = `- ${note.title}(${note.id})`
355
+ body.push(line)
356
+ used.add(note.id)
357
+ if (shared) sharedChars += line.length
358
+ else kindChars += line.length
359
+ }
360
+ // 预算用光就整组不写:留一个空标题看着像「这一类我一条都没有」。
361
+ if (body.length === 0) continue
362
+ lines.push(`## ${label}`, ...body, '')
363
+ }
364
+ const rest = notes.filter((note) => !used.has(note.id))
365
+ if (rest.length > 0) {
366
+ // 页脚按 kind 拆开:只写总数会让人以为「还剩几条都一样」,其实通常全压在事实那一类。
367
+ const byKind = new Map()
368
+ for (const note of rest) byKind.set(note.kind, (byKind.get(note.kind) ?? 0) + 1)
369
+ const parts = groups
370
+ .filter(([kind]) => byKind.has(kind))
371
+ .map(([kind, label]) => `${label} ${byKind.get(kind)}`)
372
+ const tail = groups.some(([kind]) => byKind.has(kind)) ? parts.join(' · ') : ''
373
+ lines.push(`(还有 ${rest.length} 条没列出来:${tail ? `${tail};` : ''}memory_search 查,或直接读 notes/<id>.md)`, '')
374
+ }
375
+ const text = `${lines.join('\n').trim()}\n`
376
+ ensureDir(DATA)
377
+ fs.writeFileSync(INDEX, text, 'utf8')
378
+ return { text, notes: notes.length, listed: used.size }
379
+ }
380
+
381
+ /** notes/ 里最新的那份(新建/改动都算)比 index.md 新多少。 */
382
+ function notesNewerThan(ms) {
383
+ try {
384
+ const dir = fs.statSync(NOTES).mtimeMs
385
+ if (dir > ms) return true
386
+ for (const file of fs.readdirSync(NOTES)) {
387
+ if (!file.endsWith('.md')) continue
388
+ try {
389
+ if (fs.statSync(path.join(NOTES, file)).mtimeMs > ms) return true
390
+ } catch {
391
+ // 单个文件 stat 失败不影响判断
392
+ }
393
+ }
394
+ return false
395
+ } catch {
396
+ return false
397
+ }
398
+ }
399
+
400
+ function indexText() {
401
+ try {
402
+ if (!fs.existsSync(INDEX)) return rebuildIndex().text.trim()
403
+ let indexAt = 0
404
+ try {
405
+ indexAt = fs.statSync(INDEX).mtimeMs
406
+ } catch {
407
+ indexAt = 0
408
+ }
409
+ // 笔记比索引新(手工改过、搬进来一批、做梦之后又写过)就当场重写一份,
410
+ // 不让注入的目录停在上一次:陈旧索引是「记得但想不起来」的一半原因。
411
+ if (notesNewerThan(indexAt)) return rebuildIndex().text.trim()
412
+ const text = fs.readFileSync(INDEX, 'utf8')
413
+ if (!text.includes(`fishmemory-index v${INDEX_VERSION}`)) return rebuildIndex().text.trim()
414
+ return text.trim()
415
+ } catch {
416
+ return ''
417
+ }
418
+ }
419
+
420
+ // ────────────────────────────── 转录 ──────────────────────────────
421
+ function appendJournal(entry) {
422
+ const at = entry?.at ? new Date(entry.at) : new Date()
423
+ const day = `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`
424
+ ensureDir(JOURNAL)
425
+ const role = entry?.role === 'assistant' ? 'assistant' : 'user'
426
+ const raw = String(entry?.text ?? '').slice(0, 800)
427
+ // 与迁移进来的历史行保持同一种形态:[2026/11/15 21:29:06] 用户: …/我: …
428
+ const stamp = `${at.getFullYear()}/${String(at.getMonth() + 1).padStart(2, '0')}/${String(at.getDate()).padStart(2, '0')} ${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}:${String(at.getSeconds()).padStart(2, '0')}`
429
+ const label = role === 'assistant' ? '我' : String(entry?.who ?? '').trim() || '用户'
430
+ const row = {
431
+ at: at.toISOString(),
432
+ role,
433
+ who: entry?.who ?? '',
434
+ text: /^\[\d{4}\/\d{2}\/\d{2} /.test(raw) ? raw : `[${stamp}] ${label}: ${raw}`,
435
+ session: entry?.session ?? '',
436
+ }
437
+ try {
438
+ fs.appendFileSync(path.join(JOURNAL, `${day}.jsonl`), `${JSON.stringify(row)}\n`, 'utf8')
439
+ } catch (error) {
440
+ // 不静默:写不进去要有痕迹,否则「没在记」和「记失败」分不出来。
441
+ console.warn?.(`fishmemory: 写转录失败 ${String(error)}`)
442
+ }
443
+ }
444
+
445
+ function readJournal(days = 2, limit = 400) {
446
+ let files = []
447
+ try {
448
+ files = fs.readdirSync(JOURNAL).filter((f) => f.endsWith('.jsonl')).sort()
449
+ } catch {
450
+ return []
451
+ }
452
+ const rows = []
453
+ for (const file of files.slice(-Math.max(1, days))) {
454
+ try {
455
+ const text = fs.readFileSync(path.join(JOURNAL, file), 'utf8')
456
+ for (const line of text.split('\n')) {
457
+ if (line.trim() === '') continue
458
+ try {
459
+ rows.push(JSON.parse(line))
460
+ } catch {
461
+ // 坏行跳过
462
+ }
463
+ }
464
+ } catch {
465
+ // ignore
466
+ }
467
+ }
468
+ return rows.slice(-limit)
469
+ }
470
+
471
+ function search(query, limit = 6) {
472
+ const notes = listNotes().map((note) => ({
473
+ type: 'note', id: note.id, title: note.title,
474
+ text: `${note.title} ${note.tags.join(' ')} ${note.body}`.trim(),
475
+ kind: note.kind, updated: note.updated, importance: note.importance,
476
+ }))
477
+ const journal = readJournal(3, 800).map((row) => ({
478
+ type: 'journal', id: '', title: row.role === 'assistant' ? '我' : (row.who || '对方'),
479
+ text: row.text, kind: 'event', updated: row.at, importance: 0.4,
480
+ }))
481
+ return scoreDocs(query, [...notes, ...journal]).slice(0, Math.max(1, limit))
482
+ }
483
+
484
+ function markDream(info = {}) {
485
+ let previous = {}
486
+ try {
487
+ previous = JSON.parse(fs.readFileSync(DREAM, 'utf8'))
488
+ } catch {
489
+ previous = {}
490
+ }
491
+ const next = { lastAt: new Date().toISOString(), runs: Number(previous.runs ?? 0) + 1, ...info }
492
+ ensureDir(DATA)
493
+ fs.writeFileSync(DREAM, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
494
+ return next
495
+ }
496
+
497
+ function readDream() {
498
+ try {
499
+ return JSON.parse(fs.readFileSync(DREAM, 'utf8'))
500
+ } catch {
501
+ return null
502
+ }
503
+ }
504
+
505
+ // ────────────────────────────── 文本提取 ──────────────────────────────
506
+ function textOf(message) {
507
+ const content = message?.content ?? message?.message?.content
508
+ if (typeof content === 'string') return content
509
+ if (!Array.isArray(content)) return ''
510
+ return content
511
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
512
+ .map((block) => block.text)
513
+ .join('\n')
514
+ }
515
+
516
+ /** 按最近一句**真人**说的话,从 notes/ 里捞 3 条相关的,塞进系统提示。
517
+ * 宿主每步都会往会话里塞注入消息(Time sampled / Current runtime context / system-reminder),
518
+ * 那些不是他说的话;拿它们当查询词,recall 就永远是空的 —— 这正是「记得很多、从来不会
519
+ * 主动想起」的根因(186 轮里 0 轮命中,见笔记 610d9da6b4)。 */
520
+ const RECALL_MAX = 3
521
+ const RECALL_EXCERPT = 110
522
+
523
+ const HARNESS_PREFIXES = ['<', 'Current runtime context', 'Time sampled', '(宿主刚重启过']
524
+
525
+ function isHarnessText(text) {
526
+ const t = String(text ?? '').trim()
527
+ if (t === '') return true
528
+ for (const prefix of HARNESS_PREFIXES) if (t.startsWith(prefix)) return true
529
+ if (t.includes('(以下是本轮想到的旧事')) return true
530
+ return false
531
+ }
532
+
533
+ function daysSince(at) {
534
+ const t = Date.parse(String(at ?? ''))
535
+ if (!Number.isFinite(t)) return 999
536
+ return Math.max(0, (Date.now() - t) / 86400000)
537
+ }
538
+
539
+ function recallTokens (text) {
540
+ const out = new Set()
541
+ const latin = String(text ?? '').toLowerCase().match(/[a-z0-9_\.-]{2,}/g) ?? []
542
+ for (const w of latin) if (!STOPWORDS.has(w)) out.add(w)
543
+ const han = String(text ?? '').replace(/[^\u4e00-\u9fff]/g, ' ')
544
+ for (const run of han.split(/\s+/)) {
545
+ for (let n = 2; n <= 4; n += 1) {
546
+ for (let i = 0; i + n <= run.length; i += 1) {
547
+ const gram = run.slice(i, i + n)
548
+ // 「什么」「今天」「就是」这类虚词当查询词只会把无关笔记捞上来。
549
+ if (!STOPWORDS.has(gram)) out.add(gram)
550
+ }
551
+ }
552
+ }
553
+ return out
554
+ }
555
+
556
+ /** 同一句真人话只捞一次。一轮里这段会被问十几次(每步一次),而中间我可能
557
+ * 刚写完笔记 —— 重算就会让「最近写/改的」垫底那三条整段换内容,宿主那边的
558
+ * 前缀缓存跟着白扔。等他下一句话进来,key 变了,自然重算。 */
559
+ let __recallCache = { key: null, text: '' }
560
+
561
+ /** 从宿主传进来的上下文里取会话 id。宿主各版本形状不一,挨个试,取不到就空串。 */
562
+ function sessionIdOf (arg) {
563
+ if (arg === null || typeof arg !== 'object') return ''
564
+ const picks = [
565
+ arg.agent?.id,
566
+ arg.agent?.session?.id,
567
+ arg.agent?.session?.header?.id,
568
+ arg.session?.id,
569
+ arg.session?.header?.id,
570
+ arg.ctx?.agent?.id,
571
+ arg.id,
572
+ ]
573
+ for (const v of picks) if (typeof v === 'string' && v !== '') return v
574
+ return ''
575
+ }
576
+
577
+ /** 拿「这一条会话」最新的那句真人话。
578
+ * 以前是把 __lastUser 摊平取全局最后一句 —— 两条会话同时说话就捞错人那句。
579
+ * 传了会话 id 就只认它;没传(宿主老版本 / 探测)退回全局最后一句,行为不变。 */
580
+ function recallSection (sessionId = '') {
581
+ try {
582
+ const want = String(sessionId ?? '')
583
+ const humans = [...__lastUser.entries()]
584
+ .filter(([id, v]) => v && typeof v.text === 'string' && !isHarnessText(v.text))
585
+ .filter(([id]) => want === '' || id === want)
586
+ .map(([, v]) => v)
587
+ const last = humans.length > 0 ? String(humans[humans.length - 1].text) : ''
588
+ const key = `${want}\u0000${last}`
589
+ if (__recallCache.key === key) return __recallCache.text
590
+ const text = recallSectionUncached(last)
591
+ __recallCache = { key, text }
592
+ return text
593
+ } catch (error) {
594
+ if (process.env.FM_DEBUG) console.error('[fishmemory recall]', error)
595
+ return ''
596
+ }
597
+ }
598
+
599
+ function recallSectionUncached (last) {
600
+ try {
601
+ const notes = listNotes()
602
+ if (notes.length === 0) return ''
603
+ const tokens = recallTokens(last)
604
+ const scored = []
605
+ for (const note of notes) {
606
+ // 查询词是小写化的拉丁词,笔记原文有大写(justInbound / XHS),
607
+ // 直接 includes 会漏——比之前先各自转小写。
608
+ const title = String(note.title ?? '').toLowerCase()
609
+ const tags = (Array.isArray(note.tags) ? note.tags.join(' ') : '').toLowerCase()
610
+ const body = String(note.body ?? '').toLowerCase()
611
+ let score = 0
612
+ let best = 0
613
+ const hit = new Set()
614
+ for (const t of tokens) {
615
+ if (t.length < 2) continue
616
+ if (title.includes(t)) { score += 3; best = Math.max(best, 3); hit.add(t) }
617
+ else if (tags.includes(t)) { score += 2; best = Math.max(best, 2); hit.add(t) }
618
+ else if (body.includes(t)) { score += 1; best = Math.max(best, 1); hit.add(t) }
619
+ }
620
+ if (score <= 0) continue
621
+ // 两个词撞上,或者一个词撞在标题/标签上,就进来。以前要求两个词,
622
+ // 他一句「重启好了」「继续」就永远捞不到东西。
623
+ if (hit.size < 2 && best < 2) continue
624
+ const fresh = Math.max(0, 1 - daysSince(note.updated || note.created) / 30)
625
+ scored.push({ note, score: score * (1 + 0.6 * fresh) })
626
+ }
627
+ scored.sort((a, b) => b.score - a.score || String(b.note.updated).localeCompare(String(a.note.updated)))
628
+ const picked = []
629
+ const seen = new Set()
630
+ for (const { note } of scored) {
631
+ if (picked.length >= RECALL_MAX) break
632
+ picked.push({ note, why: '' })
633
+ seen.add(note.id)
634
+ }
635
+ // 没捞到(或者只捞到一条)就垫上最近写/改过的:宁可给「最近在想的事」,
636
+ // 也不要一轮下来脑子里一条都没有 —— 那正是「从来不会主动想起」。
637
+ if (picked.length < RECALL_MAX) {
638
+ for (const note of notes) {
639
+ if (picked.length >= RECALL_MAX) break
640
+ if (seen.has(note.id)) continue
641
+ picked.push({ note, why: '(最近写/改的)' })
642
+ seen.add(note.id)
643
+ }
644
+ }
645
+ if (picked.length === 0) return ''
646
+ const lines = [last.trim() === ''
647
+ ? '## 最近写/改过的记忆(细节用 memory_search 查)'
648
+ : '## 这一轮你可能要用到的(自动捞的,细节用 memory_search)']
649
+ for (const { note, why } of picked) {
650
+ const short = String(note.body ?? '').replace(/\s+/g, ' ').trim()
651
+ const excerpt = short.length > RECALL_EXCERPT ? `${short.slice(0, RECALL_EXCERPT)}…` : short
652
+ const tail = excerpt === '' || excerpt === note.title ? '' : ` — ${excerpt}`
653
+ lines.push(`- ${note.title}(${note.id})${why}${tail}`)
654
+ }
655
+ return lines.join('\n')
656
+ } catch (error) {
657
+ if (process.env.FM_DEBUG) console.error('[fishmemory recall build]', error)
658
+ return ''
659
+ }
660
+ }
661
+
662
+ /** 距上次做梦多久、之后又转录了多少句:够了就在提示里提一句,让整理真的发生。 */
663
+ let __nudgeCache = { key: '', text: '' }
664
+
665
+ /** 转录目录的指纹:只靠文件名和大小,不读内容(每步都会问一次)。 */
666
+ function journalTally() {
667
+ try {
668
+ const files = fs.readdirSync(JOURNAL).filter((f) => f.endsWith('.jsonl')).sort()
669
+ let key = String(files.length)
670
+ for (const file of files.slice(-4)) {
671
+ try {
672
+ key += `:${file}:${fs.statSync(path.join(JOURNAL, file)).size}`
673
+ } catch {
674
+ // 单个文件坏了不影响别的
675
+ }
676
+ }
677
+ return { key }
678
+ } catch {
679
+ return { key: '' }
680
+ }
681
+ }
682
+
683
+ /** 上次做梦之后真正新增的转录行数(按行里的 at 比,ISO 字符串可以直接比大小)。
684
+ * 只要够判断「超过阈值」就停,不逐行扫完两兆的转录。 */
685
+ function journalSince (lastAtIso) {
686
+ try {
687
+ const files = fs.readdirSync(JOURNAL).filter((f) => f.endsWith('.jsonl')).sort()
688
+ let pending = 0
689
+ for (const file of files.reverse()) {
690
+ const full = path.join(JOURNAL, file)
691
+ try {
692
+ const st = fs.statSync(full)
693
+ if (lastAtIso !== '' && st.mtimeMs < Date.parse(lastAtIso)) break
694
+ const lines = fs.readFileSync(full, 'utf8').split('\n')
695
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
696
+ const line = lines[i]
697
+ if (line.trim() === '') continue
698
+ const at = /"at":"([^"]+)"/.exec(line)?.[1] ?? ''
699
+ if (lastAtIso !== '' && at !== '' && at <= lastAtIso) return pending
700
+ pending += 1
701
+ if (pending >= 200) return pending
702
+ }
703
+ } catch {
704
+ // 单个文件坏了不影响
705
+ }
706
+ }
707
+ return pending
708
+ } catch {
709
+ return 0
710
+ }
711
+ }
712
+
713
+ function dreamNudge() {
714
+ try {
715
+ const state = readDream()
716
+ const lastAt = Date.parse(String(state?.lastAt ?? ''))
717
+ const hours = Number.isFinite(lastAt) ? (Date.now() - lastAt) / 3600000 : Number.POSITIVE_INFINITY
718
+ const tally = journalTally()
719
+ let dreamKey = ''
720
+ try {
721
+ dreamKey = String(fs.statSync(DREAM).mtimeMs)
722
+ } catch {
723
+ dreamKey = 'none'
724
+ }
725
+ const key = `${dreamKey}:${tally.key}`
726
+ if (__nudgeCache.key === key && hours < 20) return __nudgeCache.text
727
+ const lastAtIso = Number.isFinite(lastAt) ? new Date(lastAt).toISOString() : ''
728
+ const pending = journalSince(lastAtIso)
729
+ let text = ''
730
+ if (!(hours < 20 && pending < 120)) {
731
+ // 文案必须稳:带上「X 小时 / N 句」的话,每说一句它就变一次,
732
+ // 每步都掀一次前缀缓存。触发与否看数字,说出来的话不带数字。
733
+ text = [
734
+ '## 该整理了(提醒,不是任务)',
735
+ '距上次做梦有些久了,这中间攒了不少原话没归到笔记里。',
736
+ '有空就用 memory_journal 读一遍最近的对话:该记的记下、说错的改掉、过期的删掉,收尾调 memory_dream。',
737
+ ].join('\n')
738
+ }
739
+ __nudgeCache = { key, text }
740
+ return text
741
+ } catch {
742
+ return ''
743
+ }
744
+ }
745
+
746
+ function promptSection() {
747
+ const body = indexText()
748
+ const lines = [
749
+ '# 我的记忆',
750
+ '- 上面那份索引是我记得的东西,细节不在里面。要具体的原话、时间、来龙去脉,用 memory_search 查。',
751
+ '- 值得长期留下的东西(规矩、教训、约定、他明确说过的偏好)用 memory_write 写进笔记,一条一件事。',
752
+ '- 写错的笔记用 memory_forget 删、或者用 memory_write 覆盖同一个 id。',
753
+ '- 转录(journal/<日期>.jsonl):宿主会话里说的话插件自己会记;QQ 这类渠道的消息不会自动进来,想留住某句原话就用 memory_append 记一行——text 照原话不改写,who 写谁说的,role 给 user 或 assistant,at 可给 ISO 时间。',
754
+ '- 索引跟着笔记自动重写,不用手动同步;「做梦」(memory_dream)管的是整理笔记本身。',
755
+ '- 末尾「这一轮你可能要用到的」是按他刚说的话现捞的:捞到了就当提醒看一眼,不是他新提的要求。',
756
+ ]
757
+ const listing = memoryListing()
758
+ if (listing !== '') lines.push('', listing)
759
+ if (body !== '') lines.push('', body)
760
+ const nudge = dreamNudge()
761
+ if (nudge !== '') lines.push('', nudge)
762
+ return lines.join('\n')
763
+ }
764
+
765
+ // ────────────────────────────── 插件入口 ──────────────────────────────
766
+ import { appendFileSync as __bootAppend } from 'node:fs'
767
+
768
+ const __lastUser = new Map()
769
+
770
+ function __bootLog(line) {
771
+ try {
772
+ // 写进数据目录,不写插件安装目录:安装目录是代码,会被 rsync/git 带走,也不该有运行期文件。
773
+ const file = path.join(DATA, 'boot.log')
774
+ if (!fs.existsSync(DATA)) fs.mkdirSync(DATA, { recursive: true })
775
+ if (fs.existsSync(file) && fs.statSync(file).size > 512 * 1024) fs.writeFileSync(file, '', 'utf8')
776
+ __bootAppend(file, `${new Date().toISOString()} ${line}\n`)
777
+ } catch {}
778
+ }
779
+ __bootLog('module evaluated')
780
+
781
+ function __apply(ctx, config = {}) {
782
+ __bootLog('apply entered')
783
+ const logger = ctx.logger ?? console
784
+ const home = DATA
785
+
786
+ // 1) 转录:听 session 事件,双方的话都记。
787
+ // 必须是根上下文:cordis 的事件只向「发出方 + 它的祖先」派发,挂在插件自己的
788
+ // ctx 上收不到别的 fiber(agent / 会话)发的事件,等于一条都不记。
789
+ try {
790
+ const bus = ctx.root ?? ctx
791
+ bus.on('session/event', (session, event) => {
792
+ try {
793
+ const type = event?.type
794
+ if (type !== 'user/message' && type !== 'assistant/message') return
795
+ // session/event 的形状是 { type, data, seq }:消息本体在 event.data 里,
796
+ // 不在 event.message(那是我先前猜错的那一版,所以一条都没记上)。
797
+ const payload = event?.data ?? event?.message ?? event
798
+ let text = textOf(payload).trim()
799
+ if (text === '' || isHarnessText(text)) return
800
+ const sessionId = String(session?.header?.id ?? session?.id ?? session?.key ?? '')
801
+ if (type === 'user/message') {
802
+ // 只收真人话(isHarnessText 已经把宿主每步塞进来的注入消息挡掉了)。
803
+ // 带时间戳:recall 用「最新一句真人话」,不是「最后一条 user/message」。
804
+ __lastUser.set(sessionId, { text, at: Date.now() })
805
+ }
806
+ else {
807
+ // 控制台会话里 assistant/message 会把对方那句原话一起带进来(首行就是用户消息),
808
+ // 直接记会把「他说的」记成「我说的」。剥掉前缀,只留我自己那部分。
809
+ const echoed = __lastUser.get(sessionId)?.text
810
+ if (typeof echoed === 'string' && echoed !== '' && text.startsWith(echoed)) {
811
+ text = text.slice(echoed.length).trim()
812
+ if (text === '') return
813
+ }
814
+ }
815
+ appendJournal({ role: type === 'user/message' ? 'user' : 'assistant', text, session: sessionId })
816
+ } catch (error) {
817
+ logger.warn?.(`fishmemory: 记转录失败 ${String(error)}`)
818
+ }
819
+ })
820
+ } catch (error) {
821
+ logger.warn?.(`fishmemory: 订阅 session/event 失败 ${String(error)}`)
822
+ }
823
+
824
+ // 2) 注入:系统提示里只放索引(小、稳)。索引由做梦重写,不按提问现检索。
825
+ try {
826
+ ctx.inject(['systemPrompt'], (inner) => {
827
+ inner.effect(() => inner.systemPrompt.context({
828
+ name: 'fishmemory/index',
829
+ order: ORDER.memoryIndex,
830
+ interpolate: false,
831
+ text: () => promptSection(),
832
+ }))
833
+ // 现捞的那三条单独一段,紧跟在索引后面(离这一轮的话最近)。
834
+ // 以前它拼在 promptSection 末尾,跟索引挤进同一段,谁都看不出它是「按这句话捞的」。
835
+ inner.effect(() => inner.systemPrompt.context({
836
+ name: 'fishmemory/recall',
837
+ order: ORDER.memoryRecall,
838
+ interpolate: false,
839
+ // 宿主调用时会把这一轮的上下文传进来(含 agent),用它锁定是哪条会话;
840
+ // 传不进来时退回老行为,不会因为形状不认就整段消失。
841
+ text: (arg) => recallSection(sessionIdOf(arg)),
842
+ }))
843
+ })
844
+ } catch (error) {
845
+ logger.warn?.(`fishmemory: 注入系统提示失败 ${String(error)}`)
846
+ }
847
+ // 3) 工具。
848
+ const tools = []
849
+ tools.push({
850
+ name: 'memory_write',
851
+ description: '把一件值得长期记住的事写成一条笔记(规矩、教训、约定、偏好、事实)。一条一件事,标题短,正文写清楚来龙去脉和为什么。',
852
+ parameters: {
853
+ type: 'object',
854
+ properties: {
855
+ text: { type: 'string', description: '正文(完整的一句话或几条,别写空话)' },
856
+ title: { type: 'string', description: '短标题,不填就取正文首句' },
857
+ kind: { type: 'string', enum: [...KINDS], description: 'rule 规矩 / lesson 教训 / fact 事实 / person 关于人 / task 待办 / event 经过' },
858
+ tags: { type: 'array', items: { type: 'string' }, description: '几个关键词,便于以后检索' },
859
+ importance: { type: 'number', description: '0~1,越重要越靠前' },
860
+ id: { type: 'string', description: '要覆盖某条旧笔记时给它的 id' },
861
+ },
862
+ required: ['text'],
863
+ },
864
+ async execute(args) {
865
+ const note = upsertNote({ ...args, source: 'model' })
866
+ rebuildIndex()
867
+ commitNotes(`write: ${note.id} ${note.title}`)
868
+ return `已写入 ${note.id}:${note.title}\n文件:${note.file}`
869
+ },
870
+ })
871
+
872
+ tools.push({
873
+ name: 'memory_search',
874
+ description: '检索记忆:先翻笔记,再翻最近几天的转录(双方的话)。不猜语义,只认字面证据。',
875
+ parameters: {
876
+ type: 'object',
877
+ properties: {
878
+ query: { type: 'string', description: '关键词或一句话' },
879
+ limit: { type: 'number', description: '返回几条,默认 6' },
880
+ },
881
+ required: ['query'],
882
+ },
883
+ async execute(args) {
884
+ const hits = search(args?.query ?? '', Number(args?.limit ?? 6) || 6)
885
+ if (hits.length === 0) return `没有找到和「${args?.query ?? ''}」相关的东西。`
886
+ const lines = hits.map((hit, i) => {
887
+ const head = hit.type === 'note'
888
+ ? `${i + 1}. [笔记 ${hit.id}] ${hit.title} · ${hit.kind} · ${hit.updated}`
889
+ : `${i + 1}. [转录 ${hit.updated}] ${hit.title}`
890
+ return `${head}\n ${String(hit.text).replace(/\s+/g, ' ').slice(0, 220)}`
891
+ })
892
+ return lines.join('\n')
893
+ },
894
+ })
895
+
896
+ tools.push({
897
+ name: 'memory_forget',
898
+ description: '删掉一条记错的笔记(id 从 memory_search 的结果里拿)。删了就没了,转录里的原话仍在。',
899
+ parameters: {
900
+ type: 'object',
901
+ properties: { id: { type: 'string', description: '笔记 id' } },
902
+ required: ['id'],
903
+ },
904
+ async execute(args) {
905
+ const id = String(args?.id ?? '').trim()
906
+ if (id === '') throw new Error('memory_forget: id 不能为空')
907
+ const note = findNote(id)
908
+ if (!note) return `没有 id 为 ${id} 的笔记。`
909
+ fs.unlinkSync(note.file)
910
+ rebuildIndex()
911
+ commitNotes(`forget: ${note.id} ${note.title}`)
912
+ return `已删除 ${id}:${note.title}`
913
+ },
914
+ })
915
+
916
+ tools.push({
917
+ name: 'memory_index',
918
+ description: '看当前索引(就是每轮注入的那份),顺便把它按笔记重新生成一遍。',
919
+ parameters: { type: 'object', properties: {} },
920
+ async execute() {
921
+ const { text, notes, listed } = rebuildIndex()
922
+ return `共 ${notes} 条笔记,索引列出 ${listed} 条。\n\n${text}`
923
+ },
924
+ })
925
+
926
+ tools.push({
927
+ name: 'memory_journal',
928
+ description: '读最近几天的转录(双方原话)。做梦时用:从原话里找该记的、该改的。',
929
+ parameters: {
930
+ type: 'object',
931
+ properties: {
932
+ days: { type: 'number', description: '往前几天,默认 2' },
933
+ limit: { type: 'number', description: '最多几条,默认 300' },
934
+ },
935
+ },
936
+ async execute(args) {
937
+ const rows = readJournal(Number(args?.days ?? 2) || 2, Number(args?.limit ?? 300) || 300)
938
+ if (rows.length === 0) return '这几天没有转录。'
939
+ return rows.map((row) => `${row.at} ${row.role === 'assistant' ? '我' : (row.who || '对方')}: ${row.text}`).join('\n')
940
+ },
941
+ })
942
+
943
+ tools.push({
944
+ name: 'memory_append',
945
+ description: '把一句原话补进今天的转录(journal)。宿主会话里的话插件自己会记,QQ 这类渠道的消息不会自动进转录——要留就用它补一行:text 照原话不改写,who 写谁说的,role 给 user 或 assistant,at 可给 ISO 时间。',
946
+ parameters: {
947
+ type: 'object',
948
+ properties: {
949
+ text: { type: 'string', description: '原话本身(别改写、别总结)' },
950
+ who: { type: 'string', description: '谁说的:对方的名字/昵称;我这个方向发的不填' },
951
+ role: { type: 'string', enum: ['user', 'assistant'], description: 'user=对方说的话(默认) assistant=我说的话' },
952
+ at: { type: 'string', description: '可选:这句话的时间(ISO 时间串),不填就是现在' },
953
+ },
954
+ required: ['text'],
955
+ },
956
+ async execute(args) {
957
+ const text = String(args?.text ?? '').trim()
958
+ if (text === '') return '没写正文,什么都没记。'
959
+ appendJournal({ text, who: args?.who, role: args?.role === 'assistant' ? 'assistant' : 'user', at: args?.at })
960
+ const at = args?.at ? new Date(args.at) : new Date()
961
+ const day = `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`
962
+ return `记进转录了(${day}.jsonl):${text.slice(0, 40)}${text.length > 40 ? '…' : ''}`
963
+ },
964
+ })
965
+
966
+ tools.push({
967
+ name: 'memory_dream',
968
+ description: '做梦收尾:把这一轮的整理结果记一笔(改了几条、加了什么),并重建索引。整理本身要你先读过转录和笔记再动手。',
969
+ parameters: {
970
+ type: 'object',
971
+ properties: {
972
+ summary: { type: 'string', description: '这一轮做了什么' },
973
+ touched: { type: 'array', items: { type: 'string' }, description: '动过的笔记 id' },
974
+ },
975
+ },
976
+ async execute(args) {
977
+ const { notes, listed } = rebuildIndex()
978
+ const info = markDream({ summary: String(args?.summary ?? ''), touched: args?.touched ?? [], notes, listed })
979
+ return `做梦完成(第 ${info.runs} 次):笔记 ${notes} 条,索引 ${listed} 条。\n${info.summary}`
980
+ },
981
+ })
982
+
983
+ let registry
984
+ try {
985
+ registry = ctx.get?.('tools') ?? ctx.tools
986
+ } catch {
987
+ registry = ctx.tools
988
+ }
989
+ if (!registry || typeof registry.register !== 'function') {
990
+ logger.warn?.('fishmemory: 没有 tools 服务,跳过注册')
991
+ } else {
992
+ const asText = (value) => [{ type: 'text', text: String(value) }]
993
+ for (const tool of tools) {
994
+ const run = tool.execute
995
+ registry.register({
996
+ ...tool,
997
+ output: tool.output ?? { schema: { type: 'string' }, render: (_args, value) => asText(value) },
998
+ async execute (args, extra) {
999
+ try {
1000
+ return await run(args, extra)
1001
+ } catch (error) {
1002
+ return `出错了:${error instanceof Error ? error.message : String(error)}`
1003
+ }
1004
+ },
1005
+ })
1006
+ }
1007
+ logger.info?.(`fishmemory: ${tools.length} 个工具已注册(笔记 ${listNotes().length} 条)`)
1008
+ }
1009
+
1010
+ // 4) 服务:别的插件想记一笔,不必自己写文件。
1011
+ //
1012
+ // 必须走 reflect.provide 注册成 cordis 的「服务」:ctx.set 只是往上下文里塞个属性,
1013
+ // 别的插件 inject(['fishmemory']) 永远等不到它(service() 恒为 null)。
1014
+ try {
1015
+ const service = {
1016
+ note: (input) => upsertNote(input),
1017
+ journal: (entry) => appendJournal(entry),
1018
+ search: (query, limit) => search(query, limit),
1019
+ index: () => indexText(),
1020
+ dream: (info) => markDream(info),
1021
+ status: () => ({ notes: listNotes().length, dream: readDream() }),
1022
+ }
1023
+ const provide = ctx.reflect?.provide?.bind(ctx.reflect) ?? ctx.provide?.bind(ctx)
1024
+ if (provide) provide('fishmemory', service, () => true)
1025
+ else logger.warn?.('fishmemory: 无法注册服务(没有 reflect.provide),别的插件拿不到我')
1026
+ } catch (error) {
1027
+ logger.warn?.(`fishmemory: 注册服务失败 ${String(error)}`)
1028
+ }
1029
+
1030
+ // 5) 首次起来时如果还没有索引,生成一份。
1031
+ try {
1032
+ if (!fs.existsSync(INDEX)) rebuildIndex()
1033
+ } catch {
1034
+ // ignore
1035
+ }
1036
+ }
1037
+
1038
+ export function mountFishMemory (ctx, config = {}) {
1039
+ __bootLog('apply entered (wrapper)')
1040
+ try {
1041
+ __apply(ctx, config)
1042
+ __bootLog('apply finished')
1043
+ } catch (error) {
1044
+ __bootLog(`apply threw: ${error?.stack ?? error}`)
1045
+ throw error
1046
+ }
1047
+ }
1048
+
1049
+
1050
+
1051
+ // 仅供本地探针使用
1052
+ export const __probe = { recallSection, recallTokens, promptSection, dreamNudge, upsertNote, clearRecallCache: () => { __recallCache = { key: null, text: '' } }, setUser: (t, sid = 'probe') => { __lastUser.set(String(sid), { text: String(t), at: Date.now() }) } }