@modusensus/dsh-mneme 0.8.14 → 0.8.16

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.
Files changed (279) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +660 -654
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +691 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -151
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +275 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/DISTILL.md +162 -0
  12. package/docs/ENTITIES.md +245 -0
  13. package/docs/LOCAL_MODEL.md +222 -0
  14. package/docs/SEMANTIC.md +256 -0
  15. package/docs/SLEEP.md +164 -0
  16. package/docs/STORAGE.md +98 -0
  17. package/lib/api-standalone.js +656 -673
  18. package/lib/api.js +1605 -1433
  19. package/lib/bootstrap.js +211 -211
  20. package/lib/client.js +6354 -5296
  21. package/lib/commands.js +95 -95
  22. package/lib/config.js +947 -843
  23. package/lib/content-hash.js +54 -54
  24. package/lib/continuity.js +220 -220
  25. package/lib/document-index.js +94 -94
  26. package/lib/document.js +303 -303
  27. package/lib/dream/clustering.js +118 -118
  28. package/lib/dream/decisions.js +694 -674
  29. package/lib/dream/narratives.js +44 -44
  30. package/lib/dream/sleep.js +819 -819
  31. package/lib/dream.js +1503 -1501
  32. package/lib/embedding.js +177 -177
  33. package/lib/entities/extractor.js +252 -252
  34. package/lib/graph/anchoring.js +179 -179
  35. package/lib/guide.js +74 -74
  36. package/lib/heat.js +144 -144
  37. package/lib/hot-memory.js +108 -46
  38. package/lib/index.js +552 -503
  39. package/lib/inject.js +428 -450
  40. package/lib/lang.js +248 -229
  41. package/lib/local-embedder.js +358 -358
  42. package/lib/maintenance.js +162 -142
  43. package/lib/mirror.js +330 -330
  44. package/lib/organize.js +450 -450
  45. package/lib/peak-hours.js +117 -117
  46. package/lib/placement.js +13 -0
  47. package/lib/pre-inject-gate.js +340 -0
  48. package/lib/quality-filter.js +126 -126
  49. package/lib/recall-stats.js +190 -175
  50. package/lib/reclaim-http.js +150 -0
  51. package/lib/reranker.js +269 -269
  52. package/lib/runtime/adopt.js +176 -176
  53. package/lib/runtime/closure.js +172 -172
  54. package/lib/runtime/download.js +247 -247
  55. package/lib/runtime/layout.js +265 -265
  56. package/lib/runtime/loader.js +252 -252
  57. package/lib/runtime/model-fetch.js +361 -361
  58. package/lib/runtime/provision.js +237 -237
  59. package/lib/runtime/tarball.js +130 -130
  60. package/lib/runtime/verify.js +223 -204
  61. package/lib/safe-slice.js +18 -0
  62. package/lib/scope.js +146 -146
  63. package/lib/search/adaptive.js +60 -60
  64. package/lib/search/bm25.js +96 -96
  65. package/lib/semantic.js +229 -229
  66. package/lib/sensitive-scan.js +209 -209
  67. package/lib/serve.js +215 -215
  68. package/lib/service.js +2688 -2605
  69. package/lib/settings.js +528 -511
  70. package/lib/store.js +3196 -3007
  71. package/lib/summarize.js +1039 -856
  72. package/lib/tools.js +743 -737
  73. package/lib/vector-index.js +110 -110
  74. package/lib/version-check.js +122 -122
  75. package/lib/write-admission.js +402 -402
  76. package/locale/en.json +6 -6
  77. package/locale/zh.json +6 -6
  78. package/package.json +118 -118
  79. package/runtime-manifest.json +526 -526
  80. package/scripts/benchmark-embed.js +201 -201
  81. package/scripts/benchmark-recall.js +249 -249
  82. package/scripts/benchmark-rerank.js +166 -166
  83. package/scripts/build-runtime-manifest.mjs +224 -224
  84. package/scripts/changelog-prep.mjs +36 -36
  85. package/scripts/check-sync.js +42 -42
  86. package/scripts/e2e-dsh.js +220 -220
  87. package/scripts/mneme-runtime.mjs +277 -277
  88. package/scripts/stress-dsh.js +255 -255
  89. package/scripts/sync-lib.js +47 -47
  90. package/scripts/sync-test-badge.mjs +69 -69
  91. package/scripts/test-count-sync.mjs +44 -44
  92. package/src/api-standalone.js +656 -673
  93. package/src/api.js +1605 -1433
  94. package/src/bootstrap.js +211 -211
  95. package/src/commands.js +95 -95
  96. package/src/config.js +947 -843
  97. package/src/content-hash.js +54 -54
  98. package/src/continuity.js +220 -220
  99. package/src/document-index.js +94 -94
  100. package/src/document.js +303 -303
  101. package/src/dream/clustering.js +118 -118
  102. package/src/dream/decisions.js +694 -674
  103. package/src/dream/narratives.js +44 -44
  104. package/src/dream/sleep.js +819 -819
  105. package/src/dream.js +1503 -1501
  106. package/src/embedding.js +177 -177
  107. package/src/entities/extractor.js +252 -252
  108. package/src/graph/anchoring.js +179 -179
  109. package/src/guide.js +74 -74
  110. package/src/heat.js +144 -144
  111. package/src/hot-memory.js +108 -46
  112. package/src/index.js +552 -503
  113. package/src/inject.js +428 -450
  114. package/src/lang.js +248 -229
  115. package/src/local-embedder.js +358 -358
  116. package/src/maintenance.js +162 -142
  117. package/src/mirror.js +330 -330
  118. package/src/organize.js +450 -450
  119. package/src/peak-hours.js +117 -117
  120. package/src/placement.js +13 -0
  121. package/src/pre-inject-gate.js +340 -0
  122. package/src/quality-filter.js +126 -126
  123. package/src/recall-stats.js +190 -175
  124. package/src/reclaim-http.js +150 -0
  125. package/src/reranker.js +269 -269
  126. package/src/runtime/adopt.js +176 -176
  127. package/src/runtime/closure.js +172 -172
  128. package/src/runtime/download.js +247 -247
  129. package/src/runtime/layout.js +265 -265
  130. package/src/runtime/loader.js +252 -252
  131. package/src/runtime/model-fetch.js +361 -361
  132. package/src/runtime/provision.js +237 -237
  133. package/src/runtime/tarball.js +130 -130
  134. package/src/runtime/verify.js +223 -204
  135. package/src/safe-slice.js +18 -0
  136. package/src/scope.js +146 -146
  137. package/src/search/adaptive.js +60 -60
  138. package/src/search/bm25.js +96 -96
  139. package/src/semantic.js +229 -229
  140. package/src/sensitive-scan.js +209 -209
  141. package/src/serve.js +215 -215
  142. package/src/service.js +2688 -2605
  143. package/src/settings.js +528 -511
  144. package/src/store.js +3196 -3007
  145. package/src/summarize.js +1039 -856
  146. package/src/tools.js +743 -737
  147. package/src/vector-index.js +110 -110
  148. package/src/version-check.js +122 -122
  149. package/src/write-admission.js +402 -402
  150. package/test/adaptive-inject-budget.test.js +85 -85
  151. package/test/api-routes-gaps.test.js +899 -218
  152. package/test/api.test.js +1725 -1690
  153. package/test/audit.test.js +448 -448
  154. package/test/baseline-persist.test.js +248 -248
  155. package/test/benchmark.test.js +94 -94
  156. package/test/bootstrap.test.js +220 -220
  157. package/test/changelog-prep.test.js +60 -60
  158. package/test/client.test.js +1582 -1169
  159. package/test/clustering.test.js +100 -100
  160. package/test/commands.test.js +106 -106
  161. package/test/config.test.js +66 -66
  162. package/test/conflict-freeze.test.js +300 -300
  163. package/test/content-hash.test.js +204 -204
  164. package/test/continuity.test.js +333 -333
  165. package/test/contrast.test.js +314 -0
  166. package/test/document-dir.test.js +233 -233
  167. package/test/document.test.js +671 -671
  168. package/test/dream-archive-guardrail.test.js +116 -116
  169. package/test/dream-candidate-hybrid.test.js +281 -281
  170. package/test/dream-coverage-degrade.test.js +86 -86
  171. package/test/dream-failure-backoff.test.js +173 -173
  172. package/test/dream-merge-guardrail.test.js +219 -0
  173. package/test/dream-peak-hours.test.js +194 -194
  174. package/test/dream.test.js +1385 -1383
  175. package/test/embedding-ready.test.js +196 -196
  176. package/test/entities.test.js +627 -547
  177. package/test/entity-recall.test.js +179 -179
  178. package/test/epistemic.test.js +325 -325
  179. package/test/fnew-0112.test.js +311 -311
  180. package/test/fnew-03.test.js +422 -422
  181. package/test/graph-anchoring.test.js +184 -184
  182. package/test/graph-api.test.js +175 -175
  183. package/test/graph-inject-budget.test.js +103 -103
  184. package/test/graph-passive-confirm.test.js +91 -91
  185. package/test/graph-weight-evolution.test.js +104 -104
  186. package/test/heat.test.js +175 -175
  187. package/test/helpers/dream-mock.js +82 -82
  188. package/test/helpers/peer-worker.mjs +25 -25
  189. package/test/helpers/runtime-source.js +60 -60
  190. package/test/helpers/tar-builder.js +80 -80
  191. package/test/helpers/write-admission-samples.js +308 -308
  192. package/test/hot-memory.test.js +211 -145
  193. package/test/inject-content-cap.test.js +91 -91
  194. package/test/inject-first-round-bm25.test.js +89 -89
  195. package/test/inject-heat.test.js +77 -77
  196. package/test/inject-parent-gate.test.js +106 -106
  197. package/test/inject-pools.test.js +194 -194
  198. package/test/inject-recall.test.js +144 -105
  199. package/test/inject-rotation.test.js +161 -161
  200. package/test/inject.test.js +443 -420
  201. package/test/lang.test.js +87 -87
  202. package/test/lastrunat-persist.test.js +101 -101
  203. package/test/lib-smoke.test.js +96 -96
  204. package/test/llm-audit.test.js +696 -598
  205. package/test/llm-message-source.test.js +207 -207
  206. package/test/local-embedder.test.js +292 -292
  207. package/test/maintenance.test.js +501 -391
  208. package/test/mcp-stdio.test.js +385 -385
  209. package/test/mirror-dirty.test.js +424 -424
  210. package/test/mirror-edit-digest.test.js +187 -187
  211. package/test/mirror-generation.test.js +499 -499
  212. package/test/mirror-types.test.js +208 -208
  213. package/test/mirror.test.js +249 -249
  214. package/test/narrative-bars.test.js +162 -162
  215. package/test/organize.test.js +418 -418
  216. package/test/peer-blockers.test.js +193 -193
  217. package/test/placement.test.js +36 -0
  218. package/test/policy-epoch.test.js +259 -259
  219. package/test/pre-inject-gate.test.js +444 -0
  220. package/test/quality-filter.test.js +186 -186
  221. package/test/reasoning-effort.test.js +752 -752
  222. package/test/recall-anti-update.test.js +82 -82
  223. package/test/recall-evals.test.js +253 -253
  224. package/test/recall-layer.test.js +326 -326
  225. package/test/recall-stats.test.js +274 -189
  226. package/test/receipt-chain.test.js +451 -451
  227. package/test/reclaim-http.test.js +209 -0
  228. package/test/reflection.test.js +226 -226
  229. package/test/reindex-backfill.test.js +62 -62
  230. package/test/reranker-single-logit.test.js +73 -73
  231. package/test/reranker.test.js +197 -197
  232. package/test/resident-status.test.js +83 -83
  233. package/test/runtime-adopt.test.js +206 -206
  234. package/test/runtime-cli.test.js +89 -89
  235. package/test/runtime-closure.test.js +193 -193
  236. package/test/runtime-download.test.js +302 -302
  237. package/test/runtime-layout.test.js +163 -163
  238. package/test/runtime-loader.test.js +255 -255
  239. package/test/runtime-manifest.test.js +159 -159
  240. package/test/runtime-model-fetch.test.js +348 -348
  241. package/test/runtime-provision.test.js +101 -101
  242. package/test/runtime-tarball.test.js +81 -81
  243. package/test/runtime-verify.test.js +319 -279
  244. package/test/scope-candidates.test.js +239 -239
  245. package/test/scope-explicit.test.js +452 -452
  246. package/test/scope-inject-soft.test.js +106 -106
  247. package/test/scope-retrieval.test.js +197 -197
  248. package/test/scope-storage.test.js +255 -255
  249. package/test/scope-strict.test.js +367 -367
  250. package/test/search-fusion.test.js +90 -90
  251. package/test/semantic.test.js +124 -124
  252. package/test/sensitive-scan.test.js +207 -207
  253. package/test/serve-bin.test.js +121 -121
  254. package/test/serve.test.js +196 -196
  255. package/test/service-search.test.js +174 -174
  256. package/test/service.test.js +410 -405
  257. package/test/settings.test.js +269 -261
  258. package/test/skip-invalid-restore.test.js +262 -262
  259. package/test/sleep-action-set.test.js +422 -422
  260. package/test/sleep-heat.test.js +126 -126
  261. package/test/sleep-scheduler-rearm.test.js +89 -89
  262. package/test/sleep.test.js +527 -527
  263. package/test/standalone-api.test.js +751 -751
  264. package/test/store-vector-cache.test.js +98 -98
  265. package/test/store.test.js +504 -396
  266. package/test/stress.test.js +209 -209
  267. package/test/summarize-occurred-at.test.js +127 -0
  268. package/test/summarize-reasoning-effort.test.js +189 -189
  269. package/test/summarize.test.js +1639 -1465
  270. package/test/supersede-state-tracking.test.js +394 -0
  271. package/test/test-count-sync.test.js +60 -60
  272. package/test/tools-dto-schema-matrix.test.js +325 -325
  273. package/test/tools-memory-get-schema.test.js +65 -65
  274. package/test/tools.test.js +428 -374
  275. package/test/updated-at-semantics.test.js +113 -113
  276. package/test/vector-index.test.js +221 -221
  277. package/test/version-check.test.js +152 -152
  278. package/test/webServer-optional.test.js +82 -82
  279. package/test/write-admission.test.js +668 -668
