nebula-memory-mcp 1.2.5 → 1.3.0
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 +46 -5
- package/mcp-server.mjs +102 -6
- package/memory/store.cjs +206 -11
- package/package.json +1 -1
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
|
-
|
|
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
|
-
|
|
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.
|
|
156
|
+
| **2.3.0**(+ 外部写入监听开关) | **1.3.0** | 1.0.9(待同步) | 引擎与上游 2.3.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.
|
|
48
|
+
version: '1.3.0',
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
// MCP 协议版本(当前规范)
|
|
@@ -55,6 +57,10 @@ const PROTOCOL_VERSION = '2024-11-05'
|
|
|
55
57
|
const NS_ROOT = path.join(DATA_DIR, '__ns__')
|
|
56
58
|
const memCache = new Map() // namespace -> NebulaMemory 实例
|
|
57
59
|
|
|
60
|
+
// 多进程/多 agent 共用同一目录时,打开这个开关:每次 recall 前增量吸收别的进程追加的行。
|
|
61
|
+
// 单进程内读写本来就是实时的,开不开都一样(只是多一次 stat)。
|
|
62
|
+
const ENGINE_OPTS = { watchExternalWrites: process.env.NEBULA_WATCH_EXTERNAL_WRITES === '1' }
|
|
63
|
+
|
|
58
64
|
function normalizeNamespace(ns) {
|
|
59
65
|
if (ns == null) return null
|
|
60
66
|
const s = String(ns).trim()
|
|
@@ -64,11 +70,91 @@ function normalizeNamespace(ns) {
|
|
|
64
70
|
return s
|
|
65
71
|
}
|
|
66
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
|
+
|
|
67
153
|
async function getMemory(ns) {
|
|
68
154
|
if (ns == null) return null // 调用方改用默认单库实例
|
|
69
155
|
if (!memCache.has(ns)) {
|
|
70
156
|
const dir = path.join(NS_ROOT, ns)
|
|
71
|
-
const m = new NebulaMemory({ dir, log: () => {} })
|
|
157
|
+
const m = new NebulaMemory({ dir, log: () => {}, options: ENGINE_OPTS })
|
|
72
158
|
await m.init()
|
|
73
159
|
memCache.set(ns, m)
|
|
74
160
|
}
|
|
@@ -160,14 +246,22 @@ const TOOLS = [
|
|
|
160
246
|
properties: { namespace: { type: 'string', description: '目标记忆库(可选)。不填=默认单库。' } },
|
|
161
247
|
},
|
|
162
248
|
},
|
|
249
|
+
{
|
|
250
|
+
name: 'list_namespaces',
|
|
251
|
+
description: '列出所有记忆库:默认库 + 每个 namespace 的节点/边数,以及当前命名空间模式(default / cwd-auto / env:<name>)。用它可以确认「多项目隔离」是否真的生效。',
|
|
252
|
+
inputSchema: { type: 'object', properties: {} },
|
|
253
|
+
},
|
|
163
254
|
]
|
|
164
255
|
|
|
165
256
|
// ── 工具执行 ─────────────────────────────────────────────────────────────
|
|
166
257
|
// defaultMem:默认单库实例;args.namespace 传了就切到对应子库。
|
|
167
258
|
async function callTool(name, args, defaultMem) {
|
|
168
|
-
const ns =
|
|
259
|
+
const { ns, from } = resolveNamespace(args.namespace)
|
|
169
260
|
const mem = ns == null ? defaultMem : await getMemory(ns)
|
|
170
261
|
switch (name) {
|
|
262
|
+
case 'list_namespaces': {
|
|
263
|
+
return { content: [{ type: 'text', text: JSON.stringify(listNamespaces(defaultMem), null, 2) }] }
|
|
264
|
+
}
|
|
171
265
|
case 'remember': {
|
|
172
266
|
const input = { text: String(args.text || '') }
|
|
173
267
|
if (args.kind) input.kind = args.kind
|
|
@@ -189,7 +283,7 @@ async function callTool(name, args, defaultMem) {
|
|
|
189
283
|
}
|
|
190
284
|
case 'stats': {
|
|
191
285
|
const s = await mem.stats()
|
|
192
|
-
return { content: [{ type: 'text', text: JSON.stringify(s) }] }
|
|
286
|
+
return { content: [{ type: 'text', text: JSON.stringify({ ...s, namespace: ns || '(default)', namespaceFrom: from }) }] }
|
|
193
287
|
}
|
|
194
288
|
case 'forget': {
|
|
195
289
|
const r = await mem.forget(String(args.id || ''))
|
|
@@ -221,7 +315,7 @@ async function main() {
|
|
|
221
315
|
process.env.MEMORY_NEBULA_DATA_DIR ||
|
|
222
316
|
path.join(os.homedir(), '.agent-memory')
|
|
223
317
|
)
|
|
224
|
-
const mem = new NebulaMemory({ dir, log: () => {} })
|
|
318
|
+
const mem = new NebulaMemory({ dir, log: () => {}, options: ENGINE_OPTS })
|
|
225
319
|
await mem.init()
|
|
226
320
|
const r = await mem.compact()
|
|
227
321
|
await mem.close()
|
|
@@ -230,8 +324,10 @@ async function main() {
|
|
|
230
324
|
}
|
|
231
325
|
|
|
232
326
|
// 默认单库实例(不传 namespace 时用),保持与旧版完全一致的行为。
|
|
233
|
-
const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {} })
|
|
327
|
+
const defaultMem = new NebulaMemory({ dir: DATA_DIR, log: () => {}, options: ENGINE_OPTS })
|
|
234
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}`)
|
|
235
331
|
|
|
236
332
|
readStdinLines(async (line) => {
|
|
237
333
|
let msg
|
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,6 +585,33 @@ function isPidAlive(pid) {
|
|
|
581
585
|
}
|
|
582
586
|
|
|
583
587
|
/** 追加一行(append 只写一行,崩溃最多丢最后一行,读入时会当坏行跳过) */
|
|
588
|
+
/** 数一个文件里有多少个换行(只看字节,不解析 JSON) */
|
|
589
|
+
function countNewlines(file) {
|
|
590
|
+
let buf;
|
|
591
|
+
try {
|
|
592
|
+
buf = fs.readFileSync(file);
|
|
593
|
+
} catch {
|
|
594
|
+
return 0;
|
|
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
|
+
|
|
584
615
|
function fileBytes(file) {
|
|
585
616
|
try {
|
|
586
617
|
return fs.statSync(file).size;
|
|
@@ -591,23 +622,22 @@ function fileBytes(file) {
|
|
|
591
622
|
|
|
592
623
|
function appendLine(file, obj) {
|
|
593
624
|
// 返回这一行在文件里的字节区间,供薄索引记录原文位置(懒加载用)。
|
|
594
|
-
// 先取文件长度当偏移:单进程追加写,长度即下一次写入的起点。
|
|
595
|
-
let off = 0;
|
|
596
|
-
try {
|
|
597
|
-
off = fs.statSync(file).size;
|
|
598
|
-
} catch {
|
|
599
|
-
off = 0;
|
|
600
|
-
}
|
|
601
625
|
const data = JSON.stringify(obj) + '\n';
|
|
602
626
|
const len = Buffer.byteLength(data, 'utf8');
|
|
627
|
+
// 先写再定位:O_APPEND 保证这次写在文件末尾的一段连续区间,
|
|
628
|
+
// 起点 = 写完后的大小 - 本行字节数。
|
|
629
|
+
// 旧实现是「先 stat 再写」——多进程同时写时 stat 到的位置会过期,
|
|
630
|
+
// 记进薄索引的偏移就是错的,懒加载会把别人那行的原文读给你(2026-11-30 修)。
|
|
603
631
|
const fd = fs.openSync(file, 'a');
|
|
632
|
+
let end = 0;
|
|
604
633
|
try {
|
|
605
634
|
fs.writeSync(fd, data, null, 'utf8');
|
|
635
|
+
end = fs.fstatSync(fd).size;
|
|
606
636
|
} finally {
|
|
607
637
|
fs.closeSync(fd);
|
|
608
638
|
}
|
|
609
639
|
// len 去掉行尾换行,只覆盖 JSON 本体;end 是下一行的起点字节位置
|
|
610
|
-
return { off, len: len - 1, end
|
|
640
|
+
return { off: Math.max(0, end - len), len: len - 1, end };
|
|
611
641
|
}
|
|
612
642
|
|
|
613
643
|
/** 人类可读的时间差(renderContext 用) */
|
|
@@ -694,6 +724,9 @@ class NebulaMemory {
|
|
|
694
724
|
// 「内容少、大小新」的假自洽索引,把别人新写的记录静默吞掉(2026-11-30 踩到)。
|
|
695
725
|
this._nodeBytes = 0;
|
|
696
726
|
this._edgeBytes = 0;
|
|
727
|
+
// 见过「别的进程追加」吗?见过就永不写薄索引 —— 并发下本实例的节点视图是残缺的,
|
|
728
|
+
// 写出来的薄索引会「大小对、行数少」,把别人写的行静默吞掉(2026-11-30 并发实测)。
|
|
729
|
+
this._sawExternalAppend = false;
|
|
697
730
|
this._badLines = 0;
|
|
698
731
|
this._indexDirty = true;
|
|
699
732
|
this._indexMeta = null;
|
|
@@ -1043,8 +1076,152 @@ class NebulaMemory {
|
|
|
1043
1076
|
* includeDormant?:boolean, includeArchived?:boolean, trackAccess?:boolean, debug?:boolean}} [options]
|
|
1044
1077
|
* @returns {Promise<Array<Object>>}
|
|
1045
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
|
+
|
|
1046
1221
|
async recall(query, options = {}) {
|
|
1047
1222
|
this._assertReady();
|
|
1223
|
+
// 多进程共用目录时,先把别的进程刚追加的行吸收进来(默认关;单进程不需要)
|
|
1224
|
+
if (this.opts.watchExternalWrites === true) this._syncExternalAppends();
|
|
1048
1225
|
// 2026-11-23:加错别字纠正 + 同义词 + 画像反哺扩展。
|
|
1049
1226
|
// 注意:recall() 与 recallFragments()/runRecall() 是两条独立路径,
|
|
1050
1227
|
// 扩展必须在这里也算一遍,否则 MCP/API 侧(走 recall)享受不到。
|
|
@@ -2014,10 +2191,19 @@ class NebulaMemory {
|
|
|
2014
2191
|
};
|
|
2015
2192
|
const nodeBytes = sizeOf(this.fileNodes);
|
|
2016
2193
|
const edgeBytes = sizeOf(this.fileEdges);
|
|
2017
|
-
|
|
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
|
+
) {
|
|
2018
2204
|
this._log(
|
|
2019
2205
|
'info',
|
|
2020
|
-
`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}),全量重建`
|
|
2021
2207
|
);
|
|
2022
2208
|
return null;
|
|
2023
2209
|
}
|
|
@@ -2279,6 +2465,12 @@ class NebulaMemory {
|
|
|
2279
2465
|
* 只写骨架:元数据 + 词频 + 原文偏移 + 边表,绝不写原文。
|
|
2280
2466
|
*/
|
|
2281
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
|
+
}
|
|
2282
2474
|
const sizeOf = (f) => {
|
|
2283
2475
|
try {
|
|
2284
2476
|
return fs.statSync(f).size;
|
|
@@ -2430,6 +2622,8 @@ class NebulaMemory {
|
|
|
2430
2622
|
|
|
2431
2623
|
_appendNode(n) {
|
|
2432
2624
|
const rec = this._publicNode(n);
|
|
2625
|
+
// 写之前先看:文件比我以为的长 → 别的进程追加过,我的视图已经不全
|
|
2626
|
+
if (this._nodeBytes > 0 && fileBytes(this.fileNodes) !== this._nodeBytes) this._sawExternalAppend = true;
|
|
2433
2627
|
const pos = appendLine(this.fileNodes, rec);
|
|
2434
2628
|
if (pos) this._nodeBytes = pos.end;
|
|
2435
2629
|
// 记下这一行的位置:薄索引写盘时要用它做原文懒加载
|
|
@@ -2467,6 +2661,7 @@ class NebulaMemory {
|
|
|
2467
2661
|
|
|
2468
2662
|
/** 追加一行边记录(同一对端点后写覆盖先写) */
|
|
2469
2663
|
_saveEdge(edge) {
|
|
2664
|
+
if (this._edgeBytes > 0 && fileBytes(this.fileEdges) !== this._edgeBytes) this._sawExternalAppend = true;
|
|
2470
2665
|
const pos = appendLine(this.fileEdges, { ...edge, ts: Date.now() });
|
|
2471
2666
|
if (pos) this._edgeBytes = pos.end;
|
|
2472
2667
|
this._edgeLines++;
|
|
@@ -2703,7 +2898,7 @@ class NebulaMemory {
|
|
|
2703
2898
|
for (const e of this.edgeMap.values()) lines.push(JSON.stringify(e));
|
|
2704
2899
|
atomicWrite(this.fileEdges, lines.length ? lines.join('\n') + '\n' : '');
|
|
2705
2900
|
this._edgeLines = lines.length;
|
|
2706
|
-
this._edgeBytes =
|
|
2901
|
+
this._edgeBytes = fileBytes(this.fileEdges);
|
|
2707
2902
|
this._log('info', `compacted edges.jsonl -> ${lines.length} lines`);
|
|
2708
2903
|
}
|
|
2709
2904
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nebula-memory-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|