nebula-memory-mcp 1.2.6 → 1.3.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/README.md CHANGED
@@ -46,10 +46,12 @@
46
46
  |---|---|---|
47
47
  | `remember` | 写入记忆 | `text`(必填)、`kind`、`importance`(1.0=永久置顶)、`tags` |
48
48
  | `recall` | 召回相关记忆 | `query`(必填)、`limit` |
49
- | `stats` | 记忆库统计 | 无 |
49
+ | `stats` | 记忆库统计(回报当前落在哪个库、怎么解析来的) | 无 |
50
50
  | `forget` | 按 id 删除 | `id`(必填) |
51
+ | `compact` | 压缩记忆库文件(清理追加历史) | 无 |
52
+ | `list_namespaces` | **列出默认库 + 各 namespace 的节点/边数**,确认隔离是否生效 | 无 |
51
53
 
52
- 四个工具都接受一个**可选** `namespace` 参数(见下节)。
54
+ 前五个工具都接受一个**可选** `namespace` 参数(见下节);`list_namespaces` 用来总览。
53
55
 
54
56
  ## 多库(namespace)
55
57
 
@@ -62,15 +64,54 @@
62
64
  - **不填** `namespace` → 用默认单库(路径即 `NEBULA_DATA_DIR`,老用户无需改任何配置);
63
65
  - **填了** → 用独立子库 `NEBULA_DATA_DIR/__ns__/<namespace>/`,各库完全隔离,召回也只在指定库内;
64
66
  - `namespace` 只允许字母、数字、`_`、`-`,长度 ≤ 64(防目录穿越,非法值会报错);
65
- - `recall` / `stats` / `forget` 同样支持 `namespace`,传了就只操作对应库。
67
+ - `recall` / `stats` / `forget` / `compact` 同样支持 `namespace`,传了就只操作对应库。
66
68
 
67
69
  典型用法:给不同项目或不同 Agent 各起一个 namespace,一句话切换记忆库,无需启动多个 MCP 进程。
68
70
 
71
+ ### 不想每次都传 namespace?两个环境变量(1.3.0 起)
72
+
73
+ | 环境变量 | 效果 |
74
+ |---|---|
75
+ | `NEBULA_DEFAULT_NAMESPACE=work` | 调用**不传** `namespace` 时,固定落到 `work` 这个子库 |
76
+ | `NEBULA_AUTO_NAMESPACE=1` | 调用**不传** `namespace` 时,按**当前工作目录**派生:`cwd-<sha1(cwd) 前 8 位>` |
77
+
78
+ ```json
79
+ {
80
+ "mcpServers": {
81
+ "agent-memory": {
82
+ "command": "npx",
83
+ "args": ["-y", "nebula-memory-mcp@latest"],
84
+ "env": {
85
+ "NEBULA_DATA_DIR": "/path/to/memory",
86
+ "NEBULA_AUTO_NAMESPACE": "1"
87
+ }
88
+ }
89
+ }
90
+ }
91
+ ```
92
+
93
+ > `NEBULA_AUTO_NAMESPACE` 是**按项目自动分库**(Cursor 写 Java 项目、Cline 写 Python 项目会自动落在不同库)。
94
+ > 它**默认关闭**:不传 namespace 就走默认单库,这是向后兼容的硬承诺 —— 自动分库会让老用户「记忆突然不见了」。
95
+
96
+ **优先级**:显式 `namespace` 参数 > `NEBULA_DEFAULT_NAMESPACE` > `NEBULA_AUTO_NAMESPACE`(cwd 派生)> 默认单库。
97
+
98
+ **验证隔离是否生效**:调 `list_namespaces`,会返回默认库与每个子库的节点/边数,以及当前模式(`default` / `cwd-auto` / `env:<name>`):
99
+
100
+ ```json
101
+ {
102
+ "default": { "dir": "...", "nodes": 1234, "edges": 2100 },
103
+ "namespaces": [{ "name": "work", "nodes": 42, "edges": 17 }],
104
+ "mode": "cwd-auto"
105
+ }
106
+ ```
107
+
69
108
  ## 环境变量
