macro-memory 0.0.0-stage → 0.9.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 (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +384 -2
  3. package/bin/macro-memory.mjs +732 -0
  4. package/docs/CHANGELOG.md +250 -0
  5. package/docs/MAC.md +156 -0
  6. package/docs/images/_architecture.svg +70 -0
  7. package/docs/images/_memory-flow.svg +75 -0
  8. package/docs/images/_token-budget.svg +40 -0
  9. package/docs/images/architecture.png +0 -0
  10. package/docs/images/hero.png +0 -0
  11. package/docs/images/memory-flow.png +0 -0
  12. package/docs/images/src/graph.html +78 -0
  13. package/docs/images/src/hero.html +88 -0
  14. package/docs/images/src/panel.html +63 -0
  15. package/docs/images/src/pipeline.html +97 -0
  16. package/docs/images/token-budget.png +0 -0
  17. package/lib/client.js +3811 -0
  18. package/lib/core/agents-file.js +95 -0
  19. package/lib/core/client.js +313 -0
  20. package/lib/core/compat/dsh-llm.js +78 -0
  21. package/lib/core/config.js +117 -0
  22. package/lib/core/engine.js +456 -0
  23. package/lib/core/fence.js +109 -0
  24. package/lib/core/index.js +102 -0
  25. package/lib/core/migrate.js +70 -0
  26. package/lib/core/mini-host.js +324 -0
  27. package/lib/core/owner.js +347 -0
  28. package/lib/core/paths.js +95 -0
  29. package/lib/core/serve.js +378 -0
  30. package/lib/core/trust.js +173 -0
  31. package/lib/index.js +567 -0
  32. package/lib/macro/brand.js +82 -0
  33. package/lib/macro/bridge.js +158 -0
  34. package/lib/macro/chain.js +206 -0
  35. package/lib/macro/contract.js +471 -0
  36. package/lib/macro/cost.js +164 -0
  37. package/lib/macro/defs/admin.js +528 -0
  38. package/lib/macro/defs/dream.js +24 -0
  39. package/lib/macro/defs/link.js +408 -0
  40. package/lib/macro/defs/project.js +237 -0
  41. package/lib/macro/defs/read.js +160 -0
  42. package/lib/macro/defs/remember.js +411 -0
  43. package/lib/macro/defs/search.js +899 -0
  44. package/lib/macro/defs/update.js +161 -0
  45. package/lib/macro/dreamledger.js +1398 -0
  46. package/lib/macro/facade.js +135 -0
  47. package/lib/macro/fusion.js +188 -0
  48. package/lib/macro/injectledger.js +843 -0
  49. package/lib/macro/linkflow.js +391 -0
  50. package/lib/macro/links.js +448 -0
  51. package/lib/macro/neighbor.js +1083 -0
  52. package/lib/macro/panel.js +96 -0
  53. package/lib/macro/platform.js +134 -0
  54. package/lib/macro/prompt.js +139 -0
  55. package/lib/macro/provenance.js +148 -0
  56. package/lib/macro/render.js +35 -0
  57. package/lib/macro/revisions.js +253 -0
  58. package/lib/macro/shared.js +113 -0
  59. package/lib/macro/shortid.js +114 -0
  60. package/lib/macro/snapshot.js +700 -0
  61. package/lib/macro/spend.js +312 -0
  62. package/lib/macro/store.js +238 -0
  63. package/lib/macro/supersede.js +197 -0
  64. package/lib/macro/tokencost.js +90 -0
  65. package/lib/macro/tools.js +67 -0
  66. package/lib/mcp/server.js +196 -0
  67. package/lib/mcp/stdio.js +151 -0
  68. package/lib/ui/page.js +300 -0
  69. package/lib/ui/server.js +226 -0
  70. package/package.json +56 -4
  71. package/vendor/VENDOR.json +39 -0
  72. package/vendor/cosmokit/LICENSE +21 -0
  73. package/vendor/cosmokit/README.md +30 -0
  74. package/vendor/cosmokit/lib/index.js +418 -0
  75. package/vendor/cosmokit/lib/types/array.d.ts +15 -0
  76. package/vendor/cosmokit/lib/types/array.d.ts.map +1 -0
  77. package/vendor/cosmokit/lib/types/index.d.ts +13 -0
  78. package/vendor/cosmokit/lib/types/index.d.ts.map +1 -0
  79. package/vendor/cosmokit/lib/types/misc.d.ts +41 -0
  80. package/vendor/cosmokit/lib/types/misc.d.ts.map +1 -0
  81. package/vendor/cosmokit/lib/types/string.d.ts +89 -0
  82. package/vendor/cosmokit/lib/types/string.d.ts.map +1 -0
  83. package/vendor/cosmokit/lib/types/time.d.ts +19 -0
  84. package/vendor/cosmokit/lib/types/time.d.ts.map +1 -0
  85. package/vendor/cosmokit/lib/types/types.d.ts +42 -0
  86. package/vendor/cosmokit/lib/types/types.d.ts.map +1 -0
  87. package/vendor/cosmokit/lib/types/volatile.d.ts +40 -0
  88. package/vendor/cosmokit/lib/types/volatile.d.ts.map +1 -0
  89. package/vendor/cosmokit/package.json +32 -0
  90. package/vendor/cosmokit/src/array.ts +42 -0
  91. package/vendor/cosmokit/src/index.ts +12 -0
  92. package/vendor/cosmokit/src/misc.ts +78 -0
  93. package/vendor/cosmokit/src/string.ts +113 -0
  94. package/vendor/cosmokit/src/time.ts +92 -0
  95. package/vendor/cosmokit/src/types.ts +168 -0
  96. package/vendor/cosmokit/src/volatile.ts +86 -0
  97. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  98. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  99. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  100. package/vendor/dsh-memory-nebula/README.md +253 -0
  101. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  102. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  103. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  104. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  105. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  106. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  107. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  108. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  109. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  110. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  111. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  112. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  113. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  114. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  115. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  116. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  117. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  118. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  119. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  120. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  121. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  122. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  123. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  124. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  125. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  126. package/vendor/dsh-memory-nebula/lib/host/recall.js +526 -0
  127. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  128. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  129. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  130. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  131. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  132. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  133. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  134. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  135. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  136. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  137. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  138. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  139. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  140. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  141. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  142. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  143. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  144. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  145. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  146. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  147. package/vendor/dsh-memory-nebula/package.json +87 -0
  148. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  149. package/vendor/meow-memory/LICENSE +21 -0
  150. package/vendor/meow-memory/README.en.md +192 -0
  151. package/vendor/meow-memory/README.md +174 -0
  152. package/vendor/meow-memory/README.pt-br.md +180 -0
  153. package/vendor/meow-memory/cordis.patch.yml +7 -0
  154. package/vendor/meow-memory/lib/client.js +3354 -0
  155. package/vendor/meow-memory/lib/client.js.map +7 -0
  156. package/vendor/meow-memory/lib/index.js +13500 -0
  157. package/vendor/meow-memory/lib/index.js.map +7 -0
  158. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  159. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  160. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  161. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  162. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  163. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  164. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  165. package/vendor/meow-memory/lib/prompts/en/labels.md +104 -0
  166. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  167. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  168. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  169. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  170. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  171. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  172. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  173. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  174. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  175. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  176. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +104 -0
  177. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  178. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  179. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  180. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  181. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  182. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  183. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  184. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  185. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  186. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  187. package/vendor/meow-memory/lib/prompts/zh/labels.md +104 -0
  188. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  189. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  190. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  191. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  192. package/vendor/meow-memory/package.json +64 -0
  193. package/vendor/schemastery/LICENSE +21 -0
  194. package/vendor/schemastery/README.md +393 -0
  195. package/vendor/schemastery/lib/index.cjs +635 -0
  196. package/vendor/schemastery/lib/index.mjs +637 -0
  197. package/vendor/schemastery/lib/types/index.d.ts +211 -0
  198. package/vendor/schemastery/lib/types/index.d.ts.map +1 -0
  199. package/vendor/schemastery/package.json +39 -0
  200. package/vendor/schemastery/src/index.ts +962 -0
@@ -0,0 +1,1083 @@
1
+ // [macro-fusion 0.2.145] 每轮星图邻域注入。
2
+ //
3
+ // 为什么要有这一层:0.2.18 起「每轮自动注入」被整段删掉,改成全靠模型自己调 memory_search。
4
+ // 省了 token,也把记忆系统降级成「模型想起来才查」——主人 2026-11-21 的话:「邻域注入我认为
5
+ // 还是有必要的」。旋钮可以省,功能不能省:这一层把「这一轮的话在星图里连着谁」自动带进来。
6
+ //
7
+ // 三条硬约束(每条都对应一次踩坑或一条既定原则):
8
+ // 1. **变化的内容不许进 system prompt 前缀**(0.2.18 的教训 / prompt 缓存)。
9
+ // 所以走 `agent/pre-step` 把一段**追加到最后一条用户消息后面**,前缀一个字节都不动。
10
+ // 2. **每轮都要跑的路径必须便宜**:只查星图、不查全库、不调模型;有上限(条数 + 字符),
11
+ // 没有邻居就一个字都不注入。宁可这一轮空着,也不许为了「显得有记忆」硬凑。
12
+ // 3. **注入的东西必须自己说明来路**:模型会把注入当成用户说的话。标题里写明「自动带来的、
13
+ // 不是用户说的」,并给出读全文的办法,否则它会把摘要当成原文引用。
14
+ import { graphNodesOf, uidOf } from './fusion.js'
15
+ import { shortIdsOf, shortenId } from './shortid.js'
16
+ import { neighborSeenPath, neighborSuspectPath, neighborFixesPath, pruneNeighborSeen, NEIGHBOR_SEEN_MAX_IDS } from './store.js'
17
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
18
+ import { dirname, join } from 'node:path'
19
+ import * as Meow from '../../vendor/meow-memory/lib/index.js'
20
+
21
+ /** 一次最多带几条邻居。 */
22
+ export const NEIGHBOR_DEFAULT_MAX = 4
23
+ /** 整块最多多少字符(含标题与收尾)。 */
24
+ export const NEIGHBOR_DEFAULT_CHARS = 420
25
+ /** 用户这一轮的话短于这么多字符就不猜(「好」「继续」「嗯」不构成检索意图)。 */
26
+ export const NEIGHBOR_MIN_QUERY = 6
27
+ /** 一个会话最多记多少条「已经带过」,防止长会话把集合撑大。 */
28
+ export const NEIGHBOR_SEEN_MAX = 200
29
+ /** [0.6.43] 扫历史注入消息反推「这个会话已经带过谁」时,最多回看多少条消息。 */
30
+ export const NEIGHBOR_SCAN_MAX = 400
31
+ /**
32
+ * [0.6.43] 与问句**一个词面都不沾**的邻居,一轮最多留几条。
33
+ *
34
+ * 病根:星图沿 1 跳扩散时,`direct ≤ 0.15` 的节点是「靠邻居连上来的」,问句里的词在它的
35
+ * label/preview 里一个都不出现。0.6.42 在真图(3,539 节点 / 16 个真问句)上量过:过 0.35 闸的
36
+ * 44 条里这类占 7 条(15.9%)。它们不是「跨词面发现」,绝大多数是「沾了同一个泛词的邻居」,
37
+ * 每轮塞进上下文就是纯噪声——模型会拿它当本轮相关事实去推理。
38
+ *
39
+ * 但一条都不留也不对:星图的用处正是「问句里没有、但确实相关」的那一跳(跨两层桥就长这样)。
40
+ * 所以留 1 条(宁少不多),其余记进 `offtopic` 计数,让面板/探针看得见「这轮砍了几条」。
41
+ */
42
+ export const NEIGHBOR_OFFTOPIC_KEEP = 1
43
+ /**
44
+ * [0.6.43] 词面闸只对「强度也不够高」的邻居生效,门槛就是这条。
45
+ *
46
+ * 为什么加这条:词面零重合 ≠ 无关。中文换一个说法、跨语言、摘要被截断,都会让二元组完全不沾,
47
+ * 而图上 0.8 的邻居仍然可能是这一轮最该看的那条。所以强度到 0.5 以上就免检,照带;
48
+ * 只有「词面不沾 + 强度也一般」的那批才受 NEIGHBOR_OFFTOPIC_KEEP 配额管。
49
+ */
50
+ export const NEIGHBOR_OFFTOPIC_SCORE = 0.5
51
+ /**
52
+ * 强度低于这个数的邻居不注入(0.6.38)。
53
+ * 为什么要有:星图会沿 1 跳把「沾一个词」的节点也算进来,强度 0.2 的那种基本是噪声——
54
+ * 每轮带 4 条噪声进上下文,比不带更糟:模型会拿它当本轮相关事实去推理。
55
+ * 判定用「有 score 才比」:老回执/无强度字段的节点照旧带,不因为在改进程里丢功能。
56
+ */
57
+ export const NEIGHBOR_MIN_SCORE = 0.35
58
+ /**
59
+ * 尾部给「觉得无关就断掉」的指导句预留的字符数。
60
+ * 这条指导是 0.6.38 的重点:注入的邻居如果是错的,模型以前只能将错就错;
61
+ * 现在要能在同一轮里用 nebula_link(action="path") 看路径、用 action="mute" 断掉那一跳。
62
+ * 但它不能挤掉真正的条目——所以先扣预留,再排版。
63
+ *
64
+ * [0.6.44] 从 150 提到 170:尾注从「两步(先 path 再 mute)」改成「一步(直接 mute,带现成 id)」,
65
+ * 多出来的十几个字换的是模型真的会动手——0.6.38 那版要它自己拼两个 id,实际很少被调用。
66
+ */
67
+ // [0.6.61] 尾部预留跟着尾注一起瘦:0.6.44 的尾注 160 字,现在常态 120 字 / 单条短形态 91 字,
68
+ // 预留 170 等于白留 50 字——那 50 字本该拿来装邻居条目。压到 130:最长那条(带现成 id 的
69
+ // flagged 尾注)仍放得下,装不下时 `picked` 本来就退回 baseTail,不会把整块挤成只有尾注。
70
+ export const NEIGHBOR_TAIL_RESERVE = 130
71
+ /**
72
+ * [0.6.44] 「这轮不沾词」的行尾标记。
73
+ * 打上标记的那条来自词面闸的配额(`NEIGHBOR_OFFTOPIC_KEEP`),是最可能无关的一条;
74
+ * 标出来 + 尾注给现成的 mute 命令,模型才可能在同轮里顺手把错边断掉,而不是将错就错。
75
+ */
76
+ export const NEIGHBOR_UNRELATED_MARK = ' · 未沾词'
77
+ /**
78
+ * [0.6.54] 同一跳错边被标到第几轮就**暂时不再带**(0 = 关,退回 0.6.53 的「标了照带」)。
79
+ *
80
+ * 病根:0.6.44 给了模型现成的 `nebula_link(action="mute")` 命令,但大多数轮次里模型不会动手
81
+ * (这很正常——它正忙着回答用户,顺手修图是次要任务)。于是同一跳错边在没有被断掉之前,
82
+ * 每轮都重新被标一次「未沾词」、再带 30~60 字进上下文,用户付的是真金白银的 token。
83
+ *
84
+ * 处方不是「标一次就断」——那会把只是换了个说法的正确邻接一起掐死(0.6.43 的教训:
85
+ * 词面零重合 ≠ 无关)。改成「连标 N 轮 → 先停带、账留着、命令照给」:噪声立刻止血,
86
+ * 图一个字节都没改,模型什么时候想修还是那一条命令。N=3 是「同一个话题来回三轮」的长度,
87
+ * 也是 0.6.49 给命中注入定的窗口(同一个量级,用户不必记两套数字)。
88
+ */
89
+ export const NEIGHBOR_SUSPECT_TURNS = 3
90
+ /** [0.6.54] 错边账最多记多少跳(超过就丢最久没再被标的那条),防长会话把文件撑大。 */
91
+ export const NEIGHBOR_SUSPECT_MAX = 120
92
+ /**
93
+ * [0.6.54] 暂时不带的那一跳,隔多少轮不再被标就自动放回。
94
+ *
95
+ * 没有这条,一次误标就是永久降级:话题过去之后再问到它,它还是被压着。
96
+ * 与 `NEIGHBOR_SUSPECT_TURNS` 同值——「连标三轮停带」和「三轮没再标放回」是同一个尺度。
97
+ */
98
+ export const NEIGHBOR_SUSPECT_DECAY = 3
99
+ /**
100
+ * [0.6.66] 修过账最多留几跳:摘掉的边是「一次性事件」,一个工作区攒到几十条就够回看了。
101
+ *
102
+ * 超过就丢最久以前那条——回看的意义在最近几周,不是全部历史。
103
+ */
104
+ export const NEIGHBOR_FIX_MAX = 60
105
+ /**
106
+ * [0.6.66] 修过账留多久(天):与邻域账本的清理尺度对齐,超过就当它已经从「最近」里退场。
107
+ *
108
+ * 星图那边的 mute 是永久的,账只是解释用的——留着太久的账既没人看,也容易和现状对不上。
109
+ */
110
+ export const NEIGHBOR_FIX_KEEP_DAYS = 90
111
+ /**
112
+ * [0.6.55] 一轮里「长期记忆」最多注入多少字的默认值(0 = 不限,逐位等同 0.6.54)。
113
+ *
114
+ * 为什么要有这条:`injectMaxChars` 只管命中注入那一段,邻域块另有 `neighborChars`,
115
+ * 会话累计另有 `injectSessionBudget`——三个上限各管一段,用户想「每轮最多 600 字」时
116
+ * 没有任何一个数能直接对上。主人 2026-11-25 的原话是「每次长期记忆注入的时候要有的限制」,
117
+ * 所以这一层做的是**跨层的一轮总账**:命中注入先花(它自己的上限照旧管它),邻域只能花
118
+ * 剩下的。优先级写死不做推断——pre-step 里邻域包在 next() 之后,命中注入永远先落进 messages。
119
+ */
120
+ export const NEIGHBOR_TURN_MAX_CHARS = 0
121
+ /**
122
+ * [0.6.55] 一轮总上限的余额少于这么多字,就整块邻域都不带。
123
+ *
124
+ * 为什么不是「有多少带多少」:邻域块的固定开销是标题(约 40 字)+ 尾注(mute 指引约 100 字),
125
+ * 余下不够 140 字时,硬塞的结果是「一条邻居 + 半句尾注」——模型看到一条没来路的条目,
126
+ * 却拿不到「怎么断掉」的办法,比这轮空着更糟。
127
+ */
128
+ export const NEIGHBOR_TURN_MIN_BLOCK = 140
129
+ /**
130
+ * [0.6.62] 「边缘单条」的强度线:一块里只活下来一条邻居、且它的强度低于这个值,就叫边缘单条。
131
+ *
132
+ * 为什么单挑这一档:`bench37` 量了真库 17 条操作型话术——**11 条**的邻域块只带 1 条,
133
+ * 强度几乎全落在 0.36–0.54(0.38 / 0.36 / 0.39 / 0.38 / 0.37 / 0.44 / 0.47 …),且 `weak=7`
134
+ * (recall 给 8 条,7 条被强度闸或词面闸刷掉)。这正是主人说的「每轮几乎都要注入」的残余:
135
+ * 一块 193 字,只换来一句「沾了一个二元组」的横向线索。强度上到 0.68 的那种(`suspect 账几天清一次`)
136
+ * 是真线索,不能一起降频——所以线画在 0.55,不是「单条就降」。
137
+ */
138
+ export const NEIGHBOR_SOLO_EDGE_SCORE = 0.55
139
+
140
+ /**
141
+ * [0.6.50] 邻域注入的账本行:往 meow 的 `dream-debug.log` 追加一行(与引擎同一个文件、同一种格式)。
142
+ *
143
+ * 为什么要补这一笔:0.6.46 给命中注入做了面板(`memory_admin(action="inject")`),可邻域这一层
144
+ * 从头到尾**一行账都不写**——用户在面板上只能看到「命中注入了多少字」,看不到「星图邻域每轮带了几条、
145
+ * 砍了几条不沾词的、被跨层去重刷掉几条」。同一份上下文里花掉的字,一半来自邻域,账上却是 0。
146
+ *
147
+ * 三条规矩(与引擎的 appendDreamLog 一致):
148
+ * 1. **写不进去不许打断注入**:账本是解释用的,不是功能的一部分,失败静默;
149
+ * 2. **没有 workspace 就不写**:探针 / 单测没有真会话时不该在磁盘上留账;
150
+ * 3. **行格式与引擎同构**:`[ISO] <kind> pid= … k=v`,这样面板一个解析器就能读两种行。
151
+ */
152
+ export function appendNeighborLog(workspace, dir, kind, rest) {
153
+ const ws = String(workspace ?? '')
154
+ if (ws === '') return
155
+ const file = join(ws, String(dir || '.dsh-meow'), 'dream-debug.log')
156
+ const line = `[${new Date().toISOString()}] ${kind} pid=${process.pid}${rest === '' ? '' : ` ${rest}`}`
157
+ try {
158
+ mkdirSync(dirname(file), { recursive: true })
159
+ appendFileSync(file, `${line}\n`, 'utf8')
160
+ } catch {
161
+ // 只影响「面板看不看得见」,不影响这一轮注不注入。
162
+ }
163
+ }
164
+
165
+ /**
166
+ * [0.6.44] 从星图回执的 `why` 里抠「上游来源 id」。
167
+ *
168
+ * recall 的扩散档写的是「经由「<来源标签>」(<来源短 id 8 位>)的<type>关联扩散而来」;
169
+ * 括号里那 8 位就是错的可能是哪一跳的起点,也是 `nebula_link(action="mute", a, b)` 的 `a`。
170
+ * 直接命中档没有上游边(why 里没有括号 id),返回空串——那种条目不谈断边。
171
+ * @param {string} why
172
+ * @returns {string} 小写 8–12 位 id;没有就空串。
173
+ */
174
+ export function neighborSourceIdOf(why) {
175
+ const m = /[((]([0-9a-z]{8,12})[))]/i.exec(String(why ?? ''))
176
+ return m === null ? '' : m[1].toLowerCase()
177
+ }
178
+ /**
179
+ * [0.6.54] 读这个工作区的错边账。
180
+ *
181
+ * 形状:`{ round, edges: { "a|b": { n, first, last } } }`,`n` 是「被标未沾词」的累计轮数,
182
+ * `last` 是最后一次被标的轮次号(工作区自己的轮次,不是全局)。读不动 / 坏 JSON / 没账
183
+ * 一律当空账——这条路径每轮都跑,绝不能因为账坏了挡住注入。
184
+ * @param {string} workspace
185
+ * @returns {{round: number, edges: Record<string, {n: number, first: number, last: number}>}}
186
+ */
187
+ export function readSuspectLedger(workspace) {
188
+ const out = { round: 0, edges: {} }
189
+ const ws = String(workspace ?? '')
190
+ if (ws === '') return out
191
+ try {
192
+ const parsed = JSON.parse(readFileSync(neighborSuspectPath(ws), 'utf8'))
193
+ const round = Number.isFinite(parsed?.round) ? Math.max(0, Math.floor(parsed.round)) : 0
194
+ const edges = {}
195
+ const src = parsed?.edges
196
+ if (src !== null && typeof src === 'object') {
197
+ for (const [key, v] of Object.entries(src)) {
198
+ const n = Number.isFinite(v?.n) ? Math.max(0, Math.floor(v.n)) : 0
199
+ const last = Number.isFinite(v?.last) ? Math.max(0, Math.floor(v.last)) : 0
200
+ const first = Number.isFinite(v?.first) ? Math.max(0, Math.floor(v.first)) : last
201
+ if (n > 0 && key.includes('|')) edges[key] = { n, first, last }
202
+ }
203
+ }
204
+ return { round, edges }
205
+ } catch {
206
+ return out
207
+ }
208
+ }
209
+
210
+ /** 写账:失败只影响「下一轮还记不记得」,不影响这一轮注不注入,所以静默。 */
211
+ function writeSuspectLedger(workspace, ledger) {
212
+ const ws = String(workspace ?? '')
213
+ if (ws === '') return
214
+ try {
215
+ const file = neighborSuspectPath(ws)
216
+ mkdirSync(dirname(file), { recursive: true })
217
+ writeFileSync(file, JSON.stringify({ v: 1, at: new Date().toISOString(), round: ledger.round, edges: ledger.edges }), 'utf8')
218
+ } catch {
219
+ // 同上:账是解释用的,不是功能的一部分。
220
+ }
221
+ }
222
+
223
+ /**
224
+ * [0.6.54] 销账:模型真把这一跳 mute 掉了,错边账里那条就该消失。
225
+ *
226
+ * 匹配用 8 位前缀双向 `startsWith`:账里存的是星图回执给的短 id,而 `nebula_link` 拿到的是
227
+ * 解析后的完整 id;两端口径不同,只有前缀能对上。返回清掉几条,调用方据此决定要不要记账。
228
+ * @param {string} workspace
229
+ * @param {string} a 上游来源 id(任意长度,≥8 位才谈得上匹配)
230
+ * @param {string} b 邻居 id
231
+ * @returns {number} 清掉几条
232
+ */
233
+ export function clearSuspectEdge(workspace, a, b) {
234
+ const ws = String(workspace ?? '')
235
+ if (ws === '') return 0
236
+ const la = String(a ?? '').toLowerCase()
237
+ const lb = String(b ?? '').toLowerCase()
238
+ if (la.length < 8 || lb.length < 8) return 0
239
+ const ledger = readSuspectLedger(ws)
240
+ let cleared = 0
241
+ for (const key of Object.keys(ledger.edges)) {
242
+ const [ka, kb] = key.split('|')
243
+ const hit = (ka.startsWith(la.slice(0, 8)) || la.startsWith(ka.slice(0, 8))) && (kb.startsWith(lb.slice(0, 8)) || lb.startsWith(kb.slice(0, 8)))
244
+ if (hit) {
245
+ delete ledger.edges[key]
246
+ cleared += 1
247
+ }
248
+ }
249
+ if (cleared > 0) writeSuspectLedger(ws, ledger)
250
+ return cleared
251
+ }
252
+
253
+ /**
254
+ * [0.6.66] 读这个工作区的修过账(摘掉过哪些跳)。
255
+ *
256
+ * 形状:`{ at, fixes: { "a8|b8": { a, b, at, round, cleared, times, note } } }`。
257
+ * 与错边账一样,坏文件 / 没账一律当空账——它是解释用的,不该挡住任何一枪。
258
+ * @param {string} workspace
259
+ * @returns {{at: string, fixes: Record<string, {a: string, b: string, at: string, round: number, cleared: number, times: number, note: string}>}}
260
+ */
261
+ export function readNeighborFixLedger(workspace) {
262
+ const out = { at: '', fixes: {} }
263
+ const ws = String(workspace ?? '')
264
+ if (ws === '') return out
265
+ try {
266
+ const parsed = JSON.parse(readFileSync(neighborFixesPath(ws), 'utf8'))
267
+ out.at = typeof parsed?.at === 'string' ? parsed.at : ''
268
+ const src = parsed?.fixes
269
+ if (src !== null && typeof src === 'object') {
270
+ for (const [key, v] of Object.entries(src)) {
271
+ const a = String(v?.a ?? '').toLowerCase()
272
+ const b = String(v?.b ?? '').toLowerCase()
273
+ if (a === '' || b === '' || !key.includes('|')) continue
274
+ out.fixes[key] = {
275
+ a,
276
+ b,
277
+ at: typeof v?.at === 'string' ? v.at : '',
278
+ round: Number.isFinite(v?.round) ? Math.max(0, Math.floor(v.round)) : 0,
279
+ cleared: Number.isFinite(v?.cleared) ? Math.max(0, Math.floor(v.cleared)) : 0,
280
+ times: Number.isFinite(v?.times) ? Math.max(1, Math.floor(v.times)) : 1,
281
+ note: typeof v?.note === 'string' ? v.note.slice(0, 240) : '',
282
+ }
283
+ }
284
+ }
285
+ return out
286
+ } catch {
287
+ return out
288
+ }
289
+ }
290
+
291
+ /** 写修过账:裁剪(条数 / 天数)后落盘,失败静默(面板少一条历史,不影响任何功能)。 */
292
+ function writeNeighborFixLedger(workspace, ledger) {
293
+ const ws = String(workspace ?? '')
294
+ if (ws === '') return
295
+ try {
296
+ const file = neighborFixesPath(ws)
297
+ mkdirSync(dirname(file), { recursive: true })
298
+ const now = Date.now()
299
+ const rows = Object.entries(ledger.fixes)
300
+ const kept = []
301
+ for (const [key, v] of rows) {
302
+ const t = Date.parse(v.at)
303
+ if (Number.isFinite(t) && now - t > NEIGHBOR_FIX_KEEP_DAYS * 86400000) continue
304
+ kept.push([key, v])
305
+ }
306
+ kept.sort((x, y) => String(y[1].at).localeCompare(String(x[1].at)))
307
+ const fixes = {}
308
+ for (const [key, v] of kept.slice(0, NEIGHBOR_FIX_MAX)) fixes[key] = v
309
+ writeFileSync(file, JSON.stringify({ v: 1, at: new Date().toISOString(), fixes }), 'utf8')
310
+ } catch {
311
+ // 同上:账是解释用的,不是功能的一部分。
312
+ }
313
+ }
314
+
315
+ /**
316
+ * [0.6.66] 记一笔「这跳被我摘掉了」——**成功摘掉就该记**,不管它在观察账里有没有到压住的门槛。
317
+ *
318
+ * 为什么不是「只有真清掉账才记」:模型可能直接从邻域尾注给的那条命令动手(那时账里 `n` 也许才 1),
319
+ * 也可能隔了很久才回头处理一条老账。只要是 mute 成功,本地就该留下「谁、什么时候、为什么」,
320
+ * 否则面板永远念不出「已经修过什么」。
321
+ * @param {string} workspace
322
+ * @param {{a?: string, b?: string, note?: string, round?: number, cleared?: number, now?: Date}} [o]
323
+ * @returns {boolean} 真写进去了没有
324
+ */
325
+ export function recordNeighborFix(workspace, o = {}) {
326
+ const ws = String(workspace ?? '')
327
+ if (ws === '') return false
328
+ const a = String(o.a ?? '').toLowerCase()
329
+ const b = String(o.b ?? '').toLowerCase()
330
+ if (a.length < 8 || b.length < 8) return false
331
+ const key = `${a.slice(0, 8)}|${b.slice(0, 8)}`
332
+ const at = (o.now instanceof Date ? o.now : new Date()).toISOString()
333
+ const ledger = readNeighborFixLedger(ws)
334
+ const old = ledger.fixes[key]
335
+ ledger.fixes[key] = {
336
+ // 只留 8 位:与观察账、与邻域注入里的 id 口径一致;0.6.64 起 8 位短 id 就能喂给 unmute。
337
+ a: a.slice(0, 8),
338
+ b: b.slice(0, 8),
339
+ at,
340
+ round: Number.isFinite(o.round) ? Math.max(0, Math.floor(o.round)) : (old?.round ?? 0),
341
+ cleared: Number.isFinite(o.cleared) ? Math.max(0, Math.floor(o.cleared)) : (old?.cleared ?? 0),
342
+ times: (old?.times ?? 0) + 1,
343
+ note: typeof o.note === 'string' && o.note.trim() !== '' ? o.note.trim().slice(0, 240) : (old?.note ?? ''),
344
+ }
345
+ writeNeighborFixLedger(ws, ledger)
346
+ return true
347
+ }
348
+
349
+ /** 修过账按时间倒序排好(面板用),最多给 limit 条。 */
350
+ export function readNeighborFixes(workspace, limit = 8) {
351
+ const ledger = readNeighborFixLedger(workspace)
352
+ const lim = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : 8
353
+ const rows = Object.values(ledger.fixes).sort((x, y) => String(y.at).localeCompare(String(x.at)))
354
+ return rows.slice(0, lim)
355
+ }
356
+
357
+ /**
358
+ * [0.6.66] 反悔之后把那一笔撤掉:unmute 一打,这条边又回到图里了。
359
+ *
360
+ * 为什么要撤而不是留成「已撤销」:面板那句写的是「星图那边已经断了」——留着一条实际连着的边,
361
+ * 下一个会话就会照着一份**过期的**账,把一条活边当死边处理(比如在解释里说「这条已经断过」)。
362
+ * 反悔本身也不需要留痕:图的状态就是唯一事实。
363
+ * @param {string} workspace
364
+ * @param {string} a
365
+ * @param {string} b
366
+ * @returns {boolean} 原来有没有这一笔
367
+ */
368
+ export function dropNeighborFix(workspace, a, b) {
369
+ const ws = String(workspace ?? '')
370
+ if (ws === '') return false
371
+ const key = `${String(a ?? '').toLowerCase().slice(0, 8)}|${String(b ?? '').toLowerCase().slice(0, 8)}`
372
+ const ledger = readNeighborFixLedger(ws)
373
+ if (ledger.fixes[key] === undefined) return false
374
+ delete ledger.fixes[key]
375
+ writeNeighborFixLedger(ws, ledger)
376
+ return true
377
+ }
378
+
379
+ /**
380
+ * [0.6.65] 错边账面板:把「哪些跳因为连标无关被压住了」摆到 memory_admin 上。
381
+ *
382
+ * 0.6.54 起账已经在写、注入侧在压,但读口只有 debug 日志里的一行行 ——
383
+ * 模型想「把上次那几跳一次修完」没有地方看,只能等它再次被标。
384
+ * 面板只念账(不自己算轮次),筛选口径与注入侧逐字一致:
385
+ * `n >= suspectTurns` 且 `round - last <= NEIGHBOR_SUSPECT_DECAY`——两边各写一套就会
386
+ * 出现「面板说还压着、注入其实放回去了」。
387
+ * @param {{workspace?: string, limit?: number, turns?: number}} [o]
388
+ * @returns {{body: string, scope: string}}
389
+ */
390
+ export function readSuspectPanel({ workspace, limit = 12, turns } = {}) {
391
+ const ws = String(workspace ?? '')
392
+ const gate = Number.isFinite(turns) ? Math.max(0, Math.floor(turns)) : NEIGHBOR_SUSPECT_TURNS
393
+ const lim = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 12
394
+ if (ws === '') {
395
+ return { body: '错边账按工作区分开记,这次拿不到工作区——不是「账是空的」。', scope: '' }
396
+ }
397
+ // [0.6.66] 修过账:销账之后那一跳从观察账里消失了,不念这一份就等于「修过也看不出来」。
398
+ const fixTotal = Object.keys(readNeighborFixLedger(ws).fixes).length
399
+ const fixRows = readNeighborFixes(ws, Math.min(lim, 6))
400
+ const fixLines = []
401
+ if (fixRows.length > 0) {
402
+ fixLines.push(`最近摘过 ${fixTotal} 跳(星图那边已经断了,重建也不会再自动连回来):`)
403
+ for (const f of fixRows) {
404
+ const bits = []
405
+ if (f.round > 0) bits.push(`第 ${f.round} 轮摘的`)
406
+ const day = f.at.slice(0, 10)
407
+ if (day !== '') bits.push(day)
408
+ if (f.times > 1) bits.push(`摘过 ${f.times} 次`)
409
+ const why = f.note === '' ? '' : `;理由:${oneLine(f.note, 40)}`
410
+ fixLines.push(`- ${f.a} ↔ ${f.b}(${bits.join(',')}${why})`)
411
+ }
412
+ if (fixTotal > fixRows.length) fixLines.push(`- …还有 ${fixTotal - fixRows.length} 跳更早摘的没列`)
413
+ fixLines.push(`摘错了想反悔:memory_link(action="unmute", a="${fixRows[0].a}", b="${fixRows[0].b}")(一次一条,id 照抄)。`)
414
+ }
415
+ const fixScope = fixTotal > 0 ? ` · 修过 ${fixTotal} 跳` : ''
416
+ const ledger = readSuspectLedger(ws)
417
+ const rows = []
418
+ for (const [key, edge] of Object.entries(ledger.edges)) {
419
+ const [a, b] = key.split('|')
420
+ if (!a || !b) continue
421
+ const withheld = edge.n >= gate && ledger.round - edge.last <= NEIGHBOR_SUSPECT_DECAY
422
+ rows.push({ a, b, n: edge.n, last: edge.last, first: edge.first, withheld })
423
+ }
424
+ rows.sort((x, y) => y.n - x.n || y.last - x.last || x.a.localeCompare(y.a))
425
+ const held = rows.filter((r) => r.withheld)
426
+ if (rows.length === 0) {
427
+ return {
428
+ body: [
429
+ `错边账是空的:目前还没有哪条自动关联被判过「未沾词」${gate > 0 ? `(连标 ${gate} 轮才压住)` : ''}。`,
430
+ ...fixLines,
431
+ ].join('\n'),
432
+ scope: `账上 0 跳 · 第 ${ledger.round} 轮${fixScope}`,
433
+ }
434
+ }
435
+ const shown = held.slice(0, lim)
436
+ const lines = []
437
+ if (held.length === 0) {
438
+ lines.push(`现在没有压着的跳(账上还留着 ${rows.length} 跳观察记录,都没到连标 ${gate} 轮,或已经三轮没再被标)。`)
439
+ } else {
440
+ lines.push(`现在压着 ${held.length} 跳(连标 ${gate} 轮以上、且最近还在被标):`)
441
+ for (const r of shown) lines.push(`- ${r.a} ↔ ${r.b}(连标 ${r.n} 轮,最近第 ${r.last} 轮)`)
442
+ if (held.length > shown.length) lines.push(`- …还有 ${held.length - shown.length} 跳没列(limit 调大一点)`)
443
+ const pairs = held.slice(0, 8)
444
+ lines.push(
445
+ `一次摘掉:memory_link(action="mute", pairs=[${pairs.map((r) => `["${r.a}","${r.b}"]`).join(',')}])`,
446
+ )
447
+ lines.push('确认确实无关再摘;这一轮只是用不上就别动——断的是错边,不是记忆。')
448
+ }
449
+ return {
450
+ body: [...lines, ...fixLines].join('\n'),
451
+ scope: `压着 ${held.length} 跳 / 账上 ${rows.length} 跳 · 第 ${ledger.round} 轮${fixScope}`,
452
+ }
453
+ }
454
+
455
+
456
+ /** 星图那一侧的工具名(走 bridge,不直接碰 vendor)。 */
457
+ export const NEIGHBOR_TOOL = 'nebula_recall'
458
+ /** 注入消息的来源标记:宿主按它折叠成一行「上下文」,也让它与用户消息区分开。 */
459
+ export const NEIGHBOR_SOURCE_KIND = 'macro-memory:neighbor'
460
+
461
+ /**
462
+ * 取这一轮「用户自己说的话」:最后一条 `source.kind === 'user'` 的文本块。
463
+ * 注入消息、工具结果、别的插件的通知都不算——否则会拿自己上一轮的注入去检索。
464
+ * @param {readonly {source?: {kind?: string}, content?: readonly {type: string, text?: string}[]}[]} messages
465
+ * @returns {string} 去掉首尾空白的文本;没有就空串。
466
+ */
467
+ export function neighborQueryOf(messages) {
468
+ const list = Array.isArray(messages) ? messages : []
469
+ for (let i = list.length - 1; i >= 0; i -= 1) {
470
+ const m = list[i]
471
+ if (m === null || typeof m !== 'object') continue
472
+ if (m.source?.kind !== 'user') continue
473
+ const blocks = Array.isArray(m.content) ? m.content : []
474
+ const text = blocks
475
+ .filter((b) => b !== null && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
476
+ .map((b) => b.text)
477
+ .join(' ')
478
+ .trim()
479
+ return text
480
+ }
481
+ return ''
482
+ }
483
+
484
+ /** 标签里不许出现换行:一行一条,读者才能一眼数清带了几条。 */
485
+ function oneLine(text, max = 60) {
486
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
487
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat
488
+ }
489
+
490
+ /**
491
+ * [0.6.43] 词面指纹:汉字取二元组、拉丁取「≥2 字符的词」。
492
+ *
493
+ * 为什么不用单字:中文里「的 / 是 / 了 / 一」几乎出现在每条记忆里,按单字算重叠等于恒真。
494
+ * 为什么不用分词器:这一层每轮都跑,而且只回答一个是非问题(这条和问句沾不沾词),
495
+ * 二元组是这一类判定里最便宜且够用的做法;真需要质量的分词在上游检索层已经做过了。
496
+ *
497
+ * @param {string} text
498
+ * @returns {Set<string>}
499
+ */
500
+ export function neighborTokens(text) {
501
+ const out = new Set()
502
+ const s = String(text ?? '').toLowerCase()
503
+ for (const run of s.match(/[\u3400-\u9fff]+/g) ?? []) {
504
+ const cps = [...run]
505
+ if (cps.length === 1) out.add(run)
506
+ else for (let i = 0; i + 1 < cps.length; i += 1) out.add(cps[i] + cps[i + 1])
507
+ }
508
+ for (const word of s.match(/[a-z0-9][a-z0-9_.-]+/g) ?? []) out.add(word)
509
+ return out
510
+ }
511
+
512
+ /** 注入块里的 id 标记:`[0mwq3aa9]` 或 `[0mwm83y43-429d…]`(8–9 位 + 可选长尾)。 */
513
+ const ID_TAG = /\[([0-9a-z]{8,9}(?:-[0-9a-f]{16,32})?)\]/gi
514
+ /** meow 侧注入消息的 `source.kind`:现行值 + 两个历史值(跨版本续读取历史时要认)。 */
515
+ const MEOW_KINDS = new Set(['plugin:macro-memory', 'macro-memory', 'meow-memory'])
516
+
517
+ /** [0.6.43] 这条消息是不是 meow 的记忆注入(含最老的 `{kind:'plugin', plugin:'meow-memory'}` 写法)。 */
518
+ function isMemorySource(source) {
519
+ if (source === null || typeof source !== 'object') return false
520
+ const kind = String(source.kind ?? '')
521
+ if (kind === NEIGHBOR_SOURCE_KIND || MEOW_KINDS.has(kind)) return true
522
+ return kind === 'plugin' && String(source.plugin ?? '') === 'meow-memory'
523
+ }
524
+
525
+ /**
526
+ * [0.6.43] 从会话历史里反推「本会话已经注入过哪些条」——跨插件的去重依据。
527
+ *
528
+ * 两条来源都认:
529
+ * ① meow 的命中注入(`source.kind === 'plugin:macro-memory'`,条目头里带完整 id);
530
+ * ② 我们自己的邻域注入(`source.kind === 'macro-memory:neighbor'`,条目里带前 8 位)。
531
+ *
532
+ * 为什么读历史而不读 meow 的账本文件:那是 `vendor/meow-memory` 的私有格式(`.dsh-meow/sessions-*`),
533
+ * 跨插件 import 它的内部函数等于把两边的版本绑死;而「历史里出现过」本身就是最直接的事实,
534
+ * 而且它顺带把「宿主重启后续会话」这个洞一起补了——重启后历史还在,账本却已经清零。
535
+ *
536
+ * @param {readonly any[]} messages
537
+ * @returns {Set<string>} 小写 id(可能是长形式,比对时按前缀认)
538
+ */
539
+ export function injectedIdsOf(messages) {
540
+ const out = new Set()
541
+ const list = Array.isArray(messages) ? messages : []
542
+ const start = Math.max(0, list.length - NEIGHBOR_SCAN_MAX)
543
+ for (let i = start; i < list.length; i += 1) {
544
+ const m = list[i]
545
+ if (m === null || typeof m !== 'object') continue
546
+ if (!isMemorySource(m.source)) continue
547
+ const blocks = Array.isArray(m.content) ? m.content : []
548
+ const text = blocks
549
+ .filter((b) => b !== null && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
550
+ .map((b) => b.text)
551
+ .join('\n')
552
+ for (const hit of text.matchAll(ID_TAG)) out.add(hit[1].toLowerCase())
553
+ if (out.size >= NEIGHBOR_SEEN_MAX) break
554
+ }
555
+ return out
556
+ }
557
+
558
+ /**
559
+ * [0.6.55] 这一轮**已经**注入了多少字(跨插件,只算本轮)。
560
+ *
561
+ * 口径:从最后一条用户消息往后数,凡是记忆注入消息(meow 的命中/重放、本层邻域)的
562
+ * 文本长度都加起来。为什么从用户消息往后数、而不是数整段历史:一轮总上限问的是
563
+ * 「这一轮花多少」,把上一轮的注入算进来,上限在第二轮就会永远顶满。
564
+ *
565
+ * 读的是**上下文里的事实**,不是账本文件:账本是私有格式、跨版本会变,而「已经进了
566
+ * 上下文的那几块」本身就是最直接的证据(0.6.43 跨层去重用的也是这条路)。
567
+ *
568
+ * @param {readonly any[]} messages
569
+ * @returns {number} 字符数;这一轮还没有注入就是 0。
570
+ */
571
+ export function injectedCharsOf(messages) {
572
+ const list = Array.isArray(messages) ? messages : []
573
+ let start = 0
574
+ for (let i = list.length - 1; i >= 0; i -= 1) {
575
+ const m = list[i]
576
+ if (m !== null && typeof m === 'object' && m.source?.kind === 'user') {
577
+ start = i + 1
578
+ break
579
+ }
580
+ }
581
+ let total = 0
582
+ for (let i = start; i < list.length; i += 1) {
583
+ const m = list[i]
584
+ if (m === null || typeof m !== 'object') continue
585
+ if (!isMemorySource(m.source)) continue
586
+ const blocks = Array.isArray(m.content) ? m.content : []
587
+ for (const b of blocks) {
588
+ if (b !== null && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string') total += b.text.length
589
+ }
590
+ }
591
+ return total
592
+ }
593
+
594
+ /** 两个 id 是不是同一条:相等,或 8 位前缀一致(星图给 8 位、meow 命中给长形式)。 */
595
+ function sameId(a, b) {
596
+ if (a === b) return true
597
+ if (a.length < 8 || b.length < 8) return false
598
+ return a.slice(0, 8) === b.slice(0, 8)
599
+ }
600
+
601
+ /**
602
+ * 把星图回执渲染成注入块。纯函数:探针直接喂文本就能验文案与上限。
603
+ *
604
+ * 形如:
605
+ * 【星图邻域·不是用户原话】这轮连着:
606
+ * - [fact] [0mwq3aa9] 0.2.144 的交付态…(强度 0.82)
607
+ * memory_read("0mwq3aa9") 看全文;明显无关就 nebula_link(action="mute", …),不用问用户。
608
+ *
609
+ * @param {string} recallText 星图工具(nebula_recall)的回执原文。
610
+ * @param {{max?: number, chars?: number, skip?: Iterable<string>, minScore?: number, query?: string}} [opts]
611
+ * `skip` 是这个会话已经带过的 id(裸 id、长 id、带工作区前缀都认;按 8 位前缀比)。
612
+ * `query` 给了就启用词面闸(0.6.43):与问句一个二元组都不沾的条目一轮最多留
613
+ * `NEIGHBOR_OFFTOPIC_KEEP` 条。不给就完全按旧口径(探针与老调用方不受影响)。
614
+ * @param {(id: string) => string} [opts.shorten] 0.6.64:id 的显示形式(缺省取其前 8 位)。
615
+ * 上层传进来的就是「最短唯一前缀」——真库 1,121 条里 8 位前缀撞 13 组,撞车的短 id 指向两条,
616
+ * 模型拿它去 read / update / mute 会撞歧义拒绝,而读起来像「那条记忆不见了」。
617
+ * @returns {{text: string, ids: string[], weak: number, offtopic: number, skipped: number, flagged: number} | null}
618
+ * `offtopic` 是被词面闸砍掉的条数,`skipped` 是被跨层去重挡掉的条数,`flagged` 是「未沾词但靠配额留下」的条数
619
+ * (这些行带 `NEIGHBOR_UNRELATED_MARK`,也就是模型最该复核的那几条)。一条都没有时返回 null。
620
+ */
621
+ export function neighborBlockOf(recallText, opts = {}) {
622
+ const max = Number.isFinite(opts.max) ? Math.max(0, Math.trunc(opts.max)) : NEIGHBOR_DEFAULT_MAX
623
+ const chars = Number.isFinite(opts.chars) ? Math.max(80, Math.trunc(opts.chars)) : NEIGHBOR_DEFAULT_CHARS
624
+ const minScore = Number.isFinite(opts.minScore) ? opts.minScore : NEIGHBOR_MIN_SCORE
625
+ if (max === 0) return null
626
+ // [0.6.54] 连标 N 轮、暂时不带的那些跳(按邻居短 id 认)。空集合 = 这一层关着。
627
+ const suspectTurns = Number.isFinite(opts.suspectTurns) ? Math.max(0, Math.floor(opts.suspectTurns)) : NEIGHBOR_SUSPECT_TURNS
628
+ const suspect =
629
+ opts.suspect instanceof Set
630
+ ? opts.suspect
631
+ : new Set(Array.isArray(opts.suspect) ? opts.suspect.map((v) => String(v).toLowerCase()) : [])
632
+ const skip = []
633
+ for (const one of opts.skip ?? []) {
634
+ const s = String(one).toLowerCase()
635
+ if (s.length >= 8) skip.push(s)
636
+ }
637
+ const qTokens = typeof opts.query === 'string' && opts.query.trim() !== '' ? neighborTokens(opts.query) : null
638
+ const shorten = typeof opts.shorten === 'function' ? opts.shorten : (id) => String(id).slice(0, 8)
639
+ const nodes = graphNodesOf(recallText)
640
+ if (nodes.length === 0) return null
641
+ // [0.6.61] 头句从 40 字压到 19 字:实测默认档一块 283–369 字里,头 + 尾占 200 字(54–71%),
642
+ // 条目只有 1–2 条(81–167 字)——框架文字比内容还长。归属护栏(不是用户原话)留着,
643
+ // 它防的是模型把邻居当成用户刚说的话;「自动带来的」「下面几条」这些交代是给第一次看的人听的,
644
+ // 每轮重复只是噪声。
645
+ const head = '【星图邻域·不是用户原话】这轮连着:'
646
+ const lines = [head]
647
+ const ids = []
648
+ // [0.6.62] 每条带出去的邻居的强度(与 ids 同序)。上层要知道「这一块是不是只有一条边缘线索」,
649
+ // 光看条数不够——0.68 的单条值得每轮带,0.38 的不值得。
650
+ const scores = []
651
+ // 条目区按「总上限 - 尾部预留」排:尾部那句「觉得无关就断掉」是 0.6.38 的重点,
652
+ // 0.6.44 又把它改成了带现成 id 的一步式命令(更长、更有用),
653
+ // 不能因为条目排得满就被挤掉。上限本身小到预留比它还大时(探针的 120 字符档),
654
+ // 先保证有条目——尾部装不下就不加(下面按剩余空间判断),绝不为了指导句把条目清零。
655
+ const bodyCap = chars <= NEIGHBOR_TAIL_RESERVE + 100 ? chars : chars - NEIGHBOR_TAIL_RESERVE
656
+ let weak = 0
657
+ let offtopic = 0
658
+ let offtopicKept = 0
659
+ let skippedIds = 0
660
+ let flagged = 0
661
+ /** [0.6.54] 被「错边账」压住、这一轮没带的跳。 */
662
+ let suspectSkipped = 0
663
+ /** [0.6.54] 压住的那几跳(含 8 位短 id):尾注据此给出**现成**的 mute 命令。 */
664
+ const suppressed = []
665
+ /** 被标记「未沾词」且 why 里能抠出来源 id 的边:尾注据此给出**现成**的 mute 命令。 */
666
+ const flaggedEdges = []
667
+ for (const node of nodes) {
668
+ if (ids.length >= max) break
669
+ const bare = uidOf(node.id).toLowerCase()
670
+ if (skip.some((one) => sameId(one, bare))) {
671
+ skippedIds += 1
672
+ continue
673
+ }
674
+ // [0.6.54] 错边闸:这一跳连标了 N 轮「未沾词」还没被修,先不带(图不动、账不动)。
675
+ // 顺序在跨层去重之后、强度闸之前:已经带过的照旧算去重,不看它是不是错边。
676
+ if (suspect.has(bare)) {
677
+ suspectSkipped += 1
678
+ const src = neighborSourceIdOf(node.why)
679
+ suppressed.push({ a: src.length >= 8 ? shorten(src) : '', b: shorten(bare) })
680
+ continue
681
+ }
682
+ if (Number.isFinite(node.score) && node.score < minScore) {
683
+ weak += 1
684
+ continue
685
+ }
686
+ // 词面闸(0.6.43):一个二元组都不沾、且强度也没到 NEIGHBOR_OFFTOPIC_SCORE 的邻居,
687
+ // 一轮最多留 NEIGHBOR_OFFTOPIC_KEEP 条。顺序在强度闸之后:先刷掉弱邻居,
688
+ // 再谈「这轮留几条不沾词的」——否则配额会被弱邻居吃掉。
689
+ // 强度够高的不沾词条目照带:图上这么近就是有实质关联,词面不重合只是换了个说法。
690
+ let unrelated = false
691
+ if (qTokens !== null && !(Number.isFinite(node.score) && node.score >= NEIGHBOR_OFFTOPIC_SCORE)) {
692
+ const bag = neighborTokens(`${node.label} ${node.why} ${node.preview}`)
693
+ let overlap = 0
694
+ for (const t of qTokens) {
695
+ if (bag.has(t)) overlap += 1
696
+ if (overlap > 0) break
697
+ }
698
+ if (overlap === 0) {
699
+ if (offtopicKept >= NEIGHBOR_OFFTOPIC_KEEP) {
700
+ offtopic += 1
701
+ continue
702
+ }
703
+ offtopicKept += 1
704
+ unrelated = true
705
+ }
706
+ }
707
+ const label = oneLine(node.label, 48)
708
+ const why = oneLine(node.why, 48)
709
+ const score = Number.isFinite(node.score) && node.score > 0 ? `(强度 ${node.score.toFixed(2)})` : ''
710
+ // [0.6.44] 靠配额留下来的那条打标记:它最可能是错边,模型得先知道「这条我自己也没底」。
711
+ const mark = unrelated ? NEIGHBOR_UNRELATED_MARK : ''
712
+ const line = `- [${node.level}] [${shorten(bare)}] ${label}${score}${why === '' ? '' : ` · ${why}`}${mark}`
713
+ // [0.6.47] 装不下就 `continue`,不是 `break`:旧写法拿一条长行(长标签 + 长 why)
714
+ // 撞上 bodyCap 就整体收工,后面更短的条目一条都不试——`neighborChars` 调小到 120 时
715
+ // 甚至第一条就放不下,整块邻域注入直接消失(静默、不打日志、下一轮一样),
716
+ // 而用户只会以为「星图没东西」。跳过这一条继续试,能放几条放几条。
717
+ if (lines.join('\n').length + line.length + 1 > bodyCap) continue
718
+ lines.push(line)
719
+ ids.push(bare)
720
+ scores.push(Number.isFinite(node.score) ? node.score : 0)
721
+ if (unrelated) {
722
+ flagged += 1
723
+ const src = neighborSourceIdOf(node.why)
724
+ if (src.length >= 8) flaggedEdges.push({ a: shorten(src), b: shorten(bare) })
725
+ }
726
+ }
727
+ // 全是弱邻居就一个字都不注入:宁可这一轮空着,也不为了让「显得有记忆」硬凑。
728
+ // [0.6.54] 但如果这一轮**唯一**发生的事是「错边账压住了几条」,就不能当成「图上没东西」——
729
+ // 上层的日志要能分开这两种空,否则用户会以为星图断了。
730
+ if (ids.length === 0) {
731
+ return suspectSkipped === 0
732
+ ? null
733
+ : { text: '', ids: [], scores: [], weak, offtopic, skipped: skippedIds, flagged, edges: flaggedEdges, suspect: suspectSkipped }
734
+ }
735
+ const first = shorten(ids[0])
736
+ // [0.6.44] 尾注从「建议」改成「可执行」:
737
+ // ① 标了「未沾词」且 why 里抠得出来源 id 的,把 mute 要的两个 id 直接拼好给模型——
738
+ // 0.6.38 那版要它自己先 path 再拼两个 id,实际上几乎不会被调用,错边就一直留着;
739
+ // ② 同时把判断标准说清(断的是**错边**,不是「这轮用不上」),否则模型会把无关的一律 mute,
740
+ // 把图修成一条没有横向关联的直线——那是比噪声更坏的结果。
741
+ // [0.6.61] 尾注三档:把「怎么拼 mute 的两个 id」这段教学从 160 字压到 70–125 字。
742
+ // ① 能给出成对 id 的(flagged)——照旧一步式命令,只删掉重复的解释;
743
+ // ② 常态多条目——保留 a/b 各填什么(这是 0.6.44 的成果,删了模型就退回先 path);
744
+ // ③ 只有一条邻居且没有可疑跳——短形态,一块省下 80 字左右,而内容一字不少。
745
+ // 「断的是错边、不是记忆」这句留着:0.6.44 的教训是删了它模型会把图上横向关联一律 mute,
746
+ // 修成一条直线比噪声更坏。
747
+ const pairsText = (edges, cap) => `[${edges.slice(0, cap).map((e) => `["${e.a}","${e.b}"]`).join(',')}]`
748
+ const genericTail = `memory_read("${first}") 看全文。明显无关就 nebula_link(action="mute", a=why 里那个来源 id, b=行首那 8 位) 断这一跳——断的是错边,不是记忆;这轮用不上就别动,不用问用户。`
749
+ // 一块里「未沾词」最多留一条(NEIGHBOR_OFFTOPIC_KEEP),所以这里只可能是单数;
750
+ // 要一次摘好几跳的是下面 supMany 那一段(账上攒下来的)。
751
+ const flaggedTail =
752
+ flaggedEdges.length > 0
753
+ ? `memory_read("${first}") 看全文。标了「未沾词」的那条若确实无关:nebula_link(action="mute", a="${flaggedEdges[0].a}", b="${flaggedEdges[0].b}") 直接断这一跳(断的是错边,不是记忆),不用问用户;这轮只是用不上就别动。`
754
+ : ''
755
+ const shortTail = `memory_read("${first}") 看全文;明显无关就 nebula_link(action="mute", a=why 里来源 id, b=行首 8 位),不用问用户。`
756
+ const baseCands = [flaggedTail, ids.length === 1 && suppressed.length === 0 ? shortTail : genericTail].filter(
757
+ (t) => t !== '',
758
+ )
759
+ // [0.6.54] 被压住的那几跳单独交代一句:不交代,模型会以为「这轮图里就这些」,
760
+ // 错边永远没人修;交代了,它想修的那一轮还能拿到现成命令。装不下就退回原尾注——
761
+ // 指导句不能挤掉条目,这是 0.6.44 定下的规矩。
762
+ // [0.6.65] 压住 ≥2 跳同样给批量命令(一次摘完,不用一跳一跳来)。
763
+ const supOne =
764
+ suppressed.length === 1
765
+ ? `另有 1 跳连续 ${suspectTurns} 轮标了「未沾词」、先不带了${suppressed[0].a === '' ? '' : `:确认无关就 nebula_link(action="mute", a="${suppressed[0].a}", b="${suppressed[0].b}")`}。`
766
+ : ''
767
+ const supMany =
768
+ suppressed.length > 1
769
+ ? `另有 ${suppressed.length} 跳连续 ${suspectTurns} 轮标了「未沾词」、先不带了:确认无关就一次摘掉 nebula_link(action="mute", pairs=${pairsText(suppressed, 3)})${suppressed.length > 3 ? `(还有 ${suppressed.length - 3} 跳用 memory_admin(action="suspect") 看)` : ''}。`
770
+ : ''
771
+ const supCands = [supMany, supOne].filter((t) => t !== '')
772
+ const room = chars - lines.join('\n').length - 1
773
+ // 先试「信息最全」的组合:压住的跳那句(含批量命令)优先,其次才是老尾注;
774
+ // 装不下时逐档退(别为了尾巴把条目挤掉,也别把「压着几跳」静默吞掉)。
775
+ let picked = ''
776
+ for (const sup of [...supCands, '']) {
777
+ for (const base of baseCands) {
778
+ if (base.length + sup.length <= room) {
779
+ picked = base + sup
780
+ break
781
+ }
782
+ }
783
+ if (picked !== '') break
784
+ }
785
+ if (picked !== '') lines.push(picked)
786
+ return { text: lines.join('\n'), ids, scores, weak, offtopic, skipped: skippedIds, flagged, edges: flaggedEdges, suspect: suspectSkipped }
787
+ }
788
+
789
+ /**
790
+ * 每轮邻域注入器。
791
+ *
792
+ * @param {object} o
793
+ * @param {any} o.ctx 插件上下文(只用 `ctx.on`)。
794
+ * @param {{tryCall: Function}} o.bridge 融合层的桥:`tryCall(name, args, exec, label)`。
795
+ * @param {{neighborInject?: boolean, neighborMax?: number, neighborChars?: number, injectTurnMaxChars?: number}} o.config 融合层配置。
796
+ * @param {(msg: string) => void} [o.logger] debug 日志。
797
+ * @param {() => string} [o.meowDir] [0.6.50] meow 的 projectDir 读口(账本落点用,缺省 .dsh-meow)。
798
+ * @param {() => Promise<{createUserMessage: Function}>} [o.loadLlm] 取宿主的消息工厂(探针可注入假货)。
799
+ */
800
+ export function createNeighborInjector({ ctx, bridge, config = {}, logger, meowDir, loadLlm }) {
801
+ const seen = new Map()
802
+ const state = { injected: 0, skipped: 0, calls: 0, failed: 0, deduped: 0, offtopic: 0, flagged: 0, suppressed: 0, capped: 0, edged: 0 }
803
+ const enabled = config.neighborInject !== false
804
+ const max = Number.isFinite(config.neighborMax) ? config.neighborMax : NEIGHBOR_DEFAULT_MAX
805
+ const chars = Number.isFinite(config.neighborChars) ? config.neighborChars : NEIGHBOR_DEFAULT_CHARS
806
+ const minScore = Number.isFinite(config.neighborMinScore) ? config.neighborMinScore : NEIGHBOR_MIN_SCORE
807
+ // [0.6.54] 错边账的窗口:0 = 整层关着(行为逐位等同 0.6.53)。
808
+ const suspectTurns = Number.isFinite(config.neighborSuspectTurns) ? Math.max(0, Math.floor(config.neighborSuspectTurns)) : NEIGHBOR_SUSPECT_TURNS
809
+ // [0.6.55] 一轮总上限(0 = 不限):命中注入先花,这一层只花剩下的。
810
+ const turnMax = Number.isFinite(config.injectTurnMaxChars) ? Math.max(0, Math.floor(config.injectTurnMaxChars)) : NEIGHBOR_TURN_MAX_CHARS
811
+ let llm = null
812
+ let llmTried = false
813
+ let pruned = false
814
+
815
+ const load = async () => {
816
+ if (llm !== null) return llm
817
+ if (llmTried) return null
818
+ llmTried = true
819
+ try {
820
+ const mod = typeof loadLlm === 'function' ? await loadLlm() : await import('@deepseek-ai/dsh-llm')
821
+ if (typeof mod?.createUserMessage === 'function') llm = mod.createUserMessage
822
+ } catch (err) {
823
+ logger?.(`[macro-memory] 邻域注入取不到消息工厂,本轮不注入:${err instanceof Error ? err.message : String(err)}`)
824
+ }
825
+ return llm
826
+ }
827
+
828
+ /**
829
+ * 读盘上的账本(一个会话一个 json)。坏文件一律当空账,绝不让它挡住本轮。
830
+ * [0.6.62] 账本除了「带过哪些 id」,还记 `edge`:上一轮带的是不是「边缘单条」块。
831
+ * 它撑着降频那条规矩——边缘单条带一轮、休一轮。老账本没有这个字段时按 0 读,
832
+ * 也就是「下一轮照常带」,不会因为升级而突然静默。
833
+ */
834
+ const readSeenFile = (sid) => {
835
+ const out = { ids: new Set(), edge: 0 }
836
+ try {
837
+ const raw = readFileSync(neighborSeenPath(sid), 'utf8')
838
+ const parsed = JSON.parse(raw)
839
+ const ids = Array.isArray(parsed?.ids) ? parsed.ids : []
840
+ for (const id of ids) {
841
+ const s = String(id ?? '').toLowerCase()
842
+ if (s.length >= 8) out.ids.add(s)
843
+ }
844
+ out.edge = parsed?.edge === 1 ? 1 : 0
845
+ } catch {
846
+ // ENOENT / 坏 JSON / 读不动:都当作「还没记过」。这一类失败只影响省 token,不影响正确性。
847
+ }
848
+ return out
849
+ }
850
+
851
+ /** 写盘:失败只记一笔日志(不打断这一轮),并在下一轮重试。 */
852
+ const writeSeenFile = (sid, st) => {
853
+ const file = neighborSeenPath(sid)
854
+ try {
855
+ mkdirSync(dirname(file), { recursive: true })
856
+ // 0.6.44:账本只进不出会长成几百 KB,每次 decide 整份 parse。留最近的 400 条就够
857
+ // (一轮最多 4 条邻域,更早的早被窗口挤出去了)。Set 的迭代顺序就是插入顺序。
858
+ const set = st.ids
859
+ const kept = set.size > NEIGHBOR_SEEN_MAX_IDS ? [...set].slice(set.size - NEIGHBOR_SEEN_MAX_IDS) : [...set]
860
+ writeFileSync(file, JSON.stringify({ sid, at: new Date().toISOString(), ids: kept, edge: st.edge === 1 ? 1 : 0 }), 'utf8')
861
+ } catch (err) {
862
+ logger?.(`[macro-memory] 邻域账本写不进去(下一轮会重试):${err instanceof Error ? err.message : String(err)}`)
863
+ }
864
+ }
865
+
866
+ const seenOf = (sid) => {
867
+ let st = seen.get(sid)
868
+ if (st === undefined) {
869
+ // 0.6.43:不再是「新会话就空账」——先把盘上这份读回来,宿主重启/续接会话不会重复注入。
870
+ st = readSeenFile(sid)
871
+ seen.set(sid, st)
872
+ }
873
+ return st
874
+ }
875
+
876
+ /**
877
+ * 决策函数:吃 pre-step 的 payload 与已定下的 decision,返回新的 decision。
878
+ * 任何一步不满足就原样返回——注入失败绝不挡住这一轮。
879
+ */
880
+ const decide = async (payload, decision) => {
881
+ if (!enabled) return decision
882
+ // [0.6.50] 账本落点:workspace 与会话头同一个口径(引擎 workspaceOfAgent 读的就是 header.cwd),
883
+ // 目录走 meow 的 projectDir。取不到 workspace 就一个字节都不写。
884
+ const agentOf = payload?.agent
885
+ const wsOf = typeof agentOf?.session?.header?.cwd === 'string' ? agentOf.session.header.cwd : ''
886
+ const dirOf = typeof meowDir === 'function' ? meowDir() : undefined
887
+ const logLine = (kind, rest) => appendNeighborLog(wsOf, dirOf, kind, rest)
888
+ // 0.6.44:进程内第一次决策时顺手清一次账本目录(太老 / 太多)。只删本插件自己的缓存,
889
+ // 失败不抛;清理结果只在 debug 日志里留一行。
890
+ if (!pruned) {
891
+ pruned = true
892
+ const r = pruneNeighborSeen()
893
+ if (r.removedByAge > 0 || r.removedByCount > 0 || r.error !== '') {
894
+ logger?.(`[macro-memory] 邻域账本清理:扫到 ${r.scanned} 个,按天删 ${r.removedByAge},按数删 ${r.removedByCount}${r.error === '' ? '' : `(错误:${r.error})`}`)
895
+ }
896
+ }
897
+ if (decision === undefined || decision === null || decision.kind !== 'enter') return decision
898
+ const messages = Array.isArray(decision.messages) ? decision.messages : []
899
+ if (messages.length === 0) {
900
+ logLine('neighbor-skip', 'reason=empty-msg')
901
+ return decision
902
+ }
903
+ const agent = payload?.agent
904
+ if (agent?.session?.header?.origin === 'subagent') {
905
+ logLine('neighbor-skip', 'reason=subagent')
906
+ return decision
907
+ }
908
+ const query = neighborQueryOf(messages)
909
+ if (query.length < NEIGHBOR_MIN_QUERY) {
910
+ logLine('neighbor-skip', 'reason=short')
911
+ return decision
912
+ }
913
+ const sid = String(agent?.session?.id ?? payload?.sessionId ?? 'unknown')
914
+ const seenState = seenOf(sid)
915
+ const already = seenState.ids
916
+ // 0.6.43 跨层去重:这一轮(以及本会话历史里)**别的注入已经带过**的条,邻域不再带第二遍。
917
+ // 命中注入(meow)与本层注入的是同一批记忆,同一条一轮里出现两次是纯浪费。
918
+ const carried = injectedIdsOf(messages)
919
+ // [0.6.55] 一轮总账:这一轮已经注入的(命中 / 重放,可能不止一块)先记账,
920
+ // 邻域只能花剩下的。0 = 不限时逐位走 0.6.54 的老路(不读、不算、不写读数)。
921
+ const carriedChars = turnMax > 0 ? injectedCharsOf(messages) : 0
922
+ let blockChars = chars
923
+ if (turnMax > 0) {
924
+ const left = turnMax - carriedChars
925
+ if (left < NEIGHBOR_TURN_MIN_BLOCK) {
926
+ state.skipped += 1
927
+ state.capped += 1
928
+ logLine('neighbor-skip', `reason=turncap sid=${sid} turnSpent=${carriedChars} turnCap=${turnMax} left=${Math.max(0, left)}`)
929
+ return decision
930
+ }
931
+ blockChars = Math.min(chars, left)
932
+ }
933
+ const skip = new Set(already)
934
+ for (const id of carried) skip.add(id)
935
+ state.calls += 1
936
+ let recallText = ''
937
+ try {
938
+ // 多要 4 条:强度/词面过滤会刷掉一部分,回执只按 limit 裁剪,先多拿几条免得永远凑不满。
939
+ const r = await bridge.tryCall(NEIGHBOR_TOOL, { query: query.slice(0, 300), limit: max + 4, hops: 1 }, undefined, '星图邻域')
940
+ recallText = typeof r?.text === 'string' ? r.text : ''
941
+ } catch (err) {
942
+ state.failed += 1
943
+ logLine('neighbor-skip', `reason=tool sid=${sid}`)
944
+ logger?.(`[macro-memory] 邻域注入这一轮没查成:${err instanceof Error ? err.message : String(err)}`)
945
+ return decision
946
+ }
947
+ // [0.6.54] 错边账:读一次(工作区一份),连标 ≥ suspectTurns 轮、且最近还在被标的跳先压住。
948
+ // 过期的(连续 NEIGHBOR_SUSPECT_DECAY 轮没再被标)当场就不算——一次误标不该永久降级。
949
+ const ledger = suspectTurns > 0 && wsOf !== '' ? readSuspectLedger(wsOf) : { round: 0, edges: {} }
950
+ const withheld = new Set()
951
+ for (const [key, edge] of Object.entries(ledger.edges)) {
952
+ if (edge.n < suspectTurns) continue
953
+ if (ledger.round - edge.last > NEIGHBOR_SUSPECT_DECAY) continue
954
+ withheld.add(String(key.split('|')[1] ?? '').toLowerCase())
955
+ }
956
+ // [0.6.64] 行首 id 给最短唯一前缀:8 位切法在真库上撞 13 组,撞车的 id 指向两条,
957
+ // 模型拿它去 read / update / mute 会撞歧义拒绝。星图回执给的常是短 id,
958
+ // `shortenId` 会先解析回唯一的那条再取前缀;解析不唯一就原样退回,不替它挑一条。
959
+ const shortIndex = wsOf === '' ? null : shortIdsOf(Meow.getDb(wsOf, dirOf))
960
+ const shorten = (id) => shortenId(shortIndex, id)
961
+ const block = neighborBlockOf(recallText, {
962
+ max,
963
+ chars: blockChars,
964
+ skip,
965
+ minScore,
966
+ query,
967
+ suspect: withheld,
968
+ suspectTurns,
969
+ shorten,
970
+ })
971
+ state.offtopic += block === null ? 0 : block.offtopic
972
+ if (block === null) {
973
+ state.skipped += 1
974
+ logLine('neighbor-skip', `reason=empty sid=${sid}`)
975
+ return decision
976
+ }
977
+ // [0.6.54] 只有「被错边账压住的那几条」这一种情况会拿到空正文:这一轮一个字都不注入,
978
+ // 但要把「压住了几条」记下来——否则用户看到的是「星图这轮没东西」,账上却查不出原因。
979
+ if (block.text === '') {
980
+ state.skipped += 1
981
+ state.suppressed += block.suspect ?? 0
982
+ const heldIds = [...withheld].slice(0, 6).join(',')
983
+ logLine(
984
+ 'neighbor-skip',
985
+ `reason=suspect sid=${sid} withheld=${block.suspect ?? 0} turns=${suspectTurns} ids=${heldIds}`,
986
+ )
987
+ return decision
988
+ }
989
+ state.deduped += block.skipped
990
+ state.flagged += block.flagged ?? 0
991
+ state.suppressed += block.suspect ?? 0
992
+ // [0.6.62] 边缘单条:一块里只活下来一条、强度又没过 0.55 的,带一轮休一轮。
993
+ // 0.6.43 的账本已经让「同一条邻居」整会话只带一次,所以每轮来的是**新**的边缘线索;
994
+ // 真库上这类块占操作型轮次的 11/17、每块 193 字(bench37),而 0.68 那种单条是真线索,
995
+ // 手感完全不同——所以只对「弱」的那一档降频,条数本身不降。
996
+ // 0 = 关掉这条规矩(逐位退回 0.6.61 的行为);配置口 neighborSoloEdge。
997
+ const edgeScore = Number.isFinite(config.neighborSoloEdge)
998
+ ? Math.min(1, Math.max(0, config.neighborSoloEdge))
999
+ : NEIGHBOR_SOLO_EDGE_SCORE
1000
+ const soloScore = Number.isFinite(block.scores?.[0]) ? block.scores[0] : 0
1001
+ const soloEdge = edgeScore > 0 && block.ids.length === 1 && soloScore < edgeScore
1002
+ if (soloEdge && seenState.edge === 1) {
1003
+ state.skipped += 1
1004
+ state.edged += 1
1005
+ seenState.edge = 0
1006
+ writeSeenFile(sid, seenState)
1007
+ logLine('neighbor-skip', `reason=edgeturn sid=${sid} score=${soloScore.toFixed(2)} chars=${block.text.length}`)
1008
+ return decision
1009
+ }
1010
+ // [0.6.54] 两件事:①这一轮真标了的跳 +1;②轮次号 +1、过期跳放回、总量封顶。
1011
+ // 顺序不能反——先盖章再判「最近被标」会把这一轮算到下一轮,账永远比实际晚一轮。
1012
+ if (suspectTurns > 0 && wsOf !== '') {
1013
+ ledger.round += 1
1014
+ const round = ledger.round
1015
+ for (const e of block.edges ?? []) {
1016
+ const key = `${e.a.slice(0, 8)}|${e.b.slice(0, 8)}`
1017
+ const old = ledger.edges[key]
1018
+ ledger.edges[key] = { n: (old?.n ?? 0) + 1, first: old?.first ?? round, last: round }
1019
+ }
1020
+ for (const key of Object.keys(ledger.edges)) {
1021
+ if (round - ledger.edges[key].last > NEIGHBOR_SUSPECT_DECAY) delete ledger.edges[key]
1022
+ }
1023
+ const keys = Object.keys(ledger.edges)
1024
+ if (keys.length > NEIGHBOR_SUSPECT_MAX) {
1025
+ keys.sort((x, y) => ledger.edges[x].last - ledger.edges[y].last)
1026
+ for (const k of keys.slice(0, keys.length - NEIGHBOR_SUSPECT_MAX)) delete ledger.edges[k]
1027
+ }
1028
+ writeSuspectLedger(wsOf, ledger)
1029
+ const still = Object.entries(ledger.edges).filter(([, e]) => e.n >= suspectTurns)
1030
+ if (still.length > 0) {
1031
+ logLine(
1032
+ 'neighbor-suspect',
1033
+ `sid=${sid} withheld=${still.length} turns=${suspectTurns} ids=${still.map(([k]) => k.split('|')[1]).join(',')}`,
1034
+ )
1035
+ }
1036
+ }
1037
+ const make = await load()
1038
+ if (make === null) {
1039
+ state.failed += 1
1040
+ logLine('neighbor-skip', `reason=llm sid=${sid}`)
1041
+ return decision
1042
+ }
1043
+ for (const id of block.ids) {
1044
+ already.add(id)
1045
+ if (already.size > NEIGHBOR_SEEN_MAX) {
1046
+ const first = already.values().next()
1047
+ if (!first.done) already.delete(first.value)
1048
+ }
1049
+ }
1050
+ // [0.6.62] 记账:这一轮带出去的是不是边缘单条,决定下一轮要不要让路。
1051
+ seenState.edge = soloEdge ? 1 : 0
1052
+ writeSeenFile(sid, seenState)
1053
+ state.injected += 1
1054
+ // 成功这一笔记的是「真正进了上下文的那一块」:条数、字数、以及三道闸各自的读数。
1055
+ logLine(
1056
+ 'neighbor-chain',
1057
+ `sid=${sid} ids=${block.ids.length} chars=${block.text.length} weak=${block.weak} offtopic=${block.offtopic} flagged=${block.flagged ?? 0} deduped=${block.skipped} max=${max} cap=${chars} minScore=${minScore} turnCap=${turnMax} turnSpent=${carriedChars} solo=${soloEdge ? 1 : 0}`,
1058
+ )
1059
+ const msg = make({
1060
+ content: [{ type: 'text', text: block.text }],
1061
+ source: { kind: NEIGHBOR_SOURCE_KIND, form: 'notice', summary: `星图邻域 ${block.ids.length} 条` },
1062
+ })
1063
+ // 追加在**后面**:前缀不动,缓存不碎;模型看到的顺序是「用户说 → 附带邻域」。
1064
+ return { ...decision, messages: [...messages, msg] }
1065
+ }
1066
+
1067
+ const dispose = ctx.on('agent/pre-step', async (payload, next) => {
1068
+ const decision = await next()
1069
+ try {
1070
+ return await decide(payload, decision)
1071
+ } catch (err) {
1072
+ state.failed += 1
1073
+ logger?.(`[macro-memory] 邻域注入出错(不影响这一轮):${err instanceof Error ? err.message : String(err)}`)
1074
+ return decision
1075
+ }
1076
+ })
1077
+
1078
+ return {
1079
+ decide,
1080
+ stats: () => ({ ...state, sessions: seen.size }),
1081
+ dispose: typeof dispose === 'function' ? dispose : () => {},
1082
+ }
1083
+ }