@@ -1,180 +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";
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
180
  }
package/lib/guide.js CHANGED
@@ -1,74 +1,74 @@
1
- // #249(第一批):能力说明——写给模型的「怎么用这套记忆」,不是给用户的文案。
2
- //
3
- // 为什么英文、且只留一份正本:注入指引的参照实现全部用英文(ACP 的
4
- // ACP_SYSTEM_PROMPT + HOW_TO_COMPRESS_RULES、mnemon 的 ROUTING_GUIDANCE、
5
- // 宿主压缩摘要规则),仓库既有先例也是 src/tools.js 的工具描述硬编码英文。
6
- // src/lang.js 的 memory.language 管的是「生成出来的记忆内容与块内标题」,与本
7
- // 模块是两件事,故不并入 STR、不做 zh/en 双写(双写只会让两份文本日后漂移)。
8
- //
9
- // 两个承载位(#249 §5):①工具描述——常驻、零注入成本,放「何时用这个工具」
10
- // 这类单工具指引(TOOL_GUIDE);②系统提示段 order 150——放工具描述装不下的
11
- // 总则(优先序、何时查 / 何时写 / 何时 no-op)。该段必须同会话内稳定,否则
12
- // 每轮变化会作废其后的前缀缓存,因此这里全是常量,不含任何运行时插值。
13
- //
14
- // 前缀 `[dsh-mneme memory]` 是机械校验用的:测试按它断言「只在开时出现、且不
15
- // 逐轮复读」,也让维护者能一眼认出这段文本的归属。
16
-
17
- const SECTION_LINES = [
18
- "[dsh-mneme memory] Read once; it applies to every turn of this session.",
19
- "1. Precedence: the current instruction and the repository's actual state outrank any stored memory. " +
20
- "When a memory contradicts either, check the instruction or the repository itself before relying on it — memory_search " +
21
- "searches stored memories only, so it finds earlier context, never the present state. Never treat an old memory as current fact.",
22
- "2. Recall on demand: call memory_search when the task depends on earlier decisions, user preferences, or project history " +
23
- "that is not already in context. Do not search for facts you can read directly from the repository.",
24
- "3. Write back sparingly: use memory_save for durable, cross-session value — a preference, a decision with its rationale, " +
25
- "an engineering constraint, a pitfall with its root cause. Trivial single-turn work is not worth a memory.",
26
- "4. When unsure, do nothing. Not acting is a valid outcome: a useless memory is paid for by every future session.",
27
- "5. Prefer the reversible tools. memory_archive hides an entry from lists, search, injection and consolidation, and " +
28
- "memory_forget suppresses it from injection, search results and lists — both are recoverable. memory_delete is permanent, " +
29
- "so reach for it only when an entry is wrong or unwanted, not merely stale."
30
- ];
31
-
32
- /** 系统提示段(order 150)的总则文本。常量:同会话内稳定是硬约束。 */
33
- export const MEMORY_GUIDE_SECTION = SECTION_LINES.join("\n");
34
-
35
- /** 单工具判断指引,追加到对应工具描述尾部(`injectGuidanceEnabled` 开启时)。 */
36
- export const TOOL_GUIDE = {
37
- memory_search:
38
- " Use this when the task depends on earlier decisions, preferences, or project history that is not already in context, " +
39
- "or to look for a newer memory behind one that seems stale. " +
40
- "Skip it for facts you can read directly from the repository.",
41
- // 第二句(#249 第二批:「能力说明里没提 scope」):TOOL_GUIDE.memory_save 此前只
42
- // 讲「该不该写」,没讲「写给谁看」——而 memory_save 的 scope 参数是**必填面**,
43
- // 漏填的后果是单向的。所以这里给的是一条判断规则而不是一句免责声明:不确定就别填
44
- // (未标注 = 处处可见,NULL 恒可见,是安全的默认);标了 scope 才在多 scope 检索里
45
- // 付出代价。那句代价必须按实写:A2 软隔离是「他 scope 降权 ×0.5 但保留可见」
46
- // (service.js),只有 A3 `strictScope`(默认关)才真的硬过滤。写「静默消失」既不
47
- // 符合默认配置下的行为,也撞上「拒绝可解释、不静默丢弃」的口径(#254 验收第 2 条),
48
- // 会让模型以为标注有它实际没有的隐私效果。
49
- // 写进工具描述而不是总则:它是 memory_save 单工具的判据,总则那五条讲的是
50
- // 「何时查 / 何时写 / 何时 no-op」,加第六条会把单工具语义抬成全局纪律。
51
- memory_save:
52
- " Save only durable, cross-session value (a preference, a decision with its rationale, an engineering constraint, " +
53
- "a pitfall with its root cause). Trivial single-turn work does not belong here, and when unsure, do not save. " +
54
- "If a memory only holds for one workspace or one agent, declare workspace_scope / agent_scope; otherwise leave both out. " +
55
- "An unscoped memory is visible everywhere; a scoped one is filtered or downranked outside its scope."
56
- };
57
-
58
- /**
59
- * #249 N3 的降级路径:宿主若不提供可挂钩的压缩前时机,双落点里的「注入」那一半就没
60
- * 有触发者。此时不把功能算作失败,而是把规则交给 agent 自判压力(§4.4 点名的降级
61
- * 形态)。落点是工具描述——常驻文本、不进每轮上下文,零注入成本。
62
- *
63
- * 英文单一正本,理由同 TOOL_GUIDE(见文件头)。字段名用存储与注入那一侧的口径
64
- * (`current_work` / `next_step` / open question,#249 §6.2);规格 §4.4 里的
65
- * Current Work / Next Step / Critical Context 是**宿主压缩模板**的字段名,不是这里的。
66
- */
67
- export const CONTINUITY_TOOL_RULE = {
68
- memory_save:
69
- " If this session's context is about to be compacted, first save a continuity note with this same tool " +
70
- "(type: project, title: one stable title for this line of work, e.g. \"continuity: <topic>\"): current_work (what you " +
71
- "are doing now), next_step, and any open question. Keep it to those fields, and reuse that same title for later " +
72
- "updates: the store merges rows of the same type + title (the merge appends to the note instead of replacing it), " +
73
- "so a fresh title each time just leaves a trail of near-duplicate project rows."
74
- };
1
+ // #249(第一批):能力说明——写给模型的「怎么用这套记忆」,不是给用户的文案。
2
+ //
3
+ // 为什么英文、且只留一份正本:注入指引的参照实现全部用英文(ACP 的
4
+ // ACP_SYSTEM_PROMPT + HOW_TO_COMPRESS_RULES、mnemon 的 ROUTING_GUIDANCE、
5
+ // 宿主压缩摘要规则),仓库既有先例也是 src/tools.js 的工具描述硬编码英文。
6
+ // src/lang.js 的 memory.language 管的是「生成出来的记忆内容与块内标题」,与本
7
+ // 模块是两件事,故不并入 STR、不做 zh/en 双写(双写只会让两份文本日后漂移)。
8
+ //
9
+ // 两个承载位(#249 §5):①工具描述——常驻、零注入成本,放「何时用这个工具」
10
+ // 这类单工具指引(TOOL_GUIDE);②系统提示段 order 150——放工具描述装不下的
11
+ // 总则(优先序、何时查 / 何时写 / 何时 no-op)。该段必须同会话内稳定,否则
12
+ // 每轮变化会作废其后的前缀缓存,因此这里全是常量,不含任何运行时插值。
13
+ //
14
+ // 前缀 `[dsh-mneme memory]` 是机械校验用的:测试按它断言「只在开时出现、且不
15
+ // 逐轮复读」,也让维护者能一眼认出这段文本的归属。
16
+
17
+ const SECTION_LINES = [
18
+ "[dsh-mneme memory] Read once; it applies to every turn of this session.",
19
+ "1. Precedence: the current instruction and the repository's actual state outrank any stored memory. " +
20
+ "When a memory contradicts either, check the instruction or the repository itself before relying on it — memory_search " +
21
+ "searches stored memories only, so it finds earlier context, never the present state. Never treat an old memory as current fact.",
22
+ "2. Recall on demand: call memory_search when the task depends on earlier decisions, user preferences, or project history " +
23
+ "that is not already in context. Do not search for facts you can read directly from the repository.",
24
+ "3. Write back sparingly: use memory_save for durable, cross-session value — a preference, a decision with its rationale, " +
25
+ "an engineering constraint, a pitfall with its root cause. Trivial single-turn work is not worth a memory.",
26
+ "4. When unsure, do nothing. Not acting is a valid outcome: a useless memory is paid for by every future session.",
27
+ "5. Prefer the reversible tools. memory_archive hides an entry from lists, search, injection and consolidation, and " +
28
+ "memory_forget suppresses it from injection, search results and lists — both are recoverable. memory_delete is permanent, " +
29
+ "so reach for it only when an entry is wrong or unwanted, not merely stale."
30
+ ];
31
+
32
+ /** 系统提示段(order 150)的总则文本。常量:同会话内稳定是硬约束。 */
33
+ export const MEMORY_GUIDE_SECTION = SECTION_LINES.join("\n");
34
+
35
+ /** 单工具判断指引,追加到对应工具描述尾部(`injectGuidanceEnabled` 开启时)。 */
36
+ export const TOOL_GUIDE = {
37
+ memory_search:
38
+ " Use this when the task depends on earlier decisions, preferences, or project history that is not already in context, " +
39
+ "or to look for a newer memory behind one that seems stale. " +
40
+ "Skip it for facts you can read directly from the repository.",
41
+ // 第二句(#249 第二批:「能力说明里没提 scope」):TOOL_GUIDE.memory_save 此前只
42
+ // 讲「该不该写」,没讲「写给谁看」——而 memory_save 的 scope 参数是**必填面**,
43
+ // 漏填的后果是单向的。所以这里给的是一条判断规则而不是一句免责声明:不确定就别填
44
+ // (未标注 = 处处可见,NULL 恒可见,是安全的默认);标了 scope 才在多 scope 检索里
45
+ // 付出代价。那句代价必须按实写:A2 软隔离是「他 scope 降权 ×0.5 但保留可见」
46
+ // (service.js),只有 A3 `strictScope`(默认关)才真的硬过滤。写「静默消失」既不
47
+ // 符合默认配置下的行为,也撞上「拒绝可解释、不静默丢弃」的口径(#254 验收第 2 条),
48
+ // 会让模型以为标注有它实际没有的隐私效果。
49
+ // 写进工具描述而不是总则:它是 memory_save 单工具的判据,总则那五条讲的是
50
+ // 「何时查 / 何时写 / 何时 no-op」,加第六条会把单工具语义抬成全局纪律。
51
+ memory_save:
52
+ " Save only durable, cross-session value (a preference, a decision with its rationale, an engineering constraint, " +
53
+ "a pitfall with its root cause). Trivial single-turn work does not belong here, and when unsure, do not save. " +
54
+ "If a memory only holds for one workspace or one agent, declare workspace_scope / agent_scope; otherwise leave both out. " +
55
+ "An unscoped memory is visible everywhere; a scoped one is filtered or downranked outside its scope."
56
+ };
57
+
58
+ /**
59
+ * #249 N3 的降级路径:宿主若不提供可挂钩的压缩前时机,双落点里的「注入」那一半就没
60
+ * 有触发者。此时不把功能算作失败,而是把规则交给 agent 自判压力(§4.4 点名的降级
61
+ * 形态)。落点是工具描述——常驻文本、不进每轮上下文,零注入成本。
62
+ *
63
+ * 英文单一正本,理由同 TOOL_GUIDE(见文件头)。字段名用存储与注入那一侧的口径
64
+ * (`current_work` / `next_step` / open question,#249 §6.2);规格 §4.4 里的
65
+ * Current Work / Next Step / Critical Context 是**宿主压缩模板**的字段名,不是这里的。
66
+ */
67
+ export const CONTINUITY_TOOL_RULE = {
68
+ memory_save:
69
+ " If this session's context is about to be compacted, first save a continuity note with this same tool " +
70
+ "(type: project, title: one stable title for this line of work, e.g. \"continuity: <topic>\"): current_work (what you " +
71
+ "are doing now), next_step, and any open question. Keep it to those fields, and reuse that same title for later " +
72
+ "updates: the store merges rows of the same type + title (the merge appends to the note instead of replacing it), " +
73
+ "so a fresh title each time just leaves a trail of near-duplicate project rows."
74
+ };