@modusensus/dsh-mneme 0.8.13 → 0.8.15

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 (271) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +655 -626
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +689 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -0
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +263 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/ENTITIES.md +245 -0
  12. package/docs/LOCAL_MODEL.md +222 -0
  13. package/docs/SEMANTIC.md +256 -0
  14. package/docs/SLEEP.md +164 -0
  15. package/docs/STORAGE.md +89 -0
  16. package/lib/api-standalone.js +673 -572
  17. package/lib/api.js +1437 -1433
  18. package/lib/bootstrap.js +211 -211
  19. package/lib/client.js +5444 -5295
  20. package/lib/commands.js +95 -95
  21. package/lib/config.js +880 -836
  22. package/lib/content-hash.js +54 -54
  23. package/lib/continuity.js +220 -220
  24. package/lib/document-index.js +94 -94
  25. package/lib/document.js +303 -303
  26. package/lib/dream/clustering.js +118 -118
  27. package/lib/dream/decisions.js +674 -674
  28. package/lib/dream/narratives.js +44 -44
  29. package/lib/dream/sleep.js +819 -819
  30. package/lib/dream.js +1501 -1501
  31. package/lib/embedding.js +177 -177
  32. package/lib/entities/extractor.js +252 -252
  33. package/lib/graph/anchoring.js +179 -179
  34. package/lib/guide.js +74 -74
  35. package/lib/heat.js +144 -144
  36. package/lib/hot-memory.js +46 -46
  37. package/lib/index.js +535 -671
  38. package/lib/inject.js +464 -450
  39. package/lib/lang.js +248 -229
  40. package/lib/local-embedder.js +358 -358
  41. package/lib/maintenance.js +142 -142
  42. package/lib/mirror.js +330 -330
  43. package/lib/organize.js +450 -450
  44. package/lib/peak-hours.js +117 -117
  45. package/lib/placement.js +13 -0
  46. package/lib/pre-inject-gate.js +340 -0
  47. package/lib/quality-filter.js +126 -126
  48. package/lib/recall-stats.js +175 -175
  49. package/lib/reranker.js +269 -269
  50. package/lib/runtime/adopt.js +176 -176
  51. package/lib/runtime/closure.js +172 -172
  52. package/lib/runtime/download.js +247 -247
  53. package/lib/runtime/layout.js +265 -265
  54. package/lib/runtime/loader.js +252 -252
  55. package/lib/runtime/model-fetch.js +361 -361
  56. package/lib/runtime/provision.js +237 -237
  57. package/lib/runtime/tarball.js +130 -130
  58. package/lib/runtime/verify.js +223 -204
  59. package/lib/scope.js +146 -146
  60. package/lib/search/adaptive.js +60 -60
  61. package/lib/search/bm25.js +96 -96
  62. package/lib/semantic.js +229 -0
  63. package/lib/sensitive-scan.js +209 -209
  64. package/lib/serve.js +215 -0
  65. package/lib/service.js +2663 -2596
  66. package/lib/settings.js +517 -509
  67. package/lib/store.js +3007 -3007
  68. package/lib/summarize.js +891 -856
  69. package/lib/tools.js +743 -737
  70. package/lib/vector-index.js +110 -110
  71. package/lib/version-check.js +122 -122
  72. package/lib/write-admission.js +402 -402
  73. package/locale/en.json +6 -6
  74. package/locale/zh.json +6 -6
  75. package/package.json +8 -4
  76. package/runtime-manifest.json +526 -526
  77. package/scripts/benchmark-embed.js +201 -201
  78. package/scripts/benchmark-recall.js +249 -249
  79. package/scripts/benchmark-rerank.js +166 -166
  80. package/scripts/build-runtime-manifest.mjs +224 -224
  81. package/scripts/changelog-prep.mjs +36 -0
  82. package/scripts/check-sync.js +42 -42
  83. package/scripts/e2e-dsh.js +220 -220
  84. package/scripts/mneme-runtime.mjs +277 -277
  85. package/scripts/stress-dsh.js +255 -255
  86. package/scripts/sync-lib.js +47 -47
  87. package/scripts/sync-test-badge.mjs +69 -69
  88. package/scripts/test-count-sync.mjs +44 -44
  89. package/src/api-standalone.js +673 -572
  90. package/src/api.js +1437 -1433
  91. package/src/bootstrap.js +211 -211
  92. package/src/commands.js +95 -95
  93. package/src/config.js +880 -836
  94. package/src/content-hash.js +54 -54
  95. package/src/continuity.js +220 -220
  96. package/src/document-index.js +94 -94
  97. package/src/document.js +303 -303
  98. package/src/dream/clustering.js +118 -118
  99. package/src/dream/decisions.js +674 -674
  100. package/src/dream/narratives.js +44 -44
  101. package/src/dream/sleep.js +819 -819
  102. package/src/dream.js +1501 -1501
  103. package/src/embedding.js +177 -177
  104. package/src/entities/extractor.js +252 -252
  105. package/src/graph/anchoring.js +179 -179
  106. package/src/guide.js +74 -74
  107. package/src/heat.js +144 -144
  108. package/src/hot-memory.js +46 -46
  109. package/src/index.js +535 -671
  110. package/src/inject.js +464 -450
  111. package/src/lang.js +248 -229
  112. package/src/local-embedder.js +358 -358
  113. package/src/maintenance.js +142 -142
  114. package/src/mirror.js +330 -330
  115. package/src/organize.js +450 -450
  116. package/src/peak-hours.js +117 -117
  117. package/src/placement.js +13 -0
  118. package/src/pre-inject-gate.js +340 -0
  119. package/src/quality-filter.js +126 -126
  120. package/src/recall-stats.js +175 -175
  121. package/src/reranker.js +269 -269
  122. package/src/runtime/adopt.js +176 -176
  123. package/src/runtime/closure.js +172 -172
  124. package/src/runtime/download.js +247 -247
  125. package/src/runtime/layout.js +265 -265
  126. package/src/runtime/loader.js +252 -252
  127. package/src/runtime/model-fetch.js +361 -361
  128. package/src/runtime/provision.js +237 -237
  129. package/src/runtime/tarball.js +130 -130
  130. package/src/runtime/verify.js +223 -204
  131. package/src/scope.js +146 -146
  132. package/src/search/adaptive.js +60 -60
  133. package/src/search/bm25.js +96 -96
  134. package/src/semantic.js +229 -0
  135. package/src/sensitive-scan.js +209 -209
  136. package/src/serve.js +215 -0
  137. package/src/service.js +2663 -2596
  138. package/src/settings.js +517 -509
  139. package/src/store.js +3007 -3007
  140. package/src/summarize.js +891 -856
  141. package/src/tools.js +743 -737
  142. package/src/vector-index.js +110 -110
  143. package/src/version-check.js +122 -122
  144. package/src/write-admission.js +402 -402
  145. package/test/adaptive-inject-budget.test.js +85 -85
  146. package/test/api-routes-gaps.test.js +218 -218
  147. package/test/api.test.js +1702 -1688
  148. package/test/audit.test.js +448 -448
  149. package/test/baseline-persist.test.js +248 -248
  150. package/test/benchmark.test.js +94 -94
  151. package/test/bootstrap.test.js +220 -220
  152. package/test/changelog-prep.test.js +60 -0
  153. package/test/client.test.js +1230 -1169
  154. package/test/clustering.test.js +100 -100
  155. package/test/commands.test.js +106 -106
  156. package/test/config.test.js +66 -66
  157. package/test/conflict-freeze.test.js +300 -300
  158. package/test/content-hash.test.js +204 -204
  159. package/test/continuity.test.js +333 -333
  160. package/test/document-dir.test.js +233 -233
  161. package/test/document.test.js +671 -671
  162. package/test/dream-archive-guardrail.test.js +116 -116
  163. package/test/dream-candidate-hybrid.test.js +281 -281
  164. package/test/dream-coverage-degrade.test.js +86 -86
  165. package/test/dream-failure-backoff.test.js +173 -173
  166. package/test/dream-peak-hours.test.js +194 -194
  167. package/test/dream.test.js +1385 -1383
  168. package/test/embedding-ready.test.js +196 -196
  169. package/test/entities.test.js +627 -547
  170. package/test/entity-recall.test.js +179 -179
  171. package/test/epistemic.test.js +325 -325
  172. package/test/fnew-0112.test.js +311 -311
  173. package/test/fnew-03.test.js +422 -422
  174. package/test/graph-anchoring.test.js +184 -184
  175. package/test/graph-api.test.js +175 -175
  176. package/test/graph-inject-budget.test.js +103 -103
  177. package/test/graph-passive-confirm.test.js +91 -91
  178. package/test/graph-weight-evolution.test.js +104 -104
  179. package/test/heat.test.js +175 -175
  180. package/test/helpers/dream-mock.js +82 -82
  181. package/test/helpers/peer-worker.mjs +25 -25
  182. package/test/helpers/runtime-source.js +60 -60
  183. package/test/helpers/tar-builder.js +80 -80
  184. package/test/helpers/write-admission-samples.js +308 -308
  185. package/test/hot-memory.test.js +145 -145
  186. package/test/inject-content-cap.test.js +91 -91
  187. package/test/inject-first-round-bm25.test.js +89 -89
  188. package/test/inject-heat.test.js +77 -61
  189. package/test/inject-parent-gate.test.js +106 -106
  190. package/test/inject-pools.test.js +194 -194
  191. package/test/inject-recall.test.js +105 -105
  192. package/test/inject-rotation.test.js +161 -161
  193. package/test/inject.test.js +420 -420
  194. package/test/lang.test.js +87 -87
  195. package/test/lastrunat-persist.test.js +101 -101
  196. package/test/lib-smoke.test.js +96 -96
  197. package/test/llm-audit.test.js +598 -598
  198. package/test/llm-message-source.test.js +207 -207
  199. package/test/local-embedder.test.js +292 -292
  200. package/test/maintenance.test.js +391 -391
  201. package/test/mcp-stdio.test.js +385 -385
  202. package/test/mirror-dirty.test.js +424 -424
  203. package/test/mirror-edit-digest.test.js +187 -187
  204. package/test/mirror-generation.test.js +499 -499
  205. package/test/mirror-types.test.js +208 -208
  206. package/test/mirror.test.js +249 -249
  207. package/test/narrative-bars.test.js +162 -162
  208. package/test/organize.test.js +418 -418
  209. package/test/peer-blockers.test.js +193 -193
  210. package/test/placement.test.js +36 -0
  211. package/test/policy-epoch.test.js +259 -259
  212. package/test/pre-inject-gate.test.js +434 -0
  213. package/test/quality-filter.test.js +186 -186
  214. package/test/reasoning-effort.test.js +752 -752
  215. package/test/recall-anti-update.test.js +82 -82
  216. package/test/recall-evals.test.js +253 -253
  217. package/test/recall-layer.test.js +326 -326
  218. package/test/recall-stats.test.js +189 -189
  219. package/test/receipt-chain.test.js +451 -451
  220. package/test/reflection.test.js +226 -226
  221. package/test/reindex-backfill.test.js +62 -62
  222. package/test/reranker-single-logit.test.js +73 -73
  223. package/test/reranker.test.js +197 -197
  224. package/test/resident-status.test.js +83 -83
  225. package/test/runtime-adopt.test.js +206 -206
  226. package/test/runtime-cli.test.js +89 -89
  227. package/test/runtime-closure.test.js +193 -193
  228. package/test/runtime-download.test.js +302 -302
  229. package/test/runtime-layout.test.js +163 -163
  230. package/test/runtime-loader.test.js +255 -255
  231. package/test/runtime-manifest.test.js +159 -159
  232. package/test/runtime-model-fetch.test.js +348 -348
  233. package/test/runtime-provision.test.js +101 -101
  234. package/test/runtime-tarball.test.js +81 -81
  235. package/test/runtime-verify.test.js +319 -279
  236. package/test/scope-candidates.test.js +239 -239
  237. package/test/scope-explicit.test.js +452 -452
  238. package/test/scope-inject-soft.test.js +106 -106
  239. package/test/scope-retrieval.test.js +197 -197
  240. package/test/scope-storage.test.js +255 -255
  241. package/test/scope-strict.test.js +367 -343
  242. package/test/search-fusion.test.js +90 -90
  243. package/test/semantic.test.js +124 -124
  244. package/test/sensitive-scan.test.js +207 -207
  245. package/test/serve-bin.test.js +121 -0
  246. package/test/serve.test.js +196 -0
  247. package/test/service-search.test.js +174 -174
  248. package/test/service.test.js +405 -405
  249. package/test/settings.test.js +261 -261
  250. package/test/skip-invalid-restore.test.js +262 -262
  251. package/test/sleep-action-set.test.js +422 -422
  252. package/test/sleep-heat.test.js +126 -126
  253. package/test/sleep-scheduler-rearm.test.js +89 -89
  254. package/test/sleep.test.js +527 -527
  255. package/test/standalone-api.test.js +751 -544
  256. package/test/store-vector-cache.test.js +98 -98
  257. package/test/store.test.js +396 -396
  258. package/test/stress.test.js +209 -209
  259. package/test/summarize-occurred-at.test.js +127 -0
  260. package/test/summarize-reasoning-effort.test.js +189 -189
  261. package/test/summarize.test.js +1465 -1465
  262. package/test/supersede-state-tracking.test.js +394 -0
  263. package/test/test-count-sync.test.js +60 -60
  264. package/test/tools-dto-schema-matrix.test.js +325 -325
  265. package/test/tools-memory-get-schema.test.js +65 -65
  266. package/test/tools.test.js +428 -374
  267. package/test/updated-at-semantics.test.js +113 -113
  268. package/test/vector-index.test.js +221 -221
  269. package/test/version-check.test.js +152 -152
  270. package/test/webServer-optional.test.js +82 -82
  271. 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
+ };