nebula-memory-mcp 1.1.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.
package/mcp-server.mjs CHANGED
@@ -42,7 +42,7 @@ const DATA_DIR = path.resolve(
42
42
 
43
43
  const SERVER_INFO = {
44
44
  name: 'agent-memory',
45
- version: '1.1.0',
45
+ version: '1.2.0',
46
46
  }
47
47
 
48
48
  // MCP 协议版本(当前规范)
@@ -151,6 +151,14 @@ const TOOLS = [
151
151
  required: ['id'],
152
152
  },
153
153
  },
154
+ {
155
+ name: 'compact',
156
+ description: '手动压缩记忆库文件:清理追加历史,磁盘显著变小、下次启动明显变快。实例保持可用,不影响读写。可选 namespace。',
157
+ inputSchema: {
158
+ type: 'object',
159
+ properties: { namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' } },
160
+ },
161
+ },
154
162
  ]
155
163
 
156
164
  // ── 工具执行 ─────────────────────────────────────────────────────────────
@@ -186,6 +194,16 @@ async function callTool(name, args, defaultMem) {
186
194
  const r = await mem.forget(String(args.id || ''))
187
195
  return { content: [{ type: 'text', text: JSON.stringify(r) }] }
188
196
  }
197
+ case 'compact': {
198
+ const r = await mem.compact()
199
+ const summary = {
200
+ ok: r.ok,
201
+ durationMs: r.durationMs,
202
+ nodeLines: `${r.before.nodeLines} -> ${r.after.nodeLines}`,
203
+ nodesFileMB: `${r.before.nodesMB} -> ${r.after.nodesMB}`,
204
+ }
205
+ return { content: [{ type: 'text', text: JSON.stringify(summary) }] }
206
+ }
189
207
  default:
190
208
  throw new Error(`unknown tool: ${name}`)
191
209
  }
@@ -193,6 +211,23 @@ async function callTool(name, args, defaultMem) {
193
211
 
194
212
  // ── 主流程 ───────────────────────────────────────────────────────────────
195
213
  async function main() {
214
+ // CLI 子命令:node mcp-server.mjs compact [数据目录]
215
+ // ⚠️ 必须在插件服务停止后使用(压缩重写 JSONL,与服务双写会冲突)。
216
+ if (process.argv[2] === 'compact') {
217
+ const dir = path.resolve(
218
+ process.argv[3] ||
219
+ process.env.NEBULA_DATA_DIR ||
220
+ process.env.MEMORY_NEBULA_DATA_DIR ||
221
+ path.join(os.homedir(), '.agent-memory')
222
+ )
223
+ const mem = new NebulaMemory({ dir, log: () => {} })
224
+ await mem.init()
225
+ const r = await mem.compact()
226
+ await mem.close()
227
+ console.log(JSON.stringify(r, null, 2))
228
+ return
229
+ }
230
+
196
231
  // 默认单库实例(不传 namespace 时用),保持与旧版完全一致的行为。
197
232
  const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {} })
198
233
  await defaultMem.init()
@@ -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,13 @@ 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 都算)
92
+ autoCompactRatio: 2.5, // 追加行数 > 存活×该比例 → 自动调度压缩(0 = 关闭自动压缩)
93
+ autoCompactDelayMs: 5000, // 跨过阈值后延迟这么多毫秒再压(防抖:写突发结束才动手)
90
94
  };
91
95
 
92
96
  /** 打分权重(1 = 原位;调大可放大该因子对排序的影响) */
@@ -129,6 +133,75 @@ function truncateChars(s, max) {
129
133
  return arr.slice(0, Math.max(0, max - 1)).join('') + '…';
130
134
  }
131
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
+
132
205
  /** 同步小睡(Windows 上 rename 撞杀软/句柄时会重试) */
