dsh-qqbot-muu 0.1.21 → 0.1.23

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.
@@ -1,802 +1,827 @@
1
- import { existsSync as __existsSync } from 'node:fs'
2
- const __repoRoot = (() => {
3
- let cached = ''
4
- const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
5
- return () => {
6
- if (cached) return cached
7
- const cands = []
8
- const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
9
- if (env) cands.push(norm(env))
10
- try {
11
- let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
12
- if (here[0] === '/' && here[2] === ':') here = here.slice(1)
13
- here = norm(here).replace(/\/+$/, '')
14
- let d = here
15
- for (let i = 0; i < 6; i += 1) {
16
- if (!d) break
17
- cands.push(d)
18
- const k = d.lastIndexOf('/')
19
- d = k > 0 ? d.slice(0, k) : ''
20
- }
21
- } catch { /* noop */ }
22
- try { cands.push(norm(process.cwd())) } catch { /* noop */ }
23
- for (const c of cands) {
24
- try {
25
- if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
26
- } catch { /* noop */ }
27
- }
28
- cached = norm(cands.find(Boolean) || '.')
29
- return cached
30
- }
31
- })()
32
- /**
33
- * memory-recall.mjs — 入站时按需召回长期记忆(Neuro 式「检索而非重放」)
34
- *
35
- * 挂点:早挂点 onInbound —— 链上唯一能 `ctx.rewrite()` 改到"进上下文那版文本"的位置。
36
- *
37
- * 它做两件事:
38
- * ① 召回:拿当前这句话去记忆库做向量近邻,命中就追加一个 [记忆] 块(≤300 字)
39
- * ② 沉淀:把这条消息(去掉 [记忆] 块的原文本)记成一条 event 记忆,带 embedding 去重
40
- *
41
- * 为什么这样省钱:
42
- * 现在每轮带的是「最近 10 条原文」(常 1000~2000 字),超出就永久丢;
43
- * 改成「4 条语义相关的提炼」≈160 字,且旧信息能随时被召回。
44
- *
45
- * 安全契约:
46
- * · 全程 try/catch,任何异常都只记日志并照常 next() —— 绝不让记忆功能影响聊天;
47
- * · 拿不到模型就退化成字符 n-gram(memory-core 内部处理),再不行就整块跳过。
48
- */
49
-
50
- // 存储后端在门面里选:优先 SQLite(memory-db),不可用自动回退 JSONL(memory-core)。
51
- import { appendFileSync } from 'node:fs';
52
- import { createHash } from 'node:crypto';
53
- import {
54
- loadConfig, recall, remember, drainInbox, digestScope, shouldDigest, formatRecallBlock, stats,
55
- ingestChatHistory, personProfile,
56
- } from '../lib/memory.mjs';
57
- // 世界书:设定按关键词命中才注入,不进常驻 prompt
58
- import { loreFor } from '../lib/lore-core.mjs';
59
- // 印象卡 + 心情 + 关系温度:让"对熟人更熟、今天状态不同"能被主模型看见
60
- // 2026-10-23:印象卡与熟识度在底层统一成 persona.fam:<senderId>,注入只留一个 [印象] 块
61
- import { familiarityBlockFor, moodBlockFor, getPersonaValue } from '../lib/profile-core.mjs';
62
- // scope / subj 统一口径(与 outbound/memory-agent、tools/memory 共用一份实现)
63
- import { scopeOfMessage, subjOfMessage } from '../lib/scope-util.mjs';
64
- // 记忆轨迹:给浮窗「记忆」页显示召回/整理是否真的跑了
65
- import { trace as traceMemory } from '../lib/memory-trace.mjs';
66
- // 反重复:把她刚说过的几句附在后面(AI 味最大来源就是重复)
67
- import { formatEchoBlock } from '../lib/self-echo.mjs';
68
- // 学来的说话习惯(从群聊/导入记录里提炼,只学表达方式)
69
- import { currentStyle } from '../lib/imitate.mjs';
70
- // 记忆"过一遍小模型":把 2 条以上的召回压成一句她自己的回忆(省 token + 去念资料感)
71
- import { rewriteRecall } from '../lib/memory-llm.mjs';
72
- // 群等级:特别关心群/私聊走完整档;普通群只看信息本身,但保留一个极短认人块(避免不认人)
73
- import { tierOf, policyFor, isPriorityPerson } from '../lib/group-tiers.mjs';
74
- import { compactBlockFor } from '../lib/profile-core.mjs';
75
- import { bedrockBlock } from '../lib/bedrock.mjs';
76
- import { beliefs } from '../lib/memory-hippo.mjs';
77
- // 表情包提醒:用会话状态记"上次发图/上次提醒"的时间(2026-10-27)
78
- import { getChatState, setChatState } from '../lib/chatlog-db.mjs';
79
- // 注入块统一预算(第 4 批「上下文统一」):与微信侧同一套打包规则
80
- import { packByBudget, joinKept } from '../lib/context-budget.mjs';
81
- // [mmtr 2026-10-27]:会遗忘的记忆层——防自增强(刚用过的降权+只记日志)与承诺账本([约定]块)
82
- import { promiseBlockFor, applyRecallGuard } from '../lib/memory-mmtr.mjs';
83
- // 2026-11-11 主人报「消息号跑到 [信条] 前面」→ 稳定块一律置顶,其余垫底
84
- import { mergeStableFirst } from '../lib/stable-first.mjs';
85
- // 2026-11-30 记忆审查:主人身份表(谁的提问算"自己人")
86
- import { personalIds } from '../lib/personal-ids.mjs';
87
-
88
- // ── 2026-11-30 注入总控(memory-config.json → inject)──────────────────────────
89
- // 目的:把"每轮都塞一大段"改成"新会话一次性全量 + 之后只注入变化",
90
- // 并让人按喜好关掉某类块(比如不喜欢带性格、不要世界书)。
91
- // 没写 inject 的旧配置 → 全部默认开,行为与以前一致(兼容)。
92
- function injectOn(cfg, key, dflt = true) {
93
- const inj = cfg && cfg.inject;
94
- if (!inj || typeof inj !== 'object') return dflt;
95
- return inj[key] !== false;
96
- }
97
-
98
- // ── 2026-11-30 记忆审查 ──────────────────────────────────────────────────
99
- // 不是一刀切:只遮蔽"可被拿去用的隐私字段",其余记忆照常注入。
100
- const SENSITIVE_PATTERNS = [
101
- { re: /(?<!\d)1[3-9]\d{9}(?!\d)/g, to: '(手机号略)' },
102
- { re: /(?<!\d)\d{17}[\dXx](?!\d)/g, to: '(身份证略)' },
103
- { re: /(?<!\d)\d{16,19}(?!\d)/g, to: '(卡号略)' },
104
- { re: /(密码|口令|验证码)\s*[::=]?\s*\S{4,}/g, to: '$1(略)' },
105
- { re: /(微信号|微信|vx|VX|QQ号|qq号|账号|帐号)\s*[::=]?\s*[A-Za-z0-9_-]{5,}/g, to: '$1(略)' },
106
- // 地址只遮蔽"带门牌号"的完整地址(避免把"城市/在市区"这类普通词误伤)
107
- { re: /([\u4e00-\u9fa5]{2,12}(?:省|市|区|县)[\u4e00-\u9fa5]{0,12}(?:路|街|道|小区|镇|村))(\s*\d{1,5}\s*(?:号|栋)(?:\s*\d{1,5}\s*(?:单元|室|楼|层))?|\s*\d{1,5}\s*(?:单元|室|楼|层))/g, to: '$1(门牌略)' },
108
- ];
109
- function redactSensitive(text) {
110
- let s = String(text || '');
111
- for (const p of SENSITIVE_PATTERNS) {
112
- try { s = s.replace(p.re, p.to); } catch { /* 浏览器/旧 node 不支持 lookbehind 就跳过这一条 */ }
113
- }
114
- return s;
115
- }
116
- /** 套记忆/倒资料的口吻(只拦"列全部/导出/念出来",普通询问不受影响) */
117
- function isDumpRequest(text) {
118
- const s = String(text || '');
119
- if (!s || s.length > 200) return false;
120
- const wantsAll = /(全部|所有|全都|整个|完整|逐条|一条一条|列出来|列一下|导出|备份|复述|念出来|背出来|发给我|打包)/;
121
- const target = /(记忆|记忆库|数据库|档案|设定|世界书|知识库|后台|系统提示|提示词|prompt|人设|配置)/i;
122
- return wantsAll.test(s) && target.test(s);
123
- }
124
- function ownerIds() {
125
- try {
126
- const ids = personalIds();
127
- const out = new Set((ids && Array.isArray(ids.owners) ? ids.owners : []).map((x) => String(x)).filter(Boolean));
128
- if (ids && ids.stelle) out.add(String(ids.stelle));
129
- return out;
130
- } catch { return new Set(); }
131
- }
132
-
133
- // 一个会话里性格/印象只强调一次(换档/压缩时纪元 +1 → 自然重置)
134
- const _personaOnce = new Set();
135
-
136
-
137
- // 性格倾向 → 一句话(主人 2026-10-26 要求让 belief 层真正被模型看到)。
138
- // trait 值是小步长缓变量,文本天然轮间稳定,不会破坏 prompt 缓存;
139
- // 只在完整档(特别关心/私聊)注入,普通群一个字不多花。
140
- const TRAIT_LABELS = {
141
- warmth: ['待人热情', '偏冷淡'],
142
- trust: ['值得信任', '需留个心眼'],
143
- humor: ['爱开玩笑', '正经话少'],
144
- reliability: ['说到做到', '常放鸽子'],
145
- boundary: ['有分寸', '爱越界'],
146
- energy: ['活跃话多', '安静寡言'],
147
- };
148
- function traitBlockFor(dataRoot, senderId) {
149
- const sid = String(senderId || '').trim();
150
- if (!sid || !/^[\w-]+$/.test(sid)) return '';
151
- let rows = [];
152
- try { rows = beliefs(dataRoot, 'person:qq:' + sid) || []; } catch { return ''; }
153
- const hits = rows
154
- .filter((b) => b && Math.abs(b.value) >= 0.3 && (b.n || 0) >= 3)
155
- .sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
156
- .slice(0, 2)
157
- .map((b) => {
158
- const pair = TRAIT_LABELS[b.key];
159
- if (!pair) return '';
160
- return b.value > 0 ? pair[0] : pair[1];
161
- })
162
- .filter(Boolean);
163
- if (!hits.length) return '';
164
- return `\n[性格观察]和他相处下来,感觉他${hits.join('、')}[/性格观察]`;
165
- }
166
-
167
- export const name = 'aa-memory-recall';
168
-
169
- /** 插件数据根(优先级:环境变量 > memory-config.json 的 dataRoot > 默认 {cwd}/dshqqbot) */
170
- function dataRootOf(cfg) {
171
- const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim();
172
- if (env) return env;
173
- return (cfg && cfg.dataRoot) || __repoRoot() + "/dshqqbot";
174
- }
175
-
176
- /** 会话作用域:群按群 openid,私聊按用户 openid(唯一口径见 lib/scope-util.mjs) */
177
- function scopeOf(ctx) {
178
- return scopeOfMessage(ctx?.message);
179
- }
180
-
181
- /** 注入量埋点(与微信侧 contextChars 对等):只写字数/预算,不写消息内容与原始 scope */
182
- function meterInject(dataRoot, scope, chars, dropped) {
183
- try {
184
- const sid = createHash('sha1').update(String(scope || '')).digest('hex').slice(0, 10);
185
- appendFileSync(`${dataRoot}/token-usage.jsonl`, JSON.stringify({
186
- ts: Date.now(), channel: 'qq', scope: sid, chars, dropped: dropped.length,
187
- }) + '\n');
188
- } catch { /* 统计失败绝不影响聊天 */ }
189
- }
190
-
191
- /** 溯源用:各宿主/各版本的消息号字段名不一致,挨个兜一遍 */
192
- function msgIdOf(m) {
193
- if (!m || typeof m !== 'object') return '';
194
- return String(m.msgId ?? m.msg_id ?? m.messageId ?? m.message_id ?? m.id ?? '').slice(0, 96);
195
- }
196
-
197
- /** 归一化:去 @、去空白、去标点,只留汉字/字母/数字 —— 用于自匹配判重 */function normText(s) {
198
- return String(s || '')
199
- .replace(/<@[^>]*>/g, '')
200
- .replace(/[\s\u3000]+/g, '')
201
- .replace(/[^\u4e00-\u9fa5A-Za-z0-9]/g, '')
202
- .toLowerCase();
203
- }
204
-
205
- /** 去掉我们上一轮可能注入过的块([记忆] / [设定] / [印象] / [关系] / [状态]),避免注入被自己的注入污染 */
206
- function stripMemoryBlock(text) {
207
- return String(text || '')
208
- .replace(/\n?\[记忆\][\s\S]*?\[\/记忆\]\n?/g, '\n')
209
- .replace(/\n?\[信条\][\s\S]*?\[\/信条\]\n?/g, '\n')
210
- .replace(/\n?\[设定\][\s\S]*?\[\/设定\]\n?/g, '\n')
211
- .replace(/\n?\[印象\][\s\S]*?\[\/印象\]\n?/g, '\n')
212
- .replace(/\n?\[旧识\][\s\S]*?\[\/旧识\]\n?/g, '\n')
213
- .replace(/\n?\[性格观察\][\s\S]*?\[\/性格观察\]\n?/g, '\n')
214
- .replace(/\n?\[成长\][\s\S]*?\[\/成长\]\n?/g, '\n')
215
- .replace(/\n?\[关系\][\s\S]*?\[\/关系\]\n?/g, '\n')
216
- .replace(/\n?\[状态\][\s\S]*?\[\/状态\]\n?/g, '\n')
217
- .replace(/\n?\[B站\][\s\S]*?\[\/B站\]\n?/g, '\n')
218
- .replace(/\n?\[学\][\s\S]*?\[\/学\]\n?/g, '\n')
219
- .replace(/\n?\[别重复\][^\n]*/g, '\n')
220
- // 2026-10-29 补漏:这三个新块以前不在清单里——若注入文本被引用/回显回来,
221
- // 会被当成用户原文再次沉淀+召回,块会越滚越大(token 放大器)
222
- .replace(/\n?\[情绪回响\][\s\S]*?\[\/情绪回响\]\n?/g, '\n')
223
- .replace(/\n?\[手边\][^\n]*/g, '\n')
224
- .replace(/\n?\[约定\][\s\S]*?\[\/约定\]\n?/g, '\n')
225
- // 2026-11-07:ab-understand 的意图提示也要剥掉,避免被回显后当成用户原话沉淀
226
- .replace(/\n?\[听懂\][\s\S]*?\[\/听懂\]\n?/g, '\n')
227
- .trim();
228
- }
229
-
230
- // 聊天台账补录的节流(每 15s 最多一次;读的是插件已落盘的 msg-history,增量很小)
231
- let _lastChatIngest = 0;
232
- function maybeIngestChat(dataRoot, cfg, logger) {
233
- try {
234
- const now = Date.now();
235
- const every = Math.max(3000, Number(cfg?.chatlog?.ingestThrottleMs) || 15000);
236
- if (now - _lastChatIngest < every) return;
237
- _lastChatIngest = now;
238
- const r = ingestChatHistory(dataRoot, cfg?.chatlog || {});
239
- if (r && r.ok && r.imported > 0) logger?.debug?.(`[chatlog] 补录 ${r.imported} 条`);
240
- } catch { /* 台账是旁路,失败不影响聊天 */ }
241
- }
242
-
243
- /** 纯表情/纯标点/复读/命令 之类不值得记 */
244
- function worthRemembering(text, cfg) {
245
- const t = String(text || '').trim();
246
- if (t.length < (cfg.minTextLen || 6)) return false;
247
- // ★ 2026-10-22 修:实测抓到了 "/bot-restart" —— 斜杠命令不是聊天内容,
248
- // 进记忆库只会污染召回(问"上次说啥"时可能召回一条命令)。
249
- if (t.startsWith('/')) return false;
250
- // 空正文占位(P0-2 引入的)也不该记
251
- if (/^(只 @ 了你一下/.test(t)) return false;
252
- // 不含任何文字/数字 = 纯标点或纯表情符号
253
- if (!/[\u4e00-\u9fa5A-Za-z0-9]/.test(t)) return false;
254
- if (/^\[(图片|语音|视频|表情|文件)[^\]]*\]$/.test(t)) return false;
255
- if (/^[哈嗯哦啊额唔咦哦嘿呀吧嘛]+$/.test(t)) return false;
256
- return true;
257
- }
258
-
259
- // ── [qqbot-mod] slow-block 节流(2026-10-28 主人定:长期可能变的块不必每条消息重复)──
260
- // 现状浪费:印象卡/旧识/学/约定/性格观察这些慢变量(分钟~天级才变)以前**每条消息都全文重发**,
261
- // 且历史里永久留存 → N 条消息 N 份,token 线性上涨。
262
- // 改法:按 scope+tag 记住上次注入的内容指纹,**内容没变就不再注入**——历史里上一份还在,
263
- // 模型照样看得见(语义不变);只有真变了才注入一份新的(新版在后,模型取最新)。
264
- // 快块([记忆]召回/[状态]/[echo])是为当前句服务的,保持每条,但连续相同内容也跳过。
265
- const _slowBlockMemo = new Map(); // key: scope+'|'+tag → 上次注入文本
266
- let _lastRoot = __repoRoot() + "/dshqqbot"; // onInbound 每轮刷新,供 blockIfChanged 持久化记账用
267
- // 2026-10-29:召回源判重——key: scope → 上次实际注入的那批记忆源文本指纹。
268
- // 连续同话题时同一批旧记忆不再每条重发(历史里上一份仍在,模型照样看得见)。
269
- const _recallSrcMemo = new Map();
270
- // 2026-10-30 主人拍板「上下间隔不远就不至于每次都发送」:距上次召回注入 <5 分钟的消息
271
- // 直接跳过召回 —— 连续聊天时上一轮的 [记忆] 块还在会话历史里(全量重发模型),模型看得见。
272
- const _recallTimeMemo = new Map(); // scope → 上次实际注入召回块的时间戳
273
-
274
- // ── 会话账本纪元(2026-11-08,P1-4)──
275
- // 问题:blockIfChanged 只按 scope|tag 去重;会话轮换/压缩后旧历史被裁掉,慢块指纹却没变
276
- // ⇒ 新会话里信条/印象/旧识等整套长期上下文不再注入(文档 P1-4)。
277
- // 解决:给账本加"纪元"维度 —— 检测到轮换/压缩时纪元 +1,所有旧账立刻失效,
278
- // 下一条消息强制整套注入一次;纪元本身落 chat_meta,重启后继续沿用 ⇒ 未轮换时仍续用旧账(重启不丢)。
279
- // 为什么不直接用 sessionId:入站 ctx 拿不到 session/event 里的 session.id(只有出站链的 session.header.id),
280
- // 所以改从 ctx.caps.kernel 订阅宿主事件,用"压缩/首次见到新会话"作为轮换信号。
281
- let _blkEpoch = null;
282
- let _blkEpochRoot = '';
283
- const _seenSessions = new Set(); // 已见过的 DSH 会话 id(最多留 40 个)
284
- let _seenSessionsLoaded = false;
285
- let _rotationHookInstalled = false;
286
- const ROTATION_HOOK_KEY = Symbol.for('im-qqbot.memory-block-epoch');
287
-
288
- let _bootChecked = false;
289
- /** 每次进程启动一个唯一戳:用来判断"这次是重启后第一次注入" */
290
- const BOOT_ID = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
291
-
292
- function epochOf(root) {
293
- const r = String(root || '');
294
- if (_blkEpoch !== null && _blkEpochRoot === r) return _blkEpoch;
295
- _blkEpochRoot = r;
296
- try {
297
- const n = Number(getChatState(r, 'blk-epoch')?.n);
298
- _blkEpoch = Number.isFinite(n) && n >= 0 ? n : 0;
299
- } catch { _blkEpoch = 0; }
300
- // 2026-11-10 主人实测「重启后印象卡失效」:慢块账本落 chat_meta,重启后照样命中"内容没变→不注入",
301
- // 可新进程的会话历史里根本没有那份块 ⇒ 卡片凭空消失。
302
- // 修法:每个进程启动后把纪元 +1,重启后整套慢块重新注入一次(一次性成本,之后继续按内容去重)。
303
- if (!_bootChecked) {
304
- _bootChecked = true;
305
- try {
306
- const mark = String(getChatState(r, 'blk-boot')?.id || '');
307
- if (mark !== BOOT_ID) {
308
- _blkEpoch += 1;
309
- _slowBlockMemo.clear();
310
- _recallSrcMemo.clear();
311
- _recallTimeMemo.clear();
312
- try { setChatState(r, 'blk-epoch', { n: _blkEpoch, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
313
- try { setChatState(r, 'blk-boot', { id: BOOT_ID, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
314
- }
315
- } catch { /* 读不到就当首次启动 */ }
316
- }
317
- // 已见会话集也持久化:重启后 resume 的旧会话不会被误判成"新轮换"(避免重启整套重发的旧毛病)
318
- if (!_seenSessionsLoaded) {
319
- try {
320
- const ids = getChatState(r, 'blk-seen-sessions')?.ids;
321
- if (Array.isArray(ids)) {
322
- for (const x of ids.slice(-40)) {
323
- const s = String(x || '').trim();
324
- if (s) _seenSessions.add(s);
325
- }
326
- }
327
- } catch { /* 读不到就当空集 */ }
328
- _seenSessionsLoaded = true;
329
- }
330
- return _blkEpoch;
331
- }
332
-
333
- function bumpEpoch(reason) {
334
- const root = String(_lastRoot || '');
335
- epochOf(root);
336
- _blkEpoch += 1;
337
- // 旧账全部作废:慢块 memo + 召回源/时间闸也一起清(新会话里上一份注入 / 5 分钟闸都不再成立)
338
- _slowBlockMemo.clear();
339
- _recallSrcMemo.clear();
340
- _recallTimeMemo.clear();
341
- _personaOnce.clear();
342
- try { setChatState(root, 'blk-epoch', { n: _blkEpoch, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
343
- try { console.debug?.(`[memory] 账本纪元 → ${_blkEpoch}(${reason})`); } catch { }
344
- }
345
-
346
- function installRotationHook(ctx) {
347
- if (_rotationHookInstalled) return;
348
- _rotationHookInstalled = true;
349
- const kernel = ctx?.caps?.kernel;
350
- if (!kernel || typeof kernel.on !== 'function') return; // 拿不到遥控器 → 退回旧行为
351
- // 热重载会重新装载本模块:先 dispose 上一份,避免监听器累积(见 ext-capabilities.d.ts 的"铁律")
352
- try { globalThis[ROTATION_HOOK_KEY]?.dispose?.(); } catch { }
353
- const handler = (session, event) => {
354
- try {
355
- epochOf(_lastRoot); // 顺便把已见会话集从 chat_meta 载入
356
- const type = String(event?.type || '');
357
- if (type === 'compaction/start') { bumpEpoch('上下文压缩'); return; }
358
- const sid = String(session?.header?.id || session?.id || '').trim();
359
- if (!sid || _seenSessions.has(sid)) return;
360
- _seenSessions.add(sid);
361
- while (_seenSessions.size > 40) _seenSessions.delete(_seenSessions.values().next().value);
362
- try { setChatState(_lastRoot, 'blk-seen-sessions', { ids: [..._seenSessions], ts: Date.now() }); } catch { }
363
- // 首次见到某会话 = 新建 / /bot-new 轮换(重启后 resume 的旧会话已在持久化集合里,不会误判)
364
- bumpEpoch('新会话');
365
- } catch { /* 事件回调绝不影响主链 */ }
366
- };
367
- try {
368
- const dispose = kernel.on('session/event', handler);
369
- globalThis[ROTATION_HOOK_KEY] = { dispose: typeof dispose === 'function' ? dispose : () => { } };
370
- } catch { /* 订阅失败就退回旧行为 */ }
371
- }
372
-
373
- function blockIfChanged(scope, tag, text) {
374
- const root = _lastRoot;
375
- const ep = epochOf(root);
376
- const key = 'e' + ep + '|' + String(scope || '') + '|' + String(tag || '');
377
- let prev = _slowBlockMemo.get(key);
378
- // 2026-11-02 主人问「怎么每轮注入这么多」:这份"上次发过什么"的记账原来只在进程内存里,
379
- // 一重启就全忘 —— 于是重启后头几条消息会把所有慢变量块**整套重发一遍**(一次上千 token)。
380
- // 现在落 chat_meta(key = blk:e<纪元>:<scope>|<tag>),重启也能续上,只在真的变了才再发。
381
- if (prev === undefined) {
382
- try { prev = String(getChatState(root, 'blk:' + key)?.text || ''); } catch { prev = ''; }
383
- }
384
- const cur = String(text || '');
385
- if (cur === prev) return ''; // 内容没变 → 不注入(历史里那份仍可见)
386
- _slowBlockMemo.set(key, cur);
387
- try { setChatState(root, 'blk:' + key, { text: cur.slice(0, 1600), ts: Date.now() }); } catch { /* 记账失败不影响注入 */ }
388
- return cur;
389
- }
390
-
391
- /** 撤销某块"已发过"的记账(块因超预算被丢弃时用,让下一条消息还能补发) */
392
- function forgetBlock(scope, tag) {
393
- const root = _lastRoot;
394
- const key = 'e' + epochOf(root) + '|' + String(scope || '') + '|' + String(tag || '');
395
- _slowBlockMemo.delete(key);
396
- // 印象被丢弃时把"一个会话只强调一次"也一起撤销,否则补发永远不会再来
397
- if (tag === 'profile' || tag === 'profile-compact') _personaOnce.delete('e' + epochOf(root) + '|' + scope + '|persona');
398
- try { setChatState(root, 'blk:' + key, { text: '', ts: Date.now() }); } catch { /* 撤销失败下轮重试 */ }
399
- }
400
-
401
-
402
- export async function onInbound(ctx, next) {
403
- let cfg;
404
- try {
405
- cfg = loadConfig(dataRootOf({})); // 2026-10-29 修:原来这里连续 load 两次(第二次包一层 dataRoot 纯属历史残留),每条消息白读一遍配置文件
406
- } catch {
407
- return next(); // 配置都读不了 → 直接放行
408
- }
409
-
410
- if (cfg.enabled === false) return next();
411
-
412
- const scope = scopeOf(ctx);
413
- if (!scope) return next();
414
-
415
- const dataRoot = dataRootOf(cfg);
416
- _lastRoot = dataRoot; // 供 blockIfChanged 把"已发过什么"落到 chat_meta
417
- installRotationHook(ctx); // P1-4:订阅会话轮换/压缩,轮换时账本纪元 +1(只装一次)
418
- const original = stripMemoryBlock(ctx.text);
419
- if (!original) return next();
420
-
421
- // ── ⓪a 顺手把聊天台账补进 SQLite(幂等、增量;给记忆分身和运维查)──
422
- maybeIngestChat(dataRoot, cfg, ctx?.logger);
423
-
424
- // ── ⓪ 先把"她自己记下的"(memory 工具写的收件箱)并入本群 ──
425
- // 工具拿不到当前 scope,所以写公共收件箱;这里在拿到 scope 之后归位。
426
- // 放在召回之前,这样她刚记的东西下一条消息就能被召回。
427
- try {
428
- const merged = await drainInbox(dataRoot, scope, cfg);
429
- if (merged > 0) ctx?.logger?.debug?.(`[memory] 收件箱并入 ${merged} 条 → ${scope}`);
430
- } catch (e) {
431
- ctx?.logger?.debug?.(`[memory] 收件箱并入失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
432
- }
433
-
434
- // ── ① 先召回(必须早于沉淀:否则会把"当前这句话"当成历史记忆注回去,白烧 token)──
435
- // 群等级策略:普通群(水群)不召回长期记忆——只看信息本身;特别关心群/私聊才召回。
436
- const tier = tierOf(dataRoot, scope, cfg.groupTiers);
437
- // 特别关心的人(2026-10-25 主人要求):普通群里遇到名单里的 QQ,也按 priority 档走
438
- // —— 完整印象卡 + 长期记忆召回/沉淀;名单在浮窗「记忆」→「特别关心(手动添加)」里维护。
439
- let tierEff = tier;
440
- try {
441
- if (tier === 'normal' && isPriorityPerson(dataRoot, ctx?.message?.senderId, cfg.groupTiers)) tierEff = 'priority';
442
- } catch { /* 名单读不到就按原档 */ }
443
- const policy = policyFor(tierEff, cfg.groupTiers);
444
- // ── 2026-11-30 注入开关 + 记忆审查 ──
445
- // owner=主人本人(豁免审查);dumpBlocked=有人在套"把记忆/设定全列出来" → 本轮不注入召回
446
- const senderIdNow = String(ctx?.message?.senderId || '');
447
- const isOwner = ownerIds().has(senderIdNow);
448
- const guardCfg = (cfg.memoryGuard && typeof cfg.memoryGuard === 'object') ? cfg.memoryGuard : {};
449
- const guardOn = guardCfg.enabled !== false;
450
- const redactOn = guardOn && !isOwner && guardCfg.redactForNonOwner !== false;
451
- const dumpBlocked = guardOn && !isOwner && guardCfg.blockDumpRequests !== false && isDumpRequest(original);
452
- if (dumpBlocked) ctx?.logger?.debug?.('[memory-guard] 识别到倾倒请求,本轮不注入召回');
453
- let memBlock = '';
454
- const recallT0 = Date.now();
455
- let recallRaw = 0;
456
- let recallKept = 0;
457
- let recallRewritten = false;
458
- let recallErr = '';
459
- if (policy.recall && injectOn(cfg, 'memory') && !dumpBlocked) {
460
- try {
461
- // ── ⓪b 短句闸(2026-10-29 token 调度)──
462
- // 「哈哈」「嗯嗯」「6」这类几乎没有语义的电荷,拿去跑向量召回只会捞回噪声,
463
- // 召回块还可能把不相关的旧事注进上下文 → 主模型多读一段废话。
464
- // 有效字符 <4 直接跳过召回(沉淀另有 worthRemembering 把关,不受影响)。
465
- const coreLen = normText(original).length;
466
- if (coreLen >= 4) {
467
- // ── ⓪c 时间闸(2026-10-30):距上次召回注入 <5 分钟 → 跳过检索(历史里仍可见)
468
- // deltaOnly=false 时退回旧行为(每条都查),供人按需关掉省 token 的增量策略。
469
- const deltaOnly = injectOn(cfg, 'deltaOnly');
470
- const _recent = deltaOnly && (Date.now() - Number(_recallTimeMemo.get(scope) || 0) < 5 * 60 * 1000);
471
- const hits = _recent ? [] : await recall(dataRoot, scope, original, cfg);
472
- recallRaw = Array.isArray(hits) ? hits.length : 0;
473
- // ★ 自匹配过滤:库里存着"这句话本身"时(上一轮沉淀的),cos 常是 0.93~0.97,
474
- // 低于 0.98 的老阈值会漏过去,于是每轮把用户刚说的话再注回去一次 —— 纯浪费 token。
475
- // 这里按**文本**判重,比按余弦稳:只要召回条目的正文等于/包含当前这句就丢掉。
476
- const qNorm = normText(original);
477
- const seenHit = new Set();
478
- const kept = (Array.isArray(hits) ? hits : []).filter((h) => {
479
- const t = normText(h && h.text);
480
- if (!t) return false;
481
- if (t === qNorm) return false;
482
- // 当前这句被完整包含在记忆里(比如记忆是"甲:乙"的长句)也算自匹配
483
- if (t.length > qNorm.length && t.includes(qNorm) && qNorm.length >= 8) return false;
484
- // 库里历史重复(去重上线前写进去的)也不要重复占额度
485
- if (seenHit.has(t)) return false;
486
- seenHit.add(t);
487
- return true;
488
- });
489
- // [mmtr 2026-10-27] 防自增强:刚被用过的记忆本轮降权 + 记使用日志(重要性不受检索影响)
490
- try { applyRecallGuard(dataRoot, scope, kept); } catch { /* 护栏失败不影响召回 */ }
491
- // 2026-11-30 记忆审查:非主人只遮蔽敏感字段(手机号/证件/地址/账号),不整条丢弃
492
- const guarded = redactOn ? kept.map((h) => (h && h.text ? { ...h, text: redactSensitive(h.text) } : h)) : kept;
493
- memBlock = formatRecallBlock(guarded, cfg);
494
- recallKept = kept.length;
495
- // ★ 同源去重(2026-10-29 token 调度):连着聊同一话题时,每条的召回命中常常是
496
- // 同一批旧记忆(top hit 不变),只是 LLM 改写出的句子措辞不同 →
497
- // 以前按改写后文本判重拦不住,等于同一份记忆每条消息重发一遍。
498
- // 改成按**召回源文本**判重:这一批和上一条注入过的完全一样 → 不再注入
499
- // (历史里上一份还在,模型照样看得见)。有新记忆进来才注入增量。
500
- const srcKey = kept.map((h) => normText(h.text)).sort().join('|');
501
- const prevSrc = _recallSrcMemo.get(scope) || '';
502
- if (deltaOnly && srcKey && srcKey === prevSrc) {
503
- memBlock = '';
504
- ctx?.logger?.debug?.('[memory] 召回源与上一条相同,跳过注入(历史里仍有)');
505
- } else if (srcKey) {
506
- _recallSrcMemo.set(scope, srcKey);
507
- }
508
- if (memBlock) {
509
- ctx?.logger?.debug?.(`[memory] 召回 ${kept.length} 条 (${kept.map((h) => h.cos.toFixed(2)).join(',')})`);
510
- _recallTimeMemo.set(scope, Date.now()); // 时间闸:只记真实注入
511
- }
512
- // ── ①a2 本地小模型"过一遍"(用户 2026-10-23 提的方案)──
513
- // · 2 条以上才值得过一次模型(1 条时原文更准);块本身已经很短(<100 字)
514
- // 也没必要过模型——省一次本地调用,延迟立省 0.5~1.5s;
515
- // · 成功 → 压成一句第一人称回忆(4 条 160 字 → 1 句 ~30 字),还顺便丢掉噪声;
516
- // · 失败/超时/模型离线 → 保留原来的编号列表(永不因此丢记忆、更不卡回复)。
517
- if (memBlock && kept.length >= 2 && memBlock.length >= 100) {
518
- try {
519
- const lr = await rewriteRecall(kept, original, cfg, { dataRoot });
520
- if (lr && lr.ok && lr.text) {
521
- memBlock = '\n[记忆]' + lr.text + '[/记忆]';
522
- recallRewritten = true;
523
- ctx?.logger?.info?.(`[memory] 本地模型改写 ${kept.length} 条 → ${lr.text.length} 字(${lr.ms}ms): ${lr.text}`);
524
- } else {
525
- ctx?.logger?.debug?.(`[memory] 保留编号列表(${(lr && lr.reason) || '?'}${lr && lr.ms ? ' ' + lr.ms + 'ms' : ''})`);
526
- }
527
- } catch (e) {
528
- ctx?.logger?.debug?.(`[memory] 改写异常(已忽略): ${e instanceof Error ? e.message : String(e)}`);
529
- }
530
- }
531
- } // ── 短句闸结束(coreLen >= 4 才走召回)
532
- } catch (e) {
533
- recallErr = e instanceof Error ? e.message : String(e);
534
- ctx?.logger?.debug?.(`[memory] 召回失败(已忽略): ${recallErr}`);
535
- }
536
- }
537
- // [记忆] 召回结果连续相同(连着聊同一话题)也不再重复注入——历史里那份还在
538
- memBlock = injectOn(cfg, 'deltaOnly') ? blockIfChanged(scope, 'mem', memBlock) : memBlock;
539
- // 轨迹只记摘要(不存全文),给浮窗看"这条消息到底有没有查库、查到几条"
540
- try {
541
- traceMemory(dataRoot, {
542
- kind: 'recall', scope, query: original.replace(/<@[^>]*>/g, '').replace(/\s+/g, ' ').trim().slice(0, 50),
543
- raw: recallRaw, hits: recallKept, rewritten: recallRewritten,
544
- ok: !recallErr, error: recallErr, ms: Date.now() - recallT0,
545
- });
546
- } catch { /* ignore */ }
547
-
548
-
549
- // ── ①b 世界书:命中关键词才带 1~2 条设定(Neuro 式,设定不进常驻 prompt)──
550
- // slow-block:同一关键词组合连续命中时不再重复注入
551
- let loreBlock = '';
552
- if (injectOn(cfg, 'worldbook')) {
553
- try {
554
- const l = loreFor(dataRoot, original, cfg.lore || {});
555
- loreBlock = blockIfChanged(scope, 'lore', l.block);
556
- if (l.block && loreBlock) ctx?.logger?.debug?.(`[lore] 注入 ${l.hits.map((h) => h.id).join(',')}`);
557
- else if (l.block) ctx?.logger?.debug?.(`[lore] 命中但与上次相同,跳过`);
558
- } catch (e) {
559
- ctx?.logger?.debug?.(`[lore] 注入失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
560
- }
561
- }
562
-
563
- // ── ①c 反重复:把她刚说过的几句附在后面(AI 味最大来源就是重复同一个句式/口头禅)──
564
- let echoBlock = '';
565
- if (injectOn(cfg, 'echo')) {
566
- try {
567
- const ec = formatEchoBlock(dataRoot, scope, cfg.echo || {});
568
- echoBlock = ec.block;
569
- if (echoBlock) ctx?.logger?.debug?.(`[echo] 反重复 ${ec.lines.length} 句`);
570
- } catch (e) {
571
- ctx?.logger?.debug?.(`[echo] 反重复生成失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
572
- }
573
- }
574
-
575
- // ── ①d 印象 + 熟识度(个人层:跨群统一;稳定模式,保云端缓存)──
576
- // 特别关心群/私聊:完整卡;普通群:只给「名字 · 等级」极简认人块(不认识的人一个字都不多花)。
577
- let profileBlock = '';
578
- if (injectOn(cfg, 'persona')) {
579
- try {
580
- const who = {
581
- senderId: String(ctx?.message?.senderId || ''),
582
- senderName: String(ctx?.message?.senderName || ''),
583
- };
584
- const profileCfg = { ...(cfg.profile || {}), ...(cfg.bond || {}) };
585
- // 2026-11-30:personaOnce(默认开)——一个会话里性格/印象只强调一次;
586
- // 之后内容再变也不重发(新会话/压缩后纪元 +1 自动重置)。
587
- const onceKey = 'e' + epochOf(dataRoot) + '|' + scope + '|persona';
588
- const personaDone = injectOn(cfg, 'personaOnce') && _personaOnce.has(onceKey);
589
- if (policy.profile === 'full') {
590
- profileBlock = familiarityBlockFor(dataRoot, scope, who, profileCfg);
591
- // [性格观察](2026-10-26):belief 层的性格倾向终于被模型看到(此前只存不消费)
592
- try {
593
- const tb = traitBlockFor(dataRoot, who.senderId);
594
- if (tb) profileBlock += tb;
595
- } catch { /* 性格观察失败不影响印象块 */ }
596
- // [成长](2026-10-26):她的自我心得(growth:latest,自我反思每天一变的慢变量)——
597
- // 让"完善自我"这条信条真的有出口:她能看到自己上一次的反思。
598
- try {
599
- const gv = getPersonaValue(dataRoot, '__global__', 'growth:latest');
600
- if (gv && gv.value) profileBlock += '\n[成长]' + String(gv.value).replace(/\s+/g, ' ').trim().slice(0, 90) + '[/成长]';
601
- } catch { /* 成长块失败不影响印象块 */ }
602
- if (profileBlock && personaDone) profileBlock = '';
603
- else {
604
- // slow-block:印象卡/性格/成长都是慢变量,内容没变就不再每条重发
605
- profileBlock = blockIfChanged(scope, 'profile', profileBlock);
606
- if (profileBlock) _personaOnce.add(onceKey);
607
- }
608
- if (profileBlock) ctx?.logger?.debug?.(`[profile] 已注入完整印象+熟识度 (tier=${tier})`);
609
- } else if (policy.profile === 'compact') {
610
- profileBlock = personaDone ? '' : blockIfChanged(scope, 'profile-compact', compactBlockFor(dataRoot, scope, who, profileCfg));
611
- if (profileBlock) _personaOnce.add(onceKey);
612
- if (profileBlock) ctx?.logger?.debug?.(`[profile] 已注入精简认人块 (tier=${tier})`);
613
- }
614
- } catch (e) {
615
- ctx?.logger?.debug?.(`[profile] 印象块失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
616
- }
617
- }
618
-
619
- // ── ①e 状态:本轮/近 30 分钟的当下心情(≤30 字,过期自动不带)──
620
- // 2026-10-31 主人拍板(信条等没必要反复出现):状态也是慢变量 —— 心情没变就不重发
621
- // (历史里上一份还在);变了/过期才注一份新的。
622
- let moodBlock = '';
623
- if (injectOn(cfg, 'mood')) {
624
- try {
625
- moodBlock = blockIfChanged(scope, 'mood', moodBlockFor(dataRoot, scope, cfg.mood || {}));
626
- if (moodBlock) ctx?.logger?.debug?.('[mood] 已注入状态');
627
- } catch (e) {
628
- ctx?.logger?.debug?.(`[mood] 状态失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
629
- }
630
- }
631
-
632
- // ── ①f 情绪回响(2026-10-29 参考 Companion-AI-Memory 的主动回忆机制)──
633
- // 不是被动等 TA 问「怎么了」,而是:检测到情绪词 → 去记忆库翻「上次因为什么」
634
- // → 把那个旧事带进上下文,让她能像熟人一样具体地接(「是又加班了吗?」)。
635
- // 隐私分层沿用:只在当前 scope 的记忆库内翻(不跨人聚合);仅 full 权限场景;
636
- // 每 scope 30 分钟最多一次;至少半小时前的旧事才算「回忆」(刚说的不算)。
637
- let moodEchoBlock = '';
638
- if (policy.profile === 'full' && cfg.moodEcho !== false && injectOn(cfg, 'moodEcho')) {
639
- try {
640
- const MOOD_WORDS = ['累', '倦', '疲惫', '加班', '熬夜', '压力大', '崩了', '破防', 'emo',
641
- '难过', '伤心', '委屈', '烦', '生气', '焦虑', '孤独', '寂寞',
642
- '开心', '高兴', '兴奋', '乐死', '爽', '感动', '幸福'];
643
- const hitWord = MOOD_WORDS.find((w) => original.includes(w));
644
- // 2026-10-29 修:状态键原来用全局 'mood-echo',注释写的是「每 scope 30 分钟一次」,
645
- // 实际 A 群触发后 B 群 30 分钟内被无辜连坐。改成按 scope 记账,与注释语义一致。
646
- const meState = getChatState(dataRoot, 'mood-echo:' + scope) || {};
647
- if (hitWord && Date.now() - (Number(meState.ts) || 0) > 30 * 60 * 1000) {
648
- setChatState(dataRoot, 'mood-echo:' + scope, { ts: Date.now() });
649
- const hits = await recall(dataRoot, scope, hitWord + ' ' + original.slice(0, 40), cfg);
650
- const older = (hits || []).filter((h) => Date.now() - Number(h.ts || 0) > 30 * 60 * 1000);
651
- if (older.length) {
652
- const h = older[0];
653
- const agoH = Math.floor((Date.now() - Number(h.ts)) / 3600000);
654
- const when = agoH >= 24 ? Math.floor(agoH / 24) + ' 天前' : (agoH >= 1 ? agoH + ' 小时前' : '刚才不久');
655
- moodEchoBlock = `\n[情绪回响]TA 情绪「${hitWord}」;你记得 ${when} 也有过——「${String(h.text).replace(/\s+/g, ' ').slice(0, 45)}」。顺着旧事关心,别干巴巴问「怎么了」。[/情绪回响]`;
656
- ctx?.logger?.debug?.(`[mood-echo] 情绪回响已注入(词=${hitWord},旧事=${when})`);
657
- }
658
- }
659
- } catch (e) {
660
- ctx?.logger?.debug?.(`[mood-echo] 情绪回响失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
661
- }
662
- }
663
-
664
- // ── ①d2 旧识:这个人的历史聊天记录导入后留下的画像 ──
665
- // 数据隔离:只读 senderId 自己那一个 scope(person:qq:<号>),不跨人聚合。
666
- // 可见性:只有拿到了"完整印象"权限的场景(特别关心群/私聊)才带;
667
- // 普通群连"认识这个人"都不展开,更不能把他在别处说过的话搬过来。
668
- let pastBlock = '';
669
- if (policy.profile === 'full' && cfg.pastProfile !== false && injectOn(cfg, 'pastProfile')) {
670
- try {
671
- const sid = String(ctx?.message?.senderId || '').trim();
672
- const p = sid ? personProfile(dataRoot, sid) : null;
673
- if (p && p.ok && p.impression) {
674
- // 画像本身已经是一句统计结论(≤120 字),这里只做截断,不改写语义
675
- const line = p.impression.replace(/\s+/g, ' ').slice(0, 120);
676
- // slow-block:旧识画像也是慢变量,没变不重发
677
- pastBlock = blockIfChanged(scope, 'past', `\n[旧识]${line}[/旧识]`);
678
- if (pastBlock) ctx?.logger?.debug?.(`[past] 已注入旧识画像 (${p.say} 条)`);
679
- }
680
- } catch (e) {
681
- ctx?.logger?.debug?.(`[past] 旧识画像失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
682
- }
683
- }
684
-
685
- // ── ①d3 学来的说话习惯:她观察群里怎么说话,只学表达方式(≤90 字)──
686
- let styleBlock = '';
687
- if (cfg.imitate?.inject !== false && injectOn(cfg, 'style')) {
688
- try {
689
- const st = currentStyle(dataRoot);
690
- if (st) styleBlock = blockIfChanged(scope, 'style', `\n[学]${String(st).slice(0, 90)}[/学]`); // slow-block
691
- } catch { /* 学不到就算了 */ }
692
- }
693
-
694
- // ── ①d4 手痒提醒:她几乎从不发表情包(2026-10-27 主人点名)──
695
- // 不是命令,只是"手边有图"的轻推:距上次发图 ≥ 30 分钟才出现,且最多每 30 分钟一次,
696
- // 免得每轮都催(催多了反而机械)。
697
- let stickerBlock = '';
698
- try {
699
- if (cfg.stickerNudge !== false && policy.capture && injectOn(cfg, 'sticker')) {
700
- const st = getChatState(dataRoot, 'sticker:last') || {};
701
- const lastTs = Number(st.ts) || 0;
702
- const gap = Date.now() - lastTs;
703
- const nudge = getChatState(dataRoot, 'sticker:nudge') || {};
704
- if (gap > 30 * 60 * 1000 && Date.now() - (Number(nudge.ts) || 0) > 30 * 60 * 1000) {
705
- stickerBlock = '\n[手边]表情包:sticker_auto 搜;兴头配一张,正事/难过不发。[/手边]';
706
- setChatState(dataRoot, 'sticker:nudge', { ts: Date.now() });
707
- }
708
- }
709
- } catch { /* 提醒失败不影响对话 */ }
710
-
711
- // ── ①d5 [约定](2026-10-27 mmtr):到期的承诺/约定自己浮上来——
712
- // 事实锁定原文、越接近截止越清晰、超宽限自动 broken 并付关系代价。
713
- let promiseB = '';
714
- if (injectOn(cfg, 'promise')) {
715
- try { promiseB = blockIfChanged(scope, 'promise', promiseBlockFor(dataRoot, scope)); } catch { /* 约定块失败不影响对话 */ } // slow-block
716
- }
717
-
718
- // 所有块合并成一次 rewrite(改两次会让中间态被别的扩展看见)
719
- // [信条](2026-10-26):底层刻写常驻块,全静态、跨群不变(prompt 缓存友好);
720
- // 放最前——它是主人手笔,LLM 只读不可改,优先级高于一切注入。
721
- // 2026-10-31 主人拍板(「信条等真的没必要反复出现那么多次」):信条全静态,
722
- // 一个 scope 只在内容变化时注入一次(历史里上一份仍在,模型照样看得见),
723
- // 不再每条消息重发 —— N 条消息 N 份信条的 token 线性浪费到此为止。
724
- const bedrock = injectOn(cfg, 'bedrock') ? blockIfChanged(scope, 'bedrock', bedrockBlock(dataRoot)) : '';
725
- // ── 注入总预算(2026-11-02):块越加越多,一条消息能带两三千字 —— 而且这些字会**永久留在对话历史里**,
726
- // 每轮都在为它们付钱(复利)。所以给总长设硬上限,按优先级装,装不下的直接这轮不带(下轮内容变了还会来)。
727
- const INJECT_BUDGET = Math.max(400, Number(cfg.injectBudgetChars) || 1200);
728
- // tag → 中文名(dropped 里是中文名,要能反查回慢块 tag 好撤销"已发过"记账)
729
- const parts = [
730
- ['bedrock', '信条', bedrock], ['mem', '记忆', memBlock], ['profile', '印象', profileBlock], ['promise', '约定', promiseB],
731
- ['mood', '状态', moodBlock], ['lore', '世界书', loreBlock], ['past', '旧识', pastBlock],
732
- ['echo', '反重复', echoBlock], ['style', '说话习惯', styleBlock], ['sticker', '表情包', stickerBlock], ['moodEcho', '情绪回响', moodEchoBlock],
733
- ];
734
- // 打包规则与微信侧共用 lib/context-budget.mjs(同一套「超预算整块丢弃 + 记 dropped」语义)
735
- const packed = packByBudget(parts.map((p) => [p[1], p[2]]), INJECT_BUDGET, 400);
736
- const extra = joinKept(packed.kept);
737
- const dropped = packed.dropped;
738
- // ★ 2026-11-30 一次性注入的漏洞修复:blockIfChanged 在打包前就记了"已发过",
739
- // 若这一块因超预算被丢掉,本会话就再也不会补发(新会话首次全量注入会缺块)。
740
- // 这里按 dropped 反查 tag,撤销记账 → 下一条消息还会再来。
741
- if (dropped.length) {
742
- for (const p of parts) {
743
- if (!dropped.includes(p[1])) continue;
744
- try { forgetBlock(scope, p[0]); } catch { /* 撤销失败不影响本轮 */ }
745
- }
746
- }
747
- if (dropped.length) ctx?.logger?.debug?.(`[budget] 注入超 ${INJECT_BUDGET} 字,本轮不带:${dropped.join('、')}`);
748
- if (extra) meterInject(dataRoot, scope, extra.length, dropped);
749
- if (extra && typeof ctx.rewrite === 'function') {
750
- // 2026-11-11:稳定块(信条/设定/印象…)置顶,易变块(记忆/状态/世界书…)垫底。
751
- // 旧写法 ctx.text + extra 会把 [信条] 塞到 [消息号] 后面(主人实测的 bug)。
752
- ctx.rewrite({ text: mergeStableFirst(ctx.text, extra) });
753
- }
754
- // ── ② 再沉淀(用"原文本",不含刚注入的记忆块)──
755
- // 普通群不沉淀长期记忆:水群只看信息本身,不把闲聊塞进向量库(省本地算力)
756
- if (policy.capture && cfg.capture !== false && worthRemembering(original, cfg)) {
757
- try {
758
- await remember(dataRoot, scope, {
759
- text: original.slice(0, 200),
760
- kind: 'event',
761
- // subj 只写"人名":以前兜底写 senderId,库里就多出 82 条主体是 32 位 openid 的记忆,
762
- // 面板按主体统计时看起来像"记到别人名下"。拿不到真名就留空(空比错好)。
763
- subj: subjOfMessage(ctx?.message),
764
- // 溯源:记住这句话是从哪条原始消息来的(不同宿主字段名不一样,挨个兜)
765
- srcMsgId: msgIdOf(ctx?.message),
766
- }, cfg);
767
- } catch (e) {
768
- ctx?.logger?.debug?.(`[memory] 沉淀失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
769
- }
770
- }
771
-
772
- // ── ③ 中层记忆:攒够 digestEvery 条就压一次"前情摘要"(零 token,抽取式)──
773
- // 只做增量判断(shouldDigest 很便宜),真正压缩才扫库;绝不删原记忆。
774
- if (policy.digest) {
775
- try {
776
- if (shouldDigest(dataRoot, scope, cfg)) {
777
- const d = digestScope(dataRoot, scope, cfg);
778
- if (d.ok) ctx?.logger?.info?.(`[memory] 中层摘要已生成: 覆盖 ${d.covered} 条 → ${d.text.slice(0, 40)}…`);
779
- }
780
- } catch (e) {
781
- ctx?.logger?.debug?.(`[memory] 摘要失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
782
- }
783
- }
784
-
785
- return next();
786
- }
787
-
788
- /** 测试钩子:清空召回节流备忘(时间闸/判重/慢块),闭环测试里背靠背两条消息也要能召回 */
789
- export function _testResetRecallMemo() {
790
- _slowBlockMemo.clear();
791
- _recallSrcMemo.clear();
792
- _recallTimeMemo.clear();
793
- _personaOnce.clear();
794
- }
795
-
796
- /** 调试用:让她能通过日志看到记忆库状态 */
797
- export function dumpStats(ctx) {
798
- try {
799
- const cfg = loadConfig(dataRootOf({}));
800
- return stats(dataRootOf(cfg), scopeOf(ctx) || 'unknown', cfg);
801
- } catch { return null; }
802
- }
1
+ import { existsSync as __existsSync } from 'node:fs'
2
+ const __repoRoot = (() => {
3
+ let cached = ''
4
+ const norm = (p) => String(p || '').split(String.fromCharCode(92)).join('/')
5
+ return () => {
6
+ if (cached) return cached
7
+ const cands = []
8
+ const env = String(process.env.QQBOT_ROOT || process.env.QQBOT_REPO_ROOT || '').trim()
9
+ if (env) cands.push(norm(env))
10
+ try {
11
+ let here = decodeURIComponent(new URL('.', import.meta.url).pathname)
12
+ if (here[0] === '/' && here[2] === ':') here = here.slice(1)
13
+ here = norm(here).replace(/\/+$/, '')
14
+ let d = here
15
+ for (let i = 0; i < 6; i += 1) {
16
+ if (!d) break
17
+ cands.push(d)
18
+ const k = d.lastIndexOf('/')
19
+ d = k > 0 ? d.slice(0, k) : ''
20
+ }
21
+ } catch { /* noop */ }
22
+ try { cands.push(norm(process.cwd())) } catch { /* noop */ }
23
+ for (const c of cands) {
24
+ try {
25
+ if (c && (__existsSync(c + '/qqbot-mod/muu-shared.mjs') || __existsSync(c + '/dshqqbot'))) { cached = c; return cached }
26
+ } catch { /* noop */ }
27
+ }
28
+ cached = norm(cands.find(Boolean) || '.')
29
+ return cached
30
+ }
31
+ })()
32
+ /**
33
+ * memory-recall.mjs — 入站时按需召回长期记忆(Neuro 式「检索而非重放」)
34
+ *
35
+ * 挂点:早挂点 onInbound —— 链上唯一能 `ctx.rewrite()` 改到"进上下文那版文本"的位置。
36
+ *
37
+ * 它做两件事:
38
+ * ① 召回:拿当前这句话去记忆库做向量近邻,命中就追加一个 [记忆] 块(≤300 字)
39
+ * ② 沉淀:把这条消息(去掉 [记忆] 块的原文本)记成一条 event 记忆,带 embedding 去重
40
+ *
41
+ * 为什么这样省钱:
42
+ * 现在每轮带的是「最近 10 条原文」(常 1000~2000 字),超出就永久丢;
43
+ * 改成「4 条语义相关的提炼」≈160 字,且旧信息能随时被召回。
44
+ *
45
+ * 安全契约:
46
+ * · 全程 try/catch,任何异常都只记日志并照常 next() —— 绝不让记忆功能影响聊天;
47
+ * · 拿不到模型就退化成字符 n-gram(memory-core 内部处理),再不行就整块跳过。
48
+ */
49
+
50
+ // 存储后端在门面里选:优先 SQLite(memory-db),不可用自动回退 JSONL(memory-core)。
51
+ import { appendFileSync } from 'node:fs';
52
+ import { createHash } from 'node:crypto';
53
+ import {
54
+ loadConfig, recall, remember, drainInbox, digestScope, shouldDigest, formatRecallBlock, stats,
55
+ ingestChatHistory, personProfile,
56
+ } from '../lib/memory.mjs';
57
+ // 世界书:设定按关键词命中才注入,不进常驻 prompt
58
+ import { loreFor } from '../lib/lore-core.mjs';
59
+ // 印象卡 + 心情 + 关系温度:让"对熟人更熟、今天状态不同"能被主模型看见
60
+ // 2026-10-23:印象卡与熟识度在底层统一成 persona.fam:<senderId>,注入只留一个 [印象] 块
61
+ import { familiarityBlockFor, moodBlockFor, getPersonaValue } from '../lib/profile-core.mjs';
62
+ // scope / subj 统一口径(与 outbound/memory-agent、tools/memory 共用一份实现)
63
+ import { scopeOfMessage, subjOfMessage } from '../lib/scope-util.mjs';
64
+ // 记忆轨迹:给浮窗「记忆」页显示召回/整理是否真的跑了
65
+ import { trace as traceMemory } from '../lib/memory-trace.mjs';
66
+ // 反重复:把她刚说过的几句附在后面(AI 味最大来源就是重复)
67
+ import { formatEchoBlock } from '../lib/self-echo.mjs';
68
+ // 学来的说话习惯(从群聊/导入记录里提炼,只学表达方式)
69
+ import { currentStyle } from '../lib/imitate.mjs';
70
+ // 记忆"过一遍小模型":把 2 条以上的召回压成一句她自己的回忆(省 token + 去念资料感)
71
+ import { rewriteRecall } from '../lib/memory-llm.mjs';
72
+ // 群等级:特别关心群/私聊走完整档;普通群只看信息本身,但保留一个极短认人块(避免不认人)
73
+ import { tierOf, policyFor, isPriorityPerson } from '../lib/group-tiers.mjs';
74
+ import { compactBlockFor } from '../lib/profile-core.mjs';
75
+ import { bedrockBlock } from '../lib/bedrock.mjs';
76
+ import { beliefs } from '../lib/memory-hippo.mjs';
77
+ // 表情包提醒:用会话状态记"上次发图/上次提醒"的时间(2026-10-27)
78
+ import { getChatState, setChatState } from '../lib/chatlog-db.mjs';
79
+ // 注入块统一预算(第 4 批「上下文统一」):与微信侧同一套打包规则
80
+ import { packByBudget, joinKept } from '../lib/context-budget.mjs';
81
+ // [mmtr 2026-10-27]:会遗忘的记忆层——防自增强(刚用过的降权+只记日志)与承诺账本([约定]块)
82
+ import { promiseBlockFor, applyRecallGuard } from '../lib/memory-mmtr.mjs';
83
+ // 2026-11-11 主人报「消息号跑到 [信条] 前面」→ 稳定块一律置顶,其余垫底
84
+ import { mergeStableFirst } from '../lib/stable-first.mjs';
85
+ // 2026-11-30 记忆审查:主人身份表(谁的提问算"自己人")
86
+ import { personalIds } from '../lib/personal-ids.mjs';
87
+ import { redactSensitive, isDumpRequest, ownerIds } from '../lib/sensitive.mjs';
88
+ import { aliasesFor } from '../lib/person-link.mjs';
89
+
90
+ // ── 2026-12-04 按来源归类的并集召回 ─────────────────────────────────────────
91
+ // 规则(主人 2026-12-04 定的口径):
92
+ // ① 每条记忆都属于它**被说出来的那个会话**:群记忆挂 group:<群号>,私聊挂 c2c:/wechat:,
93
+ // 并保留写入时间 —— 注入时把来源一起带给模型,A 群的话不会被当成 B 群的;
94
+ // ② 群与群之间**永不并集**(A 群的记忆只能在 A 群被召回,不会串到 B 群);
95
+ // ③ 同一个人的私聊之间**全并集**(QQ 号 / openid / 微信 wxid / 小天才都算),
96
+ // 因为那本来就是"和同一个人说话";
97
+ // ④ 唯一被排除在外的只有隐私字段本身(手机号/证件/密码/密钥),由 lib/sensitive.mjs 遮蔽。
98
+ function scopeKind(scope) {
99
+ const s = String(scope || '');
100
+ if (s.startsWith('group:')) return '群';
101
+ if (s.startsWith('wechat:')) return '微信';
102
+ if (s.startsWith('xtc:') || s.includes('xtc')) return '小天才';
103
+ if (s.startsWith('c2c:')) return '私聊';
104
+ if (s === '__global__') return '长期';
105
+ return '私聊';
106
+ }
107
+
108
+ async function recallUnion(dataRoot, scope, queryText, cfg) {
109
+ // 群:只查本群(不跨群、不并入私聊),但每条会带上"群 + 时间"的来源标签
110
+ let scopes = [scope];
111
+ if (!String(scope || '').startsWith('group:')) {
112
+ try {
113
+ const a = aliasesFor(dataRoot, scope);
114
+ if (Array.isArray(a) && a.length) scopes = a.filter((x) => !String(x).startsWith('group:'));
115
+ } catch { /* 身份表读不到就只查当前 scope */ }
116
+ }
117
+ // 同一个人可能同时有 c2c:<openid> / c2c:<qq号> / wechat:<wxid> 几条历史 scope
118
+ const uniq = [...new Set(scopes)].filter(Boolean).slice(0, 6);
119
+ if (uniq.length <= 1) {
120
+ const one = await recall(dataRoot, scope, queryText, cfg);
121
+ return (Array.isArray(one) ? one : []).map((it) => ({ ...it, _scope: it?._scope || scope }));
122
+ }
123
+ const out = [];
124
+ for (const sc of uniq) {
125
+ try {
126
+ const r = await recall(dataRoot, sc, queryText, cfg);
127
+ if (Array.isArray(r)) for (const it of r) out.push({ ...it, _scope: it?._scope || sc });
128
+ } catch { /* 单个 scope 失败不影响其它 */ }
129
+ }
130
+ const byKey = new Map();
131
+ for (const it of out) {
132
+ const k = String(it?.id || it?.text || '');
133
+ if (!k) continue;
134
+ const prev = byKey.get(k);
135
+ if (!prev || Number(it?.score || 0) > Number(prev?.score || 0)) byKey.set(k, it);
136
+ }
137
+ const merged = [...byKey.values()];
138
+ // 有 score 就按分数(含时间衰减)排,没有就保持各 scope 的原始先后
139
+ if (merged.some((x) => Number.isFinite(Number(x?.score)))) {
140
+ merged.sort((a, b) => Number(b?.score || 0) - Number(a?.score || 0));
141
+ }
142
+ const cap = Math.max(4, Math.min(16, Number(cfg?.recallTopK) || 8));
143
+ return merged.slice(0, cap);
144
+ }
145
+
146
+ // ── 2026-11-30 注入总控(memory-config.json → inject)──────────────────────────
147
+ // 目的:把"每轮都塞一大段"改成"新会话一次性全量 + 之后只注入变化",
148
+ // 并让人按喜好关掉某类块(比如不喜欢带性格、不要世界书)。
149
+ // 没写 inject 的旧配置 → 全部默认开,行为与以前一致(兼容)。
150
+ function injectOn(cfg, key, dflt = true) {
151
+ const inj = cfg && cfg.inject;
152
+ if (!inj || typeof inj !== 'object') return dflt;
153
+ return inj[key] !== false;
154
+ }
155
+
156
+ // ── 2026-11-30 记忆审查(2026-12-04 抽到 lib/sensitive.mjs:召回 / 记忆工具 / 设置面板共用同一份规则)──
157
+
158
+ // 一个会话里性格/印象只强调一次(换档/压缩时纪元 +1 → 自然重置)
159
+ const _personaOnce = new Set();
160
+
161
+
162
+ // 性格倾向 → 一句话(主人 2026-10-26 要求让 belief 层真正被模型看到)。
163
+ // trait 值是小步长缓变量,文本天然轮间稳定,不会破坏 prompt 缓存;
164
+ // 只在完整档(特别关心/私聊)注入,普通群一个字不多花。
165
+ const TRAIT_LABELS = {
166
+ warmth: ['待人热情', '偏冷淡'],
167
+ trust: ['值得信任', '需留个心眼'],
168
+ humor: ['爱开玩笑', '正经话少'],
169
+ reliability: ['说到做到', '常放鸽子'],
170
+ boundary: ['有分寸', '爱越界'],
171
+ energy: ['活跃话多', '安静寡言'],
172
+ };
173
+ function traitBlockFor(dataRoot, senderId) {
174
+ const sid = String(senderId || '').trim();
175
+ if (!sid || !/^[\w-]+$/.test(sid)) return '';
176
+ let rows = [];
177
+ try { rows = beliefs(dataRoot, 'person:qq:' + sid) || []; } catch { return ''; }
178
+ const hits = rows
179
+ .filter((b) => b && Math.abs(b.value) >= 0.3 && (b.n || 0) >= 3)
180
+ .sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
181
+ .slice(0, 2)
182
+ .map((b) => {
183
+ const pair = TRAIT_LABELS[b.key];
184
+ if (!pair) return '';
185
+ return b.value > 0 ? pair[0] : pair[1];
186
+ })
187
+ .filter(Boolean);
188
+ if (!hits.length) return '';
189
+ return `\n[性格观察]和他相处下来,感觉他${hits.join('、')}[/性格观察]`;
190
+ }
191
+
192
+ export const name = 'aa-memory-recall';
193
+
194
+ /** 插件数据根(优先级:环境变量 > memory-config.json 的 dataRoot > 默认 {cwd}/dshqqbot) */
195
+ function dataRootOf(cfg) {
196
+ const env = String(process.env.QQBOT_MEMORY_DATA_ROOT || '').trim();
197
+ if (env) return env;
198
+ return (cfg && cfg.dataRoot) || __repoRoot() + "/dshqqbot";
199
+ }
200
+
201
+ /** 会话作用域:群按群 openid,私聊按用户 openid(唯一口径见 lib/scope-util.mjs) */
202
+ function scopeOf(ctx) {
203
+ return scopeOfMessage(ctx?.message);
204
+ }
205
+
206
+ /** 注入量埋点(与微信侧 contextChars 对等):只写字数/预算,不写消息内容与原始 scope */
207
+ function meterInject(dataRoot, scope, chars, dropped) {
208
+ try {
209
+ const sid = createHash('sha1').update(String(scope || '')).digest('hex').slice(0, 10);
210
+ appendFileSync(`${dataRoot}/token-usage.jsonl`, JSON.stringify({
211
+ ts: Date.now(), channel: 'qq', scope: sid, chars, dropped: dropped.length,
212
+ }) + '\n');
213
+ } catch { /* 统计失败绝不影响聊天 */ }
214
+ }
215
+
216
+ /** 溯源用:各宿主/各版本的消息号字段名不一致,挨个兜一遍 */
217
+ function msgIdOf(m) {
218
+ if (!m || typeof m !== 'object') return '';
219
+ return String(m.msgId ?? m.msg_id ?? m.messageId ?? m.message_id ?? m.id ?? '').slice(0, 96);
220
+ }
221
+
222
+ /** 归一化:去 @、去空白、去标点,只留汉字/字母/数字 —— 用于自匹配判重 */function normText(s) {
223
+ return String(s || '')
224
+ .replace(/<@[^>]*>/g, '')
225
+ .replace(/[\s\u3000]+/g, '')
226
+ .replace(/[^\u4e00-\u9fa5A-Za-z0-9]/g, '')
227
+ .toLowerCase();
228
+ }
229
+
230
+ /** 去掉我们上一轮可能注入过的块([记忆] / [设定] / [印象] / [关系] / [状态]),避免注入被自己的注入污染 */
231
+ function stripMemoryBlock(text) {
232
+ return String(text || '')
233
+ .replace(/\n?\[记忆\][\s\S]*?\[\/记忆\]\n?/g, '\n')
234
+ .replace(/\n?\[信条\][\s\S]*?\[\/信条\]\n?/g, '\n')
235
+ .replace(/\n?\[设定\][\s\S]*?\[\/设定\]\n?/g, '\n')
236
+ .replace(/\n?\[印象\][\s\S]*?\[\/印象\]\n?/g, '\n')
237
+ .replace(/\n?\[旧识\][\s\S]*?\[\/旧识\]\n?/g, '\n')
238
+ .replace(/\n?\[性格观察\][\s\S]*?\[\/性格观察\]\n?/g, '\n')
239
+ .replace(/\n?\[成长\][\s\S]*?\[\/成长\]\n?/g, '\n')
240
+ .replace(/\n?\[关系\][\s\S]*?\[\/关系\]\n?/g, '\n')
241
+ .replace(/\n?\[状态\][\s\S]*?\[\/状态\]\n?/g, '\n')
242
+ .replace(/\n?\[B站\][\s\S]*?\[\/B站\]\n?/g, '\n')
243
+ .replace(/\n?\[学\][\s\S]*?\[\/学\]\n?/g, '\n')
244
+ .replace(/\n?\[别重复\][^\n]*/g, '\n')
245
+ // 2026-10-29 补漏:这三个新块以前不在清单里——若注入文本被引用/回显回来,
246
+ // 会被当成用户原文再次沉淀+召回,块会越滚越大(token 放大器)
247
+ .replace(/\n?\[情绪回响\][\s\S]*?\[\/情绪回响\]\n?/g, '\n')
248
+ .replace(/\n?\[手边\][^\n]*/g, '\n')
249
+ .replace(/\n?\[约定\][\s\S]*?\[\/约定\]\n?/g, '\n')
250
+ // 2026-11-07:ab-understand 的意图提示也要剥掉,避免被回显后当成用户原话沉淀
251
+ .replace(/\n?\[听懂\][\s\S]*?\[\/听懂\]\n?/g, '\n')
252
+ .trim();
253
+ }
254
+
255
+ // 聊天台账补录的节流(每 15s 最多一次;读的是插件已落盘的 msg-history,增量很小)
256
+ let _lastChatIngest = 0;
257
+ function maybeIngestChat(dataRoot, cfg, logger) {
258
+ try {
259
+ const now = Date.now();
260
+ const every = Math.max(3000, Number(cfg?.chatlog?.ingestThrottleMs) || 15000);
261
+ if (now - _lastChatIngest < every) return;
262
+ _lastChatIngest = now;
263
+ const r = ingestChatHistory(dataRoot, cfg?.chatlog || {});
264
+ if (r && r.ok && r.imported > 0) logger?.debug?.(`[chatlog] 补录 ${r.imported} 条`);
265
+ } catch { /* 台账是旁路,失败不影响聊天 */ }
266
+ }
267
+
268
+ /** 纯表情/纯标点/复读/命令 之类不值得记 */
269
+ function worthRemembering(text, cfg) {
270
+ const t = String(text || '').trim();
271
+ if (t.length < (cfg.minTextLen || 6)) return false;
272
+ // ★ 2026-10-22 修:实测抓到了 "/bot-restart" —— 斜杠命令不是聊天内容,
273
+ // 进记忆库只会污染召回(问"上次说啥"时可能召回一条命令)。
274
+ if (t.startsWith('/')) return false;
275
+ // 空正文占位(P0-2 引入的)也不该记
276
+ if (/^(只 @ 了你一下/.test(t)) return false;
277
+ // 不含任何文字/数字 = 纯标点或纯表情符号
278
+ if (!/[\u4e00-\u9fa5A-Za-z0-9]/.test(t)) return false;
279
+ if (/^\[(图片|语音|视频|表情|文件)[^\]]*\]$/.test(t)) return false;
280
+ if (/^[哈嗯哦啊额唔咦哦嘿呀吧嘛]+$/.test(t)) return false;
281
+ return true;
282
+ }
283
+
284
+ // ── [qqbot-mod] slow-block 节流(2026-10-28 主人定:长期可能变的块不必每条消息重复)──
285
+ // 现状浪费:印象卡/旧识/学/约定/性格观察这些慢变量(分钟~天级才变)以前**每条消息都全文重发**,
286
+ // 且历史里永久留存 → N 条消息 N 份,token 线性上涨。
287
+ // 改法:按 scope+tag 记住上次注入的内容指纹,**内容没变就不再注入**——历史里上一份还在,
288
+ // 模型照样看得见(语义不变);只有真变了才注入一份新的(新版在后,模型取最新)。
289
+ // 快块([记忆]召回/[状态]/[echo])是为当前句服务的,保持每条,但连续相同内容也跳过。
290
+ const _slowBlockMemo = new Map(); // key: scope+'|'+tag → 上次注入文本
291
+ let _lastRoot = __repoRoot() + "/dshqqbot"; // onInbound 每轮刷新,供 blockIfChanged 持久化记账用
292
+ // 2026-10-29:召回源判重——key: scope → 上次实际注入的那批记忆源文本指纹。
293
+ // 连续同话题时同一批旧记忆不再每条重发(历史里上一份仍在,模型照样看得见)。
294
+ const _recallSrcMemo = new Map();
295
+ // 2026-10-30 主人拍板「上下间隔不远就不至于每次都发送」:距上次召回注入 <5 分钟的消息
296
+ // 直接跳过召回 —— 连续聊天时上一轮的 [记忆] 块还在会话历史里(全量重发模型),模型看得见。
297
+ const _recallTimeMemo = new Map(); // scope → 上次实际注入召回块的时间戳
298
+
299
+ // ── 会话账本纪元(2026-11-08,P1-4)──
300
+ // 问题:blockIfChanged 只按 scope|tag 去重;会话轮换/压缩后旧历史被裁掉,慢块指纹却没变
301
+ // ⇒ 新会话里信条/印象/旧识等整套长期上下文不再注入(文档 P1-4)。
302
+ // 解决:给账本加"纪元"维度 —— 检测到轮换/压缩时纪元 +1,所有旧账立刻失效,
303
+ // 下一条消息强制整套注入一次;纪元本身落 chat_meta,重启后继续沿用 ⇒ 未轮换时仍续用旧账(重启不丢)。
304
+ // 为什么不直接用 sessionId:入站 ctx 拿不到 session/event 里的 session.id(只有出站链的 session.header.id),
305
+ // 所以改从 ctx.caps.kernel 订阅宿主事件,用"压缩/首次见到新会话"作为轮换信号。
306
+ let _blkEpoch = null;
307
+ let _blkEpochRoot = '';
308
+ const _seenSessions = new Set(); // 已见过的 DSH 会话 id(最多留 40 个)
309
+ let _seenSessionsLoaded = false;
310
+ let _rotationHookInstalled = false;
311
+ const ROTATION_HOOK_KEY = Symbol.for('im-qqbot.memory-block-epoch');
312
+
313
+ let _bootChecked = false;
314
+ /** 每次进程启动一个唯一戳:用来判断"这次是重启后第一次注入" */
315
+ const BOOT_ID = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
316
+
317
+ function epochOf(root) {
318
+ const r = String(root || '');
319
+ if (_blkEpoch !== null && _blkEpochRoot === r) return _blkEpoch;
320
+ _blkEpochRoot = r;
321
+ try {
322
+ const n = Number(getChatState(r, 'blk-epoch')?.n);
323
+ _blkEpoch = Number.isFinite(n) && n >= 0 ? n : 0;
324
+ } catch { _blkEpoch = 0; }
325
+ // 2026-11-10 主人实测「重启后印象卡失效」:慢块账本落 chat_meta,重启后照样命中"内容没变→不注入",
326
+ // 可新进程的会话历史里根本没有那份块 ⇒ 卡片凭空消失。
327
+ // 修法:每个进程启动后把纪元 +1,重启后整套慢块重新注入一次(一次性成本,之后继续按内容去重)。
328
+ if (!_bootChecked) {
329
+ _bootChecked = true;
330
+ try {
331
+ const mark = String(getChatState(r, 'blk-boot')?.id || '');
332
+ if (mark !== BOOT_ID) {
333
+ _blkEpoch += 1;
334
+ _slowBlockMemo.clear();
335
+ _recallSrcMemo.clear();
336
+ _recallTimeMemo.clear();
337
+ try { setChatState(r, 'blk-epoch', { n: _blkEpoch, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
338
+ try { setChatState(r, 'blk-boot', { id: BOOT_ID, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
339
+ }
340
+ } catch { /* 读不到就当首次启动 */ }
341
+ }
342
+ // 已见会话集也持久化:重启后 resume 的旧会话不会被误判成"新轮换"(避免重启整套重发的旧毛病)
343
+ if (!_seenSessionsLoaded) {
344
+ try {
345
+ const ids = getChatState(r, 'blk-seen-sessions')?.ids;
346
+ if (Array.isArray(ids)) {
347
+ for (const x of ids.slice(-40)) {
348
+ const s = String(x || '').trim();
349
+ if (s) _seenSessions.add(s);
350
+ }
351
+ }
352
+ } catch { /* 读不到就当空集 */ }
353
+ _seenSessionsLoaded = true;
354
+ }
355
+ return _blkEpoch;
356
+ }
357
+
358
+ function bumpEpoch(reason) {
359
+ const root = String(_lastRoot || '');
360
+ epochOf(root);
361
+ _blkEpoch += 1;
362
+ // 旧账全部作废:慢块 memo + 召回源/时间闸也一起清(新会话里上一份注入 / 5 分钟闸都不再成立)
363
+ _slowBlockMemo.clear();
364
+ _recallSrcMemo.clear();
365
+ _recallTimeMemo.clear();
366
+ _personaOnce.clear();
367
+ try { setChatState(root, 'blk-epoch', { n: _blkEpoch, ts: Date.now() }); } catch { /* 写失败下次再写 */ }
368
+ try { console.debug?.(`[memory] 账本纪元 → ${_blkEpoch}(${reason})`); } catch { }
369
+ }
370
+
371
+ function installRotationHook(ctx) {
372
+ if (_rotationHookInstalled) return;
373
+ _rotationHookInstalled = true;
374
+ const kernel = ctx?.caps?.kernel;
375
+ if (!kernel || typeof kernel.on !== 'function') return; // 拿不到遥控器 → 退回旧行为
376
+ // 热重载会重新装载本模块:先 dispose 上一份,避免监听器累积(见 ext-capabilities.d.ts 的"铁律")
377
+ try { globalThis[ROTATION_HOOK_KEY]?.dispose?.(); } catch { }
378
+ const handler = (session, event) => {
379
+ try {
380
+ epochOf(_lastRoot); // 顺便把已见会话集从 chat_meta 载入
381
+ const type = String(event?.type || '');
382
+ if (type === 'compaction/start') { bumpEpoch('上下文压缩'); return; }
383
+ const sid = String(session?.header?.id || session?.id || '').trim();
384
+ if (!sid || _seenSessions.has(sid)) return;
385
+ _seenSessions.add(sid);
386
+ while (_seenSessions.size > 40) _seenSessions.delete(_seenSessions.values().next().value);
387
+ try { setChatState(_lastRoot, 'blk-seen-sessions', { ids: [..._seenSessions], ts: Date.now() }); } catch { }
388
+ // 首次见到某会话 = 新建 / /bot-new 轮换(重启后 resume 的旧会话已在持久化集合里,不会误判)
389
+ bumpEpoch('新会话');
390
+ } catch { /* 事件回调绝不影响主链 */ }
391
+ };
392
+ try {
393
+ const dispose = kernel.on('session/event', handler);
394
+ globalThis[ROTATION_HOOK_KEY] = { dispose: typeof dispose === 'function' ? dispose : () => { } };
395
+ } catch { /* 订阅失败就退回旧行为 */ }
396
+ }
397
+
398
+ function blockIfChanged(scope, tag, text) {
399
+ const root = _lastRoot;
400
+ const ep = epochOf(root);
401
+ const key = 'e' + ep + '|' + String(scope || '') + '|' + String(tag || '');
402
+ let prev = _slowBlockMemo.get(key);
403
+ // 2026-11-02 主人问「怎么每轮注入这么多」:这份"上次发过什么"的记账原来只在进程内存里,
404
+ // 一重启就全忘 —— 于是重启后头几条消息会把所有慢变量块**整套重发一遍**(一次上千 token)。
405
+ // 现在落 chat_meta(key = blk:e<纪元>:<scope>|<tag>),重启也能续上,只在真的变了才再发。
406
+ if (prev === undefined) {
407
+ try { prev = String(getChatState(root, 'blk:' + key)?.text || ''); } catch { prev = ''; }
408
+ }
409
+ const cur = String(text || '');
410
+ if (cur === prev) return ''; // 内容没变 → 不注入(历史里那份仍可见)
411
+ _slowBlockMemo.set(key, cur);
412
+ try { setChatState(root, 'blk:' + key, { text: cur.slice(0, 1600), ts: Date.now() }); } catch { /* 记账失败不影响注入 */ }
413
+ return cur;
414
+ }
415
+
416
+ /** 撤销某块"已发过"的记账(块因超预算被丢弃时用,让下一条消息还能补发) */
417
+ function forgetBlock(scope, tag) {
418
+ const root = _lastRoot;
419
+ const key = 'e' + epochOf(root) + '|' + String(scope || '') + '|' + String(tag || '');
420
+ _slowBlockMemo.delete(key);
421
+ // 印象被丢弃时把"一个会话只强调一次"也一起撤销,否则补发永远不会再来
422
+ if (tag === 'profile' || tag === 'profile-compact') _personaOnce.delete('e' + epochOf(root) + '|' + scope + '|persona');
423
+ try { setChatState(root, 'blk:' + key, { text: '', ts: Date.now() }); } catch { /* 撤销失败下轮重试 */ }
424
+ }
425
+
426
+
427
+ export async function onInbound(ctx, next) {
428
+ let cfg;
429
+ try {
430
+ cfg = loadConfig(dataRootOf({})); // 2026-10-29 修:原来这里连续 load 两次(第二次包一层 dataRoot 纯属历史残留),每条消息白读一遍配置文件
431
+ } catch {
432
+ return next(); // 配置都读不了 → 直接放行
433
+ }
434
+
435
+ if (cfg.enabled === false) return next();
436
+
437
+ const scope = scopeOf(ctx);
438
+ if (!scope) return next();
439
+
440
+ const dataRoot = dataRootOf(cfg);
441
+ _lastRoot = dataRoot; // 供 blockIfChanged 把"已发过什么"落到 chat_meta
442
+ installRotationHook(ctx); // P1-4:订阅会话轮换/压缩,轮换时账本纪元 +1(只装一次)
443
+ const original = stripMemoryBlock(ctx.text);
444
+ if (!original) return next();
445
+
446
+ // ── ⓪a 顺手把聊天台账补进 SQLite(幂等、增量;给记忆分身和运维查)──
447
+ maybeIngestChat(dataRoot, cfg, ctx?.logger);
448
+
449
+ // ── ⓪ 先把"她自己记下的"(memory 工具写的收件箱)并入本群 ──
450
+ // 工具拿不到当前 scope,所以写公共收件箱;这里在拿到 scope 之后归位。
451
+ // 放在召回之前,这样她刚记的东西下一条消息就能被召回。
452
+ try {
453
+ const merged = await drainInbox(dataRoot, scope, cfg);
454
+ if (merged > 0) ctx?.logger?.debug?.(`[memory] 收件箱并入 ${merged} 条 → ${scope}`);
455
+ } catch (e) {
456
+ ctx?.logger?.debug?.(`[memory] 收件箱并入失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
457
+ }
458
+
459
+ // ── ① 先召回(必须早于沉淀:否则会把"当前这句话"当成历史记忆注回去,白烧 token)──
460
+ // 群等级策略:普通群(水群)不召回长期记忆——只看信息本身;特别关心群/私聊才召回。
461
+ const tier = tierOf(dataRoot, scope, cfg.groupTiers);
462
+ // 特别关心的人(2026-10-25 主人要求):普通群里遇到名单里的 QQ,也按 priority 档走
463
+ // —— 完整印象卡 + 长期记忆召回/沉淀;名单在浮窗「记忆」→「特别关心(手动添加)」里维护。
464
+ let tierEff = tier;
465
+ try {
466
+ if (tier === 'normal' && isPriorityPerson(dataRoot, ctx?.message?.senderId, cfg.groupTiers)) tierEff = 'priority';
467
+ } catch { /* 名单读不到就按原档 */ }
468
+ const policy = policyFor(tierEff, cfg.groupTiers);
469
+ // ── 2026-11-30 注入开关 + 记忆审查 ──
470
+ // owner=主人本人(豁免审查);dumpBlocked=有人在套"把记忆/设定全列出来" → 本轮不注入召回
471
+ const senderIdNow = String(ctx?.message?.senderId || '');
472
+ const isOwner = ownerIds().has(senderIdNow);
473
+ const guardCfg = (cfg.memoryGuard && typeof cfg.memoryGuard === 'object') ? cfg.memoryGuard : {};
474
+ const guardOn = guardCfg.enabled !== false;
475
+ const redactOn = guardOn && !isOwner && guardCfg.redactForNonOwner !== false;
476
+ const dumpBlocked = guardOn && !isOwner && guardCfg.blockDumpRequests !== false && isDumpRequest(original);
477
+ if (dumpBlocked) ctx?.logger?.debug?.('[memory-guard] 识别到倾倒请求,本轮不注入召回');
478
+ let memBlock = '';
479
+ const recallT0 = Date.now();
480
+ let recallRaw = 0;
481
+ let recallKept = 0;
482
+ let recallRewritten = false;
483
+ let recallErr = '';
484
+ if (policy.recall && injectOn(cfg, 'memory') && !dumpBlocked) {
485
+ try {
486
+ // ── ⓪b 短句闸(2026-10-29 token 调度)──
487
+ // 「哈哈」「嗯嗯」「6」这类几乎没有语义的电荷,拿去跑向量召回只会捞回噪声,
488
+ // 召回块还可能把不相关的旧事注进上下文 → 主模型多读一段废话。
489
+ // 有效字符 <4 直接跳过召回(沉淀另有 worthRemembering 把关,不受影响)。
490
+ const coreLen = normText(original).length;
491
+ if (coreLen >= 4) {
492
+ // ── ⓪c 时间闸(2026-10-30):距上次召回注入 <5 分钟 → 跳过检索(历史里仍可见)
493
+ // deltaOnly=false 时退回旧行为(每条都查),供人按需关掉省 token 的增量策略。
494
+ const deltaOnly = injectOn(cfg, 'deltaOnly');
495
+ const _recent = deltaOnly && (Date.now() - Number(_recallTimeMemo.get(scope) || 0) < 5 * 60 * 1000);
496
+ const hits = _recent ? [] : await recallUnion(dataRoot, scope, original, cfg);
497
+ recallRaw = Array.isArray(hits) ? hits.length : 0;
498
+ // ★ 自匹配过滤:库里存着"这句话本身"时(上一轮沉淀的),cos 常是 0.93~0.97,
499
+ // 低于 0.98 的老阈值会漏过去,于是每轮把用户刚说的话再注回去一次 —— 纯浪费 token。
500
+ // 这里按**文本**判重,比按余弦稳:只要召回条目的正文等于/包含当前这句就丢掉。
501
+ const qNorm = normText(original);
502
+ const seenHit = new Set();
503
+ const kept = (Array.isArray(hits) ? hits : []).filter((h) => {
504
+ const t = normText(h && h.text);
505
+ if (!t) return false;
506
+ if (t === qNorm) return false;
507
+ // 当前这句被完整包含在记忆里(比如记忆是"甲:乙"的长句)也算自匹配
508
+ if (t.length > qNorm.length && t.includes(qNorm) && qNorm.length >= 8) return false;
509
+ // 库里历史重复(去重上线前写进去的)也不要重复占额度
510
+ if (seenHit.has(t)) return false;
511
+ seenHit.add(t);
512
+ return true;
513
+ });
514
+ // [mmtr 2026-10-27] 防自增强:刚被用过的记忆本轮降权 + 记使用日志(重要性不受检索影响)
515
+ try { applyRecallGuard(dataRoot, scope, kept); } catch { /* 护栏失败不影响召回 */ }
516
+ // 2026-11-30 记忆审查:非主人只遮蔽敏感字段(手机号/证件/地址/账号),不整条丢弃
517
+ const guarded = redactOn ? kept.map((h) => (h && h.text ? { ...h, text: redactSensitive(h.text) } : h)) : kept;
518
+ memBlock = formatRecallBlock(guarded, cfg);
519
+ recallKept = kept.length;
520
+ // ★ 同源去重(2026-10-29 token 调度):连着聊同一话题时,每条的召回命中常常是
521
+ // 同一批旧记忆(top hit 不变),只是 LLM 改写出的句子措辞不同 →
522
+ // 以前按改写后文本判重拦不住,等于同一份记忆每条消息重发一遍。
523
+ // 改成按**召回源文本**判重:这一批和上一条注入过的完全一样 → 不再注入
524
+ // (历史里上一份还在,模型照样看得见)。有新记忆进来才注入增量。
525
+ const srcKey = kept.map((h) => normText(h.text)).sort().join('|');
526
+ const prevSrc = _recallSrcMemo.get(scope) || '';
527
+ if (deltaOnly && srcKey && srcKey === prevSrc) {
528
+ memBlock = '';
529
+ ctx?.logger?.debug?.('[memory] 召回源与上一条相同,跳过注入(历史里仍有)');
530
+ } else if (srcKey) {
531
+ _recallSrcMemo.set(scope, srcKey);
532
+ }
533
+ if (memBlock) {
534
+ ctx?.logger?.debug?.(`[memory] 召回 ${kept.length} 条 (${kept.map((h) => h.cos.toFixed(2)).join(',')})`);
535
+ _recallTimeMemo.set(scope, Date.now()); // 时间闸:只记真实注入
536
+ }
537
+ // ── ①a2 本地小模型"过一遍"(用户 2026-10-23 提的方案)──
538
+ // · 2 条以上才值得过一次模型(1 条时原文更准);块本身已经很短(<100 字)
539
+ // 也没必要过模型——省一次本地调用,延迟立省 0.5~1.5s;
540
+ // · 成功 → 压成一句第一人称回忆(4 条 160 字 → 1 句 ~30 字),还顺便丢掉噪声;
541
+ // · 失败/超时/模型离线 → 保留原来的编号列表(永不因此丢记忆、更不卡回复)。
542
+ if (memBlock && kept.length >= 2 && memBlock.length >= 100) {
543
+ try {
544
+ const lr = await rewriteRecall(kept, original, cfg, { dataRoot });
545
+ if (lr && lr.ok && lr.text) {
546
+ memBlock = '\n[记忆]' + lr.text + '[/记忆]';
547
+ recallRewritten = true;
548
+ ctx?.logger?.info?.(`[memory] 本地模型改写 ${kept.length} 条 → ${lr.text.length} 字(${lr.ms}ms): ${lr.text}`);
549
+ } else {
550
+ ctx?.logger?.debug?.(`[memory] 保留编号列表(${(lr && lr.reason) || '?'}${lr && lr.ms ? ' ' + lr.ms + 'ms' : ''})`);
551
+ }
552
+ } catch (e) {
553
+ ctx?.logger?.debug?.(`[memory] 改写异常(已忽略): ${e instanceof Error ? e.message : String(e)}`);
554
+ }
555
+ }
556
+ } // ── 短句闸结束(coreLen >= 4 才走召回)
557
+ } catch (e) {
558
+ recallErr = e instanceof Error ? e.message : String(e);
559
+ ctx?.logger?.debug?.(`[memory] 召回失败(已忽略): ${recallErr}`);
560
+ }
561
+ }
562
+ // [记忆] 召回结果连续相同(连着聊同一话题)也不再重复注入——历史里那份还在
563
+ memBlock = injectOn(cfg, 'deltaOnly') ? blockIfChanged(scope, 'mem', memBlock) : memBlock;
564
+ // 轨迹只记摘要(不存全文),给浮窗看"这条消息到底有没有查库、查到几条"
565
+ try {
566
+ traceMemory(dataRoot, {
567
+ kind: 'recall', scope, query: original.replace(/<@[^>]*>/g, '').replace(/\s+/g, ' ').trim().slice(0, 50),
568
+ raw: recallRaw, hits: recallKept, rewritten: recallRewritten,
569
+ ok: !recallErr, error: recallErr, ms: Date.now() - recallT0,
570
+ });
571
+ } catch { /* ignore */ }
572
+
573
+
574
+ // ── ①b 世界书:命中关键词才带 1~2 条设定(Neuro 式,设定不进常驻 prompt)──
575
+ // slow-block:同一关键词组合连续命中时不再重复注入
576
+ let loreBlock = '';
577
+ if (injectOn(cfg, 'worldbook')) {
578
+ try {
579
+ const l = loreFor(dataRoot, original, cfg.lore || {});
580
+ loreBlock = blockIfChanged(scope, 'lore', l.block);
581
+ if (l.block && loreBlock) ctx?.logger?.debug?.(`[lore] 注入 ${l.hits.map((h) => h.id).join(',')}`);
582
+ else if (l.block) ctx?.logger?.debug?.(`[lore] 命中但与上次相同,跳过`);
583
+ } catch (e) {
584
+ ctx?.logger?.debug?.(`[lore] 注入失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
585
+ }
586
+ }
587
+
588
+ // ── ①c 反重复:把她刚说过的几句附在后面(AI 味最大来源就是重复同一个句式/口头禅)──
589
+ let echoBlock = '';
590
+ if (injectOn(cfg, 'echo')) {
591
+ try {
592
+ const ec = formatEchoBlock(dataRoot, scope, cfg.echo || {});
593
+ echoBlock = ec.block;
594
+ if (echoBlock) ctx?.logger?.debug?.(`[echo] 反重复 ${ec.lines.length} 句`);
595
+ } catch (e) {
596
+ ctx?.logger?.debug?.(`[echo] 反重复生成失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
597
+ }
598
+ }
599
+
600
+ // ── ①d 印象 + 熟识度(个人层:跨群统一;稳定模式,保云端缓存)──
601
+ // 特别关心群/私聊:完整卡;普通群:只给「名字 · 等级」极简认人块(不认识的人一个字都不多花)。
602
+ let profileBlock = '';
603
+ if (injectOn(cfg, 'persona')) {
604
+ try {
605
+ const who = {
606
+ senderId: String(ctx?.message?.senderId || ''),
607
+ senderName: String(ctx?.message?.senderName || ''),
608
+ };
609
+ const profileCfg = { ...(cfg.profile || {}), ...(cfg.bond || {}) };
610
+ // 2026-11-30:personaOnce(默认开)——一个会话里性格/印象只强调一次;
611
+ // 之后内容再变也不重发(新会话/压缩后纪元 +1 自动重置)。
612
+ const onceKey = 'e' + epochOf(dataRoot) + '|' + scope + '|persona';
613
+ const personaDone = injectOn(cfg, 'personaOnce') && _personaOnce.has(onceKey);
614
+ if (policy.profile === 'full') {
615
+ profileBlock = familiarityBlockFor(dataRoot, scope, who, profileCfg);
616
+ // [性格观察](2026-10-26):belief 层的性格倾向终于被模型看到(此前只存不消费)
617
+ try {
618
+ const tb = traitBlockFor(dataRoot, who.senderId);
619
+ if (tb) profileBlock += tb;
620
+ } catch { /* 性格观察失败不影响印象块 */ }
621
+ // [成长](2026-10-26):她的自我心得(growth:latest,自我反思每天一变的慢变量)——
622
+ // 让"完善自我"这条信条真的有出口:她能看到自己上一次的反思。
623
+ try {
624
+ const gv = getPersonaValue(dataRoot, '__global__', 'growth:latest');
625
+ if (gv && gv.value) profileBlock += '\n[成长]' + String(gv.value).replace(/\s+/g, ' ').trim().slice(0, 90) + '[/成长]';
626
+ } catch { /* 成长块失败不影响印象块 */ }
627
+ if (profileBlock && personaDone) profileBlock = '';
628
+ else {
629
+ // slow-block:印象卡/性格/成长都是慢变量,内容没变就不再每条重发
630
+ profileBlock = blockIfChanged(scope, 'profile', profileBlock);
631
+ if (profileBlock) _personaOnce.add(onceKey);
632
+ }
633
+ if (profileBlock) ctx?.logger?.debug?.(`[profile] 已注入完整印象+熟识度 (tier=${tier})`);
634
+ } else if (policy.profile === 'compact') {
635
+ profileBlock = personaDone ? '' : blockIfChanged(scope, 'profile-compact', compactBlockFor(dataRoot, scope, who, profileCfg));
636
+ if (profileBlock) _personaOnce.add(onceKey);
637
+ if (profileBlock) ctx?.logger?.debug?.(`[profile] 已注入精简认人块 (tier=${tier})`);
638
+ }
639
+ } catch (e) {
640
+ ctx?.logger?.debug?.(`[profile] 印象块失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
641
+ }
642
+ }
643
+
644
+ // ── ①e 状态:本轮/近 30 分钟的当下心情(≤30 字,过期自动不带)──
645
+ // 2026-10-31 主人拍板(信条等没必要反复出现):状态也是慢变量 —— 心情没变就不重发
646
+ // (历史里上一份还在);变了/过期才注一份新的。
647
+ let moodBlock = '';
648
+ if (injectOn(cfg, 'mood')) {
649
+ try {
650
+ moodBlock = blockIfChanged(scope, 'mood', moodBlockFor(dataRoot, scope, cfg.mood || {}));
651
+ if (moodBlock) ctx?.logger?.debug?.('[mood] 已注入状态');
652
+ } catch (e) {
653
+ ctx?.logger?.debug?.(`[mood] 状态失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
654
+ }
655
+ }
656
+
657
+ // ── ①f 情绪回响(2026-10-29 参考 Companion-AI-Memory 的主动回忆机制)──
658
+ // 不是被动等 TA 问「怎么了」,而是:检测到情绪词 → 去记忆库翻「上次因为什么」
659
+ // → 把那个旧事带进上下文,让她能像熟人一样具体地接(「是又加班了吗?」)。
660
+ // 隐私分层沿用:只在当前 scope 的记忆库内翻(不跨人聚合);仅 full 权限场景;
661
+ // 每 scope 30 分钟最多一次;至少半小时前的旧事才算「回忆」(刚说的不算)。
662
+ let moodEchoBlock = '';
663
+ if (policy.profile === 'full' && cfg.moodEcho !== false && injectOn(cfg, 'moodEcho')) {
664
+ try {
665
+ const MOOD_WORDS = ['累', '倦', '疲惫', '加班', '熬夜', '压力大', '崩了', '破防', 'emo',
666
+ '难过', '伤心', '委屈', '烦', '生气', '焦虑', '孤独', '寂寞',
667
+ '开心', '高兴', '兴奋', '乐死', '爽', '感动', '幸福'];
668
+ const hitWord = MOOD_WORDS.find((w) => original.includes(w));
669
+ // 2026-10-29 修:状态键原来用全局 'mood-echo',注释写的是「每 scope 30 分钟一次」,
670
+ // 实际 A 群触发后 B 群 30 分钟内被无辜连坐。改成按 scope 记账,与注释语义一致。
671
+ const meState = getChatState(dataRoot, 'mood-echo:' + scope) || {};
672
+ if (hitWord && Date.now() - (Number(meState.ts) || 0) > 30 * 60 * 1000) {
673
+ setChatState(dataRoot, 'mood-echo:' + scope, { ts: Date.now() });
674
+ const hits = await recall(dataRoot, scope, hitWord + ' ' + original.slice(0, 40), cfg);
675
+ const older = (hits || []).filter((h) => Date.now() - Number(h.ts || 0) > 30 * 60 * 1000);
676
+ if (older.length) {
677
+ const h = older[0];
678
+ const agoH = Math.floor((Date.now() - Number(h.ts)) / 3600000);
679
+ const when = agoH >= 24 ? Math.floor(agoH / 24) + ' 天前' : (agoH >= 1 ? agoH + ' 小时前' : '刚才不久');
680
+ moodEchoBlock = `\n[情绪回响]TA 情绪「${hitWord}」;你记得 ${when} 也有过——「${String(h.text).replace(/\s+/g, ' ').slice(0, 45)}」。顺着旧事关心,别干巴巴问「怎么了」。[/情绪回响]`;
681
+ ctx?.logger?.debug?.(`[mood-echo] 情绪回响已注入(词=${hitWord},旧事=${when})`);
682
+ }
683
+ }
684
+ } catch (e) {
685
+ ctx?.logger?.debug?.(`[mood-echo] 情绪回响失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
686
+ }
687
+ }
688
+
689
+ // ── ①d2 旧识:这个人的历史聊天记录导入后留下的画像 ──
690
+ // 数据隔离:只读 senderId 自己那一个 scope(person:qq:<号>),不跨人聚合。
691
+ // 可见性:只有拿到了"完整印象"权限的场景(特别关心群/私聊)才带;
692
+ // 普通群连"认识这个人"都不展开,更不能把他在别处说过的话搬过来。
693
+ let pastBlock = '';
694
+ if (policy.profile === 'full' && cfg.pastProfile !== false && injectOn(cfg, 'pastProfile')) {
695
+ try {
696
+ const sid = String(ctx?.message?.senderId || '').trim();
697
+ const p = sid ? personProfile(dataRoot, sid) : null;
698
+ if (p && p.ok && p.impression) {
699
+ // 画像本身已经是一句统计结论(≤120 字),这里只做截断,不改写语义
700
+ const line = p.impression.replace(/\s+/g, ' ').slice(0, 120);
701
+ // slow-block:旧识画像也是慢变量,没变不重发
702
+ pastBlock = blockIfChanged(scope, 'past', `\n[旧识]${line}[/旧识]`);
703
+ if (pastBlock) ctx?.logger?.debug?.(`[past] 已注入旧识画像 (${p.say} 条)`);
704
+ }
705
+ } catch (e) {
706
+ ctx?.logger?.debug?.(`[past] 旧识画像失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
707
+ }
708
+ }
709
+
710
+ // ── ①d3 学来的说话习惯:她观察群里怎么说话,只学表达方式(≤90 字)──
711
+ let styleBlock = '';
712
+ if (cfg.imitate?.inject !== false && injectOn(cfg, 'style')) {
713
+ try {
714
+ const st = currentStyle(dataRoot);
715
+ if (st) styleBlock = blockIfChanged(scope, 'style', `\n[学]${String(st).slice(0, 90)}[/学]`); // slow-block
716
+ } catch { /* 学不到就算了 */ }
717
+ }
718
+
719
+ // ── ①d4 手痒提醒:她几乎从不发表情包(2026-10-27 主人点名)──
720
+ // 不是命令,只是"手边有图"的轻推:距上次发图 ≥ 30 分钟才出现,且最多每 30 分钟一次,
721
+ // 免得每轮都催(催多了反而机械)。
722
+ let stickerBlock = '';
723
+ try {
724
+ if (cfg.stickerNudge !== false && policy.capture && injectOn(cfg, 'sticker')) {
725
+ const st = getChatState(dataRoot, 'sticker:last') || {};
726
+ const lastTs = Number(st.ts) || 0;
727
+ const gap = Date.now() - lastTs;
728
+ const nudge = getChatState(dataRoot, 'sticker:nudge') || {};
729
+ if (gap > 30 * 60 * 1000 && Date.now() - (Number(nudge.ts) || 0) > 30 * 60 * 1000) {
730
+ stickerBlock = '\n[手边]表情包:sticker_auto 搜;兴头配一张,正事/难过不发。[/手边]';
731
+ setChatState(dataRoot, 'sticker:nudge', { ts: Date.now() });
732
+ }
733
+ }
734
+ } catch { /* 提醒失败不影响对话 */ }
735
+
736
+ // ── ①d5 [约定](2026-10-27 mmtr):到期的承诺/约定自己浮上来——
737
+ // 事实锁定原文、越接近截止越清晰、超宽限自动 broken 并付关系代价。
738
+ let promiseB = '';
739
+ if (injectOn(cfg, 'promise')) {
740
+ try { promiseB = blockIfChanged(scope, 'promise', promiseBlockFor(dataRoot, scope)); } catch { /* 约定块失败不影响对话 */ } // slow-block
741
+ }
742
+
743
+ // 所有块合并成一次 rewrite(改两次会让中间态被别的扩展看见)
744
+ // [信条](2026-10-26):底层刻写常驻块,全静态、跨群不变(prompt 缓存友好);
745
+ // 放最前——它是主人手笔,LLM 只读不可改,优先级高于一切注入。
746
+ // 2026-10-31 主人拍板(「信条等真的没必要反复出现那么多次」):信条全静态,
747
+ // 一个 scope 只在内容变化时注入一次(历史里上一份仍在,模型照样看得见),
748
+ // 不再每条消息重发 —— N 条消息 N 份信条的 token 线性浪费到此为止。
749
+ const bedrock = injectOn(cfg, 'bedrock') ? blockIfChanged(scope, 'bedrock', bedrockBlock(dataRoot)) : '';
750
+ // ── 注入总预算(2026-11-02):块越加越多,一条消息能带两三千字 —— 而且这些字会**永久留在对话历史里**,
751
+ // 每轮都在为它们付钱(复利)。所以给总长设硬上限,按优先级装,装不下的直接这轮不带(下轮内容变了还会来)。
752
+ const INJECT_BUDGET = Math.max(400, Number(cfg.injectBudgetChars) || 1200);
753
+ // tag → 中文名(dropped 里是中文名,要能反查回慢块 tag 好撤销"已发过"记账)
754
+ const parts = [
755
+ ['bedrock', '信条', bedrock], ['mem', '记忆', memBlock], ['profile', '印象', profileBlock], ['promise', '约定', promiseB],
756
+ ['mood', '状态', moodBlock], ['lore', '世界书', loreBlock], ['past', '旧识', pastBlock],
757
+ ['echo', '反重复', echoBlock], ['style', '说话习惯', styleBlock], ['sticker', '表情包', stickerBlock], ['moodEcho', '情绪回响', moodEchoBlock],
758
+ ];
759
+ // 打包规则与微信侧共用 lib/context-budget.mjs(同一套「超预算整块丢弃 + 记 dropped」语义)
760
+ const packed = packByBudget(parts.map((p) => [p[1], p[2]]), INJECT_BUDGET, 400);
761
+ const extra = joinKept(packed.kept);
762
+ const dropped = packed.dropped;
763
+ // ★ 2026-11-30 一次性注入的漏洞修复:blockIfChanged 在打包前就记了"已发过",
764
+ // 若这一块因超预算被丢掉,本会话就再也不会补发(新会话首次全量注入会缺块)。
765
+ // 这里按 dropped 反查 tag,撤销记账 → 下一条消息还会再来。
766
+ if (dropped.length) {
767
+ for (const p of parts) {
768
+ if (!dropped.includes(p[1])) continue;
769
+ try { forgetBlock(scope, p[0]); } catch { /* 撤销失败不影响本轮 */ }
770
+ }
771
+ }
772
+ if (dropped.length) ctx?.logger?.debug?.(`[budget] 注入超 ${INJECT_BUDGET} 字,本轮不带:${dropped.join('、')}`);
773
+ if (extra) meterInject(dataRoot, scope, extra.length, dropped);
774
+ if (extra && typeof ctx.rewrite === 'function') {
775
+ // 2026-11-11:稳定块(信条/设定/印象…)置顶,易变块(记忆/状态/世界书…)垫底。
776
+ // 旧写法 ctx.text + extra 会把 [信条] 塞到 [消息号] 后面(主人实测的 bug)。
777
+ ctx.rewrite({ text: mergeStableFirst(ctx.text, extra) });
778
+ }
779
+ // ── ② 再沉淀(用"原文本",不含刚注入的记忆块)──
780
+ // 普通群不沉淀长期记忆:水群只看信息本身,不把闲聊塞进向量库(省本地算力)
781
+ if (policy.capture && cfg.capture !== false && worthRemembering(original, cfg)) {
782
+ try {
783
+ await remember(dataRoot, scope, {
784
+ text: original.slice(0, 200),
785
+ kind: 'event',
786
+ // subj 只写"人名":以前兜底写 senderId,库里就多出 82 条主体是 32 位 openid 的记忆,
787
+ // 面板按主体统计时看起来像"记到别人名下"。拿不到真名就留空(空比错好)。
788
+ subj: subjOfMessage(ctx?.message),
789
+ // 溯源:记住这句话是从哪条原始消息来的(不同宿主字段名不一样,挨个兜)
790
+ srcMsgId: msgIdOf(ctx?.message),
791
+ }, cfg);
792
+ } catch (e) {
793
+ ctx?.logger?.debug?.(`[memory] 沉淀失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
794
+ }
795
+ }
796
+
797
+ // ── ③ 中层记忆:攒够 digestEvery 条就压一次"前情摘要"(零 token,抽取式)──
798
+ // 只做增量判断(shouldDigest 很便宜),真正压缩才扫库;绝不删原记忆。
799
+ if (policy.digest) {
800
+ try {
801
+ if (shouldDigest(dataRoot, scope, cfg)) {
802
+ const d = digestScope(dataRoot, scope, cfg);
803
+ if (d.ok) ctx?.logger?.info?.(`[memory] 中层摘要已生成: 覆盖 ${d.covered} 条 → ${d.text.slice(0, 40)}…`);
804
+ }
805
+ } catch (e) {
806
+ ctx?.logger?.debug?.(`[memory] 摘要失败(已忽略): ${e instanceof Error ? e.message : String(e)}`);
807
+ }
808
+ }
809
+
810
+ return next();
811
+ }
812
+
813
+ /** 测试钩子:清空召回节流备忘(时间闸/判重/慢块),闭环测试里背靠背两条消息也要能召回 */
814
+ export function _testResetRecallMemo() {
815
+ _slowBlockMemo.clear();
816
+ _recallSrcMemo.clear();
817
+ _recallTimeMemo.clear();
818
+ _personaOnce.clear();
819
+ }
820
+
821
+ /** 调试用:让她能通过日志看到记忆库状态 */
822
+ export function dumpStats(ctx) {
823
+ try {
824
+ const cfg = loadConfig(dataRootOf({}));
825
+ return stats(dataRootOf(cfg), scopeOf(ctx) || 'unknown', cfg);
826
+ } catch { return null; }
827
+ }