nebula-memory-mcp 1.3.1 → 1.4.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 +5 -1
- package/mcp-server.mjs +80 -6
- package/memory/conflict.cjs +121 -0
- package/memory/pinyin-data.cjs +3 -0
- package/memory/pinyin.cjs +182 -0
- package/memory/recall.cjs +2 -0
- package/memory/store.cjs +183 -14
- package/package.json +1 -1
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地拼音模糊匹配(零运行时依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 目标:让纯英文(拼音)输入能命中中文记忆,并对常见方言模糊音做规则扩展。
|
|
5
|
+
* 不含任何外部词典/模型:字形→音节表来自随包内置的 `pinyin-data.cjs`
|
|
6
|
+
* (由 pypinyin 0.55.0 生成,仅覆盖 GB2312 常用 6763 字,单字取默认读音)。
|
|
7
|
+
*
|
|
8
|
+
* 索引侧:为每段连续汉字生成「音节滑动窗口」token:
|
|
9
|
+
* py:fuwuqi —— 连续 1~4 个音节的拼接(用于 fuwuqi 这类整词输入)
|
|
10
|
+
* pyi:fwq —— 对应声母首字母拼接(用于 fwq 缩写输入)
|
|
11
|
+
* 查询侧:纯拉丁 token 先查 py: / pyi: 精确命中,再用模糊音规则扩展变体。
|
|
12
|
+
*
|
|
13
|
+
* 注意:多音字只取默认读音;非汉字、罕见字(GB2312 外)不产生拼音 token。
|
|
14
|
+
*/
|
|
15
|
+
'use strict'
|
|
16
|
+
|
|
17
|
+
const RAW = require('./pinyin-data.cjs')
|
|
18
|
+
|
|
19
|
+
/** 单字 → 音节(小写、无声调) */
|
|
20
|
+
const HANZI = RAW
|
|
21
|
+
|
|
22
|
+
/** 从音节表里收集合法音节集合,用于查询串切分 */
|
|
23
|
+
const SYLLABLES = new Set()
|
|
24
|
+
for (const syl of Object.values(HANZI)) {
|
|
25
|
+
const s = String(syl).toLowerCase()
|
|
26
|
+
if (/^[a-z]{1,6}$/.test(s)) SYLLABLES.add(s)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const LATIN = /^[a-z][a-z0-9]*$/i
|
|
30
|
+
|
|
31
|
+
/** 模糊音规则:声母(按音节开头匹配)与韵母(按音节结尾匹配) */
|
|
32
|
+
const INITIAL_RULES = {
|
|
33
|
+
zh: 'z',
|
|
34
|
+
z: 'zh',
|
|
35
|
+
ch: 'c',
|
|
36
|
+
c: 'ch',
|
|
37
|
+
sh: 's',
|
|
38
|
+
s: 'sh',
|
|
39
|
+
n: 'l',
|
|
40
|
+
l: 'n',
|
|
41
|
+
f: 'h',
|
|
42
|
+
h: 'f',
|
|
43
|
+
r: 'l',
|
|
44
|
+
}
|
|
45
|
+
const FINAL_RULES = {
|
|
46
|
+
an: 'ang',
|
|
47
|
+
ang: 'an',
|
|
48
|
+
en: 'eng',
|
|
49
|
+
eng: 'en',
|
|
50
|
+
in: 'ing',
|
|
51
|
+
ing: 'in',
|
|
52
|
+
ian: 'iang',
|
|
53
|
+
iang: 'ian',
|
|
54
|
+
uan: 'uang',
|
|
55
|
+
uang: 'uan',
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isLatinWord(token) {
|
|
59
|
+
return typeof token === 'string' && token.length >= 2 && token.length <= 32 && LATIN.test(token)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isHanzi(ch) {
|
|
63
|
+
return Object.prototype.hasOwnProperty.call(HANZI, ch)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 声母:zh/ch/sh 取两位,其余取首字母(含元音开头) */
|
|
67
|
+
function initialOf(syl) {
|
|
68
|
+
const s = syl.toLowerCase()
|
|
69
|
+
if (s.startsWith('zh') || s.startsWith('ch') || s.startsWith('sh')) return s.slice(0, 2)
|
|
70
|
+
return s.slice(0, 1)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 贪婪切分拼音串为音节(最长匹配);无法匹配的字符原样保留为单字符 token。
|
|
75
|
+
* 只用于查询侧模糊变体,不要求百分百语言学正确。
|
|
76
|
+
*/
|
|
77
|
+
function segment(word) {
|
|
78
|
+
const s = word.toLowerCase()
|
|
79
|
+
const out = []
|
|
80
|
+
let i = 0
|
|
81
|
+
while (i < s.length) {
|
|
82
|
+
let matched = ''
|
|
83
|
+
for (let len = Math.min(6, s.length - i); len >= 1; len -= 1) {
|
|
84
|
+
const piece = s.slice(i, i + len)
|
|
85
|
+
if (SYLLABLES.has(piece)) { matched = piece; break }
|
|
86
|
+
}
|
|
87
|
+
if (matched) { out.push(matched); i += matched.length } else { out.push(s[i]); i += 1 }
|
|
88
|
+
}
|
|
89
|
+
return out
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 单个音节的模糊变体(只做一次替换,避免组合爆炸) */
|
|
93
|
+
function syllableVariants(syl) {
|
|
94
|
+
const out = new Set([syl])
|
|
95
|
+
for (const [from, to] of Object.entries(INITIAL_RULES)) {
|
|
96
|
+
if (syl.startsWith(from)) out.add(to + syl.slice(from.length))
|
|
97
|
+
}
|
|
98
|
+
for (const [from, to] of Object.entries(FINAL_RULES)) {
|
|
99
|
+
if (syl.endsWith(from)) out.add(syl.slice(0, -from.length) + to)
|
|
100
|
+
}
|
|
101
|
+
return [...out]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 生成一个纯拉丁查询词的模糊变体(包含原词)。
|
|
106
|
+
* 对音节逐个替换,再乘起来;上限 40,避免拼音长串爆炸。
|
|
107
|
+
*/
|
|
108
|
+
function fuzzyVariants(word, { max = 40 } = {}) {
|
|
109
|
+
if (!isLatinWord(word)) return [word]
|
|
110
|
+
const parts = segment(word)
|
|
111
|
+
let acc = ['']
|
|
112
|
+
for (const part of parts) {
|
|
113
|
+
const variants = SYLLABLES.has(part) ? syllableVariants(part) : [part]
|
|
114
|
+
const next = []
|
|
115
|
+
for (const prefix of acc) {
|
|
116
|
+
for (const v of variants) {
|
|
117
|
+
next.push(prefix + v)
|
|
118
|
+
if (next.length >= max) break
|
|
119
|
+
}
|
|
120
|
+
if (next.length >= max) break
|
|
121
|
+
}
|
|
122
|
+
acc = next
|
|
123
|
+
}
|
|
124
|
+
const uniq = [...new Set(acc)].filter((w) => w.length > 0)
|
|
125
|
+
return uniq.includes(word) ? uniq : [word, ...uniq].slice(0, max)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 文本 → 拼音 token 频次表。
|
|
130
|
+
* 每段连续汉字生成 1~maxWindow 个音节的滑动窗口,
|
|
131
|
+
* 分别产出 `py:<拼接>` 与 `pyi:<声母拼接>`。
|
|
132
|
+
* @returns {Map<string, number>}
|
|
133
|
+
*/
|
|
134
|
+
function indexTokens(text, { maxWindow = 4, maxTokens = 96 } = {}) {
|
|
135
|
+
const out = new Map()
|
|
136
|
+
if (typeof text !== 'string' || !text) return out
|
|
137
|
+
|
|
138
|
+
// 先按非汉字切成若干「连续汉字 run」,再对每个 run 生成长窗口优先的 token 列表。
|
|
139
|
+
// 最后按 run 轮转取 token(round-robin),保证长文本尾部的词不会因为前面的
|
|
140
|
+
// 大段文字把预算吃光——这是按节点顺序截断最容易踩的坑。
|
|
141
|
+
const runs = []
|
|
142
|
+
let run = []
|
|
143
|
+
for (const ch of text) {
|
|
144
|
+
const syl = HANZI[ch]
|
|
145
|
+
if (syl) {
|
|
146
|
+
run.push(String(syl).toLowerCase())
|
|
147
|
+
} else if (run.length) {
|
|
148
|
+
runs.push(run)
|
|
149
|
+
run = []
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (run.length) runs.push(run)
|
|
153
|
+
|
|
154
|
+
const lists = runs.map((syls) => {
|
|
155
|
+
const inits = syls.map(initialOf)
|
|
156
|
+
const list = []
|
|
157
|
+
// 词级 2~3 音节最常用:先 3,再 2,最后 4(长词),截断时优先保住查得到词。
|
|
158
|
+
const lengths = [3, 2, 4].filter((n) => n >= 2 && n <= maxWindow && n <= syls.length)
|
|
159
|
+
for (const n of lengths) {
|
|
160
|
+
for (let i = 0; i + n <= syls.length; i += 1) {
|
|
161
|
+
list.push('py:' + syls.slice(i, i + n).join(''))
|
|
162
|
+
list.push('pyi:' + inits.slice(i, i + n).join(''))
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return list
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
let added = 0
|
|
169
|
+
const maxLen = lists.reduce((m, l) => Math.max(m, l.length), 0)
|
|
170
|
+
outer: for (let i = 0; i < maxLen; i += 1) {
|
|
171
|
+
for (const list of lists) {
|
|
172
|
+
if (i >= list.length) continue
|
|
173
|
+
const token = list[i]
|
|
174
|
+
out.set(token, (out.get(token) || 0) + 1)
|
|
175
|
+
added += 1
|
|
176
|
+
if (added >= maxTokens) break outer
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return out
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
module.exports = { isLatinWord, isHanzi, fuzzyVariants, indexTokens, segment, initialOf }
|
package/memory/recall.cjs
CHANGED
|
@@ -61,6 +61,7 @@ function eligible(node, opts) {
|
|
|
61
61
|
if (!node || node.deleted) return false;
|
|
62
62
|
if (node.archived && !opts.includeArchived) return false;
|
|
63
63
|
if (node.dormant && !opts.includeDormant && !opts.includeArchived) return false;
|
|
64
|
+
if (node.meta && node.meta.supersededBy && !opts.includeSuperseded) return false;
|
|
64
65
|
return true;
|
|
65
66
|
}
|
|
66
67
|
|
|
@@ -186,6 +187,7 @@ function runRecall(mem, query, options = {}) {
|
|
|
186
187
|
const opts = {
|
|
187
188
|
includeArchived: options.includeArchived === true,
|
|
188
189
|
includeDormant: options.includeDormant === true,
|
|
190
|
+
includeSuperseded: options.includeSuperseded === true,
|
|
189
191
|
hops: options.hops,
|
|
190
192
|
alpha: options.alpha,
|
|
191
193
|
gamma: options.gamma,
|
package/memory/store.cjs
CHANGED
|
@@ -43,6 +43,8 @@ const recallSynonyms = require('./synonyms.cjs');
|
|
|
43
43
|
const profileRecall = require('./profile-recall.cjs');
|
|
44
44
|
const typoCorrect = require('./typo-fix.cjs');
|
|
45
45
|
const pii = require('./pii.cjs');
|
|
46
|
+
const conflict = require('./conflict.cjs');
|
|
47
|
+
const pinyin = require('./pinyin.cjs');
|
|
46
48
|
|
|
47
49
|
const { LAYER, EDGE_KIND, SUMMARY_KIND } = dynamics;
|
|
48
50
|
|
|
@@ -94,6 +96,8 @@ const DEFAULTS = {
|
|
|
94
96
|
sleepEdgeMinWeight: 0.05,
|
|
95
97
|
sleepJunkDays: 30, // 寒暄类节点:这么久没被访问 + importance 极低,才归档
|
|
96
98
|
sleepJunkMaxImportance: 0.05,
|
|
99
|
+
// 谓词级冲突裁决:写入时识别「同一主体、极性相反」的旧陈述并标 superseded(只降权不删)
|
|
100
|
+
conflictResolve: true,
|
|
97
101
|
consolidateThreshold: 0.85, // episode 聚合阈值
|
|
98
102
|
consolidateMinCluster: 2,
|
|
99
103
|
consolidateMaxCluster: 12,
|
|
@@ -108,6 +112,10 @@ const DEFAULTS = {
|
|
|
108
112
|
compactionRatio: 2.5, // jsonl 行数 > 存活数×该比例 时在 close 时压缩
|
|
109
113
|
minScore: 0.01, // recall 最低分(过滤纯噪音命中)
|
|
110
114
|
sanitizeContent: true, // 写入时清洗正文(剔除思考标签、丢弃纯 JSON 工具输出);关掉则原样存储
|
|
115
|
+
// 本地拼音检索:写入时为连续汉字生成 py:/pyi: 滑动窗口 token;纯拼音查询会自动命中。
|
|
116
|
+
// pinyinIndex 控制是否建拼音索引,fuzzyPinyin 控制查询侧模糊音扩展。
|
|
117
|
+
pinyinIndex: false, // 开启后为中文记忆建 py:/pyi: 拼音窗口(薄索引约 +1.5KB/节点,冷启动变慢)
|
|
118
|
+
fuzzyPinyin: true,
|
|
111
119
|
|
|
112
120
|
// —— v2 记忆星云:召回片段 / trace / 动力学 ——
|
|
113
121
|
recallTopK: 8, // recallFragments 默认返回片段数
|
|
@@ -891,9 +899,18 @@ class NebulaMemory {
|
|
|
891
899
|
this._flushPending();
|
|
892
900
|
this._maybeCompact();
|
|
893
901
|
if (this._traceLines > num(this.opts.traceMax, 200)) this._compactTrace();
|
|
894
|
-
|
|
895
|
-
//
|
|
896
|
-
|
|
902
|
+
// 快照/薄索引都是缓存,close 不能因为一次并发 rename 失败就抛异常:
|
|
903
|
+
// 旧快照会在下次启动时因位点校验不符被重建,数据本身在 jsonl 里。
|
|
904
|
+
try {
|
|
905
|
+
this._writeIndexSnapshot();
|
|
906
|
+
} catch (e) {
|
|
907
|
+
this._log('warn', `close: index.json 写入失败(下次启动会重建): ${e.message}`);
|
|
908
|
+
}
|
|
909
|
+
try {
|
|
910
|
+
this._writeThinIndex();
|
|
911
|
+
} catch (e) {
|
|
912
|
+
this._log('warn', `close: index.thin.json 写入失败(下次启动会全量重建): ${e.message}`);
|
|
913
|
+
}
|
|
897
914
|
this._log('info', `closed dir=${this.dir} nodes=${this.nodes.size} edges=${this.edgeMap.size}`);
|
|
898
915
|
this._ready = false;
|
|
899
916
|
this._closed = true;
|
|
@@ -1102,6 +1119,37 @@ class NebulaMemory {
|
|
|
1102
1119
|
return this._rememberOne({ ...input, text: raw, _redactTypes: redacted.types });
|
|
1103
1120
|
}
|
|
1104
1121
|
|
|
1122
|
+
/**
|
|
1123
|
+
* 冲突裁决:新记录若与既有记录「同主体、同谓词类、极性相反」,把旧的标 superseded。
|
|
1124
|
+
* 铁律:只降权不删除;importance>=0.9 的永固节点豁免;已经 superseded 的不重复处理。
|
|
1125
|
+
* @returns {{id:string, claim:Object, supersededBy:string[]}|null}
|
|
1126
|
+
*/
|
|
1127
|
+
_markConflicts(rec, now) {
|
|
1128
|
+
if (this.opts.conflictResolve === false) return null;
|
|
1129
|
+
const claim = conflict.parseClaim(rec.text);
|
|
1130
|
+
if (!claim) return null;
|
|
1131
|
+
rec.meta = { ...(rec.meta || {}), claim };
|
|
1132
|
+
const superseded = [];
|
|
1133
|
+
for (const old of this.nodes.values()) {
|
|
1134
|
+
if (old.id === rec.id) continue;
|
|
1135
|
+
const c = old.meta && old.meta.claim;
|
|
1136
|
+
if (!c) continue;
|
|
1137
|
+
if (!conflict.isConflict(c, claim)) continue;
|
|
1138
|
+
if (num(old.importance, 0) >= 0.9) continue; // 永固节点豁免
|
|
1139
|
+
if (old.meta.supersededBy) continue;
|
|
1140
|
+
this._unindexNode(old);
|
|
1141
|
+
old.meta = { ...old.meta, supersededBy: rec.id, supersededAt: now };
|
|
1142
|
+
old.importance = clamp(num(old.importance, 0.5) * 0.3, num(this.opts.importanceFloor, 0.02), 1);
|
|
1143
|
+
this._indexNode(old);
|
|
1144
|
+
this._appendNode(old);
|
|
1145
|
+
superseded.push(old.id);
|
|
1146
|
+
}
|
|
1147
|
+
if (superseded.length) {
|
|
1148
|
+
this._log('info', `conflict: "${claim.s}" 的新陈述取代了 ${superseded.length} 条旧记忆`);
|
|
1149
|
+
}
|
|
1150
|
+
return { id: rec.id, claim, supersededBy: superseded };
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1105
1153
|
/** 单条写入(被 remember 调用;超长已在调用方切块)。 */
|
|
1106
1154
|
async _rememberOne(input = {}) {
|
|
1107
1155
|
const rec = this._buildRecord(input);
|
|
@@ -1128,7 +1176,7 @@ class NebulaMemory {
|
|
|
1128
1176
|
this._indexDirty = true;
|
|
1129
1177
|
this._maybeFlushIndex();
|
|
1130
1178
|
this._log('debug', `dedupe hit ${dup.id}`);
|
|
1131
|
-
return { id: dup.id, deduped: true, node: this._publicNode(dup) };
|
|
1179
|
+
return { id: dup.id, deduped: true, node: this._publicNode(dup), superseded: [] };
|
|
1132
1180
|
}
|
|
1133
1181
|
|
|
1134
1182
|
this.nodes.set(rec.id, rec);
|
|
@@ -1138,7 +1186,14 @@ class NebulaMemory {
|
|
|
1138
1186
|
this._dfVersion++;
|
|
1139
1187
|
this._indexDirty = true;
|
|
1140
1188
|
this._maybeFlushIndex();
|
|
1141
|
-
|
|
1189
|
+
// 冲突裁决:必须在新节点已落库之后跑(旧记录的 supersededBy 要指向真实 id)
|
|
1190
|
+
const conflictResult = this._markConflicts(rec, rec.ts);
|
|
1191
|
+
return {
|
|
1192
|
+
id: rec.id,
|
|
1193
|
+
deduped: false,
|
|
1194
|
+
node: this._publicNode(rec),
|
|
1195
|
+
superseded: conflictResult ? conflictResult.supersededBy : [],
|
|
1196
|
+
};
|
|
1142
1197
|
}
|
|
1143
1198
|
|
|
1144
1199
|
/**
|
|
@@ -1377,6 +1432,11 @@ class NebulaMemory {
|
|
|
1377
1432
|
|
|
1378
1433
|
const now = Date.now();
|
|
1379
1434
|
const w = this.weights;
|
|
1435
|
+
// 召回策略:hybrid(默认,四臂融合)/ lex(纯词法)/ graph(词法 × 图权重加强)
|
|
1436
|
+
const strategy = options.strategy || 'hybrid';
|
|
1437
|
+
if (!['lex', 'graph', 'hybrid'].includes(strategy)) {
|
|
1438
|
+
throw new Error(`invalid strategy: ${strategy}(支持 lex | graph | hybrid)`);
|
|
1439
|
+
}
|
|
1380
1440
|
const halfLife = Math.max(0.5, num(this.opts.halfLifeDays, 30));
|
|
1381
1441
|
const scored = [];
|
|
1382
1442
|
|
|
@@ -1386,6 +1446,8 @@ class NebulaMemory {
|
|
|
1386
1446
|
if (kinds && !kinds.includes(node.kind)) continue;
|
|
1387
1447
|
if (options.tag && !node.tags.includes(options.tag)) continue;
|
|
1388
1448
|
if (!includeArchived && node.archived) continue;
|
|
1449
|
+
// 冲突裁决:被新陈述取代的旧记忆默认不参与召回(includeSuperseded=true 可查历史)
|
|
1450
|
+
if (options.includeSuperseded !== true && node.meta && node.meta.supersededBy) continue;
|
|
1389
1451
|
if (!includeDormant && node.dormant) continue;
|
|
1390
1452
|
|
|
1391
1453
|
const lexical = this._tfidfCosine(node._tf, qv);
|
|
@@ -1398,7 +1460,14 @@ class NebulaMemory {
|
|
|
1398
1460
|
const graphFactor = 1 + w.graph * Math.min(this.opts.graphBonusCap, this._neighborWeight(id, cand) * this.opts.graphBonusScale);
|
|
1399
1461
|
const dormantFactor = node.dormant ? this.opts.dormantPenalty : 1;
|
|
1400
1462
|
const lexicalPart = w.tfidf === 1 ? lexical : Math.pow(lexical, w.tfidf);
|
|
1401
|
-
|
|
1463
|
+
// 三种策略共用同一候选集,只在打分公式上分叉:
|
|
1464
|
+
// lex → 纯词法(精确匹配时最稳,不受陈旧度/图影响)
|
|
1465
|
+
// graph → 词法 × 图权重(同一次召回里共同激活过的邻居加分)
|
|
1466
|
+
// hybrid → 四臂默认公式(词法 × 衰减 × 重要性 × 图 × dormant)
|
|
1467
|
+
let score;
|
|
1468
|
+
if (strategy === 'lex') score = lexicalPart;
|
|
1469
|
+
else if (strategy === 'graph') score = lexicalPart * graphFactor;
|
|
1470
|
+
else score = lexicalPart * decay * impFactor * graphFactor * dormantFactor;
|
|
1402
1471
|
if (!(score >= minScore)) continue;
|
|
1403
1472
|
|
|
1404
1473
|
/** @type {any} */
|
|
@@ -1423,6 +1492,16 @@ class NebulaMemory {
|
|
|
1423
1492
|
importance: round(impFactor, 4),
|
|
1424
1493
|
graph: round(graphFactor, 4),
|
|
1425
1494
|
};
|
|
1495
|
+
// 命中词:节点里实际出现过的 query token,按 query 权重排序(给 explain_recall 用)
|
|
1496
|
+
const matched = [];
|
|
1497
|
+
for (const [token, tw] of qv.w) {
|
|
1498
|
+
if (node._tf && typeof node._tf.has === 'function' && node._tf.has(token)) {
|
|
1499
|
+
matched.push({ term: token, weight: round(tw, 4) });
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
matched.sort((a, b) => b.weight - a.weight);
|
|
1503
|
+
hit.matchedTerms = matched.slice(0, 8);
|
|
1504
|
+
hit.strategy = strategy;
|
|
1426
1505
|
}
|
|
1427
1506
|
scored.push(hit);
|
|
1428
1507
|
}
|
|
@@ -1802,6 +1881,7 @@ class NebulaMemory {
|
|
|
1802
1881
|
topK,
|
|
1803
1882
|
includeArchived,
|
|
1804
1883
|
includeDormant,
|
|
1884
|
+
includeSuperseded: options.includeSuperseded === true,
|
|
1805
1885
|
mmrLambda: num(options.mmrLambda, this.opts.mmrLambda),
|
|
1806
1886
|
mmrThreshold: num(options.mmrThreshold, this.opts.mmrThreshold),
|
|
1807
1887
|
});
|
|
@@ -2300,6 +2380,11 @@ class NebulaMemory {
|
|
|
2300
2380
|
this._log('info', `index.thin.json 版本不符(app=${payload.app} thin=${payload.thinVersion} idx=${payload.indexVersion}),全量重建`);
|
|
2301
2381
|
return null;
|
|
2302
2382
|
}
|
|
2383
|
+
// 拼音索引是可选能力:开启后旧的薄索引里没有 py:/pyi: token,必须重建一次。
|
|
2384
|
+
if (this.opts.pinyinIndex !== false && payload.pinyin !== true) {
|
|
2385
|
+
this._log('info', 'index.thin.json 缺少拼音 token(pinyinIndex 已开启),全量重建');
|
|
2386
|
+
return null;
|
|
2387
|
+
}
|
|
2303
2388
|
// 位点校验:jsonl 字节数与记录一致才可信。
|
|
2304
2389
|
// 进程被强杀时不会走 close(),追加的节点没进薄索引 → 大小对不上 → 重建。
|
|
2305
2390
|
const sizeOf = (f) => {
|
|
@@ -2639,6 +2724,7 @@ class NebulaMemory {
|
|
|
2639
2724
|
app: APP,
|
|
2640
2725
|
indexVersion: INDEX_VERSION,
|
|
2641
2726
|
thinVersion: THIN_VERSION,
|
|
2727
|
+
pinyin: this.opts.pinyinIndex !== false,
|
|
2642
2728
|
builtAt: new Date().toISOString(),
|
|
2643
2729
|
dir: this.dir,
|
|
2644
2730
|
// 用本实例已知边界,而不是 fs.statSync:文件可能被别的进程追加过,
|
|
@@ -2666,12 +2752,20 @@ class NebulaMemory {
|
|
|
2666
2752
|
// 内部:索引
|
|
2667
2753
|
// -------------------------------------------------------------------------
|
|
2668
2754
|
|
|
2669
|
-
/** 节点 token 频次:正文 +
|
|
2755
|
+
/** 节点 token 频次:正文 + 标签 + 拼音窗口(py:/pyi:) */
|
|
2670
2756
|
_tfFor(node) {
|
|
2671
2757
|
const freq = tx.termFreq(node.text);
|
|
2672
2758
|
for (const tag of node.tags || []) {
|
|
2673
2759
|
for (const t of tx.tokenize(tag)) freq.set(t, (freq.get(t) || 0) + 1);
|
|
2674
2760
|
}
|
|
2761
|
+
if (this.opts.pinyinIndex !== false) {
|
|
2762
|
+
for (const [t, c] of pinyin.indexTokens(node.text, {
|
|
2763
|
+
maxWindow: num(this.opts.pinyinMaxWindow, 4),
|
|
2764
|
+
maxTokens: num(this.opts.pinyinMaxTokens, 96),
|
|
2765
|
+
})) {
|
|
2766
|
+
freq.set(t, (freq.get(t) || 0) + c);
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2675
2769
|
return freq;
|
|
2676
2770
|
}
|
|
2677
2771
|
|
|
@@ -2904,7 +2998,16 @@ class NebulaMemory {
|
|
|
2904
2998
|
_maybeFlushIndex(force = false) {
|
|
2905
2999
|
if (!this._indexDirty) return;
|
|
2906
3000
|
if (!force && this._writesSinceIndex < this.opts.indexFlushEvery) return;
|
|
2907
|
-
|
|
3001
|
+
try {
|
|
3002
|
+
this._writeIndexSnapshot();
|
|
3003
|
+
} catch (e) {
|
|
3004
|
+
// index.json 是快照缓存,不是真相源:多进程同时 flush 时 rename 会撞
|
|
3005
|
+
// EPERM/EBUSY(Windows 上尤其常见)。这里绝不能把异常抛给 remember——
|
|
3006
|
+
// 2026-12-01 并发压测里一个进程因此中断,丢了 1000 条正在写的数据。
|
|
3007
|
+
this._log('warn', `index.json 快照写入失败(保留脏标记,稍后重试): ${e.message}`);
|
|
3008
|
+
// 推迟到下一次 indexFlushEvery 再试,避免每次写入都撞一次
|
|
3009
|
+
this._writesSinceIndex = 0;
|
|
3010
|
+
}
|
|
2908
3011
|
}
|
|
2909
3012
|
|
|
2910
3013
|
/**
|
|
@@ -2934,8 +3037,16 @@ class NebulaMemory {
|
|
|
2934
3037
|
this._compactNodesNow = false;
|
|
2935
3038
|
}
|
|
2936
3039
|
this._flushPending();
|
|
2937
|
-
|
|
2938
|
-
|
|
3040
|
+
try {
|
|
3041
|
+
this._writeIndexSnapshot();
|
|
3042
|
+
} catch (e) {
|
|
3043
|
+
this._log('warn', `snapshot: index.json 写入失败(下次启动会重建): ${e.message}`);
|
|
3044
|
+
}
|
|
3045
|
+
try {
|
|
3046
|
+
this._writeThinIndex();
|
|
3047
|
+
} catch (e) {
|
|
3048
|
+
this._log('warn', `snapshot: index.thin.json 写入失败(下次启动会重建): ${e.message}`);
|
|
3049
|
+
}
|
|
2939
3050
|
this._log('info', `snapshot dir=${this.dir} nodes=${this.nodes.size} onDiskBefore=${onDisk} compacted=${needCompact}`);
|
|
2940
3051
|
return { ok: true, nodes: this.nodes.size, compacted: needCompact };
|
|
2941
3052
|
}
|
|
@@ -2943,6 +3054,9 @@ class NebulaMemory {
|
|
|
2943
3054
|
/** 注意:用 null 原型,避免 token 恰好叫 "__proto__" 时改坏对象 */
|
|
2944
3055
|
const postings = Object.create(null);
|
|
2945
3056
|
for (const [token, ids] of this.postings) {
|
|
3057
|
+
// py:/pyi: 只服务本机召回,权威索引是 index.thin.json;
|
|
3058
|
+
// 历史格式 index.json 不写它们,避免把 2.4 万节点的快照从 19MB 撑到 54MB。
|
|
3059
|
+
if (token.startsWith('py:') || token.startsWith('pyi:')) continue;
|
|
2946
3060
|
if (ids.size) postings[token] = Array.from(ids);
|
|
2947
3061
|
}
|
|
2948
3062
|
const payload = {
|
|
@@ -3051,13 +3165,34 @@ class NebulaMemory {
|
|
|
3051
3165
|
_queryVector(query) {
|
|
3052
3166
|
const freq = tx.termFreq(query);
|
|
3053
3167
|
const w = new Map();
|
|
3054
|
-
let sum = 0;
|
|
3055
3168
|
for (const [token, tf] of freq) {
|
|
3056
3169
|
const weight = (1 + Math.log(tf)) * this._idf(token);
|
|
3057
3170
|
if (!(weight > 0)) continue;
|
|
3058
3171
|
w.set(token, weight);
|
|
3059
|
-
sum += weight * weight;
|
|
3060
3172
|
}
|
|
3173
|
+
// 纯拼音查询扩展:py: 全拼窗口 / pyi: 声母窗口,再加模糊音变体。
|
|
3174
|
+
// 只在 latin token 上触发,中文查询完全不受影响;变体只加索引里真实存在的 token。
|
|
3175
|
+
if (this.opts.fuzzyPinyin !== false) {
|
|
3176
|
+
const add = (tok, factor) => {
|
|
3177
|
+
if (!this.postings.has(tok)) return;
|
|
3178
|
+
const weight = this._idf(tok) * factor;
|
|
3179
|
+
if (!(weight > 0)) return;
|
|
3180
|
+
if (weight > (w.get(tok) || 0)) w.set(tok, weight);
|
|
3181
|
+
};
|
|
3182
|
+
for (const token of freq.keys()) {
|
|
3183
|
+
if (!pinyin.isLatinWord(token)) continue;
|
|
3184
|
+
const base = token.toLowerCase();
|
|
3185
|
+
add(`py:${base}`, 1);
|
|
3186
|
+
if (base.length <= 10) add(`pyi:${base}`, 0.9);
|
|
3187
|
+
for (const variant of pinyin.fuzzyVariants(base)) {
|
|
3188
|
+
if (variant === base) continue;
|
|
3189
|
+
add(`py:${variant}`, 0.7);
|
|
3190
|
+
if (variant.length <= 10) add(`pyi:${variant}`, 0.55);
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
let sum = 0;
|
|
3195
|
+
for (const weight of w.values()) sum += weight * weight;
|
|
3061
3196
|
return { w, norm: Math.sqrt(sum), tokens: Array.from(freq.keys()) };
|
|
3062
3197
|
}
|
|
3063
3198
|
|
|
@@ -3119,27 +3254,61 @@ class NebulaMemory {
|
|
|
3119
3254
|
|
|
3120
3255
|
/**
|
|
3121
3256
|
* 同 kind 去重查找。
|
|
3257
|
+
*
|
|
3258
|
+
* 2026-12-01 蒸馏压测修复:原先按「所有 token 的倒排并集」建候选集,
|
|
3259
|
+
* 只要文本里有一个高频词(“API/系统/代码”),候选集就是全库 →
|
|
3260
|
+
* 每次 remember 都要和全部节点算一遍余弦,写入退化成 O(N²)
|
|
3261
|
+
* (实测 2000 条共享“API 密钥”的记忆要 6 秒,1 万条约 2 分钟)。
|
|
3262
|
+
*
|
|
3263
|
+
* 现在两刀:
|
|
3264
|
+
* 1) 按 token 的 df 升序(稀有词优先)收窄候选集,超过 dedupeMaxCandidates
|
|
3265
|
+
* (默认 2000)就截断——真正的近重复文本必然共享稀有 token,不会漏;
|
|
3266
|
+
* 2) 长度粗筛:长度差超过 50% 的候选不可能达到 0.92 余弦,直接跳过。
|
|
3267
|
+
*
|
|
3122
3268
|
* @param {any} rec 带 _tf 的新记录
|
|
3123
3269
|
*/
|
|
3124
3270
|
_findDuplicate(rec) {
|
|
3125
3271
|
const threshold = num(this.opts.dedupeThreshold, 0.92);
|
|
3126
|
-
const
|
|
3272
|
+
const cap = Math.max(50, num(this.opts.dedupeMaxCandidates, 2000));
|
|
3273
|
+
// 用倒排表大小当 df:this.df 可能是惰性构建的(未算过时全 0,
|
|
3274
|
+
// 会让“稀有词优先”退化成按 token 出现顺序,候选集照样被打满)。
|
|
3275
|
+
const dfOf = (tok) => {
|
|
3276
|
+
const ids = this.postings.get(tok);
|
|
3277
|
+
return ids ? ids.size : 0;
|
|
3278
|
+
};
|
|
3279
|
+
// 出现库里从未有过的新 token ⇒ 这是一条新信息,不可能与旧记忆达到 0.92 相似。
|
|
3280
|
+
// 直接跳过候选扫描:蒸馏场景下「每条都带唯一编号/名字」是常态,否则候选集
|
|
3281
|
+
// 永远被高频词撑满,写入退化成 O(N²)(2026-12-01 蒸馏压测发现)。
|
|
3127
3282
|
for (const token of rec._tf.keys()) {
|
|
3283
|
+
if (!this.postings.has(token)) return null;
|
|
3284
|
+
}
|
|
3285
|
+
const tokens = [...rec._tf.keys()].sort((a, b) => dfOf(a) - dfOf(b));
|
|
3286
|
+
const cand = new Set();
|
|
3287
|
+
for (const token of tokens) {
|
|
3128
3288
|
const ids = this.postings.get(token);
|
|
3129
3289
|
if (!ids) continue;
|
|
3130
|
-
for (const id of ids)
|
|
3290
|
+
for (const id of ids) {
|
|
3291
|
+
if (id === rec.id) continue;
|
|
3292
|
+
cand.add(id);
|
|
3293
|
+
if (cand.size >= cap) break;
|
|
3294
|
+
}
|
|
3295
|
+
if (cand.size >= cap) break;
|
|
3131
3296
|
}
|
|
3132
3297
|
let best = null;
|
|
3133
3298
|
let bestSim = 0;
|
|
3299
|
+
const lenNew = rec.text ? rec.text.length : 0;
|
|
3134
3300
|
for (const id of cand) {
|
|
3135
3301
|
const n = this.nodes.get(id);
|
|
3136
3302
|
if (!n || n.kind !== rec.kind) continue;
|
|
3303
|
+
const lenOld = n.text ? n.text.length : 0;
|
|
3304
|
+
if (Math.max(lenOld, lenNew) > 60 && Math.abs(lenOld - lenNew) > Math.max(30, 0.5 * Math.max(lenOld, lenNew))) continue;
|
|
3137
3305
|
const sim = this._tfidfCosinePair(rec._tf, n._tf);
|
|
3138
3306
|
if (sim > bestSim) {
|
|
3139
3307
|
bestSim = sim;
|
|
3140
3308
|
best = n;
|
|
3141
3309
|
}
|
|
3142
3310
|
}
|
|
3311
|
+
if (cand.size >= cap) this._log('debug', `dedupe: 候选集达上限 ${cap},已截断(写入 ${rec.id})`);
|
|
3143
3312
|
return bestSim > threshold ? best : null;
|
|
3144
3313
|
}
|
|
3145
3314
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nebula-memory-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.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",
|