nebula-memory-mcp 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@
9
9
  * - 归档:R < 0.15 且 Δt > 90 天 → archived=true(只归档、不删除,includeArchived 仍可召回);
10
10
  * - 赫布边:共激活对 w += η · aᵢ · aⱼ · (1 - w),η=0.02,(1-w) 上界防正反馈失控;
11
11
  * - 合成边(只削 hebbian,不动人工/semantic 边):60 天未触发 ×0.9,w < 0.01 删除;
12
+ * - 每节点 hebbian 边数上限(默认 16):超出按保留分 w×log2(1+触发) 剪最弱,图增长有界;
12
13
  * - L3 摘要:确定性模板「你叫…/你在…/你偏好…/最近在忙…」,不用 LLM。
13
14
  *
14
15
  * 本模块不 require store(避免循环依赖):所有记忆操作都通过传入的 mem 实例完成,
@@ -218,9 +219,55 @@ function applyHebbian(mem, acts, opts = {}) {
218
219
  }
219
220
  }
220
221
  }
222
+ // 每节点赫布边数上限:本轮触碰过的节点立即检查,防写突发期间超限膨胀
223
+ if (created + reinforced > 0) {
224
+ pruneHebbianFor(mem, normed.map(([id]) => id));
225
+ }
221
226
  return { created, reinforced, pairs };
222
227
  }
223
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
+
224
271
  // ---------------------------------------------------------------------------
225
272
  // 遗忘 / 修剪(tick)
226
273
  // ---------------------------------------------------------------------------
@@ -278,7 +325,29 @@ function forgetPass(mem, opts = {}) {
278
325
  }
279
326
  }
280
327
 
281
- return { archived, edgesDecayed, edgesRemoved, scanned, dryRun };
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 };
282
351
  }
283
352
 
284
353
  // ---------------------------------------------------------------------------
