nebula-memory-mcp 1.2.4 → 1.2.6

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/README.md CHANGED
@@ -112,7 +112,7 @@ agent-memory(引擎真源,9 个模块) ──人工对齐──▶ 本
112
112
 
113
113
  | 上游 `agent-memory` | **本仓库** | `nebula-workbuddy-mcp` | 备注 |
114
114
  |---|---|---|---|
115
- | **2.2.0**(+ PII 脱敏) | **1.2.4** | 1.0.7(待同步) | 引擎与上游 2.2.0 对齐 |
115
+ | **2.2.1**(薄索引一致性修复) | **1.2.5** | 1.0.8(待同步) | 引擎与上游 2.2.1 对齐 |
116
116
 
117
117
  ## License
118
118
 
package/mcp-server.mjs CHANGED
@@ -43,7 +43,7 @@ const DATA_DIR = path.resolve(
43
43
  const SERVER_INFO = {
44
44
  name: 'agent-memory',
45
45
  // 与 package.json 的 version 保持一致(发版时必须一起改,见 README「引擎来历与同步」)
46
- version: '1.2.4',
46
+ version: '1.2.6',
47
47
  }
48
48
 
49
49
  // MCP 协议版本(当前规范)
@@ -55,6 +55,10 @@ const PROTOCOL_VERSION = '2024-11-05'
55
55
  const NS_ROOT = path.join(DATA_DIR, '__ns__')
56
56
  const memCache = new Map() // namespace -> NebulaMemory 实例
57
57
 
58
+ // 多进程/多 agent 共用同一目录时,打开这个开关:每次 recall 前增量吸收别的进程追加的行。
59
+ // 单进程内读写本来就是实时的,开不开都一样(只是多一次 stat)。
60
+ const ENGINE_OPTS = { watchExternalWrites: process.env.NEBULA_WATCH_EXTERNAL_WRITES === '1' }
61
+
58
62
  function normalizeNamespace(ns) {
59
63
  if (ns == null) return null
60
64
  const s = String(ns).trim()
@@ -68,7 +72,7 @@ async function getMemory(ns) {
68
72
  if (ns == null) return null // 调用方改用默认单库实例
69
73
  if (!memCache.has(ns)) {
70
74
  const dir = path.join(NS_ROOT, ns)
71
- const m = new NebulaMemory({ dir, log: () => {} })
75
+ const m = new NebulaMemory({ dir, log: () => {}, options: ENGINE_OPTS })
72
76
  await m.init()
73
77
  memCache.set(ns, m)
74
78
  }
@@ -221,7 +225,7 @@ async function main() {
221
225
  process.env.MEMORY_NEBULA_DATA_DIR ||
222
226
  path.join(os.homedir(), '.agent-memory')
223
227
  )
224
- const mem = new NebulaMemory({ dir, log: () => {} })
228
+ const mem = new NebulaMemory({ dir, log: () => {}, options: ENGINE_OPTS })
225
229
  await mem.init()
226
230
  const r = await mem.compact()
227
231
  await mem.close()
@@ -230,7 +234,7 @@ async function main() {
230
234
  }
231
235
 
232
236
  // 默认单库实例(不传 namespace 时用),保持与旧版完全一致的行为。
233
- const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {} })
237
+ const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {}, options: ENGINE_OPTS })
234
238
  await defaultMem.init()
235
239
 
