nebula-memory-mcp 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,451 +1,528 @@
1
- 'use strict';
2
-
3
- /**
4
- * 记忆星云 Lite — 动力学层(S 状态 / FSRS 遗忘 / 归档 / 赫布边 / L3 摘要)
5
- *
6
- * 公式与参考实现 brain_dynamics.py 对齐(纯 JS、无外部依赖):
7
- * - 可提取度:R = exp(-Δt / S),S 是 stability(天),Δt 从 lastAccessAt 算起;
8
- * - touch:S' = S · (1 + 1.5 · (1 - R)),lastAccessAt = now,access++,act 写回;
9
- * - 归档:R < 0.15 且 Δt > 90 天 → archived=true(只归档、不删除,includeArchived 仍可召回);
10
- * - 赫布边:共激活对 w += η · aᵢ · aⱼ · (1 - w),η=0.02,(1-w) 上界防正反馈失控;
11
- * - 合成边(只削 hebbian,不动人工/semantic 边):60 天未触发 ×0.9,w < 0.01 删除;
12
- * - L3 摘要:确定性模板「你叫…/你在…/你偏好…/最近在忙…」,不用 LLM。
13
- *
14
- * 本模块不 require store(避免循环依赖):所有记忆操作都通过传入的 mem 实例完成,
15
- * mem 需要提供 store.js 里的内部方法(_queuePersist / _addEdge / _updateEdge /
16
- * _removeEdge / _rewriteNode / _insertNode / _buildRecord / _log 等)。
17
- */
18
-
19
- const DAY_MS = 86400000;
20
-
21
- /** 分层(与 nodes.jsonl 的 layer 字段一一对应) */
22
- const LAYER = Object.freeze({
23
- EVENT: 'event', // L0 事件:一轮对话的原始文本
24
- FRAGMENT: 'fragment', // L1 片段:从对话里抽出来的事实/画像/显式记忆
25
- SUMMARY: 'summary', // L3 摘要:跨片段的画像性总结
26
- });
27
-
28
- /** 边类型(edges.jsonl 的 kind 字段) */
29
- const EDGE_KIND = Object.freeze({
30
- SEMANTIC: 'semantic', // 语义相似 / 巩固时连出来的边(默认)
31
- HEBBIAN: 'hebbian', // 同一次召回里共激活形成的合成边
32
- EXPLICIT: 'explicit', // 调用方显式 link() 出来的边
33
- });
34
-
35
- /**
36
- * MEM_KIND 里没有 summary(constants.js 归 Lead 维护,我不能改),
37
- * 这里用本地常量兜底;kind 仍然是 'summary',与 SPEC 一致。
38
- */
39
- const SUMMARY_KIND = 'summary';
40
- const SUMMARY_META_KEY = 'l3-profile';
41
-
42
- // ---------------------------------------------------------------------------
43
- // 小工具(各模块自带一份,避免为了 3 个函数再开一个文件)
44
- // ---------------------------------------------------------------------------
45
-
46
- function num(v, fallback) {
47
- const n = Number(v);
48
- return Number.isFinite(n) ? n : fallback;
49
- }
50
-
51
- /** 读实例参数:优先 NebulaMemory.opts(构造时的 weights 也在这里),兼容直接挂在实例上的旧写法 */
52
- function opt(mem, key, fallback) {
53
- if (mem) {
54
- if (mem.opts && mem.opts[key] != null) return mem.opts[key];
55
- if (mem[key] != null) return mem[key];
56
- }
57
- return fallback;
58
- }
59
-
60
- function clamp(n, lo, hi) {
61
- return n < lo ? lo : n > hi ? hi : n;
62
- }
63
-
64
- function clamp01(n) {
65
- return clamp(num(n, 0), 0, 1);
66
- }
67
-
68
- function round(n, digits = 4) {
69
- const p = 10 ** digits;
70
- return Math.round(n * p) / p;
71
- }
72
-
73
- function charLen(s) {
74
- return Array.from(String(s == null ? '' : s)).length;
75
- }
76
-
77
- function truncateChars(s, max) {
78
- const arr = Array.from(String(s == null ? '' : s));
79
- if (arr.length <= max) return arr.join('');
80
- return arr.slice(0, Math.max(0, max - 1)).join('') + '…';
81
- }
82
-
83
- function trimPunct(s) {
84
- return String(s == null ? '' : s).replace(/^[\s,。、;:,.;:!?!?"'“”‘’()()【】[\]「」]+|[\s,。、;:,.;:!?!?"'“”‘’()()【】[\]「」]+$/gu, '');
85
- }
86
-
87
- // ---------------------------------------------------------------------------
88
- // S 状态:可提取度 / 分层
89
- // ---------------------------------------------------------------------------
90
-
91
- /** stability 默认 1 天;下限 0.05 天,上限 10 年,避免除零与无限增长 */
92
- function stabilityOf(node) {
93
- return clamp(num(node && node.stability, 1), 0.05, 3650);
94
- }
95
-
96
- /** 最近一次访问时间(没有就用创建时间) */
97
- function lastAccessAt(node) {
98
- return num(node && node.lastAccessAt, num(node && node.ts, Date.now()));
99
- }
100
-
101
- function ageDays(node, now = Date.now()) {
102
- return Math.max(0, (now - lastAccessAt(node)) / DAY_MS);
103
- }
104
-
105
- /** FSRS 遗忘曲线:R = exp(-Δt / S),落在 [0,1]。
106
- * importance 满值(≥1.0)视为「置顶/永久事实」(如用户 API 密钥、称呼偏好),
107
- * 不受时间衰减影响,永远可提取 —— 这是「置顶记忆不遗忘」的语义入口:
108
- * 抽取层/写入方把关键事实的 importance 设为 1.0 即自动永固,无需额外字段。 */
109
- function retention(node, now = Date.now()) {
110
- if (node && clamp01(num(node.importance, 0)) >= 1) return 1;
111
- return clamp01(Math.exp(-ageDays(node, now) / stabilityOf(node)));
112
- }
113
-
114
- /**
115
- * 由 kind + 显式 layer 推断分层(旧数据没有 layer 字段时也能平滑升级)。
116
- * @param {string} kind
117
- * @param {string} [layer]
118
- */
119
- function layerOf(kind, layer) {
120
- if (layer === LAYER.EVENT || layer === LAYER.FRAGMENT || layer === LAYER.SUMMARY) return layer;
121
- if (kind === SUMMARY_KIND) return LAYER.SUMMARY;
122
- if (kind === 'episode') return LAYER.EVENT;
123
- return LAYER.FRAGMENT;
124
- }
125
-
126
- function isValidEdgeKind(kind) {
127
- return kind === EDGE_KIND.SEMANTIC || kind === EDGE_KIND.HEBBIAN || kind === EDGE_KIND.EXPLICIT;
128
- }
129
-
130
- // ---------------------------------------------------------------------------
131
- // touch:命中一次记忆
132
- // ---------------------------------------------------------------------------
133
-
134
- /**
135
- * 更新一条被召回节点的 S 状态(FSRS)。
136
- * 注意:这里**不再**给 importance 加固定值(v1 的 accessBoost 已废弃),
137
- * 记忆的「重要性」由抽取阶段决定,访问只影响可提取度。
138
- *
139
- * @param {any} mem NebulaMemory 实例
140
- * @param {any} node 内部节点(有 stability / lastAccessAt / access 字段)
141
- * @param {{now?:number, act?:number, persist?:boolean}} [opts]
142
- * @returns {{retention:number, stability:number}}
143
- */
144
- function touchNode(mem, node, opts = {}) {
145
- if (!node) return { retention: 0, stability: 1 };
146
- const now = num(opts.now, Date.now());
147
- const r = retention(node, now);
148
- const s = stabilityOf(node);
149
- node.stability = round(clamp(s * (1 + 1.5 * (1 - r)), 0.05, 3650), 4);
150
- node.lastAccessAt = now;
151
- node.access = num(node.access, 0) + 1;
152
- node.dormant = false;
153
- if (opts.act != null) {
154
- node.act = clamp01(opts.act);
155
- node.actAt = now;
156
- }
157
- if (opts.persist !== false && typeof mem._queuePersist === 'function') mem._queuePersist(node);
158
- return { retention: round(r, 4), stability: node.stability };
159
- }
160
-
161
- // ---------------------------------------------------------------------------
162
- // 赫布边:同一次召回内共激活 → 连边 / 强化
163
- // ---------------------------------------------------------------------------
164
-
165
- /**
166
- * @param {any} mem
167
- * @param {Map<string, number>|Object} acts id → 激活量(0..1,未归一也行)
168
- * @param {{now?:number, eta?:number, minProduct?:number, minAct?:number,
169
- * initWeight?:number, maxPairs?:number, source?:string}} [opts]
170
- * @returns {{created:number, reinforced:number, pairs:number}}
171
- */
172
- function applyHebbian(mem, acts, opts = {}) {
173
- const now = num(opts.now, Date.now());
174
- const eta = num(opts.eta, num(opt(mem, 'hebbEta'), 0.02));
175
- const minProduct = num(opts.minProduct, num(opt(mem, 'hebbMinProduct'), 0.3));
176
- const minAct = num(opts.minAct, 0.2);
177
- const initWeight = num(opts.initWeight, num(opt(mem, 'hebbNewWeight'), 0.1));
178
- const maxPairs = Math.max(1, Math.floor(num(opts.maxPairs, 60)));
179
-
180
- const pairsIn = acts instanceof Map ? Array.from(acts.entries()) : Object.entries(acts || {});
181
- const list = [];
182
- for (const [id, raw] of pairsIn) {
183
- const node = mem.nodes.get(String(id));
184
- if (!node || node.deleted) continue;
185
- const a = num(raw, 0);
186
- if (a >= minAct) list.push([node.id, a]);
187
- }
188
- let maxA = 0;
189
- for (const [, a] of list) if (a > maxA) maxA = a;
190
- if (maxA <= 0 || list.length < 2) return { created: 0, reinforced: 0, pairs: 0 };
191
-
192
- // 先按本轮最大值归一到 0..1(参考实现的 _norm)
193
- const normed = list.map(([id, a]) => [id, clamp01(a / maxA)]);
194
- let created = 0;
195
- let reinforced = 0;
196
- let pairs = 0;
197
- for (let i = 0; i < normed.length && pairs < maxPairs; i++) {
198
- for (let j = i + 1; j < normed.length && pairs < maxPairs; j++) {
199
- const product = normed[i][1] * normed[j][1];
200
- if (product < minProduct) continue;
201
- pairs++;
202
- const aId = normed[i][0];
203
- const bId = normed[j][0];
204
- const key = mem._edgeKey(aId, bId);
205
- const edge = mem.edgeMap.get(key);
206
- if (edge) {
207
- const w = Math.min(1, num(edge.w, 0) + eta * product * (1 - num(edge.w, 0)));
208
- mem._updateEdge(edge, { w: round(w, 4), lastFired: now, fireCount: num(edge.fireCount, 0) + 1 });
209
- reinforced++;
210
- } else {
211
- mem._addEdge(aId, bId, initWeight, {
212
- kind: EDGE_KIND.HEBBIAN,
213
- lastFired: now,
214
- fireCount: 1,
215
- source: opts.source || 'recall',
216
- });
217
- created++;
218
- }
219
- }
220
- }
221
- return { created, reinforced, pairs };
222
- }
223
-
224
- // ---------------------------------------------------------------------------
225
- // 遗忘 / 修剪(tick)
226
- // ---------------------------------------------------------------------------
227
-
228
- /**
229
- * 一次遗忘扫描:
230
- * 1) R < archiveRetention(0.15)且闲置 > archiveMinDays(90 天)→ archived=true(不删);
231
- * 2) 合成边(hebbian)闲置 > synapseIdleDays(60 天)→ w *= 0.9,w < 0.01 删除。
232
- * dryRun=true 时只统计不落盘。
233
- *
234
- * @param {any} mem
235
- * @param {{now?:number, dryRun?:boolean, archiveRetention?:number, archiveMinDays?:number}} [opts]
236
- * @returns {{archived:number, edgesDecayed:number, edgesRemoved:number, scanned:number, dryRun:boolean}}
237
- */
238
- function forgetPass(mem, opts = {}) {
239
- const now = num(opts.now, Date.now());
240
- const dryRun = opts.dryRun === true;
241
- const archiveRetention = clamp(num(opts.archiveRetention, num(opt(mem, 'archiveRetention'), 0.15)), 0.01, 0.9);
242
- const archiveMinDays = Math.max(1, num(opts.archiveMinDays, num(opt(mem, 'archiveMinDays'), 90)));
243
- const synapseIdleDays = Math.max(1, num(opts.synapseIdleDays, num(opt(mem, 'synapseIdleDays'), 60)));
244
- const synapseDecay = clamp(num(opts.synapseDecay, num(opt(mem, 'synapseDecay'), 0.9)), 0.1, 0.99);
245
- const synapseMinWeight = clamp(num(opts.synapseMinWeight, num(opt(mem, 'synapseMinWeight'), 0.01)), 0.0001, 0.5);
246
-
247
- let archived = 0;
248
- let scanned = 0;
249
- for (const node of mem.nodes.values()) {
250
- if (node.deleted) continue;
251
- scanned++;
252
- if (node.archived) continue;
253
- const days = ageDays(node, now);
254
- if (days < archiveMinDays) continue;
255
- if (retention(node, now) >= archiveRetention) continue;
256
- archived++;
257
- if (!dryRun) {
258
- node.archived = true;
259
- node.archivedAt = now;
260
- mem._queuePersist(node);
261
- }
262
- }
263
-
264
- let edgesDecayed = 0;
265
- let edgesRemoved = 0;
266
- for (const edge of Array.from(mem.edgeMap.values())) {
267
- // 只修剪「合成边」;人工 link / 巩固生成的 semantic 边不动
268
- if ((edge.kind || EDGE_KIND.SEMANTIC) !== EDGE_KIND.HEBBIAN) continue;
269
- const idle = (now - num(edge.lastFired, num(edge.ts, now))) / DAY_MS;
270
- if (idle < synapseIdleDays) continue;
271
- const w = num(edge.w, 0) * synapseDecay;
272
- if (w < synapseMinWeight) {
273
- edgesRemoved++;
274
- if (!dryRun) mem._removeEdge(edge);
275
- } else {
276
- edgesDecayed++;
277
- if (!dryRun) mem._updateEdge(edge, { w: round(w, 4), lastFired: now });
278
- }
279
- }
280
-
281
- return { archived, edgesDecayed, edgesRemoved, scanned, dryRun };
282
- }
283
-
284
- // ---------------------------------------------------------------------------
285
- // L3 摘要(确定性模板,不用 LLM)
286
- // ---------------------------------------------------------------------------
287
-
288
- /** 收集画像摘要素材:名字 / 所在地 / 身份 / 偏好 / 最近在忙 */
289
- function collectSummary(mem) {
290
- const profiles = [];
291
- const facts = [];
292
- for (const n of mem.nodes.values()) {
293
- if (n.deleted || n.archived) continue;
294
- if (n.kind === 'profile') profiles.push(n);
295
- else if (n.kind === 'fact') facts.push(n);
296
- }
297
- if (!profiles.length && !facts.length) return null;
298
- const byImp = (a, b) => b.importance - a.importance || b.ts - a.ts;
299
- profiles.sort(byImp);
300
- facts.sort(byImp);
301
-
302
- let name = '';
303
- let identity = '';
304
- let location = '';
305
- const sources = [];
306
-
307
- for (const p of profiles) {
308
- if (!name) {
309
- const m = /名字是(.{1,16})/.exec(p.text);
310
- if (m) {
311
- name = trimPunct(m[1]);
312
- sources.push(p.id);
313
- }
314
- }
315
- if (!name) {
316
- const m = /希望被叫做(.{1,16})/.exec(p.text);
317
- if (m) {
318
- name = trimPunct(m[1]);
319
- sources.push(p.id);
320
- }
321
- }
322
- if (!identity) {
323
- const m = /身份是(.{1,16})/.exec(p.text);
324
- if (m) {
325
- identity = trimPunct(m[1]);
326
- sources.push(p.id);
327
- }
328
- }
329
- if (!location) {
330
- const m = /(?:住在|城市是|家在|来自)(.{2,14})/.exec(p.text);
331
- if (m) {
332
- location = trimPunct(m[1]);
333
- sources.push(p.id);
334
- }
335
- }
336
- if (name && location && identity) break;
337
- }
338
-
339
- // 偏好:带「偏好」标签的 fact 优先,其次看文面
340
- const prefs = [];
341
- for (const f of facts) {
342
- if (prefs.length >= 3) break;
343
- const tagged = Array.isArray(f.tags) && f.tags.includes('偏好');
344
- const looksPref = /^用户(喜欢|不喜欢|讨厌|习惯|偏好|爱|通常|平时)/.test(f.text);
345
- if (!tagged && !looksPref) continue;
346
- const t = trimPunct(f.text.replace(/^用户/, '你'));
347
- if (t && !prefs.includes(t)) prefs.push(truncateChars(t, 24));
348
- sources.push(f.id);
349
- }
350
-
351
- // 最近在忙:项目类 fact
352
- let project = '';
353
- for (const f of facts) {
354
- const tagged = Array.isArray(f.tags) && f.tags.includes('项目');
355
- const looksProject = /^用户(在做|在搞|在写|在开发|负责|用的是|用)/.test(f.text);
356
- if (!tagged && !looksProject) continue;
357
- const t = trimPunct(f.text.replace(/^用户在做|^用户在搞|^用户在写|^用户在开发/, ''));
358
- if (t) {
359
- project = truncateChars(t, 40);
360
- sources.push(f.id);
361
- break;
362
- }
363
- }
364
-
365
- const parts = [];
366
- if (name) parts.push(`你叫${name}`);
367
- if (location) parts.push(`你在${location}`);
368
- if (identity) parts.push(`你是${identity}`);
369
- if (prefs.length) parts.push(prefs.join(';'));
370
- if (project) parts.push(`最近在忙${project}`);
371
- if (!parts.length) return null;
372
-
373
- return {
374
- text: truncateChars(parts.join(';') + '。', 240),
375
- sources: Array.from(new Set(sources)),
376
- };
377
- }
378
-
379
- /** 找到已有的 L3 画像摘要节点 */
380
- function findSummaryNode(mem) {
381
- for (const n of mem.nodes.values()) {
382
- if (n.kind === SUMMARY_KIND && n.meta && n.meta[SUMMARY_META_KEY]) return n;
383
- }
384
- return null;
385
- }
386
-
387
- /**
388
- * 刷新 L3 画像摘要节点(没有就创建,有就原地重写)。
389
- * 返回 {id, updated, created} 或 null(没有任何画像/事实素材时)。
390
- *
391
- * @param {any} mem
392
- * @param {{now?:number}} [opts]
393
- */
394
- function refreshSummary(mem, opts = {}) {
395
- const now = num(opts.now, Date.now());
396
- const built = collectSummary(mem);
397
- if (!built) return null;
398
- const existing = findSummaryNode(mem);
399
- if (existing) {
400
- const changed = existing.text !== built.text;
401
- mem._rewriteNode(existing, {
402
- text: built.text,
403
- ts: now,
404
- importance: Math.max(num(existing.importance, 0), 0.95),
405
- meta: { ...(existing.meta || {}), [SUMMARY_META_KEY]: true, sources: built.sources, updatedAt: now },
406
- });
407
- return { id: existing.id, updated: changed, created: false };
408
- }
409
- const node = mem._buildRecord({
410
- text: built.text,
411
- kind: SUMMARY_KIND,
412
- layer: LAYER.SUMMARY,
413
- tags: ['画像', '摘要'],
414
- importance: 0.95,
415
- source: 'consolidate',
416
- ts: now,
417
- meta: { [SUMMARY_META_KEY]: true, sources: built.sources },
418
- });
419
- node._tf = mem._tfFor(node);
420
- mem._insertNode(node);
421
- return { id: node.id, updated: true, created: true };
422
- }
423
-
424
- module.exports = {
425
- DAY_MS,
426
- LAYER,
427
- EDGE_KIND,
428
- SUMMARY_KIND,
429
- // 状态 / 公式
430
- stabilityOf,
431
- lastAccessAt,
432
- ageDays,
433
- retention,
434
- layerOf,
435
- isValidEdgeKind,
436
- touchNode,
437
- applyHebbian,
438
- forgetPass,
439
- // L3
440
- collectSummary,
441
- findSummaryNode,
442
- refreshSummary,
443
- // 工具(store.js 复用)
444
- num,
445
- clamp,
446
- clamp01,
447
- round,
448
- charLen,
449
- truncateChars,
450
- trimPunct,
451
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * 记忆星云 Lite — 动力学层(S 状态 / FSRS 遗忘 / 归档 / 赫布边 / L3 摘要)
5
+ *
6
+ * 公式与参考实现 brain_dynamics.py 对齐(纯 JS、无外部依赖):
7
+ * - 可提取度:R = exp(-Δt / S),S 是 stability(天),Δt 从 lastAccessAt 算起;
8
+ * - touch:S' = S · (1 + 1.5 · (1 - R)),lastAccessAt = now,access++,act 写回;
9
+ * - 归档:R < 0.15 且 Δt > 90 天 → archived=true(只归档、不删除,includeArchived 仍可召回);
10
+ * - 赫布边:共激活对 w += η · aᵢ · aⱼ · (1 - w),η=0.02,(1-w) 上界防正反馈失控;
11
+ * - 合成边(只削 hebbian,不动人工/semantic 边):60 天未触发 ×0.9,w < 0.01 删除;
12
+ * - 每节点 hebbian 边数上限(默认 16):超出按保留分 w×log2(1+触发) 剪最弱,图增长有界;
13
+ * - L3 摘要:确定性模板「你叫…/你在…/你偏好…/最近在忙…」,不用 LLM。
14
+ *
15
+ * 本模块不 require store(避免循环依赖):所有记忆操作都通过传入的 mem 实例完成,
16
+ * mem 需要提供 store.js 里的内部方法(_queuePersist / _addEdge / _updateEdge /
17
+ * _removeEdge / _rewriteNode / _insertNode / _buildRecord / _log 等)。
18
+ */
19
+
20
+ const DAY_MS = 86400000;
21
+
22
+ /** 分层(与 nodes.jsonl 的 layer 字段一一对应) */
23
+ const LAYER = Object.freeze({
24
+ EVENT: 'event', // L0 事件:一轮对话的原始文本
25
+ FRAGMENT: 'fragment', // L1 片段:从对话里抽出来的事实/画像/显式记忆
26
+ SUMMARY: 'summary', // L3 摘要:跨片段的画像性总结
27
+ });
28
+
29
+ /** 边类型(edges.jsonl 的 kind 字段) */
30
+ const EDGE_KIND = Object.freeze({
31
+ SEMANTIC: 'semantic', // 语义相似 / 巩固时连出来的边(默认)
32
+ HEBBIAN: 'hebbian', // 同一次召回里共激活形成的合成边
33
+ EXPLICIT: 'explicit', // 调用方显式 link() 出来的边
34
+ });
35
+
36
+ /**
37
+ * MEM_KIND 里没有 summary(constants.js 归 Lead 维护,我不能改),
38
+ * 这里用本地常量兜底;kind 仍然是 'summary',与 SPEC 一致。
39
+ */
40
+ const SUMMARY_KIND = 'summary';
41
+ const SUMMARY_META_KEY = 'l3-profile';
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // 小工具(各模块自带一份,避免为了 3 个函数再开一个文件)
45
+ // ---------------------------------------------------------------------------
46
+
47
+ function num(v, fallback) {
48
+ const n = Number(v);
49
+ return Number.isFinite(n) ? n : fallback;
50
+ }
51
+
52
+ /** 读实例参数:优先 NebulaMemory.opts(构造时的 weights 也在这里),兼容直接挂在实例上的旧写法 */
53
+ function opt(mem, key, fallback) {
54
+ if (mem) {
55
+ if (mem.opts && mem.opts[key] != null) return mem.opts[key];
56
+ if (mem[key] != null) return mem[key];
57
+ }
58
+ return fallback;
59
+ }
60
+
61
+ function clamp(n, lo, hi) {
62
+ return n < lo ? lo : n > hi ? hi : n;
63
+ }
64
+
65
+ function clamp01(n) {
66
+ return clamp(num(n, 0), 0, 1);
67
+ }
68
+
69
+ function round(n, digits = 4) {
70
+ const p = 10 ** digits;
71
+ return Math.round(n * p) / p;
72
+ }
73
+
74
+ function charLen(s) {
75
+ return Array.from(String(s == null ? '' : s)).length;
76
+ }
77
+
78
+ function truncateChars(s, max) {
79
+ const arr = Array.from(String(s == null ? '' : s));
80
+ if (arr.length <= max) return arr.join('');
81
+ return arr.slice(0, Math.max(0, max - 1)).join('') + '…';
82
+ }
83
+
84
+ function trimPunct(s) {
85
+ return String(s == null ? '' : s).replace(/^[\s,。、;:,.;:!?!?"'“”‘’()()【】[\]「」]+|[\s,。、;:,.;:!?!?"'“”‘’()()【】[\]「」]+$/gu, '');
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // S 状态:可提取度 / 分层
90
+ // ---------------------------------------------------------------------------
91
+
92
+ /** stability 默认 1 天;下限 0.05 天,上限 10 年,避免除零与无限增长 */
93
+ function stabilityOf(node) {
94
+ return clamp(num(node && node.stability, 1), 0.05, 3650);
95
+ }
96
+
97
+ /** 最近一次访问时间(没有就用创建时间) */
98
+ function lastAccessAt(node) {
99
+ return num(node && node.lastAccessAt, num(node && node.ts, Date.now()));
100
+ }
101
+
102
+ function ageDays(node, now = Date.now()) {
103
+ return Math.max(0, (now - lastAccessAt(node)) / DAY_MS);
104
+ }
105
+
106
+ /** FSRS 遗忘曲线:R = exp(-Δt / S),落在 [0,1]。
107
+ * importance 满值(≥1.0)视为「置顶/永久事实」(如用户 API 密钥、称呼偏好),
108
+ * 不受时间衰减影响,永远可提取 —— 这是「置顶记忆不遗忘」的语义入口:
109
+ * 抽取层/写入方把关键事实的 importance 设为 1.0 即自动永固,无需额外字段。 */
110
+ function retention(node, now = Date.now()) {
111
+ if (node && clamp01(num(node.importance, 0)) >= 1) return 1;
112
+ return clamp01(Math.exp(-ageDays(node, now) / stabilityOf(node)));
113
+ }
114
+
115
+ /**
116
+ * 由 kind + 显式 layer 推断分层(旧数据没有 layer 字段时也能平滑升级)。
117
+ * @param {string} kind
118
+ * @param {string} [layer]
119
+ */
120
+ function layerOf(kind, layer) {
121
+ if (layer === LAYER.EVENT || layer === LAYER.FRAGMENT || layer === LAYER.SUMMARY) return layer;
122
+ if (kind === SUMMARY_KIND) return LAYER.SUMMARY;
123
+ if (kind === 'episode') return LAYER.EVENT;
124
+ return LAYER.FRAGMENT;
125
+ }
126
+
127
+ function isValidEdgeKind(kind) {
128
+ return kind === EDGE_KIND.SEMANTIC || kind === EDGE_KIND.HEBBIAN || kind === EDGE_KIND.EXPLICIT;
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // touch:命中一次记忆
133
+ // ---------------------------------------------------------------------------
134
+
135
+ /**
136
+ * 更新一条被召回节点的 S 状态(FSRS)。
137
+ * 注意:这里**不再**给 importance 加固定值(v1 的 accessBoost 已废弃),
138
+ * 记忆的「重要性」由抽取阶段决定,访问只影响可提取度。
139
+ *
140
+ * @param {any} mem NebulaMemory 实例
141
+ * @param {any} node 内部节点(有 stability / lastAccessAt / access 字段)
142
+ * @param {{now?:number, act?:number, persist?:boolean}} [opts]
143
+ * @returns {{retention:number, stability:number}}
144
+ */
145
+ function touchNode(mem, node, opts = {}) {
146
+ if (!node) return { retention: 0, stability: 1 };
147
+ const now = num(opts.now, Date.now());
148
+ const r = retention(node, now);
149
+ const s = stabilityOf(node);
150
+ node.stability = round(clamp(s * (1 + 1.5 * (1 - r)), 0.05, 3650), 4);
151
+ node.lastAccessAt = now;
152
+ node.access = num(node.access, 0) + 1;
153
+ node.dormant = false;
154
+ if (opts.act != null) {
155
+ node.act = clamp01(opts.act);
156
+ node.actAt = now;
157
+ }
158
+ if (opts.persist !== false && typeof mem._queuePersist === 'function') mem._queuePersist(node);
159
+ return { retention: round(r, 4), stability: node.stability };
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // 赫布边:同一次召回内共激活 → 连边 / 强化
164
+ // ---------------------------------------------------------------------------
165
+
166
+ /**
167
+ * @param {any} mem
168
+ * @param {Map<string, number>|Object} acts id → 激活量(0..1,未归一也行)
169
+ * @param {{now?:number, eta?:number, minProduct?:number, minAct?:number,
170
+ * initWeight?:number, maxPairs?:number, source?:string}} [opts]
171
+ * @returns {{created:number, reinforced:number, pairs:number}}
172
+ */
173
+ function applyHebbian(mem, acts, opts = {}) {
174
+ const now = num(opts.now, Date.now());
175
+ const eta = num(opts.eta, num(opt(mem, 'hebbEta'), 0.02));
176
+ const minProduct = num(opts.minProduct, num(opt(mem, 'hebbMinProduct'), 0.3));
177
+ const minAct = num(opts.minAct, 0.2);
178
+ const initWeight = num(opts.initWeight, num(opt(mem, 'hebbNewWeight'), 0.1));
179
+ const maxPairs = Math.max(1, Math.floor(num(opts.maxPairs, 60)));
180
+
181
+ const pairsIn = acts instanceof Map ? Array.from(acts.entries()) : Object.entries(acts || {});
182
+ const list = [];
183
+ for (const [id, raw] of pairsIn) {
184
+ const node = mem.nodes.get(String(id));
185
+ if (!node || node.deleted) continue;
186
+ const a = num(raw, 0);
187
+ if (a >= minAct) list.push([node.id, a]);
188
+ }
189
+ let maxA = 0;
190
+ for (const [, a] of list) if (a > maxA) maxA = a;
191
+ if (maxA <= 0 || list.length < 2) return { created: 0, reinforced: 0, pairs: 0 };
192
+
193
+ // 先按本轮最大值归一到 0..1(参考实现的 _norm)
194
+ const normed = list.map(([id, a]) => [id, clamp01(a / maxA)]);
195
+ let created = 0;
196
+ let reinforced = 0;
197
+ let pairs = 0;
198
+ for (let i = 0; i < normed.length && pairs < maxPairs; i++) {
199
+ for (let j = i + 1; j < normed.length && pairs < maxPairs; j++) {
200
+ const product = normed[i][1] * normed[j][1];
201
+ if (product < minProduct) continue;
202
+ pairs++;
203
+ const aId = normed[i][0];
204
+ const bId = normed[j][0];
205
+ const key = mem._edgeKey(aId, bId);
206
+ const edge = mem.edgeMap.get(key);
207
+ if (edge) {
208
+ const w = Math.min(1, num(edge.w, 0) + eta * product * (1 - num(edge.w, 0)));
209
+ mem._updateEdge(edge, { w: round(w, 4), lastFired: now, fireCount: num(edge.fireCount, 0) + 1 });
210
+ reinforced++;
211
+ } else {
212
+ mem._addEdge(aId, bId, initWeight, {
213
+ kind: EDGE_KIND.HEBBIAN,
214
+ lastFired: now,
215
+ fireCount: 1,
216
+ source: opts.source || 'recall',
217
+ });
218
+ created++;
219
+ }
220
+ }
221
+ }
222
+ // 每节点赫布边数上限:本轮触碰过的节点立即检查,防写突发期间超限膨胀
223
+ if (created + reinforced > 0) {
224
+ pruneHebbianFor(mem, normed.map(([id]) => id));
225
+ }
226
+ return { created, reinforced, pairs };
227
+ }
228
+
229
+ /** 节点视角的赫布边保留分:权重 × log2(1+触发次数),同分保新。分值由边自身属性决定,两端视角一致。 */
230
+ function hebbianRank(e) {
231
+ return num(e.w, 0) * Math.log2(1 + num(e.fireCount, 0)) + num(e.lastFired, 0) / 1e15;
232
+ }
233
+
234
+ /**
235
+ * 每节点赫布边数上限:超出 maxPerNode 的按保留分剪最弱边。
236
+ * 防止热点节点「每次召回共激活就加边」导致合成边无限累积、图结构漂移。
237
+ * maxPerNode <= 0 = 关闭。走 mem._removeEdge(tombstone 落盘,重启不复活)。
238
+ * @returns {{pruned:number, checked:number, dryRun:boolean}}
239
+ */
240
+ function pruneHebbianFor(mem, ids, opts = {}) {
241
+ const maxPerNode = Math.floor(num(opts.maxPerNode, num(opt(mem, 'hebbianMaxPerNode'), 16)));
242
+ const dryRun = opts.dryRun === true;
243
+ if (maxPerNode <= 0) return { pruned: 0, checked: 0, dryRun };
244
+ let pruned = 0;
245
+ let checked = 0;
246
+ const seen = new Set();
247
+ for (const rawId of ids || []) {
248
+ const id = String(rawId);
249
+ if (!id || seen.has(id)) continue;
250
+ seen.add(id);
251
+ const adj = mem.adj ? mem.adj.get(id) : null;
252
+ if (!adj || adj.size <= maxPerNode) continue; // 邻居总数都不超限,必无赫布超限
253
+ const hebb = [];
254
+ for (const other of adj.keys()) {
255
+ const edge = mem.edgeMap.get(mem._edgeKey(id, other));
256
+ if (!edge || edge.deleted) continue;
257
+ if ((edge.kind || EDGE_KIND.SEMANTIC) !== EDGE_KIND.HEBBIAN) continue;
258
+ hebb.push(edge);
259
+ }
260
+ checked++;
261
+ if (hebb.length <= maxPerNode) continue;
262
+ hebb.sort((x, y) => hebbianRank(y) - hebbianRank(x));
263
+ for (const e of hebb.slice(maxPerNode)) {
264
+ if (!dryRun) mem._removeEdge(e);
265
+ pruned++;
266
+ }
267
+ }
268
+ return { pruned, checked, dryRun };
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // 遗忘 / 修剪(tick)
273
+ // ---------------------------------------------------------------------------
274
+
275
+ /**
276
+ * 一次遗忘扫描:
277
+ * 1) R < archiveRetention(0.15)且闲置 > archiveMinDays(90 天)→ archived=true(不删);
278
+ * 2) 合成边(hebbian)闲置 > synapseIdleDays(60 天)→ w *= 0.9,w < 0.01 删除。
279
+ * dryRun=true 时只统计不落盘。
280
+ *
281
+ * @param {any} mem
282
+ * @param {{now?:number, dryRun?:boolean, archiveRetention?:number, archiveMinDays?:number}} [opts]
283
+ * @returns {{archived:number, edgesDecayed:number, edgesRemoved:number, scanned:number, dryRun:boolean}}
284
+ */
285
+ function forgetPass(mem, opts = {}) {
286
+ const now = num(opts.now, Date.now());
287
+ const dryRun = opts.dryRun === true;
288
+ const archiveRetention = clamp(num(opts.archiveRetention, num(opt(mem, 'archiveRetention'), 0.15)), 0.01, 0.9);
289
+ const archiveMinDays = Math.max(1, num(opts.archiveMinDays, num(opt(mem, 'archiveMinDays'), 90)));
290
+ const synapseIdleDays = Math.max(1, num(opts.synapseIdleDays, num(opt(mem, 'synapseIdleDays'), 60)));
291
+ const synapseDecay = clamp(num(opts.synapseDecay, num(opt(mem, 'synapseDecay'), 0.9)), 0.1, 0.99);
292
+ const synapseMinWeight = clamp(num(opts.synapseMinWeight, num(opt(mem, 'synapseMinWeight'), 0.01)), 0.0001, 0.5);
293
+
294
+ let archived = 0;
295
+ let scanned = 0;
296
+ for (const node of mem.nodes.values()) {
297
+ if (node.deleted) continue;
298
+ scanned++;
299
+ if (node.archived) continue;
300
+ const days = ageDays(node, now);
301
+ if (days < archiveMinDays) continue;
302
+ if (retention(node, now) >= archiveRetention) continue;
303
+ archived++;
304
+ if (!dryRun) {
305
+ node.archived = true;
306
+ node.archivedAt = now;
307
+ mem._queuePersist(node);
308
+ }
309
+ }
310
+
311
+ let edgesDecayed = 0;
312
+ let edgesRemoved = 0;
313
+ for (const edge of Array.from(mem.edgeMap.values())) {
314
+ // 只修剪「合成边」;人工 link / 巩固生成的 semantic 边不动
315
+ if ((edge.kind || EDGE_KIND.SEMANTIC) !== EDGE_KIND.HEBBIAN) continue;
316
+ const idle = (now - num(edge.lastFired, num(edge.ts, now))) / DAY_MS;
317
+ if (idle < synapseIdleDays) continue;
318
+ const w = num(edge.w, 0) * synapseDecay;
319
+ if (w < synapseMinWeight) {
320
+ edgesRemoved++;
321
+ if (!dryRun) mem._removeEdge(edge);
322
+ } else {
323
+ edgesDecayed++;
324
+ if (!dryRun) mem._updateEdge(edge, { w: round(w, 4), lastFired: now });
325
+ }
326
+ }
327
+
328
+ // 每节点赫布边数上限:衰减后全量扫描一遍,热点节点的合成边超限即按保留分剪最弱
329
+ const maxPerNode = Math.floor(num(opts.maxPerNode, num(opt(mem, 'hebbianMaxPerNode'), 16)));
330
+ let hebbianPruned = 0;
331
+ if (maxPerNode > 0) {
332
+ const byNode = new Map();
333
+ for (const edge of mem.edgeMap.values()) {
334
+ if ((edge.kind || EDGE_KIND.SEMANTIC) !== EDGE_KIND.HEBBIAN) continue;
335
+ if (!byNode.has(edge.a)) byNode.set(edge.a, []);
336
+ byNode.get(edge.a).push(edge);
337
+ if (!byNode.has(edge.b)) byNode.set(edge.b, []);
338
+ byNode.get(edge.b).push(edge);
339
+ }
340
+ for (const [, edges] of byNode) {
341
+ if (edges.length <= maxPerNode) continue;
342
+ edges.sort((x, y) => hebbianRank(y) - hebbianRank(x));
343
+ for (const e of edges.slice(maxPerNode)) {
344
+ if (!dryRun) mem._removeEdge(e);
345
+ hebbianPruned++;
346
+ }
347
+ }
348
+ }
349
+
350
+ return { archived, edgesDecayed, edgesRemoved, hebbianPruned, scanned, dryRun };
351
+ }
352
+
353
+ // ---------------------------------------------------------------------------
354
+ // L3 摘要(确定性模板,不用 LLM)
355
+ // ---------------------------------------------------------------------------
356
+
357
+ /** 收集画像摘要素材:名字 / 所在地 / 身份 / 偏好 / 最近在忙 */
358
+ function collectSummary(mem) {
359
+ const profiles = [];
360
+ const facts = [];
361
+ for (const n of mem.nodes.values()) {
362
+ if (n.deleted || n.archived) continue;
363
+ if (n.kind === 'profile') profiles.push(n);
364
+ else if (n.kind === 'fact') facts.push(n);
365
+ }
366
+ if (!profiles.length && !facts.length) return null;
367
+ const byImp = (a, b) => b.importance - a.importance || b.ts - a.ts;
368
+ profiles.sort(byImp);
369
+ facts.sort(byImp);
370
+
371
+ let name = '';
372
+ let identity = '';
373
+ let location = '';
374
+ const sources = [];
375
+
376
+ for (const p of profiles) {
377
+ if (!name) {
378
+ const m = /名字是(.{1,16})/.exec(p.text);
379
+ if (m) {
380
+ name = trimPunct(m[1]);
381
+ sources.push(p.id);
382
+ }
383
+ }
384
+ if (!name) {
385
+ const m = /希望被叫做(.{1,16})/.exec(p.text);
386
+ if (m) {
387
+ name = trimPunct(m[1]);
388
+ sources.push(p.id);
389
+ }
390
+ }
391
+ if (!identity) {
392
+ const m = /身份是(.{1,16})/.exec(p.text);
393
+ if (m) {
394
+ identity = trimPunct(m[1]);
395
+ sources.push(p.id);
396
+ }
397
+ }
398
+ if (!location) {
399
+ const m = /(?:住在|城市是|家在|来自)(.{2,14})/.exec(p.text);
400
+ if (m) {
401
+ location = trimPunct(m[1]);
402
+ sources.push(p.id);
403
+ }
404
+ }
405
+ if (name && location && identity) break;
406
+ }
407
+
408
+ // 偏好:带「偏好」标签的 fact 优先,其次看文面
409
+ const prefs = [];
410
+ for (const f of facts) {
411
+ if (prefs.length >= 3) break;
412
+ const tagged = Array.isArray(f.tags) && f.tags.includes('偏好');
413
+ const looksPref = /^用户(喜欢|不喜欢|讨厌|习惯|偏好|爱|通常|平时)/.test(f.text);
414
+ if (!tagged && !looksPref) continue;
415
+ const t = trimPunct(f.text.replace(/^用户/, '你'));
416
+ if (t && !prefs.includes(t)) prefs.push(truncateChars(t, 24));
417
+ sources.push(f.id);
418
+ }
419
+
420
+ // 最近在忙:项目类 fact
421
+ let project = '';
422
+ for (const f of facts) {
423
+ const tagged = Array.isArray(f.tags) && f.tags.includes('项目');
424
+ const looksProject = /^用户(在做|在搞|在写|在开发|负责|用的是|用)/.test(f.text);
425
+ if (!tagged && !looksProject) continue;
426
+ const t = trimPunct(f.text.replace(/^用户在做|^用户在搞|^用户在写|^用户在开发/, ''));
427
+ if (t) {
428
+ project = truncateChars(t, 40);
429
+ sources.push(f.id);
430
+ break;
431
+ }
432
+ }
433
+
434
+ const parts = [];
435
+ if (name) parts.push(`你叫${name}`);
436
+ if (location) parts.push(`你在${location}`);
437
+ if (identity) parts.push(`你是${identity}`);
438
+ if (prefs.length) parts.push(prefs.join(';'));
439
+ if (project) parts.push(`最近在忙${project}`);
440
+ if (!parts.length) return null;
441
+
442
+ return {
443
+ text: truncateChars(parts.join(';') + '。', 240),
444
+ sources: Array.from(new Set(sources)),
445
+ };
446
+ }
447
+
448
+ /** 找到已有的 L3 画像摘要节点 */
449
+ function findSummaryNode(mem) {
450
+ for (const n of mem.nodes.values()) {
451
+ if (n.kind === SUMMARY_KIND && n.meta && n.meta[SUMMARY_META_KEY]) return n;
452
+ }
453
+ return null;
454
+ }
455
+
456
+ /**
457
+ * 刷新 L3 画像摘要节点(没有就创建,内容有变化才原地重写)。
458
+ * 返回 {id, updated, created} 或 null(没有任何画像/事实素材时)。
459
+ *
460
+ * 重要:内容未变时**不写盘**。
461
+ * 早期实现每次调用都 _rewriteNode(无条件追加一行),而 tick() 每 1.5s
462
+ * 调一次,导致同一条画像摘要被追加数万行。见 2026-11-24 修复记录。
463
+ *
464
+ * @param {any} mem
465
+ * @param {{now?:number}} [opts]
466
+ */
467
+ function refreshSummary(mem, opts = {}) {
468
+ const now = num(opts.now, Date.now());
469
+ const built = collectSummary(mem);
470
+ if (!built) return null;
471
+ const existing = findSummaryNode(mem);
472
+ if (existing) {
473
+ const changed = existing.text !== built.text;
474
+ // 内容没变:不重写、不追加、不刷 ts。
475
+ // 保留 didChange=false 让调用方知道"调过但无事发生"。
476
+ if (!changed) return { id: existing.id, updated: false, created: false, didChange: false };
477
+ mem._rewriteNode(existing, {
478
+ text: built.text,
479
+ ts: now,
480
+ importance: Math.max(num(existing.importance, 0), 0.95),
481
+ meta: { ...(existing.meta || {}), [SUMMARY_META_KEY]: true, sources: built.sources, updatedAt: now },
482
+ });
483
+ return { id: existing.id, updated: true, created: false, didChange: true };
484
+ }
485
+ const node = mem._buildRecord({
486
+ text: built.text,
487
+ kind: SUMMARY_KIND,
488
+ layer: LAYER.SUMMARY,
489
+ tags: ['画像', '摘要'],
490
+ importance: 0.95,
491
+ source: 'consolidate',
492
+ ts: now,
493
+ meta: { [SUMMARY_META_KEY]: true, sources: built.sources },
494
+ });
495
+ node._tf = mem._tfFor(node);
496
+ mem._insertNode(node);
497
+ return { id: node.id, updated: true, created: true, didChange: true };
498
+ }
499
+
500
+ module.exports = {
501
+ DAY_MS,
502
+ LAYER,
503
+ EDGE_KIND,
504
+ SUMMARY_KIND,
505
+ // 状态 / 公式
506
+ stabilityOf,
507
+ lastAccessAt,
508
+ ageDays,
509
+ retention,
510
+ layerOf,
511
+ isValidEdgeKind,
512
+ touchNode,
513
+ applyHebbian,
514
+ pruneHebbianFor,
515
+ forgetPass,
516
+ // L3
517
+ collectSummary,
518
+ findSummaryNode,
519
+ refreshSummary,
520
+ // 工具(store.js 复用)
521
+ num,
522
+ clamp,
523
+ clamp01,
524
+ round,
525
+ charLen,
526
+ truncateChars,
527
+ trimPunct,
528
+ };