@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,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,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
- * 与其日均(净增速率)。归档时刻只能取 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
+ * 与其日均(净增速率)。归档时刻只能取 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
+ }