236
240
  readStdinLines(async (line) => {
package/memory/store.cjs CHANGED
@@ -82,6 +82,10 @@ const DEFAULTS = {
82
82
  dormantPenalty: 0.55, // dormant 节点在检索里的乘子
83
83
  dedupeThreshold: 0.92, // remember 去重阈值(同 kind、tf-idf 余弦)
84
84
  redact: 'on', // 写入前敏感信息脱敏:'on'(默认替换)| 'off'(完全关闭)| 'report'(只统计)
85
+ // 每次 recall 前检查 jsonl 是否被「别的进程」追加过,是就增量吸收。
86
+ // ⚠️ 只对多进程/多 agent 共用同一目录的场景有意义:
87
+ // 单进程内的读写本来就是实时的,开不开都一样(只是多一次 stat)。
88
+ watchExternalWrites: false,
85
89
  consolidateThreshold: 0.85, // episode 聚合阈值
86
90
  consolidateMinCluster: 2,
87
91
  consolidateMaxCluster: 12,
@@ -581,25 +585,59 @@ function isPidAlive(pid) {
581
585
  }
582
586
 
583
587
  /** 追加一行(append 只写一行,崩溃最多丢最后一行,读入时会当坏行跳过) */
584
- function appendLine(file, obj) {
585
- // 返回这一行在文件里的字节区间,供薄索引记录原文位置(懒加载用)。
586
- // 先取文件长度当偏移:单进程追加写,长度即下一次写入的起点。
587
- let off = 0;
588
+ /** 数一个文件里有多少个换行(只看字节,不解析 JSON) */
589
+ function countNewlines(file) {
590
+ let buf;
588
591
  try {
589
- off = fs.statSync(file).size;
592
+ buf = fs.readFileSync(file);
590
593
  } catch {
591
- off = 0;
594
+ return 0;
592
595
  }
596
+ let n = 0;
597
+ let i = -1;
598
+ while ((i = buf.indexOf(10, i + 1)) !== -1) n++;
599
+ return n;
600
+ }
601
+
602
+ function readRange(file, from, to) {
603
+ const len = Math.max(0, to - from);
604
+ if (!len) return Buffer.alloc(0);
605
+ const fd = fs.openSync(file, 'r');
606
+ try {
607
+ const buf = Buffer.allocUnsafe(len);
608
+ const n = fs.readSync(fd, buf, 0, len, from);
609
+ return buf.subarray(0, n);
610
+ } finally {
611
+ fs.closeSync(fd);
612
+ }
613
+ }
614
+
615
+ function fileBytes(file) {
616
+ try {
617
+ return fs.statSync(file).size;
618
+ } catch {
619
+ return 0;
620
+ }
621
+ }
622
+
623
+ function appendLine(file, obj) {
624
+ // 返回这一行在文件里的字节区间,供薄索引记录原文位置(懒加载用)。
593
625
  const data = JSON.stringify(obj) + '\n';
594
626
  const len = Buffer.byteLength(data, 'utf8');
627
+ // 先写再定位:O_APPEND 保证这次写在文件末尾的一段连续区间,
628
+ // 起点 = 写完后的大小 - 本行字节数。
629
+ // 旧实现是「先 stat 再写」——多进程同时写时 stat 到的位置会过期,
630
+ // 记进薄索引的偏移就是错的,懒加载会把别人那行的原文读给你(2026-11-30 修)。
595
631
  const fd = fs.openSync(file, 'a');
632
+ let end = 0;
596
633
  try {
597
634
  fs.writeSync(fd, data, null, 'utf8');
635
+ end = fs.fstatSync(fd).size;
598
636
  } finally {
599
637
  fs.closeSync(fd);
600
638
  }
601
- // len 去掉行尾换行,只覆盖 JSON 本体
602
- return { off, len: len - 1 };
639
+ // len 去掉行尾换行,只覆盖 JSON 本体;end 是下一行的起点字节位置
640
+ return { off: Math.max(0, end - len), len: len - 1, end };
603
641
  }
604
642
 
605
643
  /** 人类可读的时间差(renderContext 用) */
@@ -681,6 +719,14 @@ class NebulaMemory {
681
719
 
682
720
  this._nodeLines = 0;
683
721
  this._edgeLines = 0;
722
+ // 本实例「已经读到/写到」的 jsonl 字节边界。
723
+ // 写薄索引时用它而不是 fs.statSync:否则持有旧视图的进程会写出
724
+ // 「内容少、大小新」的假自洽索引,把别人新写的记录静默吞掉(2026-11-30 踩到)。
725
+ this._nodeBytes = 0;
726
+ this._edgeBytes = 0;
727
+ // 见过「别的进程追加」吗?见过就永不写薄索引 —— 并发下本实例的节点视图是残缺的,
728
+ // 写出来的薄索引会「大小对、行数少」,把别人写的行静默吞掉(2026-11-30 并发实测)。
729
+ this._sawExternalAppend = false;
684
730
  this._badLines = 0;
685
731
  this._indexDirty = true;
686
732
  this._indexMeta = null;
@@ -1030,8 +1076,152 @@ class NebulaMemory {
1030
1076
  * includeDormant?:boolean, includeArchived?:boolean, trackAccess?:boolean, debug?:boolean}} [options]
1031
1077
  * @returns {Promise<Array<Object>>}
1032
1078
  */
1079
+ /**
1080
+ * 增量吸收「别的进程刚追加」的节点/边。只在 opts.watchExternalWrites=true 时由 recall 调用。
1081
+ * 判定依据是字节边界:比本实例已知的大 → 读尾部增量;变小 → 说明别人压缩重写过,全量重载。
1082
+ * @returns {{changed:boolean, reloaded?:boolean}}
1083
+ */
1084
+ _syncExternalAppends() {
1085
+ if (!this._ready) return { changed: false };
1086
+ const nodeSize = fileBytes(this.fileNodes);
1087
+ const edgeSize = fileBytes(this.fileEdges);
1088
+ if (nodeSize < this._nodeBytes || edgeSize < this._edgeBytes) {
1089
+ this._reloadFromDisk();
1090
+ return { changed: true, reloaded: true };
1091
+ }
1092
+ let changed = false;
1093
+
1094
+ if (nodeSize > this._nodeBytes) {
1095
+ const from = this._nodeBytes;
1096
+ const text = readRange(this.fileNodes, from, nodeSize).toString('utf8');
1097
+ let pos = 0;
1098
+ let consumed = 0;
1099
+ let lines = 0;
1100
+ for (;;) {
1101
+ const nl = text.indexOf('\n', pos);
1102
+ if (nl < 0) break; // 只处理完整行:末尾半行可能正在被别的进程写
1103
+ const line = text.slice(pos, nl);
1104
+ const len = Buffer.byteLength(line, 'utf8');
1105
+ const off = from + consumed;
1106
+ pos = nl + 1;
1107
+ consumed += len + 1;
1108
+ lines++;
1109
+ if (!line.trim()) continue;
1110
+ let obj;
1111
+ try {
1112
+ obj = JSON.parse(line);
1113
+ } catch {
1114
+ this._badLines++;
1115
+ continue;
1116
+ }
1117
+ if (!obj || obj.id == null || typeof obj.text !== 'string') {
1118
+ this._badLines++;
1119
+ continue;
1120
+ }
1121
+ const id = String(obj.id);
1122
+ this._raw.set(id, obj);
1123
+ const existing = this.nodes.get(id);
1124
+ if (existing) this._unindexNode(existing);
1125
+ if (obj.deleted) {
1126
+ this.nodes.delete(id);
1127
+ } else {
1128
+ const node = this._adopt(obj);
1129
+ if (node) {
1130
+ node._tf = this._tfFor(node);
1131
+ this._indexNode(node);
1132
+ this.nodes.set(id, node);
1133
+ } else {
1134
+ this.nodes.delete(id);
1135
+ }
1136
+ }
1137
+ }
1138
+ this._nodeBytes = from + consumed;
1139
+ this._nodeLines += lines;
1140
+ changed = true;
1141
+ }
1142
+
1143
+ if (edgeSize > this._edgeBytes) {
1144
+ const from = this._edgeBytes;
1145
+ const text = readRange(this.fileEdges, from, edgeSize).toString('utf8');
1146
+ let pos = 0;
1147
+ let consumed = 0;
1148
+ let lines = 0;
1149
+ for (;;) {
1150
+ const nl = text.indexOf('\n', pos);
1151
+ if (nl < 0) break;
1152
+ const line = text.slice(pos, nl);
1153
+ const len = Buffer.byteLength(line, 'utf8');
1154
+ pos = nl + 1;
1155
+ consumed += len + 1;
1156
+ lines++;
1157
+ if (!line.trim()) continue;
1158
+ let obj;
1159
+ try {
1160
+ obj = JSON.parse(line);
1161
+ } catch {
1162
+ this._badLines++;
1163
+ continue;
1164
+ }
1165
+ if (!obj || obj.a == null || obj.b == null) {
1166
+ this._badLines++;
1167
+ continue;
1168
+ }
1169
+ const a = String(obj.a);
1170
+ const b = String(obj.b);
1171
+ if (!a || !b || a === b) continue;
1172
+ const [lo, hi] = a < b ? [a, b] : [b, a];
1173
+ const key = edgeKey(lo, hi);
1174
+ if (obj.deleted) {
1175
+ const e = this.edgeMap.get(key);
1176
+ if (e) {
1177
+ this.edgeMap.delete(key);
1178
+ const ma = this.adj.get(e.a);
1179
+ if (ma) ma.delete(e.b);
1180
+ const mb = this.adj.get(e.b);
1181
+ if (mb) mb.delete(e.a);
1182
+ }
1183
+ } else {
1184
+ const edge = {
1185
+ a: lo,
1186
+ b: hi,
1187
+ w: clamp(num(obj.w, 1), 0.01, 10),
1188
+ kind: dynamics.isValidEdgeKind(obj.kind) ? obj.kind : EDGE_KIND.SEMANTIC,
1189
+ lastFired: num(obj.lastFired, Date.now()),
1190
+ fireCount: num(obj.fireCount, 1),
1191
+ };
1192
+ this.edgeMap.set(key, edge);
1193
+ this._applyEdgeToAdj(edge);
1194
+ }
1195
+ }
1196
+ this._edgeBytes = from + consumed;
1197
+ this._edgeLines += lines;
1198
+ changed = true;
1199
+ }
1200
+
1201
+ if (changed) {
1202
+ this.version++;
1203
+ this._dfVersion++;
1204
+ this._indexDirty = true;
1205
+ this._log('debug', `external appends absorbed: nodes=${this.nodes.size} edges=${this.edgeMap.size}`);
1206
+ }
1207
+ return { changed };
1208
+ }
1209
+
1210
+ /** 文件被别的进程压缩/重写过(字节变少)→ 偏移全失效,全量重载 */
1211
+ _reloadFromDisk() {
1212
+ this._thin = false;
1213
+ this._loadNodes();
1214
+ this._loadEdges();
1215
+ this._rebuildDerived();
1216
+ this._loadIndexSnapshotMeta();
1217
+ this.version++;
1218
+ this._log('info', `external rewrite detected → full reload: nodes=${this.nodes.size}`);
1219
+ }
1220
+
1033
1221
  async recall(query, options = {}) {
1034
1222
  this._assertReady();
1223
+ // 多进程共用目录时,先把别的进程刚追加的行吸收进来(默认关;单进程不需要)
1224
+ if (this.opts.watchExternalWrites === true) this._syncExternalAppends();
1035
1225
  // 2026-11-23:加错别字纠正 + 同义词 + 画像反哺扩展。
1036
1226
  // 注意:recall() 与 recallFragments()/runRecall() 是两条独立路径,
1037
1227
  // 扩展必须在这里也算一遍,否则 MCP/API 侧(走 recall)享受不到。
@@ -1819,6 +2009,7 @@ class NebulaMemory {
1819
2009
  offsets.set(id, { off, len });
1820
2010
  });
1821
2011
  this._nodeLines = res.lines;
2012
+ this._nodeBytes = fileBytes(this.fileNodes);
1822
2013
  this._badLines += res.bad + invalid;
1823
2014
  for (const [id, raw] of this._raw) {
1824
2015
  if (raw.deleted) continue; // 软删记录留在 _raw 里,不进索引
@@ -1871,6 +2062,7 @@ class NebulaMemory {
1871
2062
  this.edgeMap.set(key, { a: lo, b: hi, w, kind, lastFired, fireCount });
1872
2063
  });
1873
2064
  this._edgeLines = res.lines;
2065
+ this._edgeBytes = fileBytes(this.fileEdges);
1874
2066
  this._badLines += res.bad + invalid;
1875
2067
  // 端点不存在的边(对端被 forget / 或压缩前残留)不参与内存图
1876
2068
  for (const [key, e] of this.edgeMap) {
@@ -1999,10 +2191,19 @@ class NebulaMemory {
1999
2191
  };
2000
2192
  const nodeBytes = sizeOf(this.fileNodes);
2001
2193
  const edgeBytes = sizeOf(this.fileEdges);
2002
- if (payload.nodeBytes !== nodeBytes || payload.edgeBytes !== edgeBytes) {
2194
+ // 大小相等还不够:并发写时「最后一个写者」的文件大小会等于实际大小,
2195
+ // 但它的节点视图可能少了别人写的行 → 必须再比行数。
2196
+ const nodeLines = countNewlines(this.fileNodes);
2197
+ const edgeLines = countNewlines(this.fileEdges);
2198
+ if (
2199
+ payload.nodeBytes !== nodeBytes ||
2200
+ payload.edgeBytes !== edgeBytes ||
2201
+ num(payload.nodeLines, -1) !== nodeLines ||
2202
+ num(payload.edgeLines, -1) !== edgeLines
2203
+ ) {
2003
2204
  this._log(
2004
2205
  'info',
2005
- `index.thin.json 位点不符(nodes ${payload.nodeBytes}→${nodeBytes}, edges ${payload.edgeBytes}→${edgeBytes}),全量重建`
2206
+ `index.thin.json 位点不符(nodes ${payload.nodeBytes}→${nodeBytes} / 行 ${payload.nodeLines}→${nodeLines}, edges ${payload.edgeBytes}→${edgeBytes} / 行 ${payload.edgeLines}→${edgeLines}),全量重建`
2006
2207
  );
2007
2208
  return null;
2008
2209
  }
@@ -2022,6 +2223,8 @@ class NebulaMemory {
2022
2223
  this._tombstones = num(payload.tombstones, 0);
2023
2224
  this._nodeLines = num(payload.nodeLines, 0);
2024
2225
  this._edgeLines = num(payload.edgeLines, 0);
2226
+ this._nodeBytes = num(payload.nodeBytes, 0);
2227
+ this._edgeBytes = num(payload.edgeBytes, 0);
2025
2228
  this._badLines = 0;
2026
2229
 
2027
2230
  this.postings.clear();
@@ -2262,6 +2465,12 @@ class NebulaMemory {
2262
2465
  * 只写骨架:元数据 + 词频 + 原文偏移 + 边表,绝不写原文。
2263
2466
  */
2264
2467
  _writeThinIndex() {
2468
+ if (this._sawExternalAppend) {
2469
+ // 本实例的 nodes 视图缺了别人写的行,写出去就是「大小对、行数少」的假索引。
2470
+ // 放弃写:让磁盘上那份旧索引继续失效,下一个进程会全量重建(慢一次,但数据不丢)。
2471
+ this._log('info', 'skip thin index: external appends were observed (view is incomplete)');
2472
+ return;
2473
+ }
2265
2474
  const sizeOf = (f) => {
2266
2475
  try {
2267
2476
  return fs.statSync(f).size;
@@ -2311,8 +2520,10 @@ class NebulaMemory {
2311
2520
  thinVersion: THIN_VERSION,
2312
2521
  builtAt: new Date().toISOString(),
2313
2522
  dir: this.dir,
2314
- nodeBytes: sizeOf(this.fileNodes),
2315
- edgeBytes: sizeOf(this.fileEdges),
2523
+ // 用本实例已知边界,而不是 fs.statSync:文件可能被别的进程追加过,
2524
+ // 现取大小会让薄索引「内容旧、大小新」,校验永远通过、数据永远丢(2026-11-30)。
2525
+ nodeBytes: this._nodeBytes || sizeOf(this.fileNodes),
2526
+ edgeBytes: this._edgeBytes || sizeOf(this.fileEdges),
2316
2527
  nodeLines: this._nodeLines,
2317
2528
  edgeLines: this._edgeLines,
2318
2529
  tombstones: this._countTombstones(),
@@ -2411,7 +2622,10 @@ class NebulaMemory {
2411
2622
 
2412
2623
  _appendNode(n) {
2413
2624
  const rec = this._publicNode(n);
2625
+ // 写之前先看:文件比我以为的长 → 别的进程追加过,我的视图已经不全
2626
+ if (this._nodeBytes > 0 && fileBytes(this.fileNodes) !== this._nodeBytes) this._sawExternalAppend = true;
2414
2627
  const pos = appendLine(this.fileNodes, rec);
2628
+ if (pos) this._nodeBytes = pos.end;
2415
2629
  // 记下这一行的位置:薄索引写盘时要用它做原文懒加载
2416
2630
  if (pos) {
2417
2631
  Object.defineProperty(n, '_off', { value: pos.off, writable: true, enumerable: false, configurable: true });
@@ -2447,7 +2661,9 @@ class NebulaMemory {
2447
2661
 
2448
2662
  /** 追加一行边记录(同一对端点后写覆盖先写) */
2449
2663
  _saveEdge(edge) {
2450
- appendLine(this.fileEdges, { ...edge, ts: Date.now() });
2664
+ if (this._edgeBytes > 0 && fileBytes(this.fileEdges) !== this._edgeBytes) this._sawExternalAppend = true;
2665
+ const pos = appendLine(this.fileEdges, { ...edge, ts: Date.now() });
2666
+ if (pos) this._edgeBytes = pos.end;
2451
2667
  this._edgeLines++;
2452
2668
  this._writesSinceIndex++;
2453
2669
  }
@@ -2468,7 +2684,8 @@ class NebulaMemory {
2468
2684
  if (ma) ma.delete(edge.b);
2469
2685
  const mb = this.adj.get(edge.b);
2470
2686
  if (mb) mb.delete(edge.a);
2471
- appendLine(this.fileEdges, { a: edge.a, b: edge.b, deleted: true, ts: Date.now() });
2687
+ const pos = appendLine(this.fileEdges, { a: edge.a, b: edge.b, deleted: true, ts: Date.now() });
2688
+ if (pos) this._edgeBytes = pos.end;
2472
2689
  this._edgeLines++;
2473
2690
  this._writesSinceIndex++;
2474
2691
  }
@@ -2671,6 +2888,7 @@ class NebulaMemory {
2671
2888
  }
2672
2889
  atomicWrite(this.fileNodes, lines.length ? lines.join('\n') + '\n' : '');
2673
2890
  this._nodeLines = lines.length;
2891
+ this._nodeBytes = off; // off 已经累加到「全部重写后的总字节数」
2674
2892
  this._thinDirty = true;
2675
2893
  this._log('info', `compacted nodes.jsonl -> ${lines.length} lines`);
2676
2894
  }
@@ -2680,6 +2898,7 @@ class NebulaMemory {
2680
2898
  for (const e of this.edgeMap.values()) lines.push(JSON.stringify(e));
2681
2899
  atomicWrite(this.fileEdges, lines.length ? lines.join('\n') + '\n' : '');
2682
2900
  this._edgeLines = lines.length;
2901
+ this._edgeBytes = fileBytes(this.fileEdges);
2683
2902
  this._log('info', `compacted edges.jsonl -> ${lines.length} lines`);
2684
2903
  }
2685
2904
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.2.4",
3
+ "version": "1.2.6",
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",