@@ -398,13 +467,15 @@ function refreshSummary(mem, opts = {}) {
398
467
  const existing = findSummaryNode(mem);
399
468
  if (existing) {
400
469
  const changed = existing.text !== built.text;
470
+ // 内容没变:不重写、不追加、不刷 ts(修复重复写入,2026-11-24)
471
+ if (!changed) return { id: existing.id, updated: false, created: false, didChange: false };
401
472
  mem._rewriteNode(existing, {
402
473
  text: built.text,
403
474
  ts: now,
404
475
  importance: Math.max(num(existing.importance, 0), 0.95),
405
476
  meta: { ...(existing.meta || {}), [SUMMARY_META_KEY]: true, sources: built.sources, updatedAt: now },
406
477
  });
407
- return { id: existing.id, updated: changed, created: false };
478
+ return { id: existing.id, updated: true, created: false, didChange: true };
408
479
  }
409
480
  const node = mem._buildRecord({
410
481
  text: built.text,
@@ -418,7 +489,7 @@ function refreshSummary(mem, opts = {}) {
418
489
  });
419
490
  node._tf = mem._tfFor(node);
420
491
  mem._insertNode(node);
421
- return { id: node.id, updated: true, created: true };
492
+ return { id: node.id, updated: true, created: true, didChange: true };
422
493
  }
423
494
 
424
495
  module.exports = {
@@ -435,6 +506,7 @@ module.exports = {
435
506
  isValidEdgeKind,
436
507
  touchNode,
437
508
  applyHebbian,
509
+ pruneHebbianFor,
438
510
  forgetPass,
439
511
  // L3
440
512
  collectSummary,
package/memory/recall.cjs CHANGED
@@ -35,6 +35,10 @@ const PARAMS = Object.freeze({
35
35
  // 种子 18 时合计约 18+54+36=108;这里给到 120 才能让 1/2 跳铺得开,
36
36
  // 太小(原 24)会让 18 个种子几乎吃满名额,1/2 跳各只剩 3~4 个、整张星云偏暗。
37
37
  graphTop: 120,
38
+ // 单节点扇出上限(超级节点防御)。度数超过它的节点在扩散时只取权重最高的 N 条边。
39
+ // 实测:5000 度枢纽 2 跳 p50=9ms(对照组 0.54ms),可接受但无上限会随度数线性恶化;
40
+ // 200 这个值保证「正常节点完全不受影响」,只截断病态枢纽。
41
+ maxDegree: 200,
38
42
  profileTop: 3, // 画像臂恒定入选数
39
43
  hops: 2, // 扩散跳数(不要 3 跳:语义会漂)
40
44
  alpha: 1.0, // 边权指数
@@ -72,6 +76,10 @@ function spread(mem, seeds, opts = {}) {
72
76
  const alpha = num(opts.alpha, PARAMS.alpha);
73
77
  const gamma = num(opts.gamma, PARAMS.gamma);
74
78
  const minW = num(opts.minEdgeWeight, PARAMS.minEdgeWeight);
79
+ // 单节点扇出上限(超级节点防御);0 = 不限制
80
+ const maxDeg = clamp(Math.floor(num(opts.maxDegree, PARAMS.maxDegree)), 0, 100000);
81
+ const stats = opts.stats || null;
82
+ if (stats && stats.truncatedHubs == null) stats.truncatedHubs = 0;
75
83
  /** @type {Map<string, {act:number, hop:number, via:string, seed:string}>} */
76
84
  const out = new Map();
77
85
  /** @type {Map<string, {act:number, via:string, seed:string}>} */
@@ -93,7 +101,19 @@ function spread(mem, seeds, opts = {}) {
93
101
  for (const [fromId, info] of frontier) {
94
102
  const adj = mem.adj.get(fromId);
95
103
  if (!adj) continue;
96
- for (const [toId, wRaw] of adj) {
104
+ // 超级节点防御:度数超限时只取权重最高的 maxDeg 条边。
105
+ // 实测 5000 度枢纽 2 跳 p50=9ms 尚可接受,但度数无上限时
106
+ // 每次遍历要全扫邻接表,且并发多查询会叠加放大。这里封顶换确定性。
107
+ let edges = adj;
108
+ if (maxDeg > 0 && adj.size > maxDeg) {
109
+ edges = new Map(
110
+ Array.from(adj.entries())
111
+ .sort((a, b) => num(b[1], 0) - num(a[1], 0))
112
+ .slice(0, maxDeg)
113
+ );
114
+ if (stats) stats.truncatedHubs++;
115
+ }
116
+ for (const [toId, wRaw] of edges) {
97
117
  const w = num(wRaw, 0);
98
118
  if (!(w > 0) || w < minW) continue;
99
119
  const node = mem.nodes.get(toId);
package/memory/store.cjs CHANGED
@@ -84,9 +84,11 @@ const DEFAULTS = {
84
84
  synapseIdleDays: 60, // 合成边超过这么久没触发 → 衰减
85
85
  synapseDecay: 0.9, // 每次衰减乘子
86
86
  synapseMinWeight: 0.01, // 低于它直接删除
87
+ hebbianMaxPerNode: 16, // 每节点赫布边数上限:超出按 保留分(w×log2(1+触发)) 剪最弱(0 = 关闭);防热点节点边无限累积
87
88
  observeConsolidateEvery: 20, // observe() 每 N 轮触发一次巩固
88
89
  observeConsolidateDays: 1, // 或距上次巩固超过 A 天
89
90
  tickConsolidateDays: 1, // tick() 里距上次巩固超过 A 天才真正巩固
91
+ summaryRefreshMs: 300000, // tick() 里多久刷一次 L3 画像摘要(默认 5 分钟;0 = 每次 tick 都算)
90
92
  autoCompactRatio: 2.5, // 追加行数 > 存活×该比例 → 自动调度压缩(0 = 关闭自动压缩)
91
93
  autoCompactDelayMs: 5000, // 跨过阈值后延迟这么多毫秒再压(防抖:写突发结束才动手)
92
94
  };
@@ -131,6 +133,75 @@ function truncateChars(s, max) {
131
133
  return arr.slice(0, Math.max(0, max - 1)).join('') + '…';
132
134
  }
133
135
 
136
+ /**
137
+ * 长文本切块:超过 MAX_TEXT 的正文按语义边界切成多段,而不是静默截断。
138
+ *
139
+ * 背景(2026-11-23 实测):原实现对 >2000 字的输入直接 slice 截断,
140
+ * 5 万字的文档会被无声丢弃 96%,用户以为记住了实际只剩开头。
141
+ *
142
+ * 切分优先级:段落(\n\n)→ 句子(。!?;\n)→ 字符硬切(兜底)。
143
+ * 每块长度 <= MAX_TEXT,块间保留 context 关联标记,便于后续按 docId 聚合。
144
+ *
145
+ * @param {string} text 已 cleanText 的正文
146
+ * @param {number} max 单块上限
147
+ * @returns {string[]} 切块结果(1 块 = 无需切分)
148
+ */
149
+ function splitText(text, max = MAX_TEXT) {
150
+ const chars = Array.from(String(text == null ? '' : text));
151
+ if (chars.length <= max) return [chars.join('')];
152
+
153
+ const segments = []; // { text, len }
154
+ const push = (s) => {
155
+ const t = s.trim();
156
+ if (!t) return;
157
+ segments.push({ text: t, len: Array.from(t).length });
158
+ };
159
+
160
+ // 1) 先按段落切
161
+ const paras = chars.join('').split(/\n{2,}/);
162
+ for (const p of paras) {
163
+ if (Array.from(p).length <= max) { push(p); continue }
164
+ // 2) 段落仍超长 → 按句子切
165
+ const sentences = p.split(/(?<=[。!?;!?;\n])/);
166
+ for (const s of sentences) {
167
+ if (Array.from(s).length <= max) { push(s); continue }
168
+ // 3) 单句仍超长(无标点长文)→ 字符硬切
169
+ const arr = Array.from(s);
170
+ for (let i = 0; i < arr.length; i += max) push(arr.slice(i, i + max).join(''));
171
+ }
172
+ }
173
+
174
+ // 4) 贪心合并相邻片段,尽量填满每块。
175
+ // 关键:严格按「合并后的实际长度」判断,绝不能因为放不下就丢弃片段——
176
+ // 早期实现用 curLen + seg.len 估算漏算分隔符,导致每次换块丢一段(实测丢 10~19%)。
177
+ const out = [];
178
+ let cur = '';
179
+ for (const seg of segments) {
180
+ if (!cur) { cur = seg.text; continue }
181
+ const joined = cur + seg.text
182
+ if (Array.from(joined).length <= max) {
183
+ cur = joined
184
+ } else {
185
+ out.push(cur)
186
+ cur = seg.text
187
+ }
188
+ }
189
+ if (cur) out.push(cur)
190
+
191
+ // 保守校验:合并后总字数不应少于原文的 99%(空白归一造成的差异除外)
192
+ const outChars = out.reduce((n, s) => n + Array.from(s).length, 0)
193
+ const srcChars = Array.from(text).length
194
+ if (!out.length || outChars < srcChars * 0.99) {
195
+ // 兜底:退回纯字符硬切,保证绝对不丢
196
+ const arr = Array.from(text)
197
+ const hard = []
198
+ for (let i = 0; i < arr.length; i += max) hard.push(arr.slice(i, i + max).join(''))
199
+ return hard
200
+ }
201
+ return out;
202
+ }
203
+
204
+
134
205
  /** 同步小睡(Windows 上 rename 撞杀软/句柄时会重试) */
135
206
  function sleepMs(ms) {
136
207
  try {
@@ -395,6 +466,7 @@ class NebulaMemory {
395
466
  this._traceLines = 0;
396
467
  this._traceSeq = 0;
397
468
  this._lastConsolidateAt = 0;
469
+ this._lastSummaryRefreshAt = 0; // L3 画像摘要上次刷新时刻(tick 节流用)
398
470
  this._lastTickAt = 0;
399
471
  this._observeTurns = 0;
400
472
  this._turnCounter = 0;
@@ -550,11 +622,44 @@ class NebulaMemory {
550
622
  */
551
623
  async remember(input = {}) {
552
624
  this._assertReady();
625
+ // 超长文本自动切块(2026-11-23 修复静默截断:原实现直接 slice(0, 2000))
626
+ const raw = cleanText(input.text);
627
+ const chunks = splitText(raw, MAX_TEXT);
628
+ if (chunks.length > 1) {
629
+ const docId = `doc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
630
+ this._log('info', `remember: 文本 ${Array.from(raw).length} 字超上限,自动切为 ${chunks.length} 块 (docId=${docId})`);
631
+ const ids = [];
632
+ for (let i = 0; i < chunks.length; i++) {
633
+ const r = await this._rememberOne({
634
+ ...input,
635
+ text: chunks[i],
636
+ _noDedupe: true,
637
+ meta: { ...(input.meta || {}), docId, chunkIndex: i, chunkTotal: chunks.length },
638
+ });
639
+ ids.push(r.id);
640
+ // 同文档相邻块连边,便于召回时整篇聚合
641
+ if (i > 0) {
642
+ try {
643
+ this._addEdge(ids[i - 1], r.id, 1, { kind: EDGE_KIND.SEMANTIC, source: 'chunk' })
644
+ } catch (e) {
645
+ this._log('warn', `remember: 块间连边失败 (${e.message})`)
646
+ }
647
+ }
648
+ }
649
+ return { id: ids[0], ids, deduped: false, chunks: chunks.length, docId, node: this._publicNode(this.nodes.get(ids[0])) };
650
+ }
651
+ return this._rememberOne(input);
652
+ }
653
+
654
+ /** 单条写入(被 remember 调用;超长已在调用方切块)。 */
655
+ async _rememberOne(input = {}) {
553
656
  const rec = this._buildRecord(input);
554
657
  rec._tf = this._tfFor(rec);
555
658
 
556
- // 同 kind 余弦 > 阈值 → 不新增,更新已有节点的时间与重要性
557
- const dup = this._findDuplicate(rec);
659
+ // 同 kind 余弦 > 阈值 → 不新增,更新已有节点的时间与重要性。
660
+ // 例外:长文档切块(input._noDedupe)必须整块独立保存 —— 同一篇文档的相邻块
661
+ // 本就高度相似,若互相去重会把整篇压成一条,等于又丢了内容(2026-11-23 实测确认)。
662
+ const dup = input._noDedupe ? null : this._findDuplicate(rec);
558
663
  if (dup) {
559
664
  const now = rec.ts;
560
665
  this._unindexNode(dup);
@@ -899,6 +1004,7 @@ class NebulaMemory {
899
1004
 
900
1005
  // 5) L3 画像摘要(确定性模板;没有任何画像/事实素材时返回 null)
901
1006
  const summary = dynamics.refreshSummary(this, { now });
1007
+ this._lastSummaryRefreshAt = now;
902
1008
 
903
1009
  this._lastConsolidateAt = now;
904
1010
  this._flushPending();
@@ -1038,6 +1144,7 @@ class NebulaMemory {
1038
1144
  archiveMinDays: this.opts.archiveMinDays,
1039
1145
  synapseIdleDays: this.opts.synapseIdleDays,
1040
1146
  synapseDecay: this.opts.synapseDecay,
1147
+ hebbianMaxPerNode: this.opts.hebbianMaxPerNode,
1041
1148
  synapseMinWeight: this.opts.synapseMinWeight,
1042
1149
  },
1043
1150
  trace: this._traceLines,
@@ -1287,7 +1394,16 @@ class NebulaMemory {
1287
1394
  let summary = null;
1288
1395
  let consolidated = null;
1289
1396
  if (!dryRun) {
1290
- summary = dynamics.refreshSummary(this, { now });
1397
+ // L3 画像摘要按 summaryRefreshMs 节流(修复每条 tick 重写,2026-11-24)
1398
+ const summaryInterval = Math.max(0, num(this.opts.summaryRefreshMs, 300000));
1399
+ const summaryDue =
1400
+ summaryInterval === 0 ||
1401
+ !this._lastSummaryRefreshAt ||
1402
+ now - num(this._lastSummaryRefreshAt, 0) >= summaryInterval;
1403
+ if (summaryDue) {
1404
+ summary = dynamics.refreshSummary(this, { now });
1405
+ this._lastSummaryRefreshAt = now;
1406
+ }
1291
1407
  const due =
1292
1408
  !this._lastConsolidateAt ||
1293
1409
  now - num(this._lastConsolidateAt, 0) >=
@@ -1303,6 +1419,7 @@ class NebulaMemory {
1303
1419
  archived: forget.archived,
1304
1420
  edgesDecayed: forget.edgesDecayed,
1305
1421
  edgesRemoved: forget.edgesRemoved,
1422
+ hebbianPruned: forget.hebbianPruned,
1306
1423
  scanned: forget.scanned,
1307
1424
  summaryId: summary ? summary.id : null,
1308
1425
  summaryUpdated: !!(summary && summary.updated),
@@ -1611,6 +1728,8 @@ class NebulaMemory {
1611
1728
  lastFired: Number.isFinite(meta.lastFired) ? Number(meta.lastFired) : now,
1612
1729
  fireCount: Number.isFinite(meta.fireCount) ? Number(meta.fireCount) : 1,
1613
1730
  };
1731
+ // 溯源标记(chunk = 同一文档切块间的关联;缺省不写入,保持旧数据形状)
1732
+ if (meta.source) edge.source = String(meta.source).slice(0, 32);
1614
1733
  this.edgeMap.set(edgeKey(lo, hi), edge);
1615
1734
  this._saveEdge(edge);
1616
1735
  this._applyEdgeToAdj(edge);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "mcpName": "io.github.yb-zhai/nebula-memory",
5
5
  "description": "Zero-dependency local Agent memory MCP Server (stdio JSON-RPC). Works offline, no API keys, no database. Exposes remember/recall/stats/forget to Claude Desktop, Cursor, ChatGPT and any MCP client.",
6
6
  "type": "module",