70
109
 
71
110
  | 变量 | 说明 | 默认 |
72
111
  |---|---|---|
73
- | `NEBULA_DATA_DIR` | 记忆数据目录 | `~/.agent-memory` |
112
+
113
+ | `NEBULA_AUTO_NAMESPACE` | `1` 时按 cwd 自动派生 namespace(仅在不传参数且未设默认库时生效) | 空(关闭) |
114
+ | `NEBULA_DEFAULT_NAMESPACE` | 不传 namespace 时固定使用的子库名 | 空(走默认单库) || `NEBULA_DATA_DIR` | 记忆数据目录 | `~/.agent-memory` |
74
115
 
75
116
  想让多个 AI 客户端共享记忆?把它们的 `NEBULA_DATA_DIR` 填成**同一个目录**即可。
76
117
 
@@ -112,7 +153,7 @@ agent-memory(引擎真源,9 个模块) ──人工对齐──▶ 本
112
153
 
113
154
  | 上游 `agent-memory` | **本仓库** | `nebula-workbuddy-mcp` | 备注 |
114
155
  |---|---|---|---|
115
- | **2.2.1**(薄索引一致性修复) | **1.2.5** | 1.0.8(待同步) | 引擎与上游 2.2.1 对齐 |
156
+ | **2.4.0**(+ Sleep Cycle) | **1.3.1** | 1.0.10(待同步) | 引擎与上游 2.4.0 对齐 |
116
157
 
117
158
  ## License
118
159
 
package/mcp-server.mjs CHANGED
@@ -25,6 +25,8 @@
25
25
  */
26
26
 
27
27
  import { createRequire } from 'node:module'
28
+ import { createHash } from 'node:crypto'
29
+ import fs from 'node:fs'
28
30
  import path from 'node:path'
29
31
  import os from 'node:os'
30
32
  import { fileURLToPath } from 'node:url'
