@modusensus/dsh-mneme 0.8.10 → 0.8.12
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 -5
- package/assets/icon.svg +3 -0
- package/lib/client.js +190 -58
- package/lib/config.js +47 -1
- package/lib/dream/decisions.js +16 -0
- package/lib/dream/sleep.js +3 -0
- package/lib/dream.js +57 -9
- package/lib/entities/extractor.js +4 -1
- package/lib/graph/anchoring.js +180 -0
- package/lib/index.js +5 -0
- package/lib/inject.js +15 -3
- package/lib/lang.js +10 -0
- package/lib/service.js +164 -23
- package/lib/settings.js +24 -2
- package/lib/store.js +155 -11
- package/lib/summarize.js +104 -7
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +12 -7
- package/scripts/sync-test-badge.mjs +9 -7
- package/scripts/test-count-sync.mjs +44 -0
- package/src/config.js +47 -1
- package/src/dream/decisions.js +16 -0
- package/src/dream/sleep.js +3 -0
- package/src/dream.js +57 -9
- package/src/entities/extractor.js +4 -1
- package/src/graph/anchoring.js +180 -0
- package/src/index.js +5 -0
- package/src/inject.js +15 -3
- package/src/lang.js +10 -0
- package/src/service.js +164 -23
- package/src/settings.js +24 -2
- package/src/store.js +155 -11
- package/src/summarize.js +104 -7
- package/test/api.test.js +7 -2
- package/test/baseline-persist.test.js +248 -0
- package/test/client.test.js +245 -45
- package/test/dream.test.js +75 -0
- package/test/graph-anchoring.test.js +185 -0
- package/test/graph-inject-budget.test.js +104 -0
- package/test/graph-passive-confirm.test.js +92 -0
- package/test/graph-weight-evolution.test.js +105 -0
- package/test/scope-inject-soft.test.js +106 -0
- package/test/summarize.test.js +177 -0
- package/test/test-count-sync.test.js +60 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// dsh-mneme/src/graph/anchoring.js
|
|
2
|
+
// 图谱锚定层(issue #24 · 块1 Activation Anchoring)。
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
// 纯函数模块:把「查询命中实体的多路激活信号」归一化、合并成种子集、再沿
|
|
5
|
+
// entity_relations 级联扩散。零数据库依赖——store 侧查询由调用方注入,
|
|
6
|
+
// 本模块只做信号处理,便于单测与与其他召回通路(BM25/向量)同等对待。
|
|
7
|
+
//
|
|
8
|
+
// 设计输入来自 #24 合议 + heptaspirit serendipity-engine 实战(#24 评论):
|
|
9
|
+
// - 归一化二分法:连续分(cos/PPR)走 min-max;匹配通路(精确/tag/别名)
|
|
10
|
+
// 走离散级别,不用 min-max——布尔通路用 min-max 会把「中 1 个」和「中
|
|
11
|
+
// 20 个」都拉平到 1.0,级别信息被压平。
|
|
12
|
+
// - 级联扩散加「跳数配额」:λ/θ 只管可及性,可见性由配额决定——直接按 hop
|
|
13
|
+
// 深度打 0.5/0.3/0.2 权重,配桶内 round-robin,防深跳被 1-hop 完全压住。
|
|
14
|
+
// - graphSeedCap:防「多锚点命中 + 模糊通路」把种子集撑爆成整库。
|
|
15
|
+
// - 排序稳定:并列按实体 ID 破序(同输入两次结果不同会让 A/B 调参白做)。
|
|
16
|
+
|
|
17
|
+
/** 匹配通路的离散级别(heptaspirit 建议:布尔/计数通路不用 min-max)。 */
|
|
18
|
+
export const DISCRETE_LEVELS = Object.freeze({
|
|
19
|
+
exact: 1.0, // 名称精确含于查询(布尔 1.0)
|
|
20
|
+
title: 0.8, // 实体名匹配记忆标题(tag/别名层)
|
|
21
|
+
alias: 0.6,
|
|
22
|
+
tag: 0.4, // tag 共现
|
|
23
|
+
substring: 0.2, // 子串命中(最弱,纯计数不级联)
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** 级联每跳的权重(跳数配额:1:2:3-hop = 0.5/0.3/0.2)。 */
|
|
27
|
+
export const HOP_QUOTA = Object.freeze({ 1: 0.5, 2: 0.3, 3: 0.2 });
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 连续分 min-max 归一化(向量 cos 相似度、PPR 激活分等)。
|
|
31
|
+
* 输入 [] 或全同值时返回原样(无尺度可压平,防除零)。
|
|
32
|
+
*/
|
|
33
|
+
export function minMax(scores) {
|
|
34
|
+
const arr = Array.isArray(scores) ? scores : [];
|
|
35
|
+
if (arr.length === 0) return [];
|
|
36
|
+
let min = Infinity;
|
|
37
|
+
let max = -Infinity;
|
|
38
|
+
for (const v of arr) {
|
|
39
|
+
if (v < min) min = v;
|
|
40
|
+
if (v > max) max = v;
|
|
41
|
+
}
|
|
42
|
+
if (max - min < 1e-12) return arr.map(() => 1); // 平局视为满权
|
|
43
|
+
return arr.map((v) => (v - min) / (max - min));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 把一条检测通路的结果归一化成 0..1 的打分表。
|
|
48
|
+
* path 是离散通路名(exact/tag/...)→ 查 DISCRETE_LEVELS;是连续通路
|
|
49
|
+
* (continuous=true)→ min-max。返回 { byId: Map<id, score>, order: [id...] }。
|
|
50
|
+
*/
|
|
51
|
+
export function normalizePath(hits, { path = "exact", continuous = false } = {}) {
|
|
52
|
+
const ids = Array.isArray(hits) ? hits : [];
|
|
53
|
+
const byId = new Map();
|
|
54
|
+
if (continuous) {
|
|
55
|
+
const raw = ids.map((h) => (typeof h === "number" ? h : h?.score ?? 0));
|
|
56
|
+
const norm = minMax(raw);
|
|
57
|
+
ids.forEach((h, i) => {
|
|
58
|
+
const id = typeof h === "object" ? h.id : h;
|
|
59
|
+
byId.set(id, norm[i]);
|
|
60
|
+
});
|
|
61
|
+
} else {
|
|
62
|
+
const level = DISCRETE_LEVELS[path] ?? DISCRETE_LEVELS.substring;
|
|
63
|
+
for (const id of ids) byId.set(id, level);
|
|
64
|
+
}
|
|
65
|
+
return { byId, order: [...byId.keys()] };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 合并多路激活成种子集:每路先归一化(调用方负责通路分类),再累加。
|
|
70
|
+
* seedsCap 上限(graphSeedCap,默认 12);封顶前按总分排序取前 N——保证
|
|
71
|
+
* 扩散的是活跃子图而非冷启动点爆整库。
|
|
72
|
+
* 返回 { id, name, score, paths: Set } 列表,按 score 降序、name 升序(稳定)。
|
|
73
|
+
*/
|
|
74
|
+
export function anchorSeeds({ paths = [], cap = 12 } = {}) {
|
|
75
|
+
const score = new Map();
|
|
76
|
+
const nameOf = new Map();
|
|
77
|
+
const pathSet = new Map();
|
|
78
|
+
for (const p of paths) {
|
|
79
|
+
for (const [id, s] of p.byId ?? []) {
|
|
80
|
+
score.set(id, (score.get(id) ?? 0) + s);
|
|
81
|
+
if (!pathSet.has(id)) pathSet.set(id, new Set());
|
|
82
|
+
pathSet.get(id).add(p.path ?? "?");
|
|
83
|
+
if (p.nameOf?.has?.(id)) nameOf.set(id, p.nameOf.get(id));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
let seeds = [...score.entries()].map(([id, s]) => ({
|
|
87
|
+
id,
|
|
88
|
+
name: nameOf.get(id) ?? id,
|
|
89
|
+
score: s,
|
|
90
|
+
paths: pathSet.get(id) ?? new Set()
|
|
91
|
+
}));
|
|
92
|
+
seeds.sort((a, b) => b.score - a.score || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
93
|
+
if (cap > 0 && seeds.length > cap) seeds = seeds.slice(0, cap);
|
|
94
|
+
return seeds;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 级联扩散:从种子实体出发沿 adjacency 走 BFS,为每个可达实体贴最短深度。
|
|
99
|
+
* depth 上界默认 2([1,3] 配置范围)。返回 Map<entityId, minDepth>——
|
|
100
|
+
* 调用方据此取 HOP_QUOTA[minDepth] 权重 + 桶内 round-robin(见 pickByHopQuota)。
|
|
101
|
+
* adjacency 由调用方提供(store.getEntityNeighbors(id) 或全量邻接矩阵),
|
|
102
|
+
* 本模块不感知存储。
|
|
103
|
+
*/
|
|
104
|
+
export function cascadeDepths({ seeds, adjacencyOf, maxDepth = 2 } = {}) {
|
|
105
|
+
const depths = new Map();
|
|
106
|
+
const idOfSeeds = (seeds ?? []).map((s) => (typeof s === "object" ? s.id : s));
|
|
107
|
+
const queue = [];
|
|
108
|
+
for (const id of idOfSeeds) {
|
|
109
|
+
if (!depths.has(id)) {
|
|
110
|
+
depths.set(id, 0);
|
|
111
|
+
queue.push([id, 0]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
for (let i = 0; i < queue.length; i++) {
|
|
115
|
+
const [id, d] = queue[i];
|
|
116
|
+
if (d >= maxDepth) continue;
|
|
117
|
+
let neighbors = [];
|
|
118
|
+
try {
|
|
119
|
+
neighbors = typeof adjacencyOf === "function" ? adjacencyOf(id) : (adjacencyOf?.get?.(id) ?? []);
|
|
120
|
+
} catch { /* single neighbor fetch failure: keep spreading from the rest */ }
|
|
121
|
+
for (const nb of neighbors) {
|
|
122
|
+
const nid = typeof nb === "object" ? nb.id : nb;
|
|
123
|
+
if (!nid || depths.has(nid)) continue;
|
|
124
|
+
depths.set(nid, d + 1);
|
|
125
|
+
queue.push([nid, d + 1]);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return depths;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 跳数配额选取:候选实体按深度分层,层内按(分,ID)稳定排序后取额度。
|
|
133
|
+
* quota 形如 { 1: 0.5, 2: 0.3, 3: 0.2 }——每层最多取 ceil(depthCap * quota[d]) 个,
|
|
134
|
+
* 桶内按 score 降序(并列按 ID)。返回 { ids, scoreOf, depthOf }。
|
|
135
|
+
* 这一步把「级联可及性」与「最终可见性」解耦(heptaspirit:λ/θ 只管前者)。
|
|
136
|
+
*/
|
|
137
|
+
export function pickByHopQuota({
|
|
138
|
+
depths = new Map(),
|
|
139
|
+
scoreOf = () => 0,
|
|
140
|
+
maxDepth = 2,
|
|
141
|
+
depthCap = 12
|
|
142
|
+
} = {}) {
|
|
143
|
+
const buckets = new Map(); // depth -> [{id, score}]
|
|
144
|
+
for (const [id, d] of depths) {
|
|
145
|
+
if (d === 0 || d > maxDepth) continue;
|
|
146
|
+
const key = Math.min(d, 3);
|
|
147
|
+
if (!buckets.has(key)) buckets.set(key, []);
|
|
148
|
+
buckets.get(key).push({ id, score: scoreOf(id) ?? 0 });
|
|
149
|
+
}
|
|
150
|
+
const picked = [];
|
|
151
|
+
for (const [d, items] of buckets) {
|
|
152
|
+
items.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
153
|
+
const quota = HOP_QUOTA[d] ?? 0.2;
|
|
154
|
+
const n = Math.max(1, Math.floor(depthCap * quota));
|
|
155
|
+
picked.push(...items.slice(0, n).map((x) => x.id));
|
|
156
|
+
}
|
|
157
|
+
// 队内稳定序:按深度升序(1-hop 优先),保证可感知的扩散次序。
|
|
158
|
+
picked.sort((a, b) => (depths.get(a) - depths.get(b)) || (a < b ? -1 : a > b ? 1 : 0));
|
|
159
|
+
return { ids: picked, scoreOf, depthOf: depths };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Lightweight self-check (ponytail: 非平凡逻辑留一个可运行断言)。
|
|
163
|
+
export function _selfCheck() {
|
|
164
|
+
const exact = normalizePath(["e1", "e2"], { path: "exact" });
|
|
165
|
+
const tag = normalizePath(["e2", "e3"], { path: "tag" });
|
|
166
|
+
assert(exact.byId.get("e1") === 1.0 && exact.byId.get("e2") === 1.0, "exact level");
|
|
167
|
+
assert(tag.byId.get("e2") === 0.4 && tag.byId.get("e3") === 0.4, "tag level");
|
|
168
|
+
const seeds = anchorSeeds({ paths: [exact, tag], cap: 10 });
|
|
169
|
+
assert(seeds[0].id === "e2", "merged highest first"); // e2: 精确+tag = 1.4
|
|
170
|
+
assert(seeds[0].score >= 1.4 - 1e-9, "score accumulates");
|
|
171
|
+
const adj = new Map([
|
|
172
|
+
["e2", ["n1", "n2"]],
|
|
173
|
+
["n1", ["n2", "deep3"]],
|
|
174
|
+
]);
|
|
175
|
+
const depths = cascadeDepths({ seeds, adjacencyOf: (id) => adj.get(id) ?? [], maxDepth: 2 });
|
|
176
|
+
assert(depths.get("n1") === 1 && depths.get("n2") === 1 && depths.get("deep3") === 2, "bfs depth");
|
|
177
|
+
const { ids } = pickByHopQuota({ depths, maxDepth: 2, depthCap: 12 });
|
|
178
|
+
assert(ids.includes("n1") && ids.includes("n2") && ids.includes("deep3"), "quota picks all");
|
|
179
|
+
return "anchoring self-check ok";
|
|
180
|
+
}
|
package/src/index.js
CHANGED
|
@@ -502,6 +502,11 @@ export const apply = (ctx, config) => {
|
|
|
502
502
|
logger: ctx.logger,
|
|
503
503
|
semantic: { embedder, vectorIndex },
|
|
504
504
|
lastRunAtSeed: store.lastDreamRunAt("auto"),
|
|
505
|
+
// Issue #89(基线半边):阈值基线同样跨重启恢复——只恢复 lastRunAt 的话,
|
|
506
|
+
// 重启后的第一条写入仍会绕过阈值(库里记忆多于阈值时 overBase 恒成立)开跑
|
|
507
|
+
// 整轮。种子取上次成功轮的库规模,口径与运行期刷新一致;读不到时调度器退回
|
|
508
|
+
// 零基线(= 升级前行为)。
|
|
509
|
+
baselineSeed: store.lastDreamBaseline("auto"),
|
|
505
510
|
// Issue #239(第 4 项)镜像到巩固:高峰期不做梦,顺延到最近的高峰结束时刻。
|
|
506
511
|
peakHours: cfg.dreamPeakHours ?? "",
|
|
507
512
|
peakMaxDeferMinutes: cfg.dreamPeakMaxDeferMinutes ?? 120,
|
package/src/inject.js
CHANGED
|
@@ -274,9 +274,14 @@ export function createInjector(ctx, service, settings, config) {
|
|
|
274
274
|
// 日志抢同一份预算后被降级」正是本议题要修的结构缺陷。单条仍有硬顶
|
|
275
275
|
// (PINNED_CONTENT_MAX),超出照旧带截断提示,不静默。
|
|
276
276
|
const pinnedCount = Math.max(0, Math.min(candidates.length, pinnedStats?.shown ?? 0));
|
|
277
|
+
// #24 块3:图召回线索行(graphHint)——引导语插在第一个线索行之前(保持块头
|
|
278
|
+
// 语义:先声明「这些不是事实」)。线索行自身按 graphHintLine 渲染(线索/ 前缀
|
|
279
|
+
// 区别于普通记忆行)。
|
|
280
|
+
let graphSeen = 0;
|
|
277
281
|
for (let i = 0; i < candidates.length; i++) {
|
|
278
282
|
const m = candidates[i];
|
|
279
283
|
const pinned = i < pinnedCount;
|
|
284
|
+
if (m.graphHint === true) graphSeen++;
|
|
280
285
|
// Epistemic trust (v0.4.5): when enabled, measured observations are
|
|
281
286
|
// flagged so the agent can weigh them above guesses/opinions.
|
|
282
287
|
const verified = config.trustEpistemicWeighting === true && m.epistemic_status === "observation"
|
|
@@ -284,7 +289,13 @@ export function createInjector(ctx, service, settings, config) {
|
|
|
284
289
|
: "";
|
|
285
290
|
const title = STR.entryTitle[language](m.title, m.importance);
|
|
286
291
|
const content = injectMemory(m, pinned ? PINNED_CONTENT_MAX : maxContent);
|
|
287
|
-
const full =
|
|
292
|
+
const full = m.graphHint === true
|
|
293
|
+
? STR.graphHintLine[language](m.type, title, content)
|
|
294
|
+
: STR.entryLine[language](m.type, verified, title, content);
|
|
295
|
+
// 线索行引导语插在第一个线索行之前(保持块头语义:先声明「这些不是事实」)。
|
|
296
|
+
if (m.graphHint === true && graphSeen === 1) {
|
|
297
|
+
lines.push(STR.graphHintHeader[language]);
|
|
298
|
+
}
|
|
288
299
|
if (pinned) {
|
|
289
300
|
// pin 不扣块预算(上面那条设计注释的落地):pin 一条就够击穿 MAX_BLOCK
|
|
290
301
|
// (PINNED_CONTENT_MAX 2000 > MAX_BLOCK 1500),照扣会把 budget 压成负数,
|
|
@@ -363,8 +374,9 @@ export function createInjector(ctx, service, settings, config) {
|
|
|
363
374
|
const query = lastUserQuery(ctx);
|
|
364
375
|
if (query) prefetchQueryVector(query);
|
|
365
376
|
const queryVector = queryVectorCache.get(query);
|
|
366
|
-
// v0.8.0 A3:scope
|
|
367
|
-
//
|
|
377
|
+
// v0.8.0 A3:scope 随请求解析(解析器恒返回对象,身份取不到时两维为
|
|
378
|
+
// null);硬过滤与软加权的门控都在 injectCandidates 内——strict 看
|
|
379
|
+
// strictScope,软加权看 scopeEnabled 且至少一维可解析(issue #339)。
|
|
368
380
|
const scope = resolveSessionScope(ctx);
|
|
369
381
|
// Issue #205:跨轮轮换——最近 N 个查询轮次注入过的 id 本轮不再优先。
|
|
370
382
|
const sessionId = ctx?.agent?.session?.id ?? "_";
|
package/src/lang.js
CHANGED
|
@@ -81,6 +81,16 @@ export const STR = {
|
|
|
81
81
|
zh: (n) => `〔约束/偏好类另有 ${n} 条未展示〕`,
|
|
82
82
|
en: (n) => `[${n} more constraint/preference entries not shown]`
|
|
83
83
|
},
|
|
84
|
+
// Issue #24 块3:图召回线索行的引导语——正向声明「链路信息非事实断言」,
|
|
85
|
+
// 防 LLM 单次消费把桥接召回当有依据的事实回头扩散(幻觉诱导)。
|
|
86
|
+
graphHintHeader: {
|
|
87
|
+
zh: "[检索线索] 以下为实体图搜索的链路信息,仅供定位参考,非事实断言:",
|
|
88
|
+
en: "[Retrieval hints] Entity-graph link trails below are navigation aids, not factual assertions:"
|
|
89
|
+
},
|
|
90
|
+
graphHintLine: {
|
|
91
|
+
zh: (type, title, content) => `- [线索/${type}] ${title}:${content}`,
|
|
92
|
+
en: (type, title, content) => `- [hint/${type}] ${title}: ${content}`
|
|
93
|
+
},
|
|
84
94
|
userSettingsHeader: {
|
|
85
95
|
zh: "[用户设置] 来自 dsh-mneme 的用户画像与规则:",
|
|
86
96
|
en: "[User settings] Profile and rules from dsh-mneme:"
|
package/src/service.js
CHANGED
|
@@ -11,6 +11,7 @@ import { createDocumentRegistrar } from "./document.js";
|
|
|
11
11
|
import { createOrganizer } from "./organize.js";
|
|
12
12
|
import { createBM25Index } from "./search/bm25.js";
|
|
13
13
|
import { adaptiveThreshold } from "./search/adaptive.js";
|
|
14
|
+
import { anchorSeeds, normalizePath, cascadeDepths, HOP_QUOTA } from "./graph/anchoring.js";
|
|
14
15
|
|
|
15
16
|
const INJECT_TYPES = new Set(["preference", "project", "decision", "summary", "rejected_solution", "pitfall", "constraint"]);
|
|
16
17
|
|
|
@@ -448,30 +449,92 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
448
449
|
}
|
|
449
450
|
|
|
450
451
|
/**
|
|
451
|
-
* Graph fourth recall path (issue #219). When the query text
|
|
452
|
-
* known entity name, memories linked to that entity (attrs +
|
|
453
|
-
* join the fusion pool as a confirm/backfill signal — same standing
|
|
454
|
-
* BM25, never dominating the semantic ranking. Tier scores: attr-linked
|
|
455
|
-
* 1.0 (direct evidence, same source searchByEntity trusts) > relation
|
|
456
|
-
*
|
|
457
|
-
*
|
|
458
|
-
*
|
|
452
|
+
* Graph fourth recall path (issue #219 → #24 块1 锚定层). When the query text
|
|
453
|
+
* mentions a known entity name, memories linked to that entity (attrs +
|
|
454
|
+
* relations) join the fusion pool as a confirm/backfill signal — same standing
|
|
455
|
+
* as BM25, never dominating the semantic ranking. Tier scores: attr-linked
|
|
456
|
+
* 1.0 (direct evidence, same source searchByEntity trusts) > relation edge
|
|
457
|
+
* 0.9. Archived/forgotten rows never participate. Failures degrade to [] —
|
|
458
|
+
* a recall booster, never a correctness gate (same contract as bm25Recall).
|
|
459
|
+
*
|
|
460
|
+
* #24 升级(graphAnchoringEnabled):命中实体作为锚定种子,沿 entity_relations
|
|
461
|
+
* 级联扩散邻居(默认深度 2),邻居挂联的记忆以 hop 配额权重参与——把「关系是
|
|
462
|
+
* 用出来的」延伸成检索信号:查询命中的不只有直接挂联,还有跳跃可达的活跃子图。
|
|
463
|
+
* 邻居权重 = HOP_QUOTA[hop] × linked tier(attr 1.0 / relation 0.9),仍低于
|
|
464
|
+
* 直达种子的满权,绝不喧宾夺主。
|
|
459
465
|
*/
|
|
460
466
|
function entityRecall(q, limit) {
|
|
461
467
|
if (config?.entityRecallEnabled !== true) return [];
|
|
462
468
|
try {
|
|
463
469
|
const entities = store.findEntitiesMentionedIn(q);
|
|
464
470
|
if (!entities.length) return [];
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const
|
|
470
|
-
if (!
|
|
471
|
-
hits
|
|
472
|
-
|
|
471
|
+
// 关闭锚定级联=逐字节复用 #219 单跳轴:种子裁剪/重排/截断全是 #24 新增的
|
|
472
|
+
// 行为,默认关时一条都不许漏进旧路径(graphSeedCap 也只在开启后生效——
|
|
473
|
+
// 无论 cap 调多小,关档时命中实体仍全量挂联)。
|
|
474
|
+
if (config?.graphAnchoringEnabled !== true) {
|
|
475
|
+
const linked = store.getLinkedMemoryIds(entities.map((e) => e.id));
|
|
476
|
+
if (!linked.size) return [];
|
|
477
|
+
const hits = [];
|
|
478
|
+
for (const [id, tier] of linked) {
|
|
479
|
+
const row = store.getById(id);
|
|
480
|
+
if (!row || row.archived || row.forgotten) continue;
|
|
481
|
+
hits.push({ ...row, score: tier === "attr" ? 1.0 : 0.9, source: "entity" });
|
|
482
|
+
if (hits.length >= limit * 2) break;
|
|
483
|
+
}
|
|
484
|
+
return hits;
|
|
485
|
+
}
|
|
486
|
+
// 锚定种子(精确名布尔通路——命名实体逻辑上是离散匹配,不参与 min-max)。
|
|
487
|
+
const exact = normalizePath(entities.map((e) => e.id), { path: "exact" });
|
|
488
|
+
const seeds = anchorSeeds({ paths: [exact], cap: config?.graphSeedCap ?? 12 });
|
|
489
|
+
if (!seeds.length) return [];
|
|
490
|
+
// 0-hop 直达:挂联记忆按 tier 定分(attr 1.0 / relation 0.9)——与 #219
|
|
491
|
+
// 单跳轴同分。MAX 语义:同一条记忆被多实体挂联时保留最高分。
|
|
492
|
+
const scored = new Map();
|
|
493
|
+
const push = (memId, score) => {
|
|
494
|
+
if (scored.has(memId) && scored.get(memId) >= score) return;
|
|
495
|
+
const row = store.getById(memId);
|
|
496
|
+
if (!row || row.archived || row.forgotten) return;
|
|
497
|
+
scored.set(memId, score);
|
|
498
|
+
};
|
|
499
|
+
const seedLinked = store.getLinkedMemoryIds(seeds.map((s) => s.id));
|
|
500
|
+
for (const [memId, tier] of seedLinked) {
|
|
501
|
+
push(memId, tier === "attr" ? 1.0 : 0.9);
|
|
502
|
+
}
|
|
503
|
+
// 级联:沿 entity_relations 走 BFS,邻居挂联的记忆以 hop 配额权重补位——
|
|
504
|
+
// 不覆盖种子直达分(MAX 语义保证),只填「种子里没有但邻居可达」的槽。
|
|
505
|
+
const seedIds = seeds.map((s) => s.id);
|
|
506
|
+
const adjacency = store.getEntityNeighbors(seedIds);
|
|
507
|
+
const depths = cascadeDepths({
|
|
508
|
+
seeds,
|
|
509
|
+
// 逐节点懒取邻居:初次查询只带种子那一层的邻接,BFS 走到 1-hop 节点时
|
|
510
|
+
// 必须按需再拉一层,否则 >1 跳永远拿到空邻居、graphCascadeDepth≥2 形同
|
|
511
|
+
// 虚设。节点数随图度数增长,热路径上以 graphCascadeDepth≤3 为天然上界,
|
|
512
|
+
// 真遇到大图再考虑查询配额。
|
|
513
|
+
adjacencyOf: (id) => {
|
|
514
|
+
if (!adjacency.has(id)) adjacency.set(id, store.getEntityNeighbors([id]).get(id) ?? []);
|
|
515
|
+
return adjacency.get(id);
|
|
516
|
+
},
|
|
517
|
+
maxDepth: config?.graphCascadeDepth ?? 2
|
|
518
|
+
});
|
|
519
|
+
let neighborsSeen = 0;
|
|
520
|
+
const neighborCap = (config?.graphSeedCap ?? 12) * HOP_QUOTA[1]; // 1-hop 配额即为邻居总量上界
|
|
521
|
+
for (const [nid, hop] of depths) {
|
|
522
|
+
if (hop < 1) continue;
|
|
523
|
+
if (neighborsSeen >= Math.max(1, Math.floor(neighborCap))) break;
|
|
524
|
+
neighborsSeen++;
|
|
525
|
+
const neighborLinked = store.getLinkedMemoryIds([nid]);
|
|
526
|
+
for (const [memId, tier] of neighborLinked) {
|
|
527
|
+
const tierW = tier === "attr" ? 1.0 : 0.9;
|
|
528
|
+
push(memId, HOP_QUOTA[Math.min(hop, 3)] * tierW);
|
|
529
|
+
}
|
|
473
530
|
}
|
|
474
|
-
|
|
531
|
+
const hits = [...scored.entries()]
|
|
532
|
+
.map(([id, score]) => {
|
|
533
|
+
const row = store.getById(id);
|
|
534
|
+
return { ...row, score, source: "entity" };
|
|
535
|
+
})
|
|
536
|
+
.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
537
|
+
return hits.slice(0, limit * 2);
|
|
475
538
|
} catch {
|
|
476
539
|
return [];
|
|
477
540
|
}
|
|
@@ -530,11 +593,28 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
530
593
|
* on the hot recall path). A touch failure must never break search/inject.
|
|
531
594
|
*/
|
|
532
595
|
function touchRecalled(memories) {
|
|
533
|
-
if (
|
|
596
|
+
if (!Array.isArray(memories) || memories.length === 0) return;
|
|
597
|
+
// heatEnabled=false 只关 touchLastAccess 的热度消费(既有语义),但 #24
|
|
598
|
+
// 块4 被动确认独立于 heat——graphPassiveConfirm 开时照常 bump 关联边。
|
|
599
|
+
// graphWeightEnabled 是块2 立的演化总闸:它关着时任何触达都不该改边权,被动
|
|
600
|
+
// 确认只是它底下的一个通道(后续块还会接别的确认通道),两键同开才 bump,
|
|
601
|
+
// 否则单开通道键就等于绕过「演化默认关」的承诺。
|
|
602
|
+
// 两条路径都 best-effort,失败绝不阻断检索/注入。
|
|
603
|
+
const heatOn = config?.heatEnabled !== false;
|
|
604
|
+
const passive = config?.graphPassiveConfirm === true && config?.graphWeightEnabled === true;
|
|
605
|
+
const delta = config?.graphWeightDelta ?? 0.1;
|
|
534
606
|
for (const m of memories) {
|
|
535
607
|
if (!m?.id) continue;
|
|
536
608
|
try {
|
|
537
|
-
store.touchLastAccess(m.id);
|
|
609
|
+
if (heatOn) store.touchLastAccess(m.id);
|
|
610
|
+
if (passive) {
|
|
611
|
+
// 正常触达=对该记忆挂联关系边的被动确认;bump 只加不减封顶 1.0,
|
|
612
|
+
// 自激回路由封顶天然遏制。「仅异常路径暴露给用户复核」的确认记录
|
|
613
|
+
// 侧在此落地,复核 UI 留后续块。
|
|
614
|
+
for (const rel of store.getRelationsByMemory(m.id)) {
|
|
615
|
+
store.bumpRelationWeight(rel.id, delta);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
538
618
|
} catch { /* touch is best effort */ }
|
|
539
619
|
}
|
|
540
620
|
}
|
|
@@ -1427,6 +1507,14 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1427
1507
|
? new Map(filtered.map((m) => [m.id, computeHeat(m, Date.now(), config)]))
|
|
1428
1508
|
: null;
|
|
1429
1509
|
const heatOf = (m) => (heatMap ? heatMap.get(m.id) ?? 1 : 1);
|
|
1510
|
+
// v0.8.x(issue #339 / E7 实测):A2 软加权补齐到注入通道。此前 ×0.5/×1.25
|
|
1511
|
+
// 只作用于 searchMemories——E7 考卷里「explicit 标注 + 软档」的注入集与无标注
|
|
1512
|
+
// 逐条相同(80/80),主泄露面上软档形同虚设。门控与检索侧同款:scopeEnabled
|
|
1513
|
+
// 且当前会话至少一维可解析;strictScope 硬过滤在下方先行,硬墙开启时被滤行
|
|
1514
|
+
// 不会到这里被二次降权。未激活时乘 1,排序与改动前逐字节一致。
|
|
1515
|
+
const softScopeActive = config?.scopeEnabled === true && scope != null &&
|
|
1516
|
+
Boolean(scope.agent_scope || scope.workspace_scope);
|
|
1517
|
+
const scopeMultOf = (m) => (softScopeActive ? scopeMultiplier(m, scope) : 1);
|
|
1430
1518
|
const items = filtered.sort((a, b) => {
|
|
1431
1519
|
// 编码记忆在编码任务时优先于普通 decision(与 preference 同级),
|
|
1432
1520
|
// importance 乘 codingBoostFactor 加权(封顶 5,保持 importance 语义)。
|
|
@@ -1447,8 +1535,11 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1447
1535
|
: m.importance;
|
|
1448
1536
|
const pa = priority(a);
|
|
1449
1537
|
const pb = priority(b);
|
|
1538
|
+
// 软加权乘在层内数值积上(priority 档位不动):foreign ×0.5 后压不过
|
|
1539
|
+
// 同档自己行——E7 的同 importance 档设计正是这个场景。
|
|
1450
1540
|
return pa - pb ||
|
|
1451
|
-
(effImportance(b) * qualityWeight(b) * heatOf(b)
|
|
1541
|
+
(effImportance(b) * qualityWeight(b) * heatOf(b) * scopeMultOf(b)) -
|
|
1542
|
+
(effImportance(a) * qualityWeight(a) * heatOf(a) * scopeMultOf(a));
|
|
1452
1543
|
});
|
|
1453
1544
|
let candidates = items;
|
|
1454
1545
|
if (config.hybridInject !== false && q) {
|
|
@@ -1493,6 +1584,13 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1493
1584
|
semanticItems.push(hit);
|
|
1494
1585
|
}
|
|
1495
1586
|
}
|
|
1587
|
+
// issue #339(CodeRabbit review on #350):首轮 BM25 兜底领跑合并池,
|
|
1588
|
+
// 而 selectiveInject 相似度重排要等查询向量就绪才执行——软加权必须
|
|
1589
|
+
// 在这里就位,否则 foreign 命中绕过降权直接占注入位。
|
|
1590
|
+
if (softScopeActive) {
|
|
1591
|
+
semanticItems.sort((a, b) =>
|
|
1592
|
+
(b.score ?? 0) * scopeMultOf(b) - (a.score ?? 0) * scopeMultOf(a));
|
|
1593
|
+
}
|
|
1496
1594
|
}
|
|
1497
1595
|
if (semanticItems.length) {
|
|
1498
1596
|
const seen = new Set();
|
|
@@ -1523,7 +1621,13 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1523
1621
|
const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
|
|
1524
1622
|
const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
|
|
1525
1623
|
if (sim.size) {
|
|
1526
|
-
|
|
1624
|
+
// 软加权作用在真实 sim 上;未命中的规则候选保持 -1 沉底(缺失项
|
|
1625
|
+
// 乘乘数会让 foreign 缺失项反而排到自己的缺失项之上,故不乘)。
|
|
1626
|
+
const scopedSim = (m) => {
|
|
1627
|
+
const s = sim.get(m.id);
|
|
1628
|
+
return s === undefined ? -1 : s * scopeMultOf(m);
|
|
1629
|
+
};
|
|
1630
|
+
candidates = [...candidates].sort((a, b) => scopedSim(b) - scopedSim(a));
|
|
1527
1631
|
}
|
|
1528
1632
|
} catch { /* topic re-rank unavailable: keep rule-based order */ }
|
|
1529
1633
|
}
|
|
@@ -1532,6 +1636,26 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1532
1636
|
if (config?.strictScope === true && scope) {
|
|
1533
1637
|
candidates = candidates.filter((m) => isVisibleInScope(m, scope));
|
|
1534
1638
|
}
|
|
1639
|
+
// #24 块3:图召回候选打标。entityRecall 只在 entityRecallEnabled 开启时
|
|
1640
|
+
// 有产出,这里为命中者贴 graphHint 标签——注入侧据此(a)graphInjectHint
|
|
1641
|
+
// 开=标成 [检索线索] 前缀的线索行(独立预算),(b)关=线索行只参与排序
|
|
1642
|
+
// 不改变注入块(保守档)。与检索侧共用同一图闸:块1 #341 把 entityRecall
|
|
1643
|
+
// 升级成级联后,注入侧自动吃到同样的扩散信号,无需再改。只在语义/规则候选
|
|
1644
|
+
// 为空时兜底检索,避免注入路径双倍候选成本。
|
|
1645
|
+
if (config?.entityRecallEnabled === true && q) {
|
|
1646
|
+
try {
|
|
1647
|
+
const graphHits = entityRecall(q, maxItems * 2);
|
|
1648
|
+
if (graphHits.length) {
|
|
1649
|
+
const graphIds = new Set(graphHits.map((m) => m.id));
|
|
1650
|
+
candidates = [
|
|
1651
|
+
...candidates.map((m) => graphIds.has(m.id) ? { ...m, graphHint: true } : m),
|
|
1652
|
+
...graphHits
|
|
1653
|
+
.filter((m) => !candidates.some((c) => c.id === m.id))
|
|
1654
|
+
.map((m) => ({ ...m, graphHint: true }))
|
|
1655
|
+
];
|
|
1656
|
+
}
|
|
1657
|
+
} catch { /* graph hint is best-effort */ }
|
|
1658
|
+
}
|
|
1535
1659
|
// #249 第一批:B1 pin 池。取在相关性排序之后、轮换之前——取谁按此刻的候选
|
|
1536
1660
|
// 次序(即相关性次序),取到后从候选中摘除,于是下面的轮换重排碰不到它们
|
|
1537
1661
|
// (验收:pin 不参与跨轮轮换)。独立预算的两层意义:pin 既不占 maxItems
|
|
@@ -1539,7 +1663,10 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1539
1663
|
// 超预算的条数回报给调用方,在块内如实标注(绝不静默省略)。
|
|
1540
1664
|
const pinnedBudget = Math.max(0, Math.min(5, Math.floor(config?.pinnedInjectBudget ?? 0)));
|
|
1541
1665
|
// eligible 留到块外:未展示条数要等 general 槽选完才算得准(见 selected 之后)。
|
|
1542
|
-
|
|
1666
|
+
// graphHint 行不进 pin 池:pin 是「每轮必进的约束/偏好」,而线索行按定义是
|
|
1667
|
+
// 「链路信息、非事实断言」,且 pin 长在候选池遍历之前——不排除的话,保守档
|
|
1668
|
+
// (graphInjectHint 关)也能从 pin 侧把它放回注入块,线索开关就被绕过去了。
|
|
1669
|
+
const eligible = pinnedBudget > 0 ? candidates.filter((m) => PINNED_MEMORY_TYPES.has(m.type) && m.graphHint !== true) : [];
|
|
1543
1670
|
let pinned = [];
|
|
1544
1671
|
if (pinnedBudget > 0 && eligible.length > 0) {
|
|
1545
1672
|
pinned = eligible.slice(0, pinnedBudget);
|
|
@@ -1560,9 +1687,23 @@ export function createService({ store, mirror, config, onWrite, logger, document
|
|
|
1560
1687
|
// 注入块变成文档目录(#164 失败判据:批量把历史塞进上下文)。
|
|
1561
1688
|
const documentBudget = config?.documentInjectBudget ?? 2;
|
|
1562
1689
|
let documentSeen = 0;
|
|
1690
|
+
// #24 块3:图线索行(graphHint)按独立预算 graphInjectBudget 进块;所谓
|
|
1691
|
+
// 独立=既不受 document 预算约束、也不挤占 maxItems 槽位。graphInjectHint
|
|
1692
|
+
// 关(默认保守档)时线索行**不进注入块**——它们只参与候选池排序(对融合无
|
|
1693
|
+
// 影响,因为候选池生成的唯一用途就是注入),桥接信号不污染常驻文本;开时
|
|
1694
|
+
// 才作为 [检索线索] 前缀行进入。与 document/pin 同构:预算只约束注入。
|
|
1695
|
+
const hintOpen = config?.graphInjectHint === true;
|
|
1696
|
+
let graphSeen = 0;
|
|
1697
|
+
const graphBudget = hintOpen ? Math.max(0, Math.floor(config?.graphInjectBudget ?? 1)) : 0;
|
|
1563
1698
|
const general = [];
|
|
1564
1699
|
for (const m of candidates) {
|
|
1565
|
-
if (
|
|
1700
|
+
if (m.graphHint === true) {
|
|
1701
|
+
if (!hintOpen) continue; // 保守档:线索只排序不进块
|
|
1702
|
+
if (graphSeen >= graphBudget) continue; // 独立预算内放行
|
|
1703
|
+
graphSeen++;
|
|
1704
|
+
} else if (general.length >= maxItems) {
|
|
1705
|
+
break; // 普通候选受 maxItems 槽位上界
|
|
1706
|
+
}
|
|
1566
1707
|
if (m.type === "document") {
|
|
1567
1708
|
if (documentSeen >= documentBudget) continue;
|
|
1568
1709
|
documentSeen++;
|
package/src/settings.js
CHANGED
|
@@ -58,6 +58,18 @@ const FEATURE_FLAG_BOOLEANS = [
|
|
|
58
58
|
// Issue #219:图召回轴——查询命中实体名时把挂联记忆并入检索融合池
|
|
59
59
|
// (默认关;依赖实体抽取产出,lightMode 强制关闭)。
|
|
60
60
|
"entityRecallEnabled",
|
|
61
|
+
// Issue #24 块1:图谱锚定层级联——命中实体作种子、沿关系表向邻居扩散
|
|
62
|
+
// (默认关;依赖实体抽取产出,lightMode 强制关闭)。
|
|
63
|
+
"graphAnchoringEnabled",
|
|
64
|
+
// Issue #24 块2:边权重演化总闸——关着时任何触达都不改边权(默认关;
|
|
65
|
+
// 依赖实体抽取产出,lightMode 强制关闭)。块4 的被动确认是它底下的一个通道。
|
|
66
|
+
"graphWeightEnabled",
|
|
67
|
+
// Issue #24 块3:关联提示防幻觉——图召回线索行以「[检索线索]」标注进注入
|
|
68
|
+
// (默认关=线索只参与排序不进块;依赖实体抽取产出,lightMode 强制关闭)。
|
|
69
|
+
"graphInjectHint",
|
|
70
|
+
// Issue #24 块4:被动确认通道——正常触达即对该记忆挂联的边 bump 一格
|
|
71
|
+
// (默认关;需总闸 graphWeightEnabled 同开)。
|
|
72
|
+
"graphPassiveConfirm",
|
|
61
73
|
// Issue #164:叙述条——dream 期间按 tag 主题簇合成叙述落库(source=
|
|
62
74
|
// narrative,evidence 回链簇内记忆;按需检索不常驻注入;默认关)。
|
|
63
75
|
"dreamNarrativeEnabled",
|
|
@@ -88,6 +100,9 @@ const FEATURE_FLAG_BOOLEANS = [
|
|
|
88
100
|
// Issue #89:宽容校验回归(默认开)+ 跨类型合并显式放宽(默认关)。
|
|
89
101
|
"dreamSkipInvalid",
|
|
90
102
|
"allowCrossTypeMerge",
|
|
103
|
+
// Issue #339 / E8:guarded 类型 merge 护栏(默认关)——合并对象命中
|
|
104
|
+
// 长保留类型的 merge 决策整条跳过。
|
|
105
|
+
"dreamMergeGuard",
|
|
91
106
|
// Issue #17(v0.8.0 A1):scope 隔离存储层总开关。开启后写入标注
|
|
92
107
|
// agent_scope/workspace_scope、去重键扩展(含 sensitivity);检索侧过滤在
|
|
93
108
|
// A2/A3。默认关=行为与 A1 前逐字节一致。
|
|
@@ -143,7 +158,12 @@ const FEATURE_FLAG_INT_RANGES = {
|
|
|
143
158
|
// Issue #257:sleep 冲突/模式阶段的 LLM 输出预算(原硬编码 2048,实测不足)。
|
|
144
159
|
sleepMaxTokens: [256, 131072],
|
|
145
160
|
// Issue #258:总览(dream_summarize)输入条数硬上限(0 = 不设上限)。
|
|
146
|
-
dreamSummaryMaxInputs: [0, 100000]
|
|
161
|
+
dreamSummaryMaxInputs: [0, 100000],
|
|
162
|
+
// Issue #24 块1:锚定种子上限与级联深度(闭区间与 config.js 的 z.natural() 对齐)。
|
|
163
|
+
graphSeedCap: [1, 30],
|
|
164
|
+
graphCascadeDepth: [1, 3],
|
|
165
|
+
// Issue #24 块3:图线索行的独立注入预算(0 = 线索不进块)。
|
|
166
|
+
graphInjectBudget: [0, 5]
|
|
147
167
|
};
|
|
148
168
|
// 浮点开关的闭区间(与 config.js 的 z.number().min().max() 对齐)。与整数开关
|
|
149
169
|
// 分开:面板的整数控件要求 Number.isInteger,而余弦相似度阈值必须允许小数。
|
|
@@ -151,7 +171,9 @@ const FEATURE_FLAG_NUMBER_RANGES = {
|
|
|
151
171
|
// Issue #127:vector 去重档的并入阈值。
|
|
152
172
|
summarizeDedupeMinSim: [0.5, 0.99],
|
|
153
173
|
// Issue #125:hybrid 判"高相似"的阈值。
|
|
154
|
-
dreamCandidateMinSim: [0.5, 0.99]
|
|
174
|
+
dreamCandidateMinSim: [0.5, 0.99],
|
|
175
|
+
// Issue #24 块2:单次有效触达的边权抬升幅度(与 config.js 的闭区间对齐)。
|
|
176
|
+
graphWeightDelta: [0, 1]
|
|
155
177
|
};
|
|
156
178
|
// 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
|
|
157
179
|
// 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
|