133
206
  function sleepMs(ms) {
134
207
  try {
@@ -393,6 +466,7 @@ class NebulaMemory {
393
466
  this._traceLines = 0;
394
467
  this._traceSeq = 0;
395
468
  this._lastConsolidateAt = 0;
469
+ this._lastSummaryRefreshAt = 0; // L3 画像摘要上次刷新时刻(tick 节流用)
396
470
  this._lastTickAt = 0;
397
471
  this._observeTurns = 0;
398
472
  this._turnCounter = 0;
@@ -446,6 +520,7 @@ class NebulaMemory {
446
520
  }
447
521
  this._ready = true;
448
522
  if (this._indexDirty) this._writeIndexSnapshot();
523
+ this._scheduleAutoCompact(); // 重启加载后若追加历史已膨胀,排一次自动压缩
449
524
  this._log(
450
525
  'info',
451
526
  `ready dir=${this.dir} nodes=${this.nodes.size} edges=${this.edgeMap.size} badLines=${this._badLines}`
@@ -467,6 +542,7 @@ class NebulaMemory {
467
542
  /** 关闭:落 pending 更新 → 必要时压缩 → 落索引快照。可重复调用。 */
468
543
  async close() {
469
544
  if (!this._ready) return;
545
+ if (this._autoCompactTimer) { clearTimeout(this._autoCompactTimer); this._autoCompactTimer = null; }
470
546
  this._flushPending();
471
547
  this._maybeCompact();
472
548
  if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
@@ -476,6 +552,67 @@ class NebulaMemory {
476
552
  this._closed = true;
477
553
  }
478
554
 
555
+ /**
556
+ * 手动压缩(实例保持可用):落 pending → 强制重写 nodes/edges jsonl → 落索引快照。
557
+ * 只序列化内存里的存活集,规模再大也是亚秒级;收益是磁盘文件和下一次冷启动。
558
+ * @returns {Promise<{ok:boolean, durationMs:number, before:Object, after:Object, dir:string}>}
559
+ */
560
+ async compact() {
561
+ this._assertReady();
562
+ const t = Date.now();
563
+ const sizeOf = (f) => { try { return fs.statSync(f).size; } catch { return 0; } };
564
+ const before = {
565
+ nodeLines: this._nodeLines,
566
+ edgeLines: this._edgeLines,
567
+ nodesMB: +(sizeOf(this.fileNodes) / 1048576).toFixed(1),
568
+ edgesMB: +(sizeOf(this.fileEdges) / 1048576).toFixed(1),
569
+ alive: { nodes: this.nodes.size, edges: this.edgeMap.size },
570
+ };
571
+ this._flushPending();
572
+ this._compactNodesNow = true;
573
+ this._maybeCompact();
574
+ this._compactNodesNow = false;
575
+ if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
576
+ this._writeIndexSnapshot();
577
+ const after = {
578
+ nodeLines: this._nodeLines,
579
+ edgeLines: this._edgeLines,
580
+ nodesMB: +(sizeOf(this.fileNodes) / 1048576).toFixed(1),
581
+ edgesMB: +(sizeOf(this.fileEdges) / 1048576).toFixed(1),
582
+ alive: { nodes: this.nodes.size, edges: this.edgeMap.size },
583
+ };
584
+ const out = { ok: true, durationMs: Date.now() - t, before, after, dir: this.dir };
585
+ this._log('info', `compact: nodeLines ${before.nodeLines} -> ${after.nodeLines}, ${before.nodesMB}MB -> ${after.nodesMB}MB in ${out.durationMs}ms`);
586
+ return out;
587
+ }
588
+
589
+ /**
590
+ * 自动压缩调度:追加行数超过 存活×autoCompactRatio 时,延迟 autoCompactDelayMs 执行。
591
+ * 压缩只重写存活集(亚秒级),不阻塞当前请求;阈值防抖保证一次写突发只压一次。
592
+ */
593
+ _scheduleAutoCompact() {
594
+ if (this._autoCompactTimer || this._closed) return;
595
+ const ratio = num(this.opts.autoCompactRatio, 2.5);
596
+ if (ratio <= 0) return; // 0 = 关闭
597
+ if (this._nodeLines <= Math.max(200, this.nodes.size * ratio)) return;
598
+ this._autoCompactTimer = setTimeout(() => {
599
+ this._autoCompactTimer = null;
600
+ if (this._closed || !this._ready) return;
601
+ try {
602
+ this._flushPending();
603
+ this._compactNodesNow = true;
604
+ this._maybeCompact();
605
+ this._compactNodesNow = false;
606
+ if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
607
+ this._writeIndexSnapshot();
608
+ this._log('info', `auto-compact done: nodeLines=${this._nodeLines} nodes=${this.nodes.size}`);
609
+ } catch (e) {
610
+ this._log('warn', `auto-compact failed: ${e.message}`);
611
+ }
612
+ }, Math.max(0, num(this.opts.autoCompactDelayMs, 5000)));
613
+ this._autoCompactTimer.unref?.();
614
+ }
615
+
479
616
  // -- 写入 -----------------------------------------------------------------
480
617
 
481
618
  /**
@@ -485,11 +622,44 @@ class NebulaMemory {
485
622
  */
486
623
  async remember(input = {}) {
487
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 = {}) {
488
656
  const rec = this._buildRecord(input);
489
657
  rec._tf = this._tfFor(rec);
490
658
 
491
- // 同 kind 余弦 > 阈值 → 不新增,更新已有节点的时间与重要性
492
- const dup = this._findDuplicate(rec);
659
+ // 同 kind 余弦 > 阈值 → 不新增,更新已有节点的时间与重要性。
660
+ // 例外:长文档切块(input._noDedupe)必须整块独立保存 —— 同一篇文档的相邻块
661
+ // 本就高度相似,若互相去重会把整篇压成一条,等于又丢了内容(2026-11-23 实测确认)。
662
+ const dup = input._noDedupe ? null : this._findDuplicate(rec);
493
663
  if (dup) {
494
664
  const now = rec.ts;
495
665
  this._unindexNode(dup);
@@ -834,6 +1004,7 @@ class NebulaMemory {
834
1004
 
835
1005
  // 5) L3 画像摘要(确定性模板;没有任何画像/事实素材时返回 null)
836
1006
  const summary = dynamics.refreshSummary(this, { now });
1007
+ this._lastSummaryRefreshAt = now;
837
1008
 
838
1009
  this._lastConsolidateAt = now;
839
1010
  this._flushPending();
@@ -973,6 +1144,7 @@ class NebulaMemory {
973
1144
  archiveMinDays: this.opts.archiveMinDays,
974
1145
  synapseIdleDays: this.opts.synapseIdleDays,
975
1146
  synapseDecay: this.opts.synapseDecay,
1147
+ hebbianMaxPerNode: this.opts.hebbianMaxPerNode,
976
1148
  synapseMinWeight: this.opts.synapseMinWeight,
977
1149
  },
978
1150
  trace: this._traceLines,
@@ -1222,7 +1394,16 @@ class NebulaMemory {
1222
1394
  let summary = null;
1223
1395
  let consolidated = null;
1224
1396
  if (!dryRun) {
1225
- 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
+ }
1226
1407
  const due =
1227
1408
  !this._lastConsolidateAt ||
1228
1409
  now - num(this._lastConsolidateAt, 0) >=
@@ -1238,6 +1419,7 @@ class NebulaMemory {
1238
1419
  archived: forget.archived,
1239
1420
  edgesDecayed: forget.edgesDecayed,
1240
1421
  edgesRemoved: forget.edgesRemoved,
1422
+ hebbianPruned: forget.hebbianPruned,
1241
1423
  scanned: forget.scanned,
1242
1424
  summaryId: summary ? summary.id : null,
1243
1425
  summaryUpdated: !!(summary && summary.updated),
@@ -1530,6 +1712,7 @@ class NebulaMemory {
1530
1712
  this._raw.set(n.id, rec);
1531
1713
  this._nodeLines++;
1532
1714
  this._writesSinceIndex++;
1715
+ this._scheduleAutoCompact();
1533
1716
  }
1534
1717
 
1535
1718
  _addEdge(a, b, weight, meta = {}) {
@@ -1545,6 +1728,8 @@ class NebulaMemory {
1545
1728
  lastFired: Number.isFinite(meta.lastFired) ? Number(meta.lastFired) : now,
1546
1729
  fireCount: Number.isFinite(meta.fireCount) ? Number(meta.fireCount) : 1,
1547
1730
  };
1731
+ // 溯源标记(chunk = 同一文档切块间的关联;缺省不写入,保持旧数据形状)
1732
+ if (meta.source) edge.source = String(meta.source).slice(0, 32);
1548
1733
  this.edgeMap.set(edgeKey(lo, hi), edge);
1549
1734
  this._saveEdge(edge);
1550
1735
  this._applyEdgeToAdj(edge);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.1.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",