@@ -43,7 +45,7 @@ const DATA_DIR = path.resolve(
43
45
  const SERVER_INFO = {
44
46
  name: 'agent-memory',
45
47
  // 与 package.json 的 version 保持一致(发版时必须一起改,见 README「引擎来历与同步」)
46
- version: '1.2.6',
48
+ version: '1.3.1',
47
49
  }
48
50
 
49
51
  // MCP 协议版本(当前规范)
@@ -68,6 +70,86 @@ function normalizeNamespace(ns) {
68
70
  return s
69
71
  }
70
72
 
73
+ // 命名空间解析优先级:显式参数 > NEBULA_DEFAULT_NAMESPACE > cwd 派生(opt-in)> 默认单库。
74
+ // 为什么 cwd 派生默认关:不传 namespace 走默认单库是**向后兼容**的硬承诺,
75
+ // 自动分库会让老用户「记忆突然不见了」。要按项目隔离就显式打开。
76
+ const AUTO_NS = /^(1|true|yes)$/i.test(String(process.env.NEBULA_AUTO_NAMESPACE || ''))
77
+ const DEFAULT_NS_ENV = String(process.env.NEBULA_DEFAULT_NAMESPACE || '').trim()
78
+
79
+ /** 按当前工作目录派生命名空间:cwd-<sha1(cwd) 前 8 位> */
80
+ function deriveCwdNamespace() {
81
+ return 'cwd-' + createHash('sha1').update(process.cwd()).digest('hex').slice(0, 8)
82
+ }
83
+
84
+ /**
85
+ * @returns {{ns: string|null, from: 'arg'|'env'|'cwd'|'default'}}
86
+ */
87
+ function resolveNamespace(explicit) {
88
+ const byArg = normalizeNamespace(explicit)
89
+ if (byArg) return { ns: byArg, from: 'arg' }
90
+ if (DEFAULT_NS_ENV) return { ns: normalizeNamespace(DEFAULT_NS_ENV), from: 'env' }
91
+ if (AUTO_NS) return { ns: deriveCwdNamespace(), from: 'cwd' }
92
+ return { ns: null, from: 'default' }
93
+ }
94
+
95
+ /** 数文件行数(只扫字节,不解析) */
96
+ function countLines(file) {
97
+ try {
98
+ const b = fs.readFileSync(file)
99
+ let n = 0
100
+ let i = -1
101
+ while ((i = b.indexOf(10, i + 1)) !== -1) n++
102
+ return n
103
+ } catch {
104
+ return 0
105
+ }
106
+ }
107
+
108
+ /** 文件字节数(不存在=0) */
109
+ function fileSize(file) {
110
+ try {
111
+ return fs.statSync(file).size
112
+ } catch {
113
+ return 0
114
+ }
115
+ }
116
+
117
+ /** 一个库的规模:薄索引位点对得上就用它(快),否则数行(可能正在被写) */
118
+ function libSize(dir) {
119
+ const nodesFile = path.join(dir, 'nodes.jsonl')
120
+ const edgeFile = path.join(dir, 'edges.jsonl')
121
+ try {
122
+ const p = JSON.parse(fs.readFileSync(path.join(dir, 'index.thin.json'), 'utf8'))
123
+ // 位点校验:薄索引可能是「刚 init 的空库」写的,之后又追加过 → 不能盲信
124
+ if (p.nodeBytes === fileSize(nodesFile) && p.edgeBytes === fileSize(edgeFile)) {
125
+ return { nodes: (p.nodes || []).length, edges: (p.edges || []).length }
126
+ }
127
+ } catch {
128
+ /* 没有薄索引:走数行 */
129
+ }
130
+ return { nodes: countLines(nodesFile), edges: countLines(edgeFile) }
131
+ }
132
+
133
+ /** 默认库 + 所有 namespace 的清单 */
134
+ function listNamespaces(defaultMem) {
135
+ const out = {
136
+ default: { dir: DATA_DIR, nodes: defaultMem ? defaultMem.nodes.size : 0, edges: defaultMem ? defaultMem.edgeMap.size : 0 },
137
+ namespaces: [],
138
+ mode: AUTO_NS ? 'cwd-auto' : DEFAULT_NS_ENV ? 'env:' + DEFAULT_NS_ENV : 'default',
139
+ }
140
+ try {
141
+ for (const ent of fs.readdirSync(NS_ROOT, { withFileTypes: true })) {
142
+ if (!ent.isDirectory()) continue
143
+ const dir = path.join(NS_ROOT, ent.name)
144
+ out.namespaces.push({ name: ent.name, dir, ...libSize(dir) })
145
+ }
146
+ } catch {
147
+ /* 还没有 __ns__ 目录:正常 */
148
+ }
149
+ out.namespaces.sort((a, b) => a.name.localeCompare(b.name))
150
+ return out
151
+ }
152
+
71
153
  async function getMemory(ns) {
72
154
  if (ns == null) return null // 调用方改用默认单库实例
73
155
  if (!memCache.has(ns)) {
@@ -164,14 +246,22 @@ const TOOLS = [
164
246
  properties: { namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' } },
165
247
  },
166
248
  },
249
+ {
250
+ name: 'list_namespaces',
251
+ description: '列出所有记忆库:默认库 + 每个 namespace 的节点/边数,以及当前命名空间模式(default / cwd-auto / env:<name>)。用它可以确认「多项目隔离」是否真的生效。',
252
+ inputSchema: { type: 'object', properties: {} },
253
+ },
167
254
  ]
168
255
 
169
256
  // ── 工具执行 ─────────────────────────────────────────────────────────────
170
257
  // defaultMem:默认单库实例;args.namespace 传了就切到对应子库。
171
258
  async function callTool(name, args, defaultMem) {
172
- const ns = normalizeNamespace(args.namespace)
259
+ const { ns, from } = resolveNamespace(args.namespace)
173
260
  const mem = ns == null ? defaultMem : await getMemory(ns)
174
261
  switch (name) {
262
+ case 'list_namespaces': {
263
+ return { content: [{ type: 'text', text: JSON.stringify(listNamespaces(defaultMem), null, 2) }] }
264
+ }
175
265
  case 'remember': {
176
266
  const input = { text: String(args.text || '') }
177
267
  if (args.kind) input.kind = args.kind
@@ -193,7 +283,7 @@ async function callTool(name, args, defaultMem) {
193
283
  }
194
284
  case 'stats': {
195
285
  const s = await mem.stats()
196
- return { content: [{ type: 'text', text: JSON.stringify(s) }] }
286
+ return { content: [{ type: 'text', text: JSON.stringify({ ...s, namespace: ns || '(default)', namespaceFrom: from }) }] }
197
287
  }
198
288
  case 'forget': {
199
289
  const r = await mem.forget(String(args.id || ''))
@@ -236,6 +326,8 @@ async function main() {
236
326
  // 默认单库实例(不传 namespace 时用),保持与旧版完全一致的行为。
237
327
  const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {}, options: ENGINE_OPTS })
238
328
  await defaultMem.init()
329
+ const nsMode = AUTO_NS ? `cwd-auto(当前 cwd → ${deriveCwdNamespace()})` : DEFAULT_NS_ENV ? `env:${DEFAULT_NS_ENV}` : 'default(不传 namespace 走默认单库)'
330
+ console.error(`[agent-memory] dataDir=${DATA_DIR} namespaceMode=${nsMode}`)
239
331
 
240
332
  readStdinLines(async (line) => {
241
333
  let msg
package/memory/store.cjs CHANGED
@@ -86,6 +86,14 @@ const DEFAULTS = {
86
86
  // ⚠️ 只对多进程/多 agent 共用同一目录的场景有意义:
87
87
  // 单进程内的读写本来就是实时的,开不开都一样(只是多一次 stat)。
88
88
  watchExternalWrites: false,
89
+ // —— 睡眠整理(Sleep Cycle):纯规则保洁,0 token ——
90
+ sleepOnClose: true, // close() 时「距上次 > sleepIntervalHours 且节点 > sleepMinNodes」自动跑一次
91
+ sleepIntervalHours: 24,
92
+ sleepMinNodes: 5000, // 小库没必要整理,阈值以下不触发
93
+ sleepEdgeIdleDays: 90, // 边:超过这么久没被触发、权重又极低,才裁
94
+ sleepEdgeMinWeight: 0.05,
95
+ sleepJunkDays: 30, // 寒暄类节点:这么久没被访问 + importance 极低,才归档
96
+ sleepJunkMaxImportance: 0.05,
89
97
  consolidateThreshold: 0.85, // episode 聚合阈值
90
98
  consolidateMinCluster: 2,
91
99
  consolidateMaxCluster: 12,
@@ -755,6 +763,7 @@ class NebulaMemory {
755
763
  this._lastConsolidateAt = 0;
756
764
  this._lastSummaryRefreshAt = 0; // L3 画像摘要上次刷新的时刻(tick 节流用)
757
765
  this._lastTickAt = 0;
766
+ this._lastSleepAt = 0;
758
767
  this._observeTurns = 0;
759
768
  this._turnCounter = 0;
760
769
  /** 无向边 key 归一(dynamics.js 也通过 mem._edgeKey 使用) */
@@ -830,6 +839,7 @@ class NebulaMemory {
830
839
  if (this._indexMeta) {
831
840
  this._lastConsolidateAt = num(this._indexMeta.lastConsolidateAt, 0);
832
841
  this._lastTickAt = num(this._indexMeta.lastTickAt, 0);
842
+ this._lastSleepAt = num(this._indexMeta.lastSleepAt, 0);
833
843
  this._traceSeq = num(this._indexMeta.traceSeq, 0);
834
844
  this._recallTotal = num(this._indexMeta.recallTotal, 0);
835
845
  // 首次升级到带计数器的版本时,index meta 里没有 recallTotal;
@@ -864,6 +874,20 @@ class NebulaMemory {
864
874
  async close() {
865
875
  if (!this._ready) return;
866
876
  if (this._autoCompactTimer) { clearTimeout(this._autoCompactTimer); this._autoCompactTimer = null; }
877
+ // 睡眠整理:低频 + 大库才跑(默认开;opts.sleepOnClose=false 可关)
878
+ if (this.opts.sleepOnClose !== false) {
879
+ const interval = num(this.opts.sleepIntervalHours, 24) * 3600000;
880
+ if (
881
+ this.nodes.size > num(this.opts.sleepMinNodes, 5000) &&
882
+ Date.now() - num(this._lastSleepAt, 0) > interval
883
+ ) {
884
+ try {
885
+ await this.sleepCycle({ now: Date.now() });
886
+ } catch (e) {
887
+ this._log('warn', `sleepCycle failed (ignored): ${e.message}`);
888
+ }
889
+ }
890
+ }
867
891
  this._flushPending();
868
892
  this._maybeCompact();
869
893
  if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
@@ -875,6 +899,101 @@ class NebulaMemory {
875
899
  this._closed = true;
876
900
  }
877
901
 
902
+ /**
903
+ * 睡眠整理(Sleep Cycle)—— 纯规则的本地保洁,0 token。
904
+ *
905
+ * 做三件事:① 裁掉「极低权重 + 从未触发 + 长期未动」的边;② 把长期没被访问、
906
+ * importance 极低的短寒暄节点标记 archived(**不删除**,随时可恢复);
907
+ * ③ 有改动就做一次物理压实(重复行合并 + JSONL 重写)。
908
+ *
909
+ * 护栏(这些一律不清理):importance >= 0.9、summary 层、profile 类型、
910
+ * meta 里带 hindsightSynced / synced / experience / observation 的节点。
911
+ *
912
+ * @param {{now?:number, dryRun?:boolean}} [opts]
913
+ * @returns {Promise<Object>} 统计(dryRun 时不落盘)
914
+ */
915
+ async sleepCycle(opts = {}) {
916
+ this._assertReady();
917
+ const now = num(opts.now, Date.now());
918
+ const dryRun = opts.dryRun === true;
919
+ const DAY = 86400000;
920
+ const t0 = Date.now();
921
+ const edgeIdle = num(this.opts.sleepEdgeIdleDays, 90) * DAY;
922
+ const edgeMinW = num(this.opts.sleepEdgeMinWeight, 0.05);
923
+ const junkIdle = num(this.opts.sleepJunkDays, 30) * DAY;
924
+ const junkMaxImp = num(this.opts.sleepJunkMaxImportance, 0.05);
925
+ const result = {
926
+ at: now,
927
+ dryRun,
928
+ edgesPruned: 0,
929
+ junkArchived: 0,
930
+ compacted: false,
931
+ durationMs: 0,
932
+ before: { nodes: this.nodes.size, edges: this.edgeMap.size },
933
+ after: null,
934
+ };
935
+
936
+ const isProtected = (n) => {
937
+ if (n.archived) return true;
938
+ if (num(n.importance, 0) >= 0.9) return true;
939
+ if (n.layer === 'summary') return true;
940
+ if (n.kind === 'profile') return true;
941
+ const m = n.meta || {};
942
+ if (m.hindsightSynced || m.synced === true || m.experience || m.observation) return true;
943
+ return false;
944
+ };
945
+
946
+ // ① 断边:只删边,不删节点
947
+ for (const e of [...this.edgeMap.values()]) {
948
+ if (num(e.fireCount, 0) > 0) continue;
949
+ if (num(e.w, 1) >= edgeMinW) continue;
950
+ if (now - num(e.lastFired, now) < edgeIdle) continue;
951
+ result.edgesPruned++;
952
+ if (!dryRun) this._removeEdge(e);
953
+ }
954
+
955
+ // ② 垃圾归档:只归档短寒暄,正文(哪怕很短)只要不是寒暄就不动
956
+ const JUNK = /^(嗯+|恩+|哦+|好|好的|行|可以|谢谢|多谢|收到|明白|了解|知道了|ok|okay|thanks|thank you|在吗)[。!?.!?~~]*$/i;
957
+ for (const n of [...this.nodes.values()]) {
958
+ if (isProtected(n)) continue;
959
+ if (num(n.importance, 0) > junkMaxImp) continue;
960
+ if (now - num(n.lastAccessAt, num(n.ts, now)) < junkIdle) continue;
961
+ const txt = String(n.text || '').trim();
962
+ if (!txt || txt.length > 12 || !JUNK.test(txt)) continue;
963
+ result.junkArchived++;
964
+ if (dryRun) continue;
965
+ this._unindexNode(n);
966
+ n.archived = true;
967
+ n.archivedAt = now;
968
+ this._indexNode(n);
969
+ this._appendNode(n);
970
+ }
971
+
972
+ // ③ 物理压实:有改动才做
973
+ if (!dryRun && (result.edgesPruned > 0 || result.junkArchived > 0)) {
974
+ this._flushPending();
975
+ this._compactNodesNow = true;
976
+ this._maybeCompact();
977
+ this._compactNodesNow = false;
978
+ this._writeIndexSnapshot();
979
+ this._writeThinIndex();
980
+ result.compacted = true;
981
+ }
982
+
983
+ if (!dryRun) {
984
+ this._lastSleepAt = now;
985
+ this._indexDirty = true;
986
+ this._writeIndexSnapshot();
987
+ }
988
+ result.after = { nodes: this.nodes.size, edges: this.edgeMap.size };
989
+ result.durationMs = Date.now() - t0;
990
+ this._log(
991
+ 'info',
992
+ `sleepCycle${dryRun ? ' (dryRun)' : ''}: edges-${result.edgesPruned} junk-${result.junkArchived} compacted=${result.compacted} ${result.durationMs}ms`
993
+ );
994
+ return result;
995
+ }
996
+
878
997
  /**
879
998
  * 手动压缩(实例保持可用):落 pending → 强制重写 nodes/edges jsonl → 落索引快照。
880
999
  * 只序列化内存里的存活集,规模再大也是亚秒级;收益是磁盘文件和下一次冷启动。
@@ -2123,6 +2242,7 @@ class NebulaMemory {
2123
2242
  traceSeq: payload.traceSeq,
2124
2243
  lastConsolidateAt: payload.lastConsolidateAt,
2125
2244
  lastTickAt: payload.lastTickAt,
2245
+ lastSleepAt: payload.lastSleepAt,
2126
2246
  };
2127
2247
  }
2128
2248
  const stale =
@@ -2337,6 +2457,7 @@ class NebulaMemory {
2337
2457
  recallTotal: payload.recallTotal,
2338
2458
  lastConsolidateAt: payload.lastConsolidateAt,
2339
2459
  lastTickAt: payload.lastTickAt,
2460
+ lastSleepAt: payload.lastSleepAt,
2340
2461
  };
2341
2462
  // 薄索引是权威,无需因为 index.json 陈旧就重写 19MB 快照
2342
2463
  this._indexDirty = false;
@@ -2532,6 +2653,7 @@ class NebulaMemory {
2532
2653
  recallTotal: this._recallTotal,
2533
2654
  lastConsolidateAt: this._lastConsolidateAt,
2534
2655
  lastTickAt: this._lastTickAt,
2656
+ lastSleepAt: this._lastSleepAt,
2535
2657
  nodes,
2536
2658
  edges,
2537
2659
  };
@@ -2836,6 +2958,7 @@ class NebulaMemory {
2836
2958
  recallTotal: this._recallTotal,
2837
2959
  lastConsolidateAt: this._lastConsolidateAt,
2838
2960
  lastTickAt: this._lastTickAt,
2961
+ lastSleepAt: this._lastSleepAt,
2839
2962
  postings,
2840
2963
  };
2841
2964
  atomicWrite(this.fileIndex, JSON.stringify(payload));
@@ -2853,6 +2976,7 @@ class NebulaMemory {
2853
2976
  recallTotal: payload.recallTotal,
2854
2977
  lastConsolidateAt: payload.lastConsolidateAt,
2855
2978
  lastTickAt: payload.lastTickAt,
2979
+ lastSleepAt: payload.lastSleepAt,
2856
2980
  };
2857
2981
  }
2858
2982
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nebula-memory-mcp",
3
- "version": "1.2.6",
3
+ "version": "1.3.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",