nebula-memory-mcp 1.2.1 → 1.2.3

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/memory/recall.cjs CHANGED
@@ -1,417 +1,455 @@
1
- 'use strict';
2
-
3
- /**
4
- * 记忆星云 Lite — 四臂召回(lexical / activation / graph / profile)
5
- *
6
- * 设计对齐 MEMORY-NEBULA-SPEC.md §3 与参考实现 brain_engine.py:
7
- *
8
- * ① lexical :query token 倒排并集 → 现有 bigram TF-IDF 余弦,取 top 40;
9
- * ② activation :A(v) = importance · R(v),R = exp(-Δt/S),取 top 12;
10
- * ③ graph :词法臂前 6 个种子做 2 跳扩散,
11
- * A(v) = MAX ∏(w^α · γ^hop) · seed(α=1.0、γ=0.55),取 top 24;
12
- * ④ profile :kind='profile' 或 layer='summary' 里 importance 最高的 3 条恒定入选。
13
- *
14
- * 融合:final = 0.55·lexNorm + 0.30·actNorm + 0.15·recencyR。
15
- * 去冗余:token 重叠 MMR(λ=0.7,相似度 > 0.85 的后选者降权)。
16
- *
17
- * 本模块只做「算」,不写盘、不改状态;touch / trace / 配额由 store.js 与
18
- * fragments.js 负责,保证四臂可以单独测、单独调参。
19
- */
20
-
21
- const tx = require('./tokenize.cjs');
22
- const dyn = require('./dynamics.cjs');
23
-
24
- /** 三因子融合权重(SPEC §3;改名时同步 trace.weights) */
25
- const RECALL_WEIGHTS = Object.freeze({ lexical: 0.55, activation: 0.3, recency: 0.15 });
26
-
27
- const PARAMS = Object.freeze({
28
- lexTop: 40, // 词法臂候选上限
29
- actTop: 12, // 激活臂候选上限
30
- // 图扩散种子数(= 星云里点亮的「种子」数)。
31
- // 对齐旧版 dsh-brain-nebula 的 seedLimit=18(旧版从召回结果前 18 条取种子);
32
- // 整合版这里取词法臂前 N 条作为扩散起点,6 会让种子明显偏少、星云偏暗。
33
- graphSeeds: 18,
34
- // 图扩散候选上限。旧版配额是 1跳=max(24,种子×3)、2跳=max(12,种子×2),
35
- // 种子 18 时合计约 18+54+36=108;这里给到 120 才能让 1/2 跳铺得开,
36
- // 太小(原 24)会让 18 个种子几乎吃满名额,1/2 跳各只剩 3~4 个、整张星云偏暗。
37
- graphTop: 120,
38
- // 单节点扇出上限(超级节点防御)。度数超过它的节点在扩散时只取权重最高的 N 条边。
39
- // 实测:5000 度枢纽 2 跳 p50=9ms(对照组 0.54ms),可接受但无上限会随度数线性恶化;
40
- // 200 这个值保证「正常节点完全不受影响」,只截断病态枢纽。
41
- maxDegree: 200,
42
- profileTop: 3, // 画像臂恒定入选数
43
- hops: 2, // 扩散跳数(不要 3 跳:语义会漂)
44
- alpha: 1.0, // 边权指数
45
- gamma: 0.55, // 每跳衰减
46
- mmrLambda: 0.7, // MMR 相关性权重
47
- mmrThreshold: 0.85, // 超过这个 token 重叠算「冗余」
48
- minEdgeWeight: 0.001,
49
- });
50
-
51
- const { num, clamp, clamp01, round, layerOf } = dyn;
52
-
53
- /**
54
- * 判断节点是否参与本轮候选。
55
- * archived 默认出池(includeArchived=true 才召回);dormant 沿用 v1 语义。
56
- */
57
- function eligible(node, opts) {
58
- if (!node || node.deleted) return false;
59
- if (node.archived && !opts.includeArchived) return false;
60
- if (node.dormant && !opts.includeDormant && !opts.includeArchived) return false;
61
- return true;
62
- }
63
-
64
- /**
65
- * 2 跳扩散:A(v) = MAX over paths ∏(w^α · γ^hop) · seed。
66
- * 用 MAX 而不是 SUM,避免 hub 节点霸屏(设计草案的结论)。
67
- *
68
- * @param {any} mem
69
- * @param {Map<string, number>} seeds id → seed 分数(0..1)
70
- * @param {{hops?:number, alpha?:number, gamma?:number, minEdgeWeight?:number,
71
- * includeArchived?:boolean, includeDormant?:boolean}} [opts]
72
- * @returns {Map<string, {act:number, hop:number, via:string, seed:string}>}
73
- */
74
- function spread(mem, seeds, opts = {}) {
75
- const hops = clamp(Math.floor(num(opts.hops, PARAMS.hops)), 1, 3);
76
- const alpha = num(opts.alpha, PARAMS.alpha);
77
- const gamma = num(opts.gamma, PARAMS.gamma);
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;
83
- /** @type {Map<string, {act:number, hop:number, via:string, seed:string}>} */
84
- const out = new Map();
85
- /** @type {Map<string, {act:number, via:string, seed:string}>} */
86
- let frontier = new Map();
87
-
88
- for (const [id, score] of seeds) {
89
- const node = mem.nodes.get(id);
90
- if (!node) continue;
91
- const s = clamp01(score);
92
- if (!(s > 0)) continue;
93
- out.set(id, { act: s, hop: 0, via: id, seed: id });
94
- frontier.set(id, { act: s, via: id, seed: id });
95
- }
96
-
97
- for (let hop = 1; hop <= hops; hop++) {
98
- if (!frontier.size) break;
99
- /** @type {Map<string, {act:number, via:string, seed:string}>} */
100
- const next = new Map();
101
- for (const [fromId, info] of frontier) {
102
- const adj = mem.adj.get(fromId);
103
- if (!adj) continue;
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) {
117
- const w = num(wRaw, 0);
118
- if (!(w > 0) || w < minW) continue;
119
- const node = mem.nodes.get(toId);
120
- if (!eligible(node, opts)) continue;
121
- const cand = info.act * Math.pow(w, alpha) * Math.pow(gamma, hop);
122
- if (!(cand > 0)) continue;
123
- const prev = next.get(toId);
124
- if (!prev || cand > prev.act) next.set(toId, { act: cand, via: fromId, seed: info.seed });
125
- }
126
- }
127
- for (const [id, info] of next) {
128
- const prev = out.get(id);
129
- if (!prev || info.act > prev.act) out.set(id, { act: info.act, hop, via: info.via, seed: info.seed });
130
- }
131
- frontier = next;
132
- }
133
- return out;
134
- }
135
-
136
- /** 候选对象工厂 */
137
- function blankEntry(node) {
138
- return {
139
- id: node.id,
140
- node,
141
- lex: 0,
142
- activationRaw: 0,
143
- graphRaw: 0,
144
- actRaw: 0,
145
- hop: 0,
146
- via: null,
147
- seed: null,
148
- arms: { lexical: false, activation: false, graph: false, profile: false },
149
- lexNorm: 0,
150
- actNorm: 0,
151
- recency: 0,
152
- base: 0,
153
- tset: null,
154
- };
155
- }
156
-
157
- /** 给候选补上 token 集合(MMR 用),懒计算 */
158
- function ensureTset(entry) {
159
- if (!entry.tset) entry.tset = tx.tokenSet(entry.node.text);
160
- return entry.tset;
161
- }
162
-
163
- /**
164
- * 跑一次四臂召回(纯计算)。
165
- *
166
- * @param {any} mem NebulaMemory(需要 nodes / postings / adj / edgeMap / _queryVector / _tfidfCosine)
167
- * @param {string} query
168
- * @param {Object} [options]
169
- * @returns {{
170
- * query:string, ts:number, latencyMs:number, tokensUsed:number,
171
- * seeds:Array<{id:string,score:number}>,
172
- * activated:Array<{id:string,act:number,hop:number,arms:string}>,
173
- * picked:Array<any>, candidates:number, dropped:number, penalized:number,
174
- * arms:{lexical:number,activation:number,graph:number,profile:number},
175
- * weights:Object, byId:Map<string,any>, params:Object
176
- * }}
177
- */
178
- function runRecall(mem, query, options = {}) {
179
- const t0 = Date.now();
180
- const now = num(options.now, Date.now());
181
- const q = query == null ? '' : String(query);
182
- const topK = clamp(Math.floor(num(options.topK, 8)), 1, 30);
183
- const opts = {
184
- includeArchived: options.includeArchived === true,
185
- includeDormant: options.includeDormant === true,
186
- hops: options.hops,
187
- alpha: options.alpha,
188
- gamma: options.gamma,
189
- };
190
- const lexTopN = clamp(Math.floor(num(options.lexTop, PARAMS.lexTop)), 1, 200);
191
- const actTopN = clamp(Math.floor(num(options.actTop, PARAMS.actTop)), 1, 100);
192
- const graphTopN = clamp(Math.floor(num(options.graphTop, PARAMS.graphTop)), 1, 200);
193
- const graphSeedN = clamp(Math.floor(num(options.graphSeeds, PARAMS.graphSeeds)), 1, 20);
194
- const profileTopN = clamp(Math.floor(num(options.profileTop, PARAMS.profileTop)), 0, 10);
195
- const lambda = clamp(num(options.mmrLambda, PARAMS.mmrLambda), 0, 1);
196
- const mmrThreshold = clamp(num(options.mmrThreshold, PARAMS.mmrThreshold), 0, 1);
197
-
198
- /** @type {Map<string, any>} */
199
- const byId = new Map();
200
- const ensure = (node) => {
201
- let e = byId.get(node.id);
202
- if (!e) {
203
- e = blankEntry(node);
204
- byId.set(node.id, e);
205
- }
206
- return e;
207
- };
208
-
209
- // ---- ① lexical ---------------------------------------------------------
210
- const qv = mem._queryVector(q);
211
- const tokensUsed = qv && qv.w ? qv.w.size : 0;
212
- /** @type {Array<{id:string, lex:number}>} */
213
- let lexPool = [];
214
- if (tokensUsed) {
215
- const ids = new Set();
216
- for (const token of qv.w.keys()) {
217
- const set = mem.postings.get(token);
218
- if (!set) continue;
219
- for (const id of set) ids.add(id);
220
- }
221
- for (const id of ids) {
222
- const node = mem.nodes.get(id);
223
- if (!eligible(node, opts)) continue;
224
- const tf = node._tf || mem._tfFor(node);
225
- const lex = mem._tfidfCosine(tf, qv);
226
- if (lex > 0) lexPool.push({ id, lex });
227
- }
228
- }
229
- lexPool.sort((a, b) => b.lex - a.lex || a.id.localeCompare(b.id));
230
- const lexTop = lexPool.slice(0, lexTopN);
231
- for (const item of lexTop) {
232
- const e = ensure(mem.nodes.get(item.id));
233
- e.lex = Math.max(e.lex, item.lex);
234
- e.arms.lexical = true;
235
- }
236
- const maxLex = lexTop.length ? lexTop[0].lex : 0;
237
-
238
- // ---- ② activation ------------------------------------------------------
239
- /** @type {Array<{id:string, act:number}>} */
240
- const actPool = [];
241
- for (const node of mem.nodes.values()) {
242
- if (!eligible(node, opts)) continue;
243
- const act = num(node.importance, 0.5) * dyn.retention(node, now);
244
- if (act > 0) actPool.push({ id: node.id, act });
245
- }
246
- actPool.sort((a, b) => b.act - a.act || a.id.localeCompare(b.id));
247
- const actTop = actPool.slice(0, actTopN);
248
- for (const item of actTop) {
249
- const e = ensure(mem.nodes.get(item.id));
250
- e.activationRaw = Math.max(e.activationRaw, item.act);
251
- e.arms.activation = true;
252
- }
253
-
254
- // ---- ③ graph(词法臂前 N 个种子,2 跳扩散)------------------------------
255
- const seedMap = new Map();
256
- const seeds = [];
257
- for (const item of lexTop.slice(0, graphSeedN)) {
258
- const score = maxLex > 0 ? item.lex / maxLex : 0;
259
- if (!(score > 0)) continue;
260
- seedMap.set(item.id, score);
261
- seeds.push({ id: item.id, score: round(score, 4) });
262
- }
263
- /** @type {Array<{id:string, act:number, hop:number, via:string, seed:string}>} */
264
- const graphPool = [];
265
- if (seedMap.size) {
266
- const spreadRes = spread(mem, seedMap, opts);
267
- for (const [id, info] of spreadRes) {
268
- if (info.hop <= 0) continue;
269
- graphPool.push({ id, act: info.act, hop: info.hop, via: info.via, seed: info.seed });
270
- }
271
- graphPool.sort((a, b) => b.act - a.act || a.hop - b.hop || a.id.localeCompare(b.id));
272
- graphPool.length = Math.min(graphPool.length, graphTopN);
273
- for (const item of graphPool) {
274
- const node = mem.nodes.get(item.id);
275
- if (!node) continue;
276
- const e = ensure(node);
277
- e.graphRaw = Math.max(e.graphRaw, item.act);
278
- e.arms.graph = true;
279
- if (!(e.hop > 0)) {
280
- e.hop = item.hop;
281
- e.via = item.via;
282
- e.seed = item.seed;
283
- }
284
- }
285
- }
286
-
287
- // ---- ④ profile(恒定入选,直接置顶)-------------------------------------
288
- const profilePool = [];
289
- if (profileTopN > 0) {
290
- for (const node of mem.nodes.values()) {
291
- if (!eligible(node, opts)) continue;
292
- if (node.kind === 'profile' || layerOf(node.kind, node.layer) === dyn.LAYER.SUMMARY) profilePool.push(node);
293
- }
294
- profilePool.sort((a, b) => b.importance - a.importance || b.ts - a.ts);
295
- profilePool.length = Math.min(profilePool.length, profileTopN);
296
- for (const node of profilePool) {
297
- const e = ensure(node);
298
- e.arms.profile = true;
299
- }
300
- }
301
-
302
- // ---- 融合 ---------------------------------------------------------------
303
- const entries = Array.from(byId.values());
304
- let maxAct = 0;
305
- for (const e of entries) {
306
- e.actRaw = Math.max(e.activationRaw, e.graphRaw);
307
- if (e.actRaw > maxAct) maxAct = e.actRaw;
308
- }
309
- for (const e of entries) {
310
- e.lexNorm = maxLex > 0 ? clamp01(e.lex / maxLex) : 0;
311
- e.actNorm = maxAct > 0 ? clamp01(e.actRaw / maxAct) : 0;
312
- e.recency = dyn.retention(e.node, now);
313
- e.base =
314
- RECALL_WEIGHTS.lexical * e.lexNorm +
315
- RECALL_WEIGHTS.activation * e.actNorm +
316
- RECALL_WEIGHTS.recency * e.recency;
317
- }
318
-
319
- // ---- 去冗余:画像置顶 + MMR --------------------------------------------
320
- const pool = entries.slice().sort((a, b) => b.base - a.base || a.id.localeCompare(b.id));
321
- /** @type {any[]} */
322
- const picked = [];
323
- const pinned = pool.filter((e) => e.arms.profile).slice(0, Math.min(profileTopN, topK));
324
- for (const e of pinned) picked.push(e);
325
- const rest = pool.filter((e) => !pinned.includes(e));
326
-
327
- let penalized = 0;
328
- while (picked.length < topK && rest.length) {
329
- let bestIdx = -1;
330
- let bestVal = -Infinity;
331
- let bestSim = 0;
332
- for (let i = 0; i < rest.length; i++) {
333
- const e = rest[i];
334
- const set = ensureTset(e);
335
- let maxSim = 0;
336
- for (const p of picked) {
337
- const sim = tx.jaccard(set, ensureTset(p));
338
- if (sim > maxSim) maxSim = sim;
339
- }
340
- const val = lambda * e.base + (1 - lambda) * (1 - maxSim);
341
- if (val > bestVal) {
342
- bestVal = val;
343
- bestIdx = i;
344
- bestSim = maxSim;
345
- }
346
- }
347
- if (bestIdx < 0) break;
348
- if (bestSim > mmrThreshold) penalized++;
349
- picked.push(rest.splice(bestIdx, 1)[0]);
350
- }
351
-
352
- // ---- 臂归属 / 解释文案 --------------------------------------------------
353
- const reasons = { lexical: '直接命中', graph: '联想', profile: '画像', activation: '最近' };
354
- for (const e of picked) {
355
- let arm = 'activation';
356
- if (e.arms.profile) arm = 'profile';
357
- else if (e.arms.graph && e.hop > 0) arm = 'graph';
358
- else if (e.arms.lexical) arm = 'lexical';
359
- e.arm = arm;
360
- e.why = reasons[arm];
361
- e.score = round(e.base, 6);
362
- e.actNorm = round(e.actNorm, 4);
363
- e.lexNorm = round(e.lexNorm, 4);
364
- e.recency = round(e.recency, 4);
365
- }
366
-
367
- // ---- trace 用:激活列表(按激活值排,最多 24 条)-------------------------
368
- /** @type {Map<string, any>} */
369
- const actMap = new Map();
370
- const armsTag = (e) => `${e.arms.lexical ? 'l' : ''}${e.arms.activation ? 'a' : ''}${e.arms.graph ? 'g' : ''}${e.arms.profile ? 'p' : ''}`;
371
- for (const item of actTop) {
372
- const e = byId.get(item.id);
373
- if (!e) continue;
374
- actMap.set(item.id, { id: item.id, act: e.actRaw, hop: 0, arms: armsTag(e) });
375
- }
376
- for (const item of graphPool) {
377
- const e = byId.get(item.id);
378
- if (!e) continue;
379
- const prev = actMap.get(item.id);
380
- const rec = { id: item.id, act: round(e.actRaw, 4), hop: item.hop, arms: armsTag(e) };
381
- if (!prev || rec.act > prev.act) actMap.set(item.id, rec);
382
- }
383
- const activated = Array.from(actMap.values())
384
- .sort((a, b) => b.act - a.act || a.id.localeCompare(b.id))
385
- .slice(0, 24)
386
- .map((r) => ({ id: r.id, act: round(r.act, 4), hop: r.hop, arms: r.arms }));
387
-
388
- return {
389
- query: q,
390
- ts: now,
391
- latencyMs: Date.now() - t0,
392
- tokensUsed,
393
- seeds,
394
- activated,
395
- picked,
396
- candidates: pool.length,
397
- dropped: Math.max(0, pool.length - picked.length),
398
- penalized,
399
- arms: {
400
- lexical: lexTop.length,
401
- activation: actTop.length,
402
- graph: graphPool.length,
403
- profile: profilePool.length,
404
- },
405
- weights: RECALL_WEIGHTS,
406
- byId,
407
- params: { lexTopN, actTopN, graphTopN, graphSeedN, profileTopN, lambda, mmrThreshold, topK },
408
- };
409
- }
410
-
411
- module.exports = {
412
- RECALL_WEIGHTS,
413
- PARAMS,
414
- runRecall,
415
- spread,
416
- eligible,
417
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * 记忆星云 Lite — 四臂召回(lexical / activation / graph / profile)
5
+ *
6
+ * 设计对齐 MEMORY-NEBULA-SPEC.md §3 与参考实现 brain_engine.py:
7
+ *
8
+ * ① lexical :query token 倒排并集 → 现有 bigram TF-IDF 余弦,取 top 40;
9
+ * ② activation :A(v) = importance · R(v),R = exp(-Δt/S),取 top 12;
10
+ * ③ graph :词法臂前 6 个种子做 2 跳扩散,
11
+ * A(v) = MAX ∏(w^α · γ^hop) · seed(α=1.0、γ=0.55),取 top 24;
12
+ * ④ profile :kind='profile' 或 layer='summary' 里 importance 最高的 3 条恒定入选。
13
+ *
14
+ * 融合:final = 0.55·lexNorm + 0.30·actNorm + 0.15·recencyR。
15
+ * 去冗余:token 重叠 MMR(λ=0.7,相似度 > 0.85 的后选者降权)。
16
+ *
17
+ * 本模块只做「算」,不写盘、不改状态;touch / trace / 配额由 store.js 与
18
+ * fragments.js 负责,保证四臂可以单独测、单独调参。
19
+ */
20
+
21
+ const tx = require('./tokenize.cjs');
22
+ const dyn = require('./dynamics.cjs');
23
+ const synonyms = require('./synonyms.cjs');
24
+ const profileRecall = require('./profile-recall.cjs');
25
+ const typoCorrect = require('./typo-fix.cjs');
26
+
27
+ /** 三因子融合权重(SPEC §3;改名时同步 trace.weights) */
28
+ const RECALL_WEIGHTS = Object.freeze({ lexical: 0.55, activation: 0.3, recency: 0.15 });
29
+
30
+ const PARAMS = Object.freeze({
31
+ lexTop: 40, // 词法臂候选上限
32
+ actTop: 12, // 激活臂候选上限
33
+ // 图扩散种子数(= 星云里点亮的「种子」数)。
34
+ // 对齐旧版 dsh-brain-nebula 的 seedLimit=18(旧版从召回结果前 18 条取种子);
35
+ // 整合版这里取词法臂前 N 条作为扩散起点,6 会让种子明显偏少、星云偏暗。
36
+ graphSeeds: 18,
37
+ // 图扩散候选上限。旧版配额是 1跳=max(24,种子×3)、2跳=max(12,种子×2),
38
+ // 种子 18 时合计约 18+54+36=108;这里给到 120 才能让 1/2 跳铺得开,
39
+ // 太小(原 24)会让 18 个种子几乎吃满名额,1/2 跳各只剩 3~4 个、整张星云偏暗。
40
+ graphTop: 120,
41
+ // 单节点扇出上限(超级节点防御)。度数超过它的节点在扩散时只取权重最高的 N 条边。
42
+ // 实测:5000 度枢纽 2 跳 p50=9ms(对照组 0.54ms),可接受但无上限会随度数线性恶化;
43
+ // 200 这个值保证「正常节点完全不受影响」,只截断病态枢纽。
44
+ maxDegree: 200,
45
+ profileTop: 3, // 画像臂恒定入选数
46
+ hops: 2, // 扩散跳数(不要 3 跳:语义会漂)
47
+ alpha: 1.0, // 边权指数
48
+ gamma: 0.55, // 每跳衰减
49
+ mmrLambda: 0.7, // MMR 相关性权重
50
+ mmrThreshold: 0.85, // 超过这个 token 重叠算「冗余」
51
+ minEdgeWeight: 0.001,
52
+ });
53
+
54
+ const { num, clamp, clamp01, round, layerOf } = dyn;
55
+
56
+ /**
57
+ * 判断节点是否参与本轮候选。
58
+ * archived 默认出池(includeArchived=true 才召回);dormant 沿用 v1 语义。
59
+ */
60
+ function eligible(node, opts) {
61
+ if (!node || node.deleted) return false;
62
+ if (node.archived && !opts.includeArchived) return false;
63
+ if (node.dormant && !opts.includeDormant && !opts.includeArchived) return false;
64
+ return true;
65
+ }
66
+
67
+ /**
68
+ * 2 跳扩散:A(v) = MAX over paths ∏(w^α · γ^hop) · seed。
69
+ * 用 MAX 而不是 SUM,避免 hub 节点霸屏(设计草案的结论)。
70
+ *
71
+ * @param {any} mem
72
+ * @param {Map<string, number>} seeds id → seed 分数(0..1)
73
+ * @param {{hops?:number, alpha?:number, gamma?:number, minEdgeWeight?:number,
74
+ * includeArchived?:boolean, includeDormant?:boolean}} [opts]
75
+ * @returns {Map<string, {act:number, hop:number, via:string, seed:string}>}
76
+ */
77
+ function spread(mem, seeds, opts = {}) {
78
+ const hops = clamp(Math.floor(num(opts.hops, PARAMS.hops)), 1, 3);
79
+ const alpha = num(opts.alpha, PARAMS.alpha);
80
+ const gamma = num(opts.gamma, PARAMS.gamma);
81
+ const minW = num(opts.minEdgeWeight, PARAMS.minEdgeWeight);
82
+ // 单节点扇出上限(超级节点防御);0 = 不限制
83
+ const maxDeg = clamp(Math.floor(num(opts.maxDegree, PARAMS.maxDegree)), 0, 100000);
84
+ const stats = opts.stats || null;
85
+ if (stats && stats.truncatedHubs == null) stats.truncatedHubs = 0;
86
+ /** @type {Map<string, {act:number, hop:number, via:string, seed:string}>} */
87
+ const out = new Map();
88
+ /** @type {Map<string, {act:number, via:string, seed:string}>} */
89
+ let frontier = new Map();
90
+
91
+ for (const [id, score] of seeds) {
92
+ const node = mem.nodes.get(id);
93
+ if (!node) continue;
94
+ const s = clamp01(score);
95
+ if (!(s > 0)) continue;
96
+ out.set(id, { act: s, hop: 0, via: id, seed: id });
97
+ frontier.set(id, { act: s, via: id, seed: id });
98
+ }
99
+
100
+ for (let hop = 1; hop <= hops; hop++) {
101
+ if (!frontier.size) break;
102
+ /** @type {Map<string, {act:number, via:string, seed:string}>} */
103
+ const next = new Map();
104
+ for (const [fromId, info] of frontier) {
105
+ const adj = mem.adj.get(fromId);
106
+ if (!adj) continue;
107
+ // 超级节点防御:度数超限时只取权重最高的 maxDeg 条边。
108
+ // 实测 5000 度枢纽 2 跳 p50=9ms 尚可接受,但度数无上限时
109
+ // 每次遍历要全扫邻接表,且并发多查询会叠加放大。这里封顶换确定性。
110
+ let edges = adj;
111
+ if (maxDeg > 0 && adj.size > maxDeg) {
112
+ edges = new Map(
113
+ Array.from(adj.entries())
114
+ .sort((a, b) => num(b[1], 0) - num(a[1], 0))
115
+ .slice(0, maxDeg)
116
+ );
117
+ if (stats) stats.truncatedHubs++;
118
+ }
119
+ for (const [toId, wRaw] of edges) {
120
+ const w = num(wRaw, 0);
121
+ if (!(w > 0) || w < minW) continue;
122
+ const node = mem.nodes.get(toId);
123
+ if (!eligible(node, opts)) continue;
124
+ const cand = info.act * Math.pow(w, alpha) * Math.pow(gamma, hop);
125
+ if (!(cand > 0)) continue;
126
+ const prev = next.get(toId);
127
+ if (!prev || cand > prev.act) next.set(toId, { act: cand, via: fromId, seed: info.seed });
128
+ }
129
+ }
130
+ for (const [id, info] of next) {
131
+ const prev = out.get(id);
132
+ if (!prev || info.act > prev.act) out.set(id, { act: info.act, hop, via: info.via, seed: info.seed });
133
+ }
134
+ frontier = next;
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /** 候选对象工厂 */
140
+ function blankEntry(node) {
141
+ return {
142
+ id: node.id,
143
+ node,
144
+ lex: 0,
145
+ activationRaw: 0,
146
+ graphRaw: 0,
147
+ actRaw: 0,
148
+ hop: 0,
149
+ via: null,
150
+ seed: null,
151
+ arms: { lexical: false, activation: false, graph: false, profile: false },
152
+ lexNorm: 0,
153
+ actNorm: 0,
154
+ recency: 0,
155
+ base: 0,
156
+ tset: null,
157
+ };
158
+ }
159
+
160
+ /** 给候选补上 token 集合(MMR 用),懒计算 */
161
+ function ensureTset(entry) {
162
+ if (!entry.tset) entry.tset = tx.tokenSet(entry.node.text);
163
+ return entry.tset;
164
+ }
165
+
166
+ /**
167
+ * 跑一次四臂召回(纯计算)。
168
+ *
169
+ * @param {any} mem NebulaMemory(需要 nodes / postings / adj / edgeMap / _queryVector / _tfidfCosine)
170
+ * @param {string} query
171
+ * @param {Object} [options]
172
+ * @returns {{
173
+ * query:string, ts:number, latencyMs:number, tokensUsed:number,
174
+ * seeds:Array<{id:string,score:number}>,
175
+ * activated:Array<{id:string,act:number,hop:number,arms:string}>,
176
+ * picked:Array<any>, candidates:number, dropped:number, penalized:number,
177
+ * arms:{lexical:number,activation:number,graph:number,profile:number},
178
+ * weights:Object, byId:Map<string,any>, params:Object
179
+ * }}
180
+ */
181
+ function runRecall(mem, query, options = {}) {
182
+ const t0 = Date.now();
183
+ const now = num(options.now, Date.now());
184
+ const q = query == null ? '' : String(query);
185
+ const topK = clamp(Math.floor(num(options.topK, 8)), 1, 30);
186
+ const opts = {
187
+ includeArchived: options.includeArchived === true,
188
+ includeDormant: options.includeDormant === true,
189
+ hops: options.hops,
190
+ alpha: options.alpha,
191
+ gamma: options.gamma,
192
+ };
193
+ const lexTopN = clamp(Math.floor(num(options.lexTop, PARAMS.lexTop)), 1, 200);
194
+ const actTopN = clamp(Math.floor(num(options.actTop, PARAMS.actTop)), 1, 100);
195
+ const graphTopN = clamp(Math.floor(num(options.graphTop, PARAMS.graphTop)), 1, 200);
196
+ const graphSeedN = clamp(Math.floor(num(options.graphSeeds, PARAMS.graphSeeds)), 1, 20);
197
+ const profileTopN = clamp(Math.floor(num(options.profileTop, PARAMS.profileTop)), 0, 10);
198
+ const lambda = clamp(num(options.mmrLambda, PARAMS.mmrLambda), 0, 1);
199
+ const mmrThreshold = clamp(num(options.mmrThreshold, PARAMS.mmrThreshold), 0, 1);
200
+
201
+ /** @type {Map<string, any>} */
202
+ const byId = new Map();
203
+ const ensure = (node) => {
204
+ let e = byId.get(node.id);
205
+ if (!e) {
206
+ e = blankEntry(node);
207
+ byId.set(node.id, e);
208
+ }
209
+ return e;
210
+ };
211
+
212
+ // ---- ① lexical ---------------------------------------------------------
213
+ // 2026-11-23:词法臂之前只做原始 query 的 bigram 匹配,跨表述场景召回率低
214
+ // (实测 near 87.5% / mid 37.5% / far 33.3%)。这里加三路补偿:
215
+ // a) 错别字/音近字纠正:拼音输入法打错(「铸造厂」→「铸造厂」)
216
+ // b) 同义词扩展:固定词级对应(「供应商」↔「铸造厂」)
217
+ // c) 画像反哺:个人化提问(「我孩子多大」)时把画像节点关键词并入查询
218
+ // 三路都可通过 options 关闭;Hindsight 的完整语义检索仍是更高层的能力。
219
+ const typoFix = typoCorrect.correctQuery(q, {
220
+ enabled: options.fixTypos !== false,
221
+ });
222
+ const qAfterTypo = typoFix.corrected;
223
+
224
+ const synOpts = options.synonyms || {};
225
+ const synExpand = synonyms.expandQuery(qAfterTypo, {
226
+ enabled: synOpts.enabled !== false && options.expandSynonyms !== false,
227
+ maxExpansions: synOpts.maxExpansions,
228
+ });
229
+ const profBoost = profileRecall.boostPersonalQuery(mem, qAfterTypo, {
230
+ enabled: options.profileBoost !== false && (options.profileRecall || {}).enabled !== false,
231
+ maxTokens: (options.profileRecall || {}).maxTokens,
232
+ });
233
+
234
+ // 合成检索 query:纠错后的原文 + 同义词 + 画像词
235
+ const extraTokens = [...synExpand.expansions, ...profBoost.tokens];
236
+ const qEffective = extraTokens.length ? (qAfterTypo + ' ' + extraTokens.join(' ')) : qAfterTypo;
237
+
238
+ const qv = mem._queryVector(qEffective);
239
+ const tokensUsed = qv && qv.w ? qv.w.size : 0;
240
+ const expansionInfo = {
241
+ typoFixes: typoFix.fixes,
242
+ synonyms: synExpand.matched,
243
+ synonymExpansions: synExpand.expansions.length,
244
+ profileBoosted: profBoost.boosted,
245
+ profileTokens: profBoost.tokens.length,
246
+ effectiveQueryLen: Array.from(qEffective).length,
247
+ };
248
+ /** @type {Array<{id:string, lex:number}>} */
249
+ let lexPool = [];
250
+ if (tokensUsed) {
251
+ const ids = new Set();
252
+ for (const token of qv.w.keys()) {
253
+ const set = mem.postings.get(token);
254
+ if (!set) continue;
255
+ for (const id of set) ids.add(id);
256
+ }
257
+ for (const id of ids) {
258
+ const node = mem.nodes.get(id);
259
+ if (!eligible(node, opts)) continue;
260
+ const tf = node._tf || mem._tfFor(node);
261
+ const lex = mem._tfidfCosine(tf, qv);
262
+ if (lex > 0) lexPool.push({ id, lex });
263
+ }
264
+ }
265
+ lexPool.sort((a, b) => b.lex - a.lex || a.id.localeCompare(b.id));
266
+ const lexTop = lexPool.slice(0, lexTopN);
267
+ for (const item of lexTop) {
268
+ const e = ensure(mem.nodes.get(item.id));
269
+ e.lex = Math.max(e.lex, item.lex);
270
+ e.arms.lexical = true;
271
+ }
272
+ const maxLex = lexTop.length ? lexTop[0].lex : 0;
273
+
274
+ // ---- ② activation ------------------------------------------------------
275
+ /** @type {Array<{id:string, act:number}>} */
276
+ const actPool = [];
277
+ for (const node of mem.nodes.values()) {
278
+ if (!eligible(node, opts)) continue;
279
+ const act = num(node.importance, 0.5) * dyn.retention(node, now);
280
+ if (act > 0) actPool.push({ id: node.id, act });
281
+ }
282
+ actPool.sort((a, b) => b.act - a.act || a.id.localeCompare(b.id));
283
+ const actTop = actPool.slice(0, actTopN);
284
+ for (const item of actTop) {
285
+ const e = ensure(mem.nodes.get(item.id));
286
+ e.activationRaw = Math.max(e.activationRaw, item.act);
287
+ e.arms.activation = true;
288
+ }
289
+
290
+ // ---- ③ graph(词法臂前 N 个种子,2 跳扩散)------------------------------
291
+ const seedMap = new Map();
292
+ const seeds = [];
293
+ for (const item of lexTop.slice(0, graphSeedN)) {
294
+ const score = maxLex > 0 ? item.lex / maxLex : 0;
295
+ if (!(score > 0)) continue;
296
+ seedMap.set(item.id, score);
297
+ seeds.push({ id: item.id, score: round(score, 4) });
298
+ }
299
+ /** @type {Array<{id:string, act:number, hop:number, via:string, seed:string}>} */
300
+ const graphPool = [];
301
+ if (seedMap.size) {
302
+ const spreadRes = spread(mem, seedMap, opts);
303
+ for (const [id, info] of spreadRes) {
304
+ if (info.hop <= 0) continue;
305
+ graphPool.push({ id, act: info.act, hop: info.hop, via: info.via, seed: info.seed });
306
+ }
307
+ graphPool.sort((a, b) => b.act - a.act || a.hop - b.hop || a.id.localeCompare(b.id));
308
+ graphPool.length = Math.min(graphPool.length, graphTopN);
309
+ for (const item of graphPool) {
310
+ const node = mem.nodes.get(item.id);
311
+ if (!node) continue;
312
+ const e = ensure(node);
313
+ e.graphRaw = Math.max(e.graphRaw, item.act);
314
+ e.arms.graph = true;
315
+ if (!(e.hop > 0)) {
316
+ e.hop = item.hop;
317
+ e.via = item.via;
318
+ e.seed = item.seed;
319
+ }
320
+ }
321
+ }
322
+
323
+ // ---- ④ profile(恒定入选,直接置顶)-------------------------------------
324
+ const profilePool = [];
325
+ if (profileTopN > 0) {
326
+ for (const node of mem.nodes.values()) {
327
+ if (!eligible(node, opts)) continue;
328
+ if (node.kind === 'profile' || layerOf(node.kind, node.layer) === dyn.LAYER.SUMMARY) profilePool.push(node);
329
+ }
330
+ profilePool.sort((a, b) => b.importance - a.importance || b.ts - a.ts);
331
+ profilePool.length = Math.min(profilePool.length, profileTopN);
332
+ for (const node of profilePool) {
333
+ const e = ensure(node);
334
+ e.arms.profile = true;
335
+ }
336
+ }
337
+
338
+ // ---- 融合 ---------------------------------------------------------------
339
+ const entries = Array.from(byId.values());
340
+ let maxAct = 0;
341
+ for (const e of entries) {
342
+ e.actRaw = Math.max(e.activationRaw, e.graphRaw);
343
+ if (e.actRaw > maxAct) maxAct = e.actRaw;
344
+ }
345
+ for (const e of entries) {
346
+ e.lexNorm = maxLex > 0 ? clamp01(e.lex / maxLex) : 0;
347
+ e.actNorm = maxAct > 0 ? clamp01(e.actRaw / maxAct) : 0;
348
+ e.recency = dyn.retention(e.node, now);
349
+ e.base =
350
+ RECALL_WEIGHTS.lexical * e.lexNorm +
351
+ RECALL_WEIGHTS.activation * e.actNorm +
352
+ RECALL_WEIGHTS.recency * e.recency;
353
+ }
354
+
355
+ // ---- 去冗余:画像置顶 + MMR --------------------------------------------
356
+ const pool = entries.slice().sort((a, b) => b.base - a.base || a.id.localeCompare(b.id));
357
+ /** @type {any[]} */
358
+ const picked = [];
359
+ const pinned = pool.filter((e) => e.arms.profile).slice(0, Math.min(profileTopN, topK));
360
+ for (const e of pinned) picked.push(e);
361
+ const rest = pool.filter((e) => !pinned.includes(e));
362
+
363
+ let penalized = 0;
364
+ while (picked.length < topK && rest.length) {
365
+ let bestIdx = -1;
366
+ let bestVal = -Infinity;
367
+ let bestSim = 0;
368
+ for (let i = 0; i < rest.length; i++) {
369
+ const e = rest[i];
370
+ const set = ensureTset(e);
371
+ let maxSim = 0;
372
+ for (const p of picked) {
373
+ const sim = tx.jaccard(set, ensureTset(p));
374
+ if (sim > maxSim) maxSim = sim;
375
+ }
376
+ const val = lambda * e.base + (1 - lambda) * (1 - maxSim);
377
+ if (val > bestVal) {
378
+ bestVal = val;
379
+ bestIdx = i;
380
+ bestSim = maxSim;
381
+ }
382
+ }
383
+ if (bestIdx < 0) break;
384
+ if (bestSim > mmrThreshold) penalized++;
385
+ picked.push(rest.splice(bestIdx, 1)[0]);
386
+ }
387
+
388
+ // ---- 臂归属 / 解释文案 --------------------------------------------------
389
+ const reasons = { lexical: '直接命中', graph: '联想', profile: '画像', activation: '最近' };
390
+ for (const e of picked) {
391
+ let arm = 'activation';
392
+ if (e.arms.profile) arm = 'profile';
393
+ else if (e.arms.graph && e.hop > 0) arm = 'graph';
394
+ else if (e.arms.lexical) arm = 'lexical';
395
+ e.arm = arm;
396
+ e.why = reasons[arm];
397
+ e.score = round(e.base, 6);
398
+ e.actNorm = round(e.actNorm, 4);
399
+ e.lexNorm = round(e.lexNorm, 4);
400
+ e.recency = round(e.recency, 4);
401
+ }
402
+
403
+ // ---- trace 用:激活列表(按激活值排,最多 24 条)-------------------------
404
+ /** @type {Map<string, any>} */
405
+ const actMap = new Map();
406
+ const armsTag = (e) => `${e.arms.lexical ? 'l' : ''}${e.arms.activation ? 'a' : ''}${e.arms.graph ? 'g' : ''}${e.arms.profile ? 'p' : ''}`;
407
+ for (const item of actTop) {
408
+ const e = byId.get(item.id);
409
+ if (!e) continue;
410
+ actMap.set(item.id, { id: item.id, act: e.actRaw, hop: 0, arms: armsTag(e) });
411
+ }
412
+ for (const item of graphPool) {
413
+ const e = byId.get(item.id);
414
+ if (!e) continue;
415
+ const prev = actMap.get(item.id);
416
+ const rec = { id: item.id, act: round(e.actRaw, 4), hop: item.hop, arms: armsTag(e) };
417
+ if (!prev || rec.act > prev.act) actMap.set(item.id, rec);
418
+ }
419
+ const activated = Array.from(actMap.values())
420
+ .sort((a, b) => b.act - a.act || a.id.localeCompare(b.id))
421
+ .slice(0, 24)
422
+ .map((r) => ({ id: r.id, act: round(r.act, 4), hop: r.hop, arms: r.arms }));
423
+
424
+ return {
425
+ query: q,
426
+ ts: now,
427
+ latencyMs: Date.now() - t0,
428
+ tokensUsed,
429
+ seeds,
430
+ activated,
431
+ picked,
432
+ candidates: pool.length,
433
+ dropped: Math.max(0, pool.length - picked.length),
434
+ penalized,
435
+ arms: {
436
+ lexical: lexTop.length,
437
+ activation: actTop.length,
438
+ graph: graphPool.length,
439
+ profile: profilePool.length,
440
+ },
441
+ weights: RECALL_WEIGHTS,
442
+ byId,
443
+ params: { lexTopN, actTopN, graphTopN, graphSeedN, profileTopN, lambda, mmrThreshold, topK },
444
+ /** 2026-11-23 查询扩展诊断:同义词命中词 / 扩展数 / 画像是否反哺 / 有效 query 长度 */
445
+ expansion: expansionInfo,
446
+ };
447
+ }
448
+
449
+ module.exports = {
450
+ RECALL_WEIGHTS,
451
+ PARAMS,
452
+ runRecall,
453
+ spread,
454
+ eligible,
455
+ };