@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,126 +1,126 @@
1
- // Rule-based memory quality filter (Bug7). Pure + total: no shared state, no
2
- // async, no external calls, so it can be unit-tested in isolation and wired
3
- // into the writer without any I/O or store access.
4
- //
5
- // evaluateMemoryQuality scores a memory 0-100 and tags low-value signals. The
6
- // writer then decides (config.memoryQualityFilter):
7
- // score >= degradeThreshold (60) → stored normally
8
- // archiveThreshold (30) <= score < 60 → quality_score persisted; the
9
- // injection sort re-ranks by importance * quality_score/100 (degraded)
10
- // score < archiveThreshold (30) → archived + tagged low_quality (still
11
- // recallable via explicit search, just never auto-injected)
12
- //
13
- // Signals and their deductions from the base 100:
14
- // meta meta-memory vocabulary (the memory talks about the
15
- // memory system itself, not the user's world) −45
16
- // self_referential title/content mentions its own type label −15
17
- // short_content content shorter than minContentLength −80
18
- // repetitive dedup ratio (unique chars / total) < 0.3 −50
19
- // duplicate bigram similarity to a recent memory > 0.85 −80
20
- //
21
- // The meta signal alone lands a well-formed memory in the degraded band
22
- // (30..60) — it is still stored and searchable, just demoted in injection.
23
- // Reaching the archive band (< 30) needs a degenerate body (short, repetitive
24
- // or near-duplicated) or stacked signals.
25
-
26
- export const META_MEMORY_RE =
27
- /记忆|mneme|recall|inject|上下文|token|prompt|系统指令|作为AI|作为助手|我需要记住|总结一下刚才/;
28
-
29
- // Own-type labels, used for self-reference detection (the English type value
30
- // the AI writers emit plus the Chinese equivalent a human would type).
31
- const TYPE_LABELS = {
32
- preference: ["preference", "偏好"],
33
- project: ["project", "项目"],
34
- decision: ["decision", "决策", "决定"],
35
- history: ["history", "历史", "事件"],
36
- summary: ["summary", "总结", "摘要", "总览"],
37
- pattern: ["pattern", "模式", "规律"],
38
- rejected_solution: ["rejected_solution", "被否决", "废弃方案"],
39
- pitfall: ["pitfall", "踩坑"],
40
- constraint: ["constraint", "约束"]
41
- };
42
-
43
- /** Normalized bigram-overlap similarity in [0,1]; 0 for tiny/empty inputs. */
44
- export function textSimilarity(a, b) {
45
- const bigrams = (s) => {
46
- const set = new Set();
47
- const t = String(s).replace(/\s+/g, "");
48
- for (let i = 0; i < t.length - 1; i++) set.add(t.slice(i, i + 2));
49
- return set;
50
- };
51
- const A = bigrams(a);
52
- const B = bigrams(b);
53
- if (!A.size || !B.size) return 0;
54
- let inter = 0;
55
- for (const g of A) if (B.has(g)) inter++;
56
- return inter / Math.min(A.size, B.size);
57
- }
58
-
59
- /** Fraction of characters that are unique (dedup ratio in [0,1]). */
60
- export function dedupRatio(text) {
61
- const t = String(text);
62
- if (!t.length) return 0;
63
- return new Set(t).size / t.length;
64
- }
65
-
66
- /**
67
- * Score a memory's quality. `recentContents` (optional) is the list of recent
68
- * memory contents used for near-duplicate detection; when omitted the duplicate
69
- * signal is skipped. Never throws: every input is coerced defensively.
70
- * @param {object} memory { type, title, content }
71
- * @param {object} [options]
72
- * @param {number} [options.minContentLength=10]
73
- * @param {string[]} [options.recentContents] up to ~20 recent contents
74
- * @returns {{score: number, tags: string[], reason: string}}
75
- */
76
- export function evaluateMemoryQuality(memory, options = {}) {
77
- const minContentLength = options.minContentLength ?? 10;
78
- const recentContents = Array.isArray(options.recentContents) ? options.recentContents : [];
79
- const title = String(memory?.title ?? "");
80
- const content = String(memory?.content ?? "");
81
- const text = `${title}\n${content}`;
82
- const trimmed = content.trim();
83
- const tags = [];
84
- const reasons = [];
85
- let score = 100;
86
-
87
- if (META_MEMORY_RE.test(text)) {
88
- score -= 45;
89
- tags.push("meta");
90
- reasons.push("meta-memory vocabulary");
91
- }
92
-
93
- const labels = TYPE_LABELS[memory?.type];
94
- if (labels && labels.some((l) => text.includes(l))) {
95
- score -= 15;
96
- tags.push("self_referential");
97
- reasons.push("mentions its own type");
98
- }
99
-
100
- if (minContentLength > 0 && trimmed.length < minContentLength) {
101
- score -= 80;
102
- tags.push("short_content");
103
- reasons.push(`content shorter than ${minContentLength} chars`);
104
- }
105
-
106
- if (trimmed.length > 0 && dedupRatio(trimmed) < 0.3) {
107
- score -= 50;
108
- tags.push("repetitive");
109
- reasons.push("repetitive content");
110
- }
111
-
112
- if (recentContents.length > 0 && trimmed.length > 0) {
113
- for (const other of recentContents) {
114
- if (textSimilarity(trimmed, other) > 0.85) {
115
- score -= 80;
116
- tags.push("duplicate");
117
- reasons.push("near-duplicate of a recent memory");
118
- break;
119
- }
120
- }
121
- }
122
-
123
- score = Math.max(0, Math.min(100, Math.round(score)));
124
- if (score < 30) tags.push("low_quality");
125
- return { score, tags: [...new Set(tags)], reason: reasons.length ? reasons.join("; ") : "ok" };
126
- }
1
+ // Rule-based memory quality filter (Bug7). Pure + total: no shared state, no
2
+ // async, no external calls, so it can be unit-tested in isolation and wired
3
+ // into the writer without any I/O or store access.
4
+ //
5
+ // evaluateMemoryQuality scores a memory 0-100 and tags low-value signals. The
6
+ // writer then decides (config.memoryQualityFilter):
7
+ // score >= degradeThreshold (60) → stored normally
8
+ // archiveThreshold (30) <= score < 60 → quality_score persisted; the
9
+ // injection sort re-ranks by importance * quality_score/100 (degraded)
10
+ // score < archiveThreshold (30) → archived + tagged low_quality (still
11
+ // recallable via explicit search, just never auto-injected)
12
+ //
13
+ // Signals and their deductions from the base 100:
14
+ // meta meta-memory vocabulary (the memory talks about the
15
+ // memory system itself, not the user's world) −45
16
+ // self_referential title/content mentions its own type label −15
17
+ // short_content content shorter than minContentLength −80
18
+ // repetitive dedup ratio (unique chars / total) < 0.3 −50
19
+ // duplicate bigram similarity to a recent memory > 0.85 −80
20
+ //
21
+ // The meta signal alone lands a well-formed memory in the degraded band
22
+ // (30..60) — it is still stored and searchable, just demoted in injection.
23
+ // Reaching the archive band (< 30) needs a degenerate body (short, repetitive
24
+ // or near-duplicated) or stacked signals.
25
+
26
+ export const META_MEMORY_RE =
27
+ /记忆|mneme|recall|inject|上下文|token|prompt|系统指令|作为AI|作为助手|我需要记住|总结一下刚才/;
28
+
29
+ // Own-type labels, used for self-reference detection (the English type value
30
+ // the AI writers emit plus the Chinese equivalent a human would type).
31
+ const TYPE_LABELS = {
32
+ preference: ["preference", "偏好"],
33
+ project: ["project", "项目"],
34
+ decision: ["decision", "决策", "决定"],
35
+ history: ["history", "历史", "事件"],
36
+ summary: ["summary", "总结", "摘要", "总览"],
37
+ pattern: ["pattern", "模式", "规律"],
38
+ rejected_solution: ["rejected_solution", "被否决", "废弃方案"],
39
+ pitfall: ["pitfall", "踩坑"],
40
+ constraint: ["constraint", "约束"]
41
+ };
42
+
43
+ /** Normalized bigram-overlap similarity in [0,1]; 0 for tiny/empty inputs. */
44
+ export function textSimilarity(a, b) {
45
+ const bigrams = (s) => {
46
+ const set = new Set();
47
+ const t = String(s).replace(/\s+/g, "");
48
+ for (let i = 0; i < t.length - 1; i++) set.add(t.slice(i, i + 2));
49
+ return set;
50
+ };
51
+ const A = bigrams(a);
52
+ const B = bigrams(b);
53
+ if (!A.size || !B.size) return 0;
54
+ let inter = 0;
55
+ for (const g of A) if (B.has(g)) inter++;
56
+ return inter / Math.min(A.size, B.size);
57
+ }
58
+
59
+ /** Fraction of characters that are unique (dedup ratio in [0,1]). */
60
+ export function dedupRatio(text) {
61
+ const t = String(text);
62
+ if (!t.length) return 0;
63
+ return new Set(t).size / t.length;
64
+ }
65
+
66
+ /**
67
+ * Score a memory's quality. `recentContents` (optional) is the list of recent
68
+ * memory contents used for near-duplicate detection; when omitted the duplicate
69
+ * signal is skipped. Never throws: every input is coerced defensively.
70
+ * @param {object} memory { type, title, content }
71
+ * @param {object} [options]
72
+ * @param {number} [options.minContentLength=10]
73
+ * @param {string[]} [options.recentContents] up to ~20 recent contents
74
+ * @returns {{score: number, tags: string[], reason: string}}
75
+ */
76
+ export function evaluateMemoryQuality(memory, options = {}) {
77
+ const minContentLength = options.minContentLength ?? 10;
78
+ const recentContents = Array.isArray(options.recentContents) ? options.recentContents : [];
79
+ const title = String(memory?.title ?? "");
80
+ const content = String(memory?.content ?? "");
81
+ const text = `${title}\n${content}`;
82
+ const trimmed = content.trim();
83
+ const tags = [];
84
+ const reasons = [];
85
+ let score = 100;
86
+
87
+ if (META_MEMORY_RE.test(text)) {
88
+ score -= 45;
89
+ tags.push("meta");
90
+ reasons.push("meta-memory vocabulary");
91
+ }
92
+
93
+ const labels = TYPE_LABELS[memory?.type];
94
+ if (labels && labels.some((l) => text.includes(l))) {
95
+ score -= 15;
96
+ tags.push("self_referential");
97
+ reasons.push("mentions its own type");
98
+ }
99
+
100
+ if (minContentLength > 0 && trimmed.length < minContentLength) {
101
+ score -= 80;
102
+ tags.push("short_content");
103
+ reasons.push(`content shorter than ${minContentLength} chars`);
104
+ }
105
+
106
+ if (trimmed.length > 0 && dedupRatio(trimmed) < 0.3) {
107
+ score -= 50;
108
+ tags.push("repetitive");
109
+ reasons.push("repetitive content");
110
+ }
111
+
112
+ if (recentContents.length > 0 && trimmed.length > 0) {
113
+ for (const other of recentContents) {
114
+ if (textSimilarity(trimmed, other) > 0.85) {
115
+ score -= 80;
116
+ tags.push("duplicate");
117
+ reasons.push("near-duplicate of a recent memory");
118
+ break;
119
+ }
120
+ }
121
+ }
122
+
123
+ score = Math.max(0, Math.min(100, Math.round(score)));
124
+ if (score < 30) tags.push("low_quality");
125
+ return { score, tags: [...new Set(tags)], reason: reasons.length ? reasons.join("; ") : "ok" };
126
+ }
@@ -1,175 +1,190 @@
1
- // dsh-mneme/src/recall-stats.js
2
- // 记忆复用统计(#217):对 recall_runs + memories 做只读聚合,面板「记忆复用」
3
- // 卡与 GET /api/dsh-mneme/recall-stats 的数据源。
4
- // 独立成模块的原因:service.js 已过 2000 行参考线(AGENTS.md 尺寸约定,#221),
5
- // 新内聚块从第一行就落在自己的文件里,service.js 保留 barrel 出口、调用方零改动。
6
- // 纯读不写,绝不触发任何 write hook。
7
-
8
- import { scopeKeyOf } from "./scope.js";
9
-
10
- /**
11
- * 口径(issue #217 评论 2026-09-18,锚 5bd2dab):
12
- * - Top-N:窗口内 recall_runs.candidates(最终返回集)按 id 计数,join
13
- * memories 补 type/source;记忆已删的 type=null(标题/来源回退候选值)。
14
- * candidates 只存最终集,「入池未中」语义(B)现有表拿不到——v1 只报
15
- * 零曝光(A),B 待 recordRecall 记录形状扩展。
16
- * - 僵尸率:活跃(未归档未遗忘)且窗口内零候选出现;分母剔除写入不足
17
- * 豁免期的记忆(按当前时刻计,exemptCount 单独报数)。
18
- * - 注入命中率:注入侧无留痕,待 #217 mode='inject' 口径拍板后接入。
19
- * - 注入命中率:mode='inject' 行单独计数(2026-09-19 拍板),slotFillRate =
20
- * 注入条数 / (轮数 × maxInjectSlots,默认 5);注入候选同时进 hits——注入是
21
- * 曝光型访问事件,计入 Top-N 与僵尸零曝光判定。
22
- * - coverage:recallRecordDefault 开启前的窗口算不到,earliestRunAt 为
23
- * null(窗口内无回执)或早于窗口起点时,前端标注可信度;扫描行数有
24
- * 上限,超出标 truncated(degraded 口径),不静默少算。
25
- * - archive(#275 拍板的第五指标,与上面几项同位):
26
- * · total = 归档区现有行数;addedInWindow / perDay = 窗口内进入归档区的行数
27
- * 与其日均(净增速率)。归档时刻只能取 updated_at(setArchived 翻标志位时刷
28
- * 它)——这是代理口径:对已归档行做一次 memory_update,或对同一行重复调
29
- * setArchived(…, true),都会被算成「本窗口新进归档」,perDay 因此偏高。精确
30
- * 口径要一个 archived_at 列(schema 变更,属第二批题材),本版不加;真正的
31
- * 「净」增本来也要跨快照比 total(物理删除落地后,差值才会由负向变化体现)。
32
- * · compressible = 可压掉行数:同 type、同 scope 三维且内容哈希完全相同的归档
33
- * 行里,多出来的那些(每组留一行)。用内容哈希而不是向量近重复,是因为回收
34
- * 动作本身会清掉归档行向量(clearArchivedEmbeddings)——指标不能建在它自己
35
- * 的输入会被回收掉的数据上;精确重复与 #254 的计量口径同一把尺。
36
- *
37
- * @param {object} store - createStore 产物(只调用 listRecallRunsSince / all)
38
- * @param {{ windowDays?: number, exemptDays?: number }} [options]
39
- */
40
- export function recallStats(store, options = {}) {
41
- const rawWindow = Number(options.windowDays ?? 30);
42
- const windowDays = Number.isInteger(rawWindow) && rawWindow >= 1 && rawWindow <= 365 ? rawWindow : 30;
43
- // 豁免期天数(issue #217 建议 7 天):option 化是给测试归零用 + 维护者
44
- // 调口径不留硬编码;越界值静默回默认(与 windowDays 同款宽容)。
45
- const rawExempt = Number(options.exemptDays ?? 7);
46
- const exemptDays = Number.isInteger(rawExempt) && rawExempt >= 0 && rawExempt <= 365 ? rawExempt : 7;
47
- // 注入槽位数(#217 增量):slotFillRate 分母用;默认 5 与 injectCandidates
48
- // 的 maxItems 默认一致,option 化防调用方自定义槽位时算错填充率。
49
- const rawSlots = Number(options.maxInjectSlots ?? 5);
50
- const maxInjectSlots = Number.isInteger(rawSlots) && rawSlots >= 1 ? rawSlots : 5;
51
- const now = Date.now();
52
- const sinceMs = now - windowDays * 86400000;
53
- const since = new Date(sinceMs).toISOString();
54
-
55
- const { rows: runs, total } = store.listRecallRunsSince(since);
56
- const hits = new Map(); // id -> { count, title, source }
57
- // 注入命中率口径(#217 增量,2026-09-19 拍板):mode='inject' 行单独计数,
58
- // slotFillRate = 注入条数 / (轮数 × 槽位数);注入候选同时进 hits——注入是
59
- // 曝光型访问事件,计入 Top-N 与僵尸零曝光判定。
60
- let injectRuns = 0;
61
- let injectedCount = 0;
62
- for (const run of runs) {
63
- const cands = run.candidates ?? [];
64
- if (run.mode === "inject") {
65
- injectRuns += 1;
66
- injectedCount += cands.length;
67
- }
68
- for (const cand of cands) {
69
- if (!cand?.id) continue;
70
- const cur = hits.get(cand.id) ?? { count: 0, title: cand.title ?? null, source: cand.source ?? null };
71
- cur.count += 1;
72
- hits.set(cand.id, cur);
73
- }
74
- }
75
-
76
- const memories = store.all();
77
- const memoryIndex = new Map(memories.map((m) => [m.id, m]));
78
- const EXEMPT_MS = exemptDays * 86400000;
79
- const byType = {};
80
- const bySource = {};
81
- let activeCount = 0;
82
- let zombieCount = 0;
83
- let exemptCount = 0;
84
- // 第五指标(#275):归档区一侧单独累计,分组键与 #254 的去重候选集同构
85
- // (type + 哈希 + scope 三维)——可压掉的必须是「本来就会被判成同一件事」的行。
86
- let archivedTotal = 0;
87
- let archivedInWindow = 0;
88
- const hashGroups = new Map();
89
- for (const m of memories) {
90
- if (m.archived) {
91
- archivedTotal += 1;
92
- const archivedMs = Date.parse(m.updated_at ?? "");
93
- if (Number.isFinite(archivedMs) && archivedMs >= sinceMs) archivedInWindow += 1;
94
- if (m.content_hash) {
95
- const key = [
96
- m.type ?? "",
97
- m.content_hash,
98
- scopeKeyOf(m.agent_scope) ?? "",
99
- scopeKeyOf(m.workspace_scope) ?? "",
100
- scopeKeyOf(m.sensitivity) ?? ""
101
- ].join("\u0000");
102
- hashGroups.set(key, (hashGroups.get(key) ?? 0) + 1);
103
- }
104
- continue;
105
- }
106
- if (m.forgotten) continue;
107
- const createdMs = Date.parse(m.created_at ?? "");
108
- // created_at 解析不了时无法证明已过机会期 → 归入豁免,宁漏勿误伤
109
- if (!Number.isFinite(createdMs) || now - createdMs < EXEMPT_MS) {
110
- exemptCount += 1;
111
- continue;
112
- }
113
- activeCount += 1;
114
- const zombied = !hits.has(m.id);
115
- if (zombied) zombieCount += 1;
116
- const type = m.type ?? "unknown";
117
- const source = m.source ?? "unknown";
118
- if (!byType[type]) byType[type] = { active: 0, zombie: 0 };
119
- const t = byType[type];
120
- t.active += 1;
121
- if (zombied) t.zombie += 1;
122
- if (!bySource[source]) bySource[source] = { active: 0, zombie: 0 };
123
- const s = bySource[source];
124
- s.active += 1;
125
- if (zombied) s.zombie += 1;
126
- }
127
-
128
- const topRecalled = [...hits.entries()]
129
- .map(([id, h]) => {
130
- const m = memoryIndex.get(id);
131
- return { id, title: m?.title ?? h.title, type: m?.type ?? null, source: m?.source ?? h.source, count: h.count };
132
- })
133
- .sort((a, b) => b.count - a.count || a.id.localeCompare(b.id))
134
- .slice(0, 10);
135
-
136
- let compressibleGroups = 0;
137
- let compressibleRows = 0;
138
- for (const n of hashGroups.values()) {
139
- if (n < 2) continue;
140
- compressibleGroups += 1;
141
- compressibleRows += n - 1;
142
- }
143
-
144
- return {
145
- windowDays,
146
- generatedAt: new Date(now).toISOString(),
147
- coverage: {
148
- runsScanned: runs.length,
149
- runsTotal: total,
150
- truncated: total > runs.length,
151
- earliestRunAt: runs.length ? runs[0].created_at : null
152
- },
153
- injection: {
154
- runs: injectRuns,
155
- injectedCount,
156
- slotFillRate: injectRuns > 0 ? injectedCount / (injectRuns * maxInjectSlots) : null
157
- },
158
- topRecalled,
159
- // #275 第五指标:归档净增速率 + 可压掉行数(口径见文件头)
160
- archive: {
161
- total: archivedTotal,
162
- addedInWindow: archivedInWindow,
163
- perDay: Math.round((archivedInWindow / windowDays) * 100) / 100,
164
- compressible: { rows: compressibleRows, groups: compressibleGroups }
165
- },
166
- zombie: {
167
- activeCount,
168
- zombieCount,
169
- exemptCount,
170
- rate: activeCount > 0 ? zombieCount / activeCount : null,
171
- byType,
172
- bySource
173
- }
174
- };
175
- }
1
+ // dsh-mneme/src/recall-stats.js
2
+ // 记忆复用统计(#217):对 recall_runs + memories 做只读聚合,面板「记忆复用」
3
+ // 卡与 GET /api/dsh-mneme/recall-stats 的数据源。
4
+ // 独立成模块的原因:service.js 已过 2000 行参考线(AGENTS.md 尺寸约定,#221),
5
+ // 新内聚块从第一行就落在自己的文件里,service.js 保留 barrel 出口、调用方零改动。
6
+ // 纯读不写,绝不触发任何 write hook。
7
+
8
+ import { scopeKeyOf } from "./scope.js";
9
+
10
+ /**
11
+ * 口径(issue #217 评论 2026-09-18,锚 5bd2dab):
12
+ * - Top-N:窗口内 recall_runs.candidates(最终返回集)按 id 计数,join
13
+ * memories 补 type/source;记忆已删的 type=null(标题/来源回退候选值)。
14
+ * candidates 只存最终集,「入池未中」语义(B)现有表拿不到——v1 只报
15
+ * 零曝光(A),B 待 recordRecall 记录形状扩展。
16
+ * - 僵尸率:活跃(未归档未遗忘)且窗口内零候选出现;分母剔除写入不足
17
+ * 豁免期的记忆(按当前时刻计,exemptCount 单独报数)。
18
+ * - 注入命中率:注入侧无留痕,待 #217 mode='inject' 口径拍板后接入。
19
+ * - 注入命中率:mode='inject' 行单独计数(2026-09-19 拍板),slotFillRate =
20
+ * 注入条数 / (轮数 × maxInjectSlots,默认 5);注入候选同时进 hits——注入是
21
+ * 曝光型访问事件,计入 Top-N 与僵尸零曝光判定。
22
+ * - coverage:recallRecordDefault 开启前的窗口算不到,earliestRunAt 为
23
+ * null(窗口内无回执)或早于窗口起点时,前端标注可信度;扫描行数有
24
+ * 上限,超出标 truncated(degraded 口径),不静默少算。
25
+ * - archive(#275 拍板的第五指标,与上面几项同位):
26
+ * · total = 归档区现有行数;addedInWindow / perDay = 窗口内进入归档区的行数
27
+ * 与其日均(净增速率)。归档时刻取 archived_at(#275 第二批落的精确列):
28
+ * setArchived 只在「活跃 → 归档」那一次落值,取消归档清 NULL,重复归档不刷新。
29
+ * 本指标 v1 曾用 updated_at 代理(setArchived 翻标志位时刷它),偏差方向是
30
+ * **偏高**——对已归档行做一次 memory_update、或对同一行重复调 setArchived(…,
31
+ * true),都会把旧归档算成「本窗口新进」。archived_at 就是为消灭这两个假阳性
32
+ * 而加的,别再退回 updated_at。真正的「净」增本来也要跨快照比 total(物理
33
+ * 删除落地后,差值才会由负向变化体现)。
34
+ * · undated = archived_at 为 NULL 的归档行数(本列落地前就已归档的存量行,时刻
35
+ * 不可追溯)。**刻意不计入 addedInWindow**:它们的归档时刻早于本列落地,无法
36
+ * 证明落在窗口内还是窗口外(迁移当刻,窗口内的存量归档行同样会是 NULL)。用
37
+ * updated_at 顶替就是走回被推翻的代理口径;按 0 充数则是把「不知道」伪装成
38
+ * 「没有」。单列出来让读侧自判可信度——宁少不脏。
39
+ * · compressible = 可压掉行数:同 type、同 scope 三维且内容哈希完全相同的归档
40
+ * 行里,多出来的那些(每组留一行)。用内容哈希而不是向量近重复,是因为回收
41
+ * 动作本身会清掉归档行向量(clearArchivedEmbeddings)——指标不能建在它自己
42
+ * 的输入会被回收掉的数据上;精确重复与 #254 的计量口径同一把尺。
43
+ *
44
+ * @param {object} store - createStore 产物(只调用 listRecallRunsSince / all)
45
+ * @param {{ windowDays?: number, exemptDays?: number }} [options]
46
+ */
47
+ export function recallStats(store, options = {}) {
48
+ const rawWindow = Number(options.windowDays ?? 30);
49
+ const windowDays = Number.isInteger(rawWindow) && rawWindow >= 1 && rawWindow <= 365 ? rawWindow : 30;
50
+ // 豁免期天数(issue #217 建议 7 天):option 化是给测试归零用 + 维护者
51
+ // 调口径不留硬编码;越界值静默回默认(与 windowDays 同款宽容)。
52
+ const rawExempt = Number(options.exemptDays ?? 7);
53
+ const exemptDays = Number.isInteger(rawExempt) && rawExempt >= 0 && rawExempt <= 365 ? rawExempt : 7;
54
+ // 注入槽位数(#217 增量):slotFillRate 分母用;默认 5 与 injectCandidates
55
+ // 的 maxItems 默认一致,option 化防调用方自定义槽位时算错填充率。
56
+ const rawSlots = Number(options.maxInjectSlots ?? 5);
57
+ const maxInjectSlots = Number.isInteger(rawSlots) && rawSlots >= 1 ? rawSlots : 5;
58
+ const now = Date.now();
59
+ const sinceMs = now - windowDays * 86400000;
60
+ const since = new Date(sinceMs).toISOString();
61
+
62
+ const { rows: runs, total } = store.listRecallRunsSince(since);
63
+ const hits = new Map(); // id -> { count, title, source }
64
+ // 注入命中率口径(#217 增量,2026-09-19 拍板):mode='inject' 行单独计数,
65
+ // slotFillRate = 注入条数 / (轮数 × 槽位数);注入候选同时进 hits——注入是
66
+ // 曝光型访问事件,计入 Top-N 与僵尸零曝光判定。
67
+ let injectRuns = 0;
68
+ let injectedCount = 0;
69
+ for (const run of runs) {
70
+ const cands = run.candidates ?? [];
71
+ if (run.mode === "inject") {
72
+ injectRuns += 1;
73
+ injectedCount += cands.length;
74
+ }
75
+ for (const cand of cands) {
76
+ if (!cand?.id) continue;
77
+ const cur = hits.get(cand.id) ?? { count: 0, title: cand.title ?? null, source: cand.source ?? null };
78
+ cur.count += 1;
79
+ hits.set(cand.id, cur);
80
+ }
81
+ }
82
+
83
+ const memories = store.all();
84
+ const memoryIndex = new Map(memories.map((m) => [m.id, m]));
85
+ const EXEMPT_MS = exemptDays * 86400000;
86
+ const byType = {};
87
+ const bySource = {};
88
+ let activeCount = 0;
89
+ let zombieCount = 0;
90
+ let exemptCount = 0;
91
+ // 第五指标(#275):归档区一侧单独累计,分组键与 #254 的去重候选集同构
92
+ // (type + 哈希 + scope 三维)——可压掉的必须是「本来就会被判成同一件事」的行。
93
+ let archivedTotal = 0;
94
+ let archivedInWindow = 0;
95
+ let archivedUndated = 0;
96
+ const hashGroups = new Map();
97
+ for (const m of memories) {
98
+ if (m.archived) {
99
+ archivedTotal += 1;
100
+ // 精确口径:只认 archived_at。NULL = 本列落地前的存量归档行,时刻不可追溯
101
+ // (见文件头 undated 段)——不拿 updated_at 顶替,那正是被本批推翻的代理口径。
102
+ const archivedMs = Date.parse(m.archived_at ?? "");
103
+ if (Number.isFinite(archivedMs)) {
104
+ if (archivedMs >= sinceMs) archivedInWindow += 1;
105
+ } else {
106
+ archivedUndated += 1;
107
+ }
108
+ if (m.content_hash) {
109
+ const key = [
110
+ m.type ?? "",
111
+ m.content_hash,
112
+ scopeKeyOf(m.agent_scope) ?? "",
113
+ scopeKeyOf(m.workspace_scope) ?? "",
114
+ scopeKeyOf(m.sensitivity) ?? ""
115
+ ].join("\u0000");
116
+ hashGroups.set(key, (hashGroups.get(key) ?? 0) + 1);
117
+ }
118
+ continue;
119
+ }
120
+ if (m.forgotten) continue;
121
+ const createdMs = Date.parse(m.created_at ?? "");
122
+ // created_at 解析不了时无法证明已过机会期 → 归入豁免,宁漏勿误伤
123
+ if (!Number.isFinite(createdMs) || now - createdMs < EXEMPT_MS) {
124
+ exemptCount += 1;
125
+ continue;
126
+ }
127
+ activeCount += 1;
128
+ const zombied = !hits.has(m.id);
129
+ if (zombied) zombieCount += 1;
130
+ const type = m.type ?? "unknown";
131
+ const source = m.source ?? "unknown";
132
+ if (!byType[type]) byType[type] = { active: 0, zombie: 0 };
133
+ const t = byType[type];
134
+ t.active += 1;
135
+ if (zombied) t.zombie += 1;
136
+ if (!bySource[source]) bySource[source] = { active: 0, zombie: 0 };
137
+ const s = bySource[source];
138
+ s.active += 1;
139
+ if (zombied) s.zombie += 1;
140
+ }
141
+
142
+ const topRecalled = [...hits.entries()]
143
+ .map(([id, h]) => {
144
+ const m = memoryIndex.get(id);
145
+ return { id, title: m?.title ?? h.title, type: m?.type ?? null, source: m?.source ?? h.source, count: h.count };
146
+ })
147
+ .sort((a, b) => b.count - a.count || a.id.localeCompare(b.id))
148
+ .slice(0, 10);
149
+
150
+ let compressibleGroups = 0;
151
+ let compressibleRows = 0;
152
+ for (const n of hashGroups.values()) {
153
+ if (n < 2) continue;
154
+ compressibleGroups += 1;
155
+ compressibleRows += n - 1;
156
+ }
157
+
158
+ return {
159
+ windowDays,
160
+ generatedAt: new Date(now).toISOString(),
161
+ coverage: {
162
+ runsScanned: runs.length,
163
+ runsTotal: total,
164
+ truncated: total > runs.length,
165
+ earliestRunAt: runs.length ? runs[0].created_at : null
166
+ },
167
+ injection: {
168
+ runs: injectRuns,
169
+ injectedCount,
170
+ slotFillRate: injectRuns > 0 ? injectedCount / (injectRuns * maxInjectSlots) : null
171
+ },
172
+ topRecalled,
173
+ // #275 第五指标:归档净增速率 + 可压掉行数(口径见文件头)
174
+ archive: {
175
+ total: archivedTotal,
176
+ addedInWindow: archivedInWindow,
177
+ perDay: Math.round((archivedInWindow / windowDays) * 100) / 100,
178
+ undated: archivedUndated,
179
+ compressible: { rows: compressibleRows, groups: compressibleGroups }
180
+ },
181
+ zombie: {
182
+ activeCount,
183
+ zombieCount,
184
+ exemptCount,
185
+ rate: activeCount > 0 ? zombieCount / activeCount : null,
186
+ byType,
187
+ bySource
188
+ }
189
+ };
190
+ }