macro-memory 0.0.0-stage → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +386 -2
  3. package/bin/macro-memory.mjs +735 -0
  4. package/docs/CHANGELOG.md +268 -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 +201 -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,843 @@
1
+ /**
2
+ * 注入账本面板(0.6.46):`memory_admin(action="inject")` 的正文从这里出。
3
+ *
4
+ * 为什么要有这个面板:0.6.41 / 0.6.44 / 0.6.45 三道闸(单条正文上限、会话预算、同话题抑制、
5
+ * 命中闸门)都在往 `dream-debug.log` 里写账,可**只有写、没有读**——日志躺在项目目录里,
6
+ * 用户想问「这几小时到底注入了多少字、被挡的是哪一类」只能自己去翻几千行文本。
7
+ * 一个只有写口的账本,等于把「可解释」做成了「我写过」。
8
+ *
9
+ * 三条规矩(和 dreamledger.js 同一套):
10
+ * 1. 面板只念日志,不自己算:所有数字都能从 `dream-debug.log` 的行里验算出来。
11
+ * 2. 「没有账」和「读不出来」分开说:前者是这窗口还没到过注入这一步(或日志被轮转掉了),
12
+ * 后者是文件在但读不动——把后者说成前者是最难查的那种谎。
13
+ * 3. 认旧格式:0.6.43 及以前的 `hit-chain` 行只有 `textLen=/hit=`,没有 floor/gated/skip。
14
+ * 面板照算字数,但要明说「这几行是旧格式,闸门读数不全」,不许把缺字段读成 0。
15
+ *
16
+ * [0.6.50] 这本账现在读**两种**注入:命中注入(`hit-chain` / `hit-skip`)与星图邻域
17
+ * (`neighbor-chain` / `neighbor-skip`)。它们花的是同一份上下文预算:以前面板只念命中那一半,
18
+ * 邻域每轮带几条、砍了几条不沾词的、被跨层去重刷掉几条,全是黑箱。两段分开算、
19
+ * 分开写,因为「注入了多少字」和「邻域带了多少条」是两个不能相加的量。
20
+ *
21
+ * [0.6.51] 但**同一轮**要合账:命中注入与邻域是同一份上下文预算是真的,分两段念的结果是
22
+ * 谁也答不出「这一轮到底被塞了多少字」。按「同 sid + 两秒内」把两边配回同一轮,单列一行
23
+ * 「一轮合计」,明细里把那两行并成一行——只在两边都有账的轮上算,配不上的不硬凑。
24
+ *
25
+ * [0.6.52] 再往上加一层「一场会话」:按 sid 把同一场会话的所有轮并起来,报
26
+ * 「命中 N 轮 / X 字 + 邻域 M 轮 / Y 字 = Z 字」。轮内合计回答「这一轮花了多少」,
27
+ * 会话累计回答「这场聊下来花了多少」——两个问题,两行分开写,都不许互相顶替。
28
+ *
29
+ * [0.6.53] 同一份账里往往不止一场会话(多窗口 / 多工作目录并发),只念最近一场会让别的
30
+ * 场次的字数完全看不见。补一行「其他场次」(按时间新的在前,最多 3 场),每场给合计字数
31
+ * 与命中/邻域轮数——念得少,但「除了这一场还有谁在花钱」不再是黑箱。
32
+ */
33
+ import { existsSync, readFileSync, statSync } from 'node:fs'
34
+ import { join } from 'node:path'
35
+
36
+ /** 出厂默认(与 vendor/meow-memory/lib/index.js 的 DEF 常量一致;面板只用来兜底,不参与判定)。 */
37
+ const DEFAULTS = {
38
+ injectFloor: 0.35,
39
+ injectBodyMax: 240,
40
+ injectSessionBudget: 0,
41
+ injectRepeatSim: 0.25,
42
+ injectReinjectTurns: 12,
43
+ hitTopK: 2,
44
+ }
45
+
46
+ /** `[2026-11-24T19:04:01.510Z] hit-chain pid=1 sid=abc textLen=240 hit=yes ...` */
47
+ const LINE_RE = /^\[([0-9T:.\-Z]+)\]\s+(hit-chain|hit-skip|neighbor-chain|neighbor-skip|neighbor-suspect|neighbor-fix)\b(.*)$/
48
+
49
+ /**
50
+ * [0.6.51] 把「同一轮的命中注入」与「同一轮的邻域链」配成一对。
51
+ * 口径与 hit-skip 配轮一致:同 sid、两秒内、每条只用一次,取时间最近的那条。
52
+ * 只返回配上的轮——配不上的不许猜。
53
+ */
54
+ function pairRounds(hits, chains) {
55
+ const used = new Set()
56
+ const out = []
57
+ for (const h of hits) {
58
+ if (h.hit !== 'yes') continue
59
+ let best = -1
60
+ let bestGap = Infinity
61
+ for (let i = 0; i < chains.length; i += 1) {
62
+ if (used.has(i)) continue
63
+ const c = chains[i]
64
+ if (h.sid !== '' && c.sid !== '' && h.sid !== c.sid) continue
65
+ const gap = Math.abs((h.at ?? 0) - (c.at ?? 0))
66
+ if (gap > 2000) continue
67
+ if (gap < bestGap) {
68
+ best = i
69
+ bestGap = gap
70
+ }
71
+ }
72
+ if (best < 0) continue
73
+ used.add(best)
74
+ out.push({ hit: h, chain: chains[best] })
75
+ }
76
+ return out
77
+ }
78
+
79
+ /** `k=v` 逐对拆开(值里不含空格;日志本身就是这么写的)。 */
80
+ function pairsOf(rest) {
81
+ const out = Object.create(null)
82
+ for (const part of String(rest ?? '').trim().split(/\s+/)) {
83
+ const at = part.indexOf('=')
84
+ if (at <= 0) continue
85
+ out[part.slice(0, at)] = part.slice(at + 1)
86
+ }
87
+ return out
88
+ }
89
+
90
+ function numOf(raw, fallback = 0) {
91
+ const n = Number(raw)
92
+ return Number.isFinite(n) ? n : fallback
93
+ }
94
+
95
+ /** 从 hit-skip 行的 `extra` 原文里抠一个 `key=123`(只用于挡下轮那些读数)。 */
96
+ function extraNumOf(e, key) {
97
+ const m = new RegExp(`(?:^|\\s)${key}=(\\d+)`).exec(String(e.extra ?? ''))
98
+ return m === null ? 0 : Number(m[1])
99
+ }
100
+
101
+ /** `2026-11-24T19:04:01.510Z` → 毫秒;解不出给 0(时间不明,别拿现在顶)。 */
102
+ function timeOf(iso) {
103
+ const t = Date.parse(String(iso))
104
+ return Number.isFinite(t) ? t : 0
105
+ }
106
+
107
+ /** 本机时间的「MM-DD HH:mm」:面板只给到分钟,秒在这里没有信息量。 */
108
+ function stamp(at) {
109
+ const t = Number(at)
110
+ if (!Number.isFinite(t) || t <= 0) return '时间不明'
111
+ const d = new Date(t)
112
+ const p = (n) => String(n).padStart(2, '0')
113
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
114
+ }
115
+
116
+ function p50Of(sorted) {
117
+ if (sorted.length === 0) return 0
118
+ return sorted[Math.floor(sorted.length / 2)]
119
+ }
120
+
121
+ /**
122
+ * 读一份日志文本 → 事件数组 + 坏行数。
123
+ *
124
+ * 只认 `hit-chain` / `hit-skip` 两种行;其余行(pre-step / check / dream / turn-stopping)
125
+ * 一律跳过,**不计坏行**——它们不是这本账要读的东西,把它们算成「解析失败」会让
126
+ * 面板看起来像日志坏了。
127
+ */
128
+ /**
129
+ * [0.6.72] `drops=id8:score:reason,…` 的解析:`-` 是「这一轮没人落选」,
130
+ * 字段缺席(undefined / null)是「这份日志还没有这一栏」——两者不许混,
131
+ * 混了就会把老日志读成「每轮都一条没挡」。
132
+ */
133
+ function dropsOf(raw) {
134
+ if (raw === undefined || raw === null) return null
135
+ const text = String(raw)
136
+ if (text === '' || text === '-') return []
137
+ return text
138
+ .split(',')
139
+ .map((part) => {
140
+ const seg = part.split(':')
141
+ const scoreRaw = String(seg[1] ?? '')
142
+ return {
143
+ id: String(seg[0] ?? ''),
144
+ score: scoreRaw === '' || scoreRaw === '-' ? null : numOf(scoreRaw),
145
+ reason: String(seg[2] ?? ''),
146
+ }
147
+ })
148
+ .filter((d) => d.id !== '')
149
+ }
150
+
151
+ export function parseInjectLog(text) {
152
+ const events = []
153
+ let bad = 0
154
+ let legacy = 0
155
+ for (const raw of String(text ?? '').split(/\r?\n/)) {
156
+ const line = raw.trim()
157
+ if (line === '' || !/hit-|neighbor-/.test(line)) continue
158
+ const m = LINE_RE.exec(line)
159
+ if (m === null) {
160
+ bad += 1
161
+ continue
162
+ }
163
+ const at = timeOf(m[1])
164
+ const kv = pairsOf(m[3])
165
+ if (m[2] === 'neighbor-chain') {
166
+ // 0.6.50:邻域这一轮真的进了上下文——记的是「进了多少」(条数 + 字符)。
167
+ events.push({
168
+ kind: 'neighbor',
169
+ at,
170
+ sid: String(kv.sid ?? ''),
171
+ ids: numOf(kv.ids),
172
+ chars: numOf(kv.chars),
173
+ weak: numOf(kv.weak),
174
+ offtopic: numOf(kv.offtopic),
175
+ flagged: numOf(kv.flagged),
176
+ deduped: numOf(kv.deduped),
177
+ max: numOf(kv.max),
178
+ cap: numOf(kv.cap),
179
+ minScore: kv.minScore === undefined ? null : numOf(kv.minScore),
180
+ // [0.6.55] 一轮总账:这一轮开始前已经注入了多少字(turnSpent),上限是多少(turnCap,0=不限)。
181
+ turnCap: kv.turnCap === undefined ? 0 : numOf(kv.turnCap),
182
+ turnSpent: kv.turnSpent === undefined ? null : numOf(kv.turnSpent),
183
+ // [0.6.62] 这一块是不是「边缘单条」:是的话下一轮让路(solo=1)。
184
+ solo: numOf(kv.solo),
185
+ })
186
+ } else if (m[2] === 'neighbor-skip') {
187
+ events.push({
188
+ kind: 'nskip',
189
+ at,
190
+ sid: String(kv.sid ?? ''),
191
+ reason: String(kv.reason ?? ''),
192
+ extra: m[3].trim(),
193
+ })
194
+ } else if (m[2] === 'neighbor-suspect') {
195
+ // [0.6.54] 这一轮有几跳错边被「连标 N 轮」的窗口压住了(图没动,账留着)。
196
+ events.push({
197
+ kind: 'nsuspect',
198
+ at,
199
+ sid: String(kv.sid ?? ''),
200
+ withheld: numOf(kv.withheld),
201
+ turns: numOf(kv.turns),
202
+ ids: String(kv.ids ?? '').split(',').filter((v) => v !== ''),
203
+ })
204
+ } else if (m[2] === 'neighbor-fix') {
205
+ // [0.6.54] 模型真把一跳断掉了:a/b 是那一跳两端、cleared 是销掉几条账。
206
+ events.push({
207
+ kind: 'nfix',
208
+ at,
209
+ a: String(kv.a ?? ''),
210
+ b: String(kv.b ?? ''),
211
+ via: String(kv.via ?? ''),
212
+ cleared: numOf(kv.cleared),
213
+ })
214
+ } else if (m[2] === 'hit-chain') {
215
+ // 0.6.43 及以前:没有 floor=,也没有 gated= —— 只记了字数与出口
216
+ const isLegacy = kv.floor === undefined && kv.gated === undefined
217
+ if (isLegacy) legacy += 1
218
+ // spent 写的是「已花/上限」(如 `268/∞`、`780/800`):取除号前那一半才是已花,
219
+ // 直接 Number('268/∞') 会得到 NaN,被兜成 0,面板就会说「这轮一个字都没花」。
220
+ const spentRaw = kv.spent === undefined ? '' : String(kv.spent)
221
+ // [0.6.71] 按条流水:`picks=id8:chars:mode,id8:chars:mode`。字段缺席(0.6.70 及以前)
222
+ // 读成「没有按条记录」,不许读成「这一轮一条都没进」——两件事,后者是 bug。
223
+ const picksRaw = kv.picks === undefined ? null : String(kv.picks)
224
+ const picks = picksRaw === null || picksRaw === '-' || picksRaw === ''
225
+ ? []
226
+ : picksRaw.split(',').map((part) => {
227
+ const seg = part.split(':')
228
+ return { id: String(seg[0] ?? ''), chars: numOf(seg[1]), mode: String(seg[2] ?? '') }
229
+ }).filter((p) => p.id !== '')
230
+ events.push({
231
+ kind: 'hit',
232
+ at,
233
+ sid: String(kv.sid ?? ''),
234
+ len: numOf(kv.textLen),
235
+ picks,
236
+ hasPicks: picksRaw !== null,
237
+ // [0.6.72] 落选名单:这一轮被挡在门外的条目(id / 分数 / 原因)。
238
+ drops: dropsOf(kv.drops),
239
+ hasDrops: kv.drops !== undefined,
240
+ // 三态(照日志原样,不改写):yes=真注入了记忆;null=这一轮没有命中注入;
241
+ // 缺字段=更老的版本,连这个键都没有——不许当成 null 读。
242
+ hit: kv.hit === undefined ? 'unknown' : String(kv.hit),
243
+ floor: kv.floor === undefined ? null : numOf(kv.floor),
244
+ gated: kv.gated === undefined ? null : numOf(kv.gated),
245
+ bodyCut: kv.bodyCut === undefined ? null : numOf(kv.bodyCut),
246
+ repeated: kv.repeated === undefined ? null : numOf(kv.repeated),
247
+ // [0.6.49] 老条目放回:这一轮把多少条超出重放窗口的条目从「本会话已给过」名单里摘掉。
248
+ released: kv.released === undefined ? null : numOf(kv.released),
249
+ reinjectTurns: kv.reinject === undefined ? null : numOf(kv.reinject),
250
+ spent: spentRaw === '' ? null : numOf(spentRaw.split('/')[0]),
251
+ limit: spentRaw.includes('/') ? spentRaw.split('/')[1] : '',
252
+ legacy: isLegacy,
253
+ })
254
+ } else {
255
+ // 0.6.44 起才有:四种出口 empty / floor / budget / repeat
256
+ events.push({
257
+ kind: 'skip',
258
+ at,
259
+ sid: String(kv.sid ?? ''),
260
+ reason: String(kv.reason ?? ''),
261
+ // [0.6.72] 整轮被挡下时,落选名单写在这一行(命中成功时写在 hit-chain 那一行)。
262
+ drops: dropsOf(kv.drops),
263
+ hasDrops: kv.drops !== undefined,
264
+ extra: m[3].trim(),
265
+ legacy: false,
266
+ })
267
+ }
268
+ }
269
+ // 两代日志拼起来后顺序天然是对的(.old 在前),但同一毫秒内可能乱:稳定排序兜一层。
270
+ events.sort((a, b) => a.at - b.at)
271
+ return { events, bad, legacy }
272
+ }
273
+
274
+ /** 面板正文:账目 + 最近若干轮明细。`limit` 只控明细条数,统计永远覆盖整份日志。 */
275
+ export function readInjectPanel({ workspace, dir, limit = 12, config = {} } = {}) {
276
+ const base = join(String(workspace ?? ''), String(dir || '.dsh-meow'))
277
+ const nowFile = join(base, 'dream-debug.log')
278
+ const oldFile = join(base, 'dream-debug.log.old')
279
+ const files = []
280
+ for (const f of [oldFile, nowFile]) {
281
+ if (!existsSync(f)) continue
282
+ let size = 0
283
+ try {
284
+ size = statSync(f).size
285
+ } catch {
286
+ size = 0
287
+ }
288
+ files.push({ path: f, size, text: safeRead(f) })
289
+ }
290
+ const gate = [
291
+ `floor ${numOf(config.injectFloor, DEFAULTS.injectFloor)}`,
292
+ `单条 ${numOf(config.injectBodyMax, DEFAULTS.injectBodyMax)} 字`,
293
+ `会话累计 ${numOf(config.injectSessionBudget, DEFAULTS.injectSessionBudget) > 0 ? `${numOf(config.injectSessionBudget)} 字` : '不限'}`,
294
+ `同话题 ${numOf(config.injectRepeatSim, DEFAULTS.injectRepeatSim)}`,
295
+ `重放 ${numOf(config.injectReinjectTurns, DEFAULTS.injectReinjectTurns) > 0 ? `${numOf(config.injectReinjectTurns, DEFAULTS.injectReinjectTurns)} 轮` : '关(永久拉黑)'}`,
296
+ `每轮最多 ${numOf(config.hitTopK, DEFAULTS.hitTopK)} 条`,
297
+ ].join(' · ')
298
+
299
+ if (files.length === 0) {
300
+ return {
301
+ body:
302
+ `这个工作区里还没有注入账(找的是 ${nowFile})。\n` +
303
+ '没到过注入这一步、或者插件换到别的库目录时都会这样——不是「账本是空的」。',
304
+ scope: '',
305
+ }
306
+ }
307
+ const totalBytes = files.reduce((a, f) => a + f.size, 0)
308
+ const joined = files.map((f) => f.text).join('\n')
309
+ const { events, bad, legacy } = parseInjectLog(joined)
310
+ const hits = events.filter((e) => e.kind === 'hit')
311
+ const skips = events.filter((e) => e.kind === 'skip')
312
+ const chains = events.filter((e) => e.kind === 'neighbor')
313
+ const neighborSkips = events.filter((e) => e.kind === 'nskip')
314
+ // [0.6.54] 错边账的两支:压住的(nsuspect)与真被断掉的(nfix)。
315
+ const suspects = events.filter((e) => e.kind === 'nsuspect')
316
+ const fixes = events.filter((e) => e.kind === 'nfix')
317
+
318
+ if (events.length === 0) {
319
+ return {
320
+ body:
321
+ `日志在(${fmtKb(totalBytes)}),但里面一行注入账都没有。\n` +
322
+ `日志:${nowFile}` +
323
+ (bad > 0 ? `\n另有 ${bad} 行长得像注入账却解析不出来,一行都没算进去。` : ''),
324
+ scope: '',
325
+ }
326
+ }
327
+
328
+ const injected = hits.filter((e) => e.hit === 'yes')
329
+ const noHit = hits.filter((e) => e.hit !== 'yes')
330
+ const lens = injected.map((e) => e.len).sort((a, b) => a - b)
331
+ const sum = lens.reduce((a, b) => a + b, 0)
332
+ const avg = lens.length > 0 ? Math.round(sum / lens.length) : 0
333
+ // [0.6.47] 闸门读数过去只数「注入成功」的那些轮:整轮被 floor / repeat 挡下时
334
+ // `hit=null`,这些数字一条都不计——闸最生效的时候面板显示 0,排查时会被读成「闸没生效」。
335
+ // 挡下的轮,真正的读数在 hit-skip 那一行(`gated=` / `repeated=`),两边一起加。
336
+ const gated = hits.reduce((a, e) => a + (e.gated ?? 0), 0) + skips.reduce((a, e) => a + extraNumOf(e, 'gated'), 0)
337
+ const bodyCut = hits.reduce((a, e) => a + (e.bodyCut ?? 0), 0)
338
+ const repeated = hits.reduce((a, e) => a + (e.repeated ?? 0), 0) + skips.reduce((a, e) => a + extraNumOf(e, 'repeated'), 0)
339
+ const released = hits.reduce((a, e) => a + (e.released ?? 0), 0) + skips.reduce((a, e) => a + extraNumOf(e, 'released'), 0)
340
+ const reinjectTurns = hits.reduce((a, e) => (e.reinjectTurns !== null ? e.reinjectTurns : a), numOf(config.injectReinjectTurns, DEFAULTS.injectReinjectTurns))
341
+
342
+ // [0.6.51] 一轮合计:命中与邻域都有的那些轮,把两份字数加在一起再统计。
343
+ // 只在两边都配上的轮上算(配不上的单边轮不进来),并在行里写清「几轮」,
344
+ // 免得被读成「所有轮的平均」。
345
+ const roundPairs = pairRounds(hits, chains)
346
+ const roundLen = roundPairs.map((p) => p.hit.len + p.chain.chars)
347
+ const roundSum = roundLen.reduce((a, b) => a + b, 0)
348
+ const roundAvg = roundLen.length > 0 ? Math.round(roundSum / roundLen.length) : 0
349
+ const roundMax = roundLen.length > 0 ? Math.max(...roundLen) : 0
350
+ const roundNeighborSum = roundPairs.reduce((a, p) => a + p.chain.chars, 0)
351
+ const roundShare = roundSum > 0 ? Math.round((roundNeighborSum / roundSum) * 100) : 0
352
+
353
+ // [0.6.52] 一场会话的累计:同一 sid 的注入轮与邻域轮各自求和,再给一行合计。
354
+ // 「最近一场」按最后一条带 sid 的账取(日志顺序已排序),sid 为空的老账不进这一行。
355
+ const sessionOf = new Map()
356
+ const touch = (sid, at) => {
357
+ if (sid === '') return null
358
+ let box = sessionOf.get(sid)
359
+ if (box === undefined) {
360
+ box = { sid, last: 0, hitRounds: 0, hitChars: 0, chainRounds: 0, chainChars: 0 }
361
+ sessionOf.set(sid, box)
362
+ }
363
+ if ((at ?? 0) > box.last) box.last = at ?? 0
364
+ return box
365
+ }
366
+ for (const h of hits) {
367
+ const box = touch(h.sid, h.at)
368
+ if (box === null || h.hit !== 'yes') continue
369
+ box.hitRounds += 1
370
+ box.hitChars += h.len
371
+ }
372
+ for (const c of chains) {
373
+ const box = touch(c.sid, c.at)
374
+ if (box === null) continue
375
+ box.chainRounds += 1
376
+ box.chainChars += c.chars
377
+ }
378
+ let sessionLast = null
379
+ for (const box of sessionOf.values()) {
380
+ if (sessionLast === null || box.last > sessionLast.last) sessionLast = box
381
+ }
382
+
383
+ const byReason = new Map()
384
+ for (const s of skips) byReason.set(s.reason, (byReason.get(s.reason) ?? 0) + 1)
385
+
386
+ // [0.6.47] 轮数不许双计:0.6.44 起每一轮都会写一行 `hit-chain`,被闸挡下的轮**另外**
387
+ // 再写一行 `hit-skip`——两行是同一轮的两半。旧算法把 hits 与 skips 直接相加,
388
+ // 挡下越多,轮数、每轮均值、命中率虚高得越多(挡一半就翻倍)。
389
+ // 这里先按「同 sid + 两秒内 + hit≠yes」把 skip 配回它那一轮,配不上的(只有 skip 行的
390
+ // 老写法 / 手工拼的日志)才单独算一轮。
391
+ const pairedHits = new Set()
392
+ const pairedSkips = new Set()
393
+ for (const s of skips) {
394
+ for (let i = 0; i < hits.length; i += 1) {
395
+ if (pairedHits.has(i)) continue
396
+ const h = hits[i]
397
+ if (h.hit === 'yes') continue
398
+ if (s.sid !== '' && h.sid !== '' && s.sid !== h.sid) continue
399
+ if (Math.abs((h.at ?? 0) - (s.at ?? 0)) > 2000) continue
400
+ pairedHits.add(i)
401
+ pairedSkips.add(s)
402
+ break
403
+ }
404
+ }
405
+ const unpairedSkips = skips.filter((s) => !pairedSkips.has(s))
406
+ const rounds = hits.length + unpairedSkips.length
407
+
408
+ const lines = [`闸门:${gate}`, '']
409
+ const blockedRounds = Math.max(0, rounds - injected.length)
410
+ lines.push(`出口:${rounds} 轮里有 ${injected.length} 轮注入、${blockedRounds} 轮没注入`)
411
+ if (noHit.length > 0) {
412
+ // 旧格式里「没命中」只有一行 hit=null,没写为什么(0.6.44 起才有四种 hit-skip 出口)。
413
+ // 这句必须跟着那行一起出现在正文里,否则「挡下 0 轮 + 16 轮没命中」会被读成「闸门从没生效」。
414
+ lines.push(`- 其中 ${noHit.length} 轮是「算了但没注入」:0.6.44 起会分别写明是未命中 / 闸门 / 预算 / 同话题,更早的行只记了这一句。`)
415
+ }
416
+ if (skips.length > 0) {
417
+ const known = ['empty', 'floor', 'budget', 'repeat']
418
+ for (const r of known) {
419
+ const n = byReason.get(r)
420
+ if (!n) continue
421
+ lines.push(`- ${reasonLabel(r)}:${n} 轮`)
422
+ }
423
+ for (const [r, n] of byReason) {
424
+ if (known.includes(r)) continue
425
+ lines.push(`- ${r === '' ? '出口没写原因' : r}:${n} 轮`)
426
+ }
427
+ }
428
+ if (injected.length > 0) {
429
+ lines.push(
430
+ '',
431
+ `字数:合计 ${sum.toLocaleString('en-US')} 字 / 平均 ${avg} 字每轮 / 中位 ${p50Of(lens)} / 最省 ${lens[0]} / 最多 ${lens[lens.length - 1]}`,
432
+ )
433
+ // [0.6.71] 按条流水:上面那行只说「一共花了多少」,被问「该动哪一条」时答不上来。
434
+ // 引擎现在把每条实际进了多少字写进 `picks=`,这里把账算出来:先给总量占比,
435
+ // 再点出吃额度最多的几条,最后诚实交代哪些轮还没有按条记录(老日志)。
436
+ const picked = injected.filter((e) => e.picks.length > 0)
437
+ const pickTotal = picked.reduce((a, e) => a + e.picks.length, 0)
438
+ const pickChars = picked.reduce((a, e) => a + e.picks.reduce((s, p) => s + p.chars, 0), 0)
439
+ if (pickTotal > 0) {
440
+ const byPick = new Map()
441
+ for (const e of picked) {
442
+ for (const p of e.picks) {
443
+ const box = byPick.get(p.id)
444
+ if (box === undefined) byPick.set(p.id, { id: p.id, times: 1, chars: p.chars })
445
+ else {
446
+ box.times += 1
447
+ box.chars += p.chars
448
+ }
449
+ }
450
+ }
451
+ const rankedPicks = [...byPick.values()].sort((a, b) => b.chars - a.chars || b.times - a.times || a.id.localeCompare(b.id))
452
+ const pickInjected = picked.reduce((a, e) => a + e.len, 0)
453
+ const share = pickInjected > 0 ? Math.round((pickChars / pickInjected) * 100) : 0
454
+ lines.push(
455
+ `按条流水:${picked.length} 轮有按条记录,${pickTotal} 条次共 ${pickChars.toLocaleString('en-US')} 字(占这些轮注入字数的 ${share}%)`,
456
+ )
457
+ const topPicks = rankedPicks.slice(0, 3)
458
+ lines.push(
459
+ `- 吃额度最多:${topPicks
460
+ .map((b) => `${b.id} ${b.times} 次 / ${b.chars.toLocaleString('en-US')} 字`)
461
+ .join(' · ')}${rankedPicks.length > topPicks.length ? `(另有 ${rankedPicks.length - topPicks.length} 条)` : ''}`,
462
+ )
463
+ lines.push(
464
+ '- 按条字数 = 这一轮真正写进上下文的那段(被压过的条只算压过的长度);要动某一条先 memory_read(id) 看全文,再 memory_update 压短或归档',
465
+ )
466
+ // 三种轮要分开数:有记录的、有记录但一条没进的(`picks=-`)、根本没记录的(老日志)。
467
+ // 合成一句「N 轮没有按条记录」会把「这轮被闸挡住了」说成「这轮没记账」。
468
+ const noPick = injected.filter((e) => !e.hasPicks).length
469
+ const emptyPick = injected.filter((e) => e.hasPicks && e.picks.length === 0).length
470
+ if (emptyPick > 0) {
471
+ lines.push(`- 另有 ${emptyPick} 轮有按条记录但一条没进(被闸门或预算挡下的轮,字数是骨架与边界句)`)
472
+ }
473
+ if (noPick > 0) {
474
+ lines.push(`- 另有 ${noPick} 轮没有按条记录(\`picks=\` 是 0.6.71 起才写的):这些轮的字数照算,但算不出是哪几条`)
475
+ }
476
+ } else {
477
+ lines.push(
478
+ `按条流水:这 ${injected.length} 轮都还没有按条记录(\`picks=\` 是 0.6.71 起才写的)——跑一轮新版再看,那时能看清这一轮具体是哪几条在花字数。`,
479
+ )
480
+ }
481
+ }
482
+ // 这三行与「注入了多少轮」无关:全被挡下的会话里它们才是唯一有信息量的读数。
483
+ if (gated > 0) lines.push(`闸门挡下的条目:${gated} 条(过线但没进注入的)`)
484
+ if (bodyCut > 0) lines.push(`正文被压:${bodyCut} 条(只留了首句或前几句,全文要用 id 去 memory_read)`)
485
+ if (repeated > 0) lines.push(`同话题抑制:${repeated} 条(上一轮注入过、相似度超线的条目,按条算不按轮算)`)
486
+ // [0.6.49] 「放回」不是「跳过」:它是把本会话里隔得够久的条目重新放回候选,
487
+ // 所以它涨的一般伴随注入条数涨——面板上单列一行,免得被读成又被挡了一批。
488
+ if (released > 0) lines.push(`老条目放回:${released} 条(隔 ${reinjectTurns} 轮没再给过的条目重新进候选;0 = 永不放回)`)
489
+ // [0.6.72] 落选名单:上面三行只给总数(挡下几条 / 压了几条 / 抑制几条),答不出
490
+ // 「为什么这条记忆从来不出现」。引擎从 0.6.72 起把每条落选的 id / 分数 / 原因写进
491
+ // `drops=`,这里按条目聚合,并按主因给一句可执行的对策——四种原因的对策完全不同,
492
+ // 猜错就是白改:分数不够要补词面,单字兜底要补两字词,同话题抑制其实什么都不用改,
493
+ // 被字数上限挤掉的则要压短条目或调额度。
494
+ const dropEvents = [...injected, ...skips]
495
+ // 「有这一栏」与「这一栏里有人」是两件事:`drops=-` 的轮记了账但没人落选,
496
+ // 不能算进「N 轮记下 M 条次」的 N 里。
497
+ const dropRounds = dropEvents.filter((e) => Array.isArray(e.drops) && e.drops.length > 0)
498
+ const dropAll = []
499
+ for (const e of dropRounds) for (const d of e.drops) dropAll.push({ ...d, at: e.at })
500
+ if (dropAll.length > 0) {
501
+ const byDrop = new Map()
502
+ for (const d of dropAll) {
503
+ const box = byDrop.get(d.id) ?? { id: d.id, times: 0, byReason: new Map(), lastAt: 0, lastScore: null }
504
+ box.times += 1
505
+ box.byReason.set(d.reason, (box.byReason.get(d.reason) ?? 0) + 1)
506
+ if (d.at >= box.lastAt) {
507
+ box.lastAt = d.at
508
+ box.lastScore = d.score
509
+ }
510
+ byDrop.set(d.id, box)
511
+ }
512
+ const rankedDrops = [...byDrop.values()].sort((a, b) => b.times - a.times || b.lastAt - a.lastAt || a.id.localeCompare(b.id))
513
+ const reasonCount = new Map()
514
+ for (const d of dropAll) reasonCount.set(d.reason, (reasonCount.get(d.reason) ?? 0) + 1)
515
+ const reasonText = [...reasonCount.entries()]
516
+ .sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])))
517
+ .map(([k, v]) => `${k === '' ? '未记' : k} ${v}`)
518
+ .join(' · ')
519
+ lines.push(
520
+ '',
521
+ `落选名单:${dropRounds.length} 轮记下 ${dropAll.length} 条次,去重 ${rankedDrops.length} 条(${reasonText})`,
522
+ )
523
+ const topDrops = rankedDrops.slice(0, 3)
524
+ for (const box of topDrops) {
525
+ const reasons = [...box.byReason.entries()]
526
+ .sort((a, b) => b[1] - a[1])
527
+ .map(([k, v]) => `${k === '' ? '未记' : k} ${v}`)
528
+ .join(' / ')
529
+ const scoreText = box.lastScore === null ? '' : `,最近分数 ${box.lastScore.toFixed(2)}`
530
+ lines.push(`- ${box.id} 挡了 ${box.times} 次(${reasons}),最近 ${stamp(box.lastAt)}${scoreText}`)
531
+ lines.push(` ${dropAdvice(box)}`)
532
+ }
533
+ if (rankedDrops.length > topDrops.length) lines.push(`- 另有 ${rankedDrops.length - topDrops.length} 条落选(按次数排在后面)`)
534
+ const noDrop = dropEvents.filter((e) => e.hasDrops !== true).length
535
+ if (noDrop > 0) lines.push(`- 另有 ${noDrop} 轮没有落选记录(\`drops=\` 是 0.6.72 起才写的):这些轮挡了谁算不出来`)
536
+ lines.push(' 被挡的条目仍在 memory_search 的候选里(闸门只拦注入,不拦检索)——「没进上下文」不等于「没了」;id 是日志里的前 8 位,认全用 memory_search')
537
+ } else if (dropEvents.length > 0) {
538
+ // 一个落选都没有,与「这份日志还没有这一栏」是两件事,分开说。
539
+ const noDrop = dropEvents.filter((e) => e.hasDrops !== true).length
540
+ lines.push(
541
+ '',
542
+ noDrop === dropEvents.length
543
+ ? `落选名单:这 ${dropEvents.length} 轮都还没有落选记录(\`drops=\` 是 0.6.72 起才写的)——跑一轮新版再看,那时能看清哪几条被挡、为什么。`
544
+ : '落选名单:这一段时间没有条目落选(每一轮的候选都进上下文了)。',
545
+ )
546
+ }
547
+ // [0.6.50] 邻域这一半:它和命中注入花同一份预算,但口径不同——命中是「注入了多少字」,
548
+ // 邻域是「这一轮星图带了几条、砍了几条」。两个数不许相加(同一条记忆可能两层都带,
549
+ // 跨层去重是**邻域**跳过的,命中那边已经算过它自己的字)。
550
+ if (chains.length > 0 || neighborSkips.length > 0 || suspects.length > 0 || fixes.length > 0) {
551
+ const nRounds = chains.length + neighborSkips.length
552
+ const nLens = chains.map((e) => e.chars).sort((a, b) => a - b)
553
+ const nSum = nLens.reduce((a, b) => a + b, 0)
554
+ const nAvg = nLens.length > 0 ? Math.round(nSum / nLens.length) : 0
555
+ const nIds = chains.reduce((a, e) => a + e.ids, 0)
556
+ const nDeduped = chains.reduce((a, e) => a + e.deduped, 0)
557
+ const nOfftopic = chains.reduce((a, e) => a + e.offtopic, 0)
558
+ const nWeak = chains.reduce((a, e) => a + e.weak, 0)
559
+ const nFlagged = chains.reduce((a, e) => a + e.flagged, 0)
560
+ lines.push(
561
+ '',
562
+ chains.length > 0
563
+ ? `邻域注入:${nRounds} 轮里 ${chains.length} 轮带进上下文(合计 ${nSum.toLocaleString('en-US')} 字 / 平均 ${nAvg} 字每轮 / 中位 ${p50Of(nLens)} / 最多 ${nLens[nLens.length - 1]} · 共 ${nIds} 条)`
564
+ : `邻域注入:${nRounds} 轮一次都没带进上下文`,
565
+ )
566
+ if (neighborSkips.length > 0) {
567
+ const byN = new Map()
568
+ for (const e of neighborSkips) byN.set(e.reason, (byN.get(e.reason) ?? 0) + 1)
569
+ const bits = []
570
+ for (const [r, n] of byN) bits.push(`${neighborReasonLabel(r)} ${n} 轮`)
571
+ lines.push(`- 没带的原因:${bits.join(' · ')}`)
572
+ }
573
+ if (nDeduped > 0) lines.push(`- 跨层去重:跳过 ${nDeduped} 条(别的注入这轮已经带过,邻域不再带第二遍)`)
574
+ if (nOfftopic > 0) lines.push(`- 未沾词:${nOfftopic} 条(强度够但一个词面都不沾,一轮只留一条,其余砍掉)`)
575
+ if (nWeak > 0) lines.push(`- 强度不够:${nWeak} 条(低于门槛,一条都没带)`)
576
+ if (nFlagged > 0) lines.push(`- 打标记:${nFlagged} 条(带了「未沾词」标记,尾部给了 mute 指引)`)
577
+ // [0.6.54] 错边这一行回答的是「那些标了未沾词的跳,后来怎么了」:
578
+ // 压住了几跳(先不带,省下来的就是上下文)、AI 真断掉了几跳(mute 之后当场销账)。
579
+ // 两边都为 0 就不出行——没发生的事不该占一行。
580
+ const withheldLast = suspects.length > 0 ? suspects[suspects.length - 1].withheld : 0
581
+ const withheldTurns = suspects.length > 0 ? suspects[suspects.length - 1].turns : 0
582
+ const fixedTotal = fixes.reduce((a, e) => a + e.cleared, 0)
583
+ if (withheldLast > 0 || fixedTotal > 0) {
584
+ const bits = []
585
+ if (withheldLast > 0)
586
+ bits.push(`暂时不带 ${withheldLast} 跳(连标 ${withheldTurns} 轮还没修,图没动、账留着)`)
587
+ if (fixedTotal > 0) bits.push(`AI 已断 ${fixedTotal} 跳(mute 之后当场销账)`)
588
+ lines.push(`- 错边:${bits.join(' · ')}`)
589
+ }
590
+ // [0.6.55] 一轮总上限:回答「用户设的那个数,实际是怎么被花掉的」。
591
+ // 只报真设了上限的轮(turnCap > 0)——没设的人不该被一行「不限」占掉视线。
592
+ const capped = chains.filter((e) => e.turnCap > 0)
593
+ if (capped.length > 0) {
594
+ const last = capped[capped.length - 1]
595
+ const carried = last.turnSpent ?? 0
596
+ const spent = carried + last.chars
597
+ const left = Math.max(0, last.turnCap - spent)
598
+ lines.push(
599
+ `- 一轮总上限 ${last.turnCap.toLocaleString('en-US')} 字:最近一轮 命中 ${carried.toLocaleString('en-US')} + 邻域 ${last.chars.toLocaleString('en-US')} = ${spent.toLocaleString('en-US')}(还剩 ${left.toLocaleString('en-US')} 字)`,
600
+ )
601
+ }
602
+ }
603
+ if (roundPairs.length > 0) {
604
+ lines.push(
605
+ '',
606
+ `一轮合计:命中与邻域都有账的 ${roundPairs.length} 轮里,一起花 ${roundSum.toLocaleString('en-US')} 字(平均 ${roundAvg} 字 / 最多 ${roundMax} 字;其中邻域 ${roundNeighborSum.toLocaleString('en-US')} 字,占 ${roundShare}%)`,
607
+ )
608
+ }
609
+ if (sessionLast !== null && sessionLast.hitChars + sessionLast.chainChars > 0) {
610
+ const total = sessionLast.hitChars + sessionLast.chainChars
611
+ const short = sessionLast.sid.length > 8 ? sessionLast.sid.slice(0, 8) + '…' : sessionLast.sid
612
+ lines.push(
613
+ '',
614
+ `本场会话(${short}):命中注入 ${sessionLast.hitRounds} 轮 / ${sessionLast.hitChars.toLocaleString('en-US')} 字,` +
615
+ `邻域 ${sessionLast.chainRounds} 轮 / ${sessionLast.chainChars.toLocaleString('en-US')} 字,合计 ${total.toLocaleString('en-US')} 字`,
616
+ )
617
+ }
618
+ if (sessionLast !== null) {
619
+ // [0.6.53] 除最近一场之外的场次:只列有字的,按时间新的在前,最多 3 场。
620
+ // 零字的场次(整场都在挡下)不进「其他场次」,也不进「另有 N 场」——它没花钱。
621
+ const withChars = [...sessionOf.values()].filter((b) => b.hitChars + b.chainChars > 0)
622
+ const others = withChars
623
+ .filter((b) => b !== sessionLast)
624
+ .sort((a, b) => b.last - a.last)
625
+ .slice(0, 3)
626
+ if (others.length > 0) {
627
+ const parts = others.map((b) => {
628
+ const total = b.hitChars + b.chainChars
629
+ const short = b.sid.length > 8 ? b.sid.slice(0, 8) + '…' : b.sid
630
+ return `${short} ${total.toLocaleString('en-US')} 字(命中 ${b.hitRounds} 轮 / 邻域 ${b.chainRounds} 轮)`
631
+ })
632
+ const more = withChars.length - 1 - others.length
633
+ lines.push(`其他场次:${parts.join(' · ')}${more > 0 ? `(另有 ${more} 场未列)` : ''}`)
634
+ }
635
+ }
636
+ if (legacy > 0) {
637
+ // 旧格式只记「注入成功」的那些轮,挡下的轮根本没写行——所以「0 轮挡下」这种读数
638
+ // 在旧格式日志上必须当场解释掉,否则会被读成「从来没挡过任何东西」。
639
+ lines.push(
640
+ '',
641
+ `另有 ${legacy} 行是 0.6.43 及以前的旧格式(没有 floor / gated 读数,挡下的轮也没写行):` +
642
+ '字数照算,闸门读数与「挡下」计数不全——上面的挡下轮数只统计新格式。',
643
+ )
644
+ }
645
+
646
+ // [0.6.51] 明细里同理:同一轮的命中行与邻域行并成一行,邻域那行不再单独出现。
647
+ // [0.6.54] 同一轮里 reason=suspect 的 nskip 行与 nsuspect 行说的是同一件事:
648
+ // 前者记「这轮一个字都没带」,后者记「压住了哪几跳」。都写了一行就取信息多的那条。
649
+ const suspectTurnsAt = neighborSkips.filter((e) => e.reason === 'suspect').map((e) => e.at)
650
+ const nearSuspectSkip = (at) => suspectTurnsAt.some((v) => Math.abs(v - at) <= 2000)
651
+ const chainOfHit = new Map()
652
+ const mergedChains = new Set()
653
+ for (const p of roundPairs) {
654
+ chainOfHit.set(p.hit, p.chain)
655
+ mergedChains.add(p.chain)
656
+ }
657
+
658
+ const want = Math.max(0, Math.trunc(numOf(limit, 12)))
659
+ if (want > 0) {
660
+ const recent = events.slice(-want).reverse()
661
+ lines.push('', `最近 ${recent.length} 轮(新的在前):`)
662
+ for (const e of recent) {
663
+ if (e.kind === 'hit') {
664
+ if (e.hit !== 'yes') {
665
+ // 旧格式的「没命中」:字数照印(那点字是骨架/边界句,不是记忆),原因不明就说原因不明
666
+ lines.push(`- ${stamp(e.at)} 没注入(${e.len} 字骨架${e.hit === 'unknown' ? ',出口没记' : ''})`)
667
+ continue
668
+ }
669
+ const bits = [`注入 ${e.len} 字`]
670
+ if (e.gated !== null && e.gated > 0) bits.push(`挡 ${e.gated} 条`)
671
+ if (e.bodyCut !== null && e.bodyCut > 0) bits.push(`压 ${e.bodyCut} 条`)
672
+ if (e.repeated !== null && e.repeated > 0) bits.push(`同类 ${e.repeated}`)
673
+ if (e.released !== null && e.released > 0) bits.push(`放回 ${e.released}`)
674
+ // [0.6.72] 这一轮谁被挡了:写在注入字数后面,与 picks 对称——这边「进了谁」,那边「谁没进」。
675
+ // 必须带「落选」两个字:picks 的条目是 `id N 字`,落选的是 `id 原因 分数`,
676
+ // 不标出来两串挨在一起会被读成同一种东西。
677
+ if (Array.isArray(e.drops) && e.drops.length > 0) {
678
+ bits.push(`落选 ${e.drops.map((d) => `${d.id} ${d.reason}${d.score === null ? '' : ` ${d.score.toFixed(2)}`}`).join(' / ')}`)
679
+ }
680
+ const mate = chainOfHit.get(e)
681
+ if (mate) {
682
+ bits.push(`邻域 ${mate.ids} 条 ${mate.chars} 字(合计 ${e.len + mate.chars} 字)`)
683
+ }
684
+ // [0.6.71] 这一轮具体进了哪几条:紧跟在字数后面,明细行自己就能回答「哪几条」。
685
+ // 被压过的条带上模式(squeeze/clip/head),一眼能看出这条是「真进去了」还是「只留了个头」。
686
+ if (e.picks.length > 0) {
687
+ bits.push(
688
+ e.picks
689
+ .map((p) => `${p.id} ${p.chars} 字${p.mode === '' || p.mode === 'full' ? '' : `(${p.mode})`}`)
690
+ .join(' · '),
691
+ )
692
+ }
693
+ lines.push(`- ${stamp(e.at)} ${bits.join(' · ')}`)
694
+ } else if (e.kind === 'neighbor') {
695
+ // 0.6.51:已经并进上面那行「注入 … 字 · 邻域 … 字(合计)」的那一轮,不再重复出现。
696
+ if (mergedChains.has(e)) continue
697
+ const bits = [`邻域 ${e.ids} 条`, `${e.chars} 字`]
698
+ if (e.offtopic > 0) bits.push(`未沾词 ${e.offtopic}`)
699
+ if (e.deduped > 0) bits.push(`去重 ${e.deduped}`)
700
+ if (e.flagged > 0) bits.push(`打标 ${e.flagged}`)
701
+ lines.push(`- ${stamp(e.at)} ${bits.join(' · ')}`)
702
+ } else if (e.kind === 'nskip') {
703
+ const nkv = pairsOf(e.extra)
704
+ const heldIds = String(nkv.ids ?? '').split(',').filter((v) => v !== '')
705
+ const held = heldIds.length > 0 ? ` · ${heldIds.length} 跳:${heldIds.slice(0, 4).join('、')}` : ''
706
+ lines.push(`- ${stamp(e.at)} 邻域没带:${neighborReasonLabel(e.reason)}${held}`)
707
+ } else if (e.kind === 'nfix') {
708
+ // 压住的那一支(nsuspect)不单独出行:它总和同一轮的 neighbor-chain 一起写,
709
+ // 上面那行「邻域 N 条」已经代表这一轮了;只有「真断了」是模型改了图,值得单独一条。
710
+ lines.push(`- ${stamp(e.at)} 断开一跳:${e.a} ↔ ${e.b}(${e.via || 'mute'},销账 ${e.cleared} 条)`)
711
+ } else if (e.kind === 'nsuspect') {
712
+ // 这一轮如果连一条都没带,上面「邻域没带」那行已经报了压住几跳,别再说一遍。
713
+ if (nearSuspectSkip(e.at)) continue
714
+ const who = e.ids.length > 0 ? `:${e.ids.slice(0, 4).join('、')}` : ''
715
+ lines.push(`- ${stamp(e.at)} 错边压住:${e.withheld} 跳先不带(窗口 ${e.turns} 轮)${who}`)
716
+ } else {
717
+ lines.push(`- ${stamp(e.at)} 挡下:${reasonLabel(e.reason)}${detailOf(e)}`)
718
+ }
719
+ }
720
+ } else if (want === 0) {
721
+ lines.push('', '按你给的 limit=0 这次一条明细都不列(统计照算)。')
722
+ }
723
+
724
+ lines.push('', `日志:${nowFile}${files.length > 1 ? `(含 1 份 .old)` : ''} · ${fmtKb(totalBytes)} · ${events.length} 行账`)
725
+ if (bad > 0) lines.push(`另有 ${bad} 行长得像注入账却解析不出来,一行都没算进去。`)
726
+
727
+ const oldest = events[0]?.at ?? 0
728
+ const newest = events[events.length - 1]?.at ?? 0
729
+ const scope =
730
+ oldest > 0
731
+ ? `覆盖 ${stamp(oldest)} 到 ${stamp(newest)} 的 ${rounds} 轮出口记录${chains.length + neighborSkips.length > 0 ? ` · 邻域 ${chains.length + neighborSkips.length} 轮` : ''}`
732
+ : `覆盖 ${rounds} 轮出口记录(时间读不出来)`
733
+ return { body: lines.join('\n'), scope }
734
+ }
735
+
736
+ function detailOf(e) {
737
+ const extra = String(e.extra ?? '')
738
+ if (extra === '') return ''
739
+ // 去掉 reason=k 之后剩下的 kv,只挑读者能用的
740
+ const kv = pairsOf(extra)
741
+ const bits = []
742
+ if (kv.gated !== undefined) bits.push(`挡 ${numOf(kv.gated)} 条`)
743
+ if (kv.floor !== undefined) bits.push(`floor ${kv.floor}`)
744
+ if (kv.similar !== undefined) bits.push(`相似 ${kv.similar}`)
745
+ if (kv.sim !== undefined) bits.push(`相似 ${kv.sim}`)
746
+ if (kv.spent !== undefined) bits.push(`累计 ${kv.spent}`)
747
+ if (kv.released !== undefined && numOf(kv.released) > 0) bits.push(`放回 ${numOf(kv.released)} 条`)
748
+ if (kv.reinject !== undefined) bits.push(`窗口 ${kv.reinject} 轮`)
749
+ // [0.6.72] 整轮被挡的那些轮,明细里也要看得见「挡的是谁」——只写「挡 3 条」,读者还得回头翻名单。
750
+ const skipDrops = dropsOf(kv.drops)
751
+ if (skipDrops !== null && skipDrops.length > 0) bits.push(`落选 ${skipDrops.map((d) => d.id).join('/')}`)
752
+ return bits.length > 0 ? `(${bits.join(' · ')})` : ''
753
+ }
754
+
755
+ /** [0.6.50] 邻域这边的出口名:与命中那边的四种出口不是一套,别复用 reasonLabel。 */
756
+ function neighborReasonLabel(reason) {
757
+ switch (String(reason)) {
758
+ case 'short':
759
+ return '问句太短(不到 6 字,不猜)'
760
+ case 'empty':
761
+ return '星图没给出可用的邻居(全被强度 / 词面 / 已带过刷掉)'
762
+ case 'tool':
763
+ return '星图没查成(工具失败)'
764
+ case 'llm':
765
+ return '拿不到消息工厂'
766
+ case 'empty-msg':
767
+ return '这一轮没有消息'
768
+ case 'subagent':
769
+ return '子代理轮不注入'
770
+ case 'suspect':
771
+ return '错边压住(连续标了未沾词,先不带)'
772
+ case 'turncap':
773
+ return '撞一轮总上限(本轮剩余不够开一块)'
774
+ case 'edgeturn':
775
+ return '边缘单条歇一轮(下轮照带)'
776
+ default:
777
+ return reason === '' ? '出口没写原因' : reason
778
+ }
779
+ }
780
+
781
+ function reasonLabel(reason) {
782
+ switch (String(reason)) {
783
+ case 'empty':
784
+ return '未命中(没有条目过搜索线)'
785
+ case 'floor':
786
+ return '命中闸门(过搜索线但没过 floor)'
787
+ // [0.6.72] 0.6.60 的字面兜底出口从前没名字,明细里一直念原文 `literal`;
788
+ // 现在落选名单会点名这类条目,出口名必须说人话。
789
+ case 'literal':
790
+ return '只对上单字(字面兜底不算证据)'
791
+ case 'budget':
792
+ return '会话预算用尽'
793
+ case 'repeat':
794
+ return '同话题抑制(上轮已注入)'
795
+ // [0.6.73] 陪跑线:不是分数不够,是比第一名差太远(相对门槛)。
796
+ case 'margin':
797
+ return '陪跑(比第一名差太远)'
798
+ default:
799
+ return reason === '' ? '出口没写原因' : reason
800
+ }
801
+ }
802
+
803
+ /**
804
+ * [0.6.72] 落选原因 → 一句能照做的话。四种原因的对策互不相同,混着给等于没给:
805
+ * floor 差在词面(补 keywords 才是正解,importance 每档只 +25%),literal 差在「只对上一个字」,
806
+ * repeat 根本不是毛病(同一话题上一轮刚给过),cap 差在额度而不是分数。
807
+ */
808
+ const DROP_ADVICE = {
809
+ floor: '分数不到门槛(词面对上了但不够):要它进来就把你真正会问它的说法补进 keywords(memory_update(id="…", keywords=[…]));提 importance 每档只多 25%,救不回差得远的',
810
+ literal: '只对上一个字(单字兜底不算证据):keywords 里补一个两字以上的词,正文里也把那个词写全',
811
+ repeat: '上一轮刚给过同一批(同话题只注入更相关的新信息):换一轮或换个问法就会回来,急用就 memory_search',
812
+ cap: '这一轮的字数上限把它挤出去了:条目压短(memory_update),或调大 injectMaxChars / injectTurnMaxChars',
813
+ // [0.6.73] 陪跑与前面四种都不同:它不是「分数不够格」,是这一轮第一名已经够强——
814
+ // 要它常进来,得让它变成「这句话的第一名」,而不是去调门槛(调低 marginRatio 只是把噪声也放进来)。
815
+ margin: '陪跑(第一名比它强太多,这一轮的名额该给第一名):它不是坏了,只是没成为这句话的第一名;想让它常进来,就把你真正会问它的说法补进 keywords,或把陪跑线调低(0 = 关)',
816
+ }
817
+
818
+ function dropAdvice(box) {
819
+ let best = ''
820
+ let n = -1
821
+ for (const [k, v] of box.byReason) {
822
+ if (v > n) {
823
+ n = v
824
+ best = k
825
+ }
826
+ }
827
+ return DROP_ADVICE[best] ?? `被挡的原因「${best === '' ? '未记' : best}」没有现成对策——先看上面的闸门读数,再 memory_read 看这一条本身`
828
+ }
829
+
830
+ function fmtKb(bytes) {
831
+ const n = Number(bytes) || 0
832
+ if (n < 1024) return `${n} B`
833
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
834
+ return `${(n / 1024 / 1024).toFixed(2)} MB`
835
+ }
836
+
837
+ function safeRead(path) {
838
+ try {
839
+ return readFileSync(path, 'utf8')
840
+ } catch {
841
+ return ''
842
+ }
843
+ }