dsh-cross-memory 0.0.0-stage → 0.2.0

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 (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/cordis.patch.yml +27 -0
  4. package/docs/DETAIL.md +13 -0
  5. package/docs/DETAIL.zh.md +17 -0
  6. package/icon.svg +1 -0
  7. package/lib/backfill.js +273 -0
  8. package/lib/citations.js +305 -0
  9. package/lib/client.js +1550 -0
  10. package/lib/config.js +736 -0
  11. package/lib/consolidate.js +1119 -0
  12. package/lib/extract.js +570 -0
  13. package/lib/gate.js +137 -0
  14. package/lib/git-origin.js +224 -0
  15. package/lib/index.js +4475 -0
  16. package/lib/log.js +260 -0
  17. package/lib/loops.js +186 -0
  18. package/lib/notices.js +195 -0
  19. package/lib/notify.js +33 -0
  20. package/lib/persona.js +112 -0
  21. package/lib/query.js +93 -0
  22. package/lib/raw-recall.js +286 -0
  23. package/lib/reflection.js +291 -0
  24. package/lib/remote.js +455 -0
  25. package/lib/render.js +678 -0
  26. package/lib/retention.js +64 -0
  27. package/lib/schedule.js +245 -0
  28. package/lib/search.js +1068 -0
  29. package/lib/skills.js +220 -0
  30. package/lib/state.js +701 -0
  31. package/lib/storage.js +1424 -0
  32. package/lib/sync-runtime.js +268 -0
  33. package/lib/sync.js +620 -0
  34. package/lib/test/activity.test.js +74 -0
  35. package/lib/test/archive.test.js +182 -0
  36. package/lib/test/backfill.test.js +144 -0
  37. package/lib/test/citations.test.js +91 -0
  38. package/lib/test/client-wiring.test.js +134 -0
  39. package/lib/test/consolidate-job.test.js +95 -0
  40. package/lib/test/consolidate.test.js +430 -0
  41. package/lib/test/consolidation-selection.test.js +152 -0
  42. package/lib/test/dedupe-keys.test.js +230 -0
  43. package/lib/test/delta.test.js +93 -0
  44. package/lib/test/derived.test.js +110 -0
  45. package/lib/test/disputes-panel.test.js +314 -0
  46. package/lib/test/eval.test.js +171 -0
  47. package/lib/test/expand.test.js +164 -0
  48. package/lib/test/extract.test.js +1020 -0
  49. package/lib/test/git-origin.test.js +189 -0
  50. package/lib/test/injection.test.js +440 -0
  51. package/lib/test/kind-filter.test.js +49 -0
  52. package/lib/test/legacy-state.test.js +69 -0
  53. package/lib/test/log.test.js +156 -0
  54. package/lib/test/loops.test.js +86 -0
  55. package/lib/test/memory.test.js +855 -0
  56. package/lib/test/notices.test.js +140 -0
  57. package/lib/test/persona.test.js +73 -0
  58. package/lib/test/prefilter.test.js +73 -0
  59. package/lib/test/preset.test.js +77 -0
  60. package/lib/test/raw-recall.test.js +186 -0
  61. package/lib/test/recall.test.js +433 -0
  62. package/lib/test/reflection.test.js +64 -0
  63. package/lib/test/remote.test.js +227 -0
  64. package/lib/test/retention.test.js +117 -0
  65. package/lib/test/retrieval.test.js +142 -0
  66. package/lib/test/rotation.test.js +228 -0
  67. package/lib/test/schedule.test.js +112 -0
  68. package/lib/test/settings-card.test.js +58 -0
  69. package/lib/test/skills.test.js +129 -0
  70. package/lib/test/state.test.js +212 -0
  71. package/lib/test/subagent-contract.test.js +139 -0
  72. package/lib/test/sweep.test.js +159 -0
  73. package/lib/test/sync.test.js +314 -0
  74. package/lib/test/time.test.js +171 -0
  75. package/lib/time.js +303 -0
  76. package/lib/tool.js +330 -0
  77. package/lib/types/backfill.d.ts +96 -0
  78. package/lib/types/citations.d.ts +105 -0
  79. package/lib/types/config.d.ts +811 -0
  80. package/lib/types/consolidate.d.ts +742 -0
  81. package/lib/types/extract.d.ts +352 -0
  82. package/lib/types/gate.d.ts +83 -0
  83. package/lib/types/git-origin.d.ts +23 -0
  84. package/lib/types/index.d.ts +1316 -0
  85. package/lib/types/log.d.ts +144 -0
  86. package/lib/types/loops.d.ts +82 -0
  87. package/lib/types/notices.d.ts +117 -0
  88. package/lib/types/notify.d.ts +12 -0
  89. package/lib/types/persona.d.ts +43 -0
  90. package/lib/types/query.d.ts +45 -0
  91. package/lib/types/raw-recall.d.ts +84 -0
  92. package/lib/types/reflection.d.ts +122 -0
  93. package/lib/types/remote.d.ts +233 -0
  94. package/lib/types/render.d.ts +286 -0
  95. package/lib/types/retention.d.ts +66 -0
  96. package/lib/types/schedule.d.ts +116 -0
  97. package/lib/types/search.d.ts +583 -0
  98. package/lib/types/skills.d.ts +71 -0
  99. package/lib/types/state.d.ts +294 -0
  100. package/lib/types/storage.d.ts +458 -0
  101. package/lib/types/sync-runtime.d.ts +103 -0
  102. package/lib/types/sync.d.ts +222 -0
  103. package/lib/types/test/activity.test.d.ts +1 -0
  104. package/lib/types/test/archive.test.d.ts +1 -0
  105. package/lib/types/test/backfill.test.d.ts +1 -0
  106. package/lib/types/test/citations.test.d.ts +1 -0
  107. package/lib/types/test/client-wiring.test.d.ts +1 -0
  108. package/lib/types/test/consolidate-job.test.d.ts +1 -0
  109. package/lib/types/test/consolidate.test.d.ts +1 -0
  110. package/lib/types/test/consolidation-selection.test.d.ts +1 -0
  111. package/lib/types/test/dedupe-keys.test.d.ts +1 -0
  112. package/lib/types/test/delta.test.d.ts +1 -0
  113. package/lib/types/test/derived.test.d.ts +1 -0
  114. package/lib/types/test/disputes-panel.test.d.ts +1 -0
  115. package/lib/types/test/eval.test.d.ts +1 -0
  116. package/lib/types/test/expand.test.d.ts +1 -0
  117. package/lib/types/test/extract.test.d.ts +1 -0
  118. package/lib/types/test/git-origin.test.d.ts +1 -0
  119. package/lib/types/test/injection.test.d.ts +1 -0
  120. package/lib/types/test/kind-filter.test.d.ts +1 -0
  121. package/lib/types/test/legacy-state.test.d.ts +1 -0
  122. package/lib/types/test/log.test.d.ts +1 -0
  123. package/lib/types/test/loops.test.d.ts +1 -0
  124. package/lib/types/test/memory.test.d.ts +1 -0
  125. package/lib/types/test/notices.test.d.ts +1 -0
  126. package/lib/types/test/persona.test.d.ts +1 -0
  127. package/lib/types/test/prefilter.test.d.ts +1 -0
  128. package/lib/types/test/preset.test.d.ts +1 -0
  129. package/lib/types/test/raw-recall.test.d.ts +1 -0
  130. package/lib/types/test/recall.test.d.ts +1 -0
  131. package/lib/types/test/reflection.test.d.ts +1 -0
  132. package/lib/types/test/remote.test.d.ts +1 -0
  133. package/lib/types/test/retention.test.d.ts +1 -0
  134. package/lib/types/test/retrieval.test.d.ts +1 -0
  135. package/lib/types/test/rotation.test.d.ts +1 -0
  136. package/lib/types/test/schedule.test.d.ts +1 -0
  137. package/lib/types/test/settings-card.test.d.ts +1 -0
  138. package/lib/types/test/skills.test.d.ts +1 -0
  139. package/lib/types/test/state.test.d.ts +1 -0
  140. package/lib/types/test/subagent-contract.test.d.ts +1 -0
  141. package/lib/types/test/sweep.test.d.ts +1 -0
  142. package/lib/types/test/sync.test.d.ts +1 -0
  143. package/lib/types/test/time.test.d.ts +1 -0
  144. package/lib/types/time.d.ts +67 -0
  145. package/lib/types/tool.d.ts +9 -0
  146. package/lib/types/types.d.ts +374 -0
  147. package/lib/types/workspace.d.ts +20 -0
  148. package/lib/types.js +47 -0
  149. package/lib/workspace.js +65 -0
  150. package/locale/en.json +7 -0
  151. package/locale/zh.json +7 -0
  152. package/package.json +126 -4
package/lib/search.js ADDED
@@ -0,0 +1,1068 @@
1
+ import { queryMessages } from './query.js';
2
+ import { parseTimeRange, within } from './time.js';
3
+ /** A CJK ideograph, including the extension blocks in common use. */
4
+ const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u;
5
+ /** A CJK character inside a query or a memory field. */
6
+ const CJK_CHAR = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/gu;
7
+ /** A maximal run of CJK characters. */
8
+ const CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/gu;
9
+ /**
10
+ * Shortest shared CJK run that counts as strong evidence.
11
+ *
12
+ * Two, and this is the single most consequential constant in the file. At three,
13
+ * a Chinese query only matched a memory when the two shared the same *phrase* —
14
+ * the right idea and the wrong threshold. Natural turns and titles restate the
15
+ * same topic in different words, so 「帮我把这次改动提交一下」 shares no
16
+ * three-character run with 「把混装的工作区改动拆成两笔提交」 even though both are
17
+ * unmistakably about committing changes. Measured on the real store, six
18
+ * realistic mid-conversation turns recalled nothing at all, and every one had a
19
+ * memory sitting right there: 「抽取任务好像没在跑」 against 「后台抽取 2026-09-22
20
+ * 起停摆」 is the clearest — one shared pair, 抽取, and no shared phrase.
21
+ *
22
+ * At two, each shared pair counts as its own unit of evidence and the
23
+ * *structural* gate does the work instead: recall requires two of them
24
+ * ({@link DEFAULT_RECALL_MIN_TERMS}), so an isolated common pair still cannot
25
+ * carry a match. That is the case three was introduced for — 「该插件是否有日志」
26
+ * shares 插件, and only 插件, with a memory about plugin registration order — and
27
+ * it stays rejected, because it is one term rather than two. Three was buying a
28
+ * proxy for "more than one"; two counts that directly, and it counts pairs that
29
+ * are not adjacent to each other.
30
+ */
31
+ const MIN_SHARED_RUN = 2;
32
+ /** Lowercase Latin, digits, and underscore — the "word" case. */
33
+ const WORD = /[a-z0-9_]+/gu;
34
+ /** Score added when the whole query appears verbatim in one field. */
35
+ export const FIELD_WEIGHTS = {
36
+ title: 40,
37
+ keys: 26,
38
+ tags: 20,
39
+ appliesTo: 18,
40
+ body: 12,
41
+ };
42
+ /**
43
+ * Score added per query term that appears in one field.
44
+ *
45
+ * Much smaller than {@link FIELD_WEIGHTS} because a term is one signal among
46
+ * many; the whole-query match is the strong claim. `body` is capped per term so
47
+ * a long memory that happens to repeat a word cannot dominate.
48
+ */
49
+ export const TERM_WEIGHTS = {
50
+ title: 8,
51
+ keys: 7,
52
+ tags: 6,
53
+ appliesTo: 5,
54
+ body: 2,
55
+ };
56
+ /** Most body occurrences of one term that still earn score. */
57
+ export const BODY_TERM_CAP = 4;
58
+ /**
59
+ * Every CJK run of a query, longest first.
60
+ *
61
+ * Runs are the right unit for evidence because a run is what a bigram list
62
+ * loses: "插件日志" enters the scorer as the overlapping pair 插件/件日/日志, so a
63
+ * shared *run* is invisible to per-term counting, while a shared common pair
64
+ * looks like two independent hits.
65
+ *
66
+ * @param text - the lowercased query.
67
+ * @returns each maximal CJK run.
68
+ */
69
+ function cjkRuns(text) {
70
+ return text.match(CJK_RUN) ?? [];
71
+ }
72
+ /**
73
+ * The windows of the query's CJK runs that one field contains.
74
+ *
75
+ * Every window of at least `minimum` characters that the field also contains is
76
+ * returned, so the caller can ask whether a *particular* bigram is backed by a
77
+ * run rather than by an isolated pair. Adjacent windows overlap, and the set
78
+ * collapses them.
79
+ *
80
+ * @param queryRuns - the query's CJK runs.
81
+ * @param field - the lowercased field text.
82
+ * @param minimum - shortest shared run that counts.
83
+ * @returns the shared windows, as a set of substrings.
84
+ */
85
+ function sharedRuns(queryRuns, field, minimum) {
86
+ const shared = new Set();
87
+ if (field.length === 0)
88
+ return shared;
89
+ for (const run of queryRuns) {
90
+ for (let start = 0; start + minimum <= run.length; start += 1) {
91
+ for (let end = start + minimum; end <= run.length; end += 1) {
92
+ const window = run.slice(start, end);
93
+ if (field.includes(window))
94
+ shared.add(window);
95
+ }
96
+ }
97
+ }
98
+ return shared;
99
+ }
100
+ /** Split text into searchable terms: ASCII words and CJK character bigrams.
101
+ *
102
+ * A CJK run also contributes bigrams of its neighbours, so "该插件是否有日志"
103
+ * yields "该插","插件","件是","是否","否有","有日","日志". A one-character run
104
+ * contributes itself, since a lone ideograph has no bigram.
105
+ *
106
+ * @param text - raw text.
107
+ * @returns lowercase terms; a run that yields nothing contributes nothing.
108
+ */
109
+ export function tokenize(text) {
110
+ const lower = text.toLowerCase();
111
+ const terms = [];
112
+ for (const word of lower.match(WORD) ?? [])
113
+ terms.push(word);
114
+ const chars = lower.match(CJK_CHAR) ?? [];
115
+ if (chars.length === 1)
116
+ terms.push(chars[0]);
117
+ for (let index = 0; index + 1 < chars.length; index += 1) {
118
+ terms.push(`${chars[index]}${chars[index + 1]}`);
119
+ }
120
+ return terms;
121
+ }
122
+ /**
123
+ * A term's weight for scoring purposes.
124
+ *
125
+ * One CJK bigram is a much weaker claim than one Latin word — "日志" occurs in
126
+ * countless texts where "logging" does not — so a bigram earns less. Without
127
+ * this every Chinese question would clear the recall gate on noise alone.
128
+ *
129
+ * @param term - one term from {@link tokenize}.
130
+ * @returns a multiplier in `(0, 1]`.
131
+ */
132
+ export function termWeight(term) {
133
+ const cjk = (term.match(CJK_CHAR) ?? []).length;
134
+ if (cjk === 0)
135
+ return 1;
136
+ // Two-character bigram: half credit. A longer CJK term cannot occur (the
137
+ // tokenizer emits bigrams), but treat it as stronger if it ever does.
138
+ return cjk <= 2 ? 0.5 : Math.min(1, 0.5 + (cjk - 2) * 0.15);
139
+ }
140
+ /** A short token carries little signal and is skipped as a query term. */
141
+ function isNoise(token) {
142
+ if (CJK.test(token))
143
+ return false;
144
+ return token.length < 2;
145
+ }
146
+ /** Count occurrences of `needle` in `haystack`. */
147
+ function occurrences(haystack, needle) {
148
+ if (needle.length === 0)
149
+ return 0;
150
+ let count = 0;
151
+ let index = haystack.indexOf(needle);
152
+ while (index >= 0) {
153
+ count += 1;
154
+ index = haystack.indexOf(needle, index + needle.length);
155
+ }
156
+ return count;
157
+ }
158
+ /** Words of one field, for exact-token tests. */
159
+ function words(field) {
160
+ return new Set(field.match(WORD) ?? []);
161
+ }
162
+ /** Lowercase one entry's fields once. */
163
+ function searchable(entry) {
164
+ const title = entry.title.toLowerCase();
165
+ const body = entry.body.toLowerCase();
166
+ const keys = entry.keys.join(' ').toLowerCase();
167
+ const tags = entry.tags.join(' ').toLowerCase();
168
+ const appliesTo = (entry.appliesTo ?? '').toLowerCase();
169
+ return {
170
+ title,
171
+ body,
172
+ keys,
173
+ tags,
174
+ appliesTo,
175
+ titleWords: words(title),
176
+ bodyWords: words(body),
177
+ keyWords: words(keys),
178
+ tagWords: words(tags),
179
+ appliesWords: words(appliesTo),
180
+ };
181
+ }
182
+ /**
183
+ * Whether one term matches one field.
184
+ *
185
+ * Latin terms are matched as whole words: "log" must not match "logging" or
186
+ * "login", or every memory mentioning a login screen would answer a question
187
+ * about logging. CJK has no such boundaries — a bigram inside a longer run is
188
+ * a real morphological hit — so those stay substring tests.
189
+ *
190
+ * @param field - the lowercased field text.
191
+ * @param fieldWords - the field's Latin words.
192
+ * @param term - one query term.
193
+ * @returns true when the field contains the term.
194
+ */
195
+ function matches(field, fieldWords, term) {
196
+ if (CJK.test(term))
197
+ return field.includes(term);
198
+ return fieldWords.has(term);
199
+ }
200
+ /**
201
+ * Below this many candidates the prefilter is skipped.
202
+ *
203
+ * The index is a superset of what can match, so a narrow result is not proof of
204
+ * a narrow answer: a turn of two common bigrams can leave a handful of entries
205
+ * whose *combinations* would have cleared the gate. Scanning everything in that
206
+ * case costs nothing (the store is small by definition when the candidate set
207
+ * is) and removes the only path by which the index could lose a recall.
208
+ */
209
+ const PREFILTER_FLOOR = 12;
210
+ /**
211
+ * A term → entry-index map, cached against the array it was built from.
212
+ *
213
+ * Built from the same two primitives the matcher uses — {@link matches} for CJK
214
+ * asks `field.includes(term)`, Latin asks word membership — so the index is a
215
+ * superset of anything that could match. Single CJK characters are indexed too,
216
+ * because a one-character query tokenizes to exactly that character.
217
+ */
218
+ const termIndexCache = new WeakMap();
219
+ /**
220
+ * Build (or reuse) the term index for one entry array.
221
+ *
222
+ * @param entries - entries from one scope, in list order.
223
+ * @returns term → ascending entry indexes.
224
+ */
225
+ export function termIndex(entries) {
226
+ const cached = termIndexCache.get(entries);
227
+ if (cached !== undefined)
228
+ return cached;
229
+ const index = new Map();
230
+ const add = (term, at) => {
231
+ const list = index.get(term);
232
+ if (list === undefined)
233
+ index.set(term, [at]);
234
+ else if (list[list.length - 1] !== at)
235
+ list.push(at);
236
+ };
237
+ entries.forEach((entry, at) => {
238
+ const fields = searchable(entry);
239
+ for (const text of [fields.title, fields.body, fields.keys, fields.tags, fields.appliesTo]) {
240
+ for (const term of tokenize(text))
241
+ add(term, at);
242
+ // A single CJK character is only reachable through `includes`, which a
243
+ // bigram-only index would miss.
244
+ for (const char of text.match(CJK_CHAR) ?? [])
245
+ add(char, at);
246
+ }
247
+ });
248
+ termIndexCache.set(entries, index);
249
+ return index;
250
+ }
251
+ /**
252
+ * The entries that share at least one token with the query.
253
+ *
254
+ * @param entries - the scope's entries.
255
+ * @param query - the turn's text.
256
+ * @returns candidates, or the whole array when the prefilter would be unreliable.
257
+ */
258
+ export function prefilterEntries(entries, query) {
259
+ if (entries.length <= PREFILTER_FLOOR)
260
+ return entries;
261
+ const index = termIndex(entries);
262
+ const hits = new Set();
263
+ for (const term of tokenize(query)) {
264
+ const found = index.get(term);
265
+ if (found === undefined)
266
+ continue;
267
+ for (const at of found)
268
+ hits.add(at);
269
+ }
270
+ if (hits.size < PREFILTER_FLOOR)
271
+ return entries;
272
+ return entries.filter((_entry, at) => hits.has(at));
273
+ }
274
+ /**
275
+ * Score one entry against one already-extracted query string, with evidence.
276
+ *
277
+ * Exact and per-term hits are counted in the title, keys, tags, `appliesTo`,
278
+ * and body, weighted so a title hit dominates a body hit. `appliesTo` is
279
+ * included because it is the field that says *when* a memory matters — the
280
+ * single most useful signal for a conversational turn that shares no noun with
281
+ * the memory's title.
282
+ *
283
+ * @param entry - candidate entry.
284
+ * @param normalized - one lowercased, trimmed query string.
285
+ * @returns the score and the evidence behind it.
286
+ */
287
+ function matchOne(entry, normalized, hub) {
288
+ const fields = searchable(entry);
289
+ let score = 0;
290
+ // The whole query as a phrase. CJK quirk: `tags`/`keys` hold several values in
291
+ // one string, and Japanese/Chinese text has no word boundaries, so a phrase
292
+ // test is meaningful there; for Latin fields it means the query is a phrase
293
+ // in that field, which is exactly the strong signal it should be.
294
+ let phrase = false;
295
+ if (matches(fields.title, fields.titleWords, normalized)) {
296
+ score += FIELD_WEIGHTS.title;
297
+ phrase = true;
298
+ }
299
+ if (matches(fields.keys, fields.keyWords, normalized)) {
300
+ score += FIELD_WEIGHTS.keys;
301
+ phrase = true;
302
+ }
303
+ if (matches(fields.tags, fields.tagWords, normalized)) {
304
+ score += FIELD_WEIGHTS.tags;
305
+ phrase = true;
306
+ }
307
+ if (matches(fields.appliesTo, fields.appliesWords, normalized)) {
308
+ score += FIELD_WEIGHTS.appliesTo;
309
+ phrase = true;
310
+ }
311
+ if (matches(fields.body, fields.bodyWords, normalized))
312
+ score += FIELD_WEIGHTS.body;
313
+ const strong = new Set();
314
+ // Only the strong fields feed the evidence count: a term in the BODY is
315
+ // deliberately excluded, because a long memory mentions many things and a body
316
+ // word is the weakest claim available.
317
+ const queryRuns = cjkRuns(normalized);
318
+ const cjkBacked = new Set();
319
+ for (const field of [fields.title, fields.keys, fields.tags, fields.appliesTo]) {
320
+ for (const run of sharedRuns(queryRuns, field, MIN_SHARED_RUN)) {
321
+ // Every bigram of a shared run is marked, so a query sharing 插件日志的
322
+ // counts 插件, 插件日, and 日志 rather than one anonymous run.
323
+ for (let index = 0; index + 2 <= run.length; index += 1)
324
+ cjkBacked.add(run.slice(index, index + 2));
325
+ }
326
+ }
327
+ for (const term of tokenize(normalized)) {
328
+ if (isNoise(term))
329
+ continue;
330
+ const weight = termWeight(term);
331
+ let strongHit = false;
332
+ if (matches(fields.title, fields.titleWords, term)) {
333
+ score += (TERM_WEIGHTS.title + (CJK.test(term) ? 0 : occurrences(fields.title, term))) * weight;
334
+ strongHit = true;
335
+ }
336
+ if (matches(fields.keys, fields.keyWords, term)) {
337
+ score += TERM_WEIGHTS.keys * weight;
338
+ strongHit = true;
339
+ }
340
+ if (matches(fields.tags, fields.tagWords, term)) {
341
+ score += TERM_WEIGHTS.tags * weight;
342
+ strongHit = true;
343
+ }
344
+ if (matches(fields.appliesTo, fields.appliesWords, term)) {
345
+ score += TERM_WEIGHTS.appliesTo * weight;
346
+ strongHit = true;
347
+ }
348
+ if (strongHit && hub?.(term) !== true) {
349
+ if (CJK.test(term)) {
350
+ if (cjkBacked.has(term))
351
+ strong.add(term);
352
+ }
353
+ else if (term.length >= 3) {
354
+ strong.add(term);
355
+ }
356
+ }
357
+ score += Math.min(BODY_TERM_CAP, occurrences(fields.body, term)) * TERM_WEIGHTS.body * weight;
358
+ }
359
+ return { score, evidence: { strongTerms: strong.size, phrase } };
360
+ }
361
+ /**
362
+ * Score and evidence of one entry against one already-extracted query.
363
+ *
364
+ * Prefer this over {@link relevanceOfOne} when the caller has to *justify* a
365
+ * decision: a recall delta is bounded by evidence, not only by score.
366
+ *
367
+ * @param entry - candidate entry.
368
+ * @param query - one query string; empty scores zero.
369
+ * @returns the score and the evidence behind it.
370
+ */
371
+ export function matchOf(entry, query) {
372
+ const normalized = query.trim().toLowerCase();
373
+ if (normalized.length === 0)
374
+ return { score: 0, evidence: { strongTerms: 0, phrase: false } };
375
+ return matchOne(entry, normalized);
376
+ }
377
+ /**
378
+ * Relevance of one entry to one already-extracted query string.
379
+ *
380
+ * @param entry - candidate entry.
381
+ * @param query - one query string; empty scores zero.
382
+ * @returns a non-negative score; `0` means no match.
383
+ */
384
+ export function relevanceOfOne(entry, query) {
385
+ return matchOf(entry, query).score;
386
+ }
387
+ /** Score every candidate query of a turn and keep the strongest. */
388
+ function bestMatch(entry, query, hub) {
389
+ const messages = queryMessages(query);
390
+ let bestScore = 0;
391
+ let bestEvidence = { strongTerms: 0, phrase: false };
392
+ let best = '';
393
+ let mentions = 0;
394
+ for (const message of messages) {
395
+ const { score, evidence } = matchOne(entry, message, hub);
396
+ if (score > 0)
397
+ mentions += 1;
398
+ if (score > bestScore || (score === bestScore && evidence.strongTerms > bestEvidence.strongTerms)) {
399
+ bestScore = score;
400
+ bestEvidence = evidence;
401
+ best = message;
402
+ }
403
+ }
404
+ if (bestScore === 0)
405
+ return { relevance: 0, evidence: bestEvidence, best: '' };
406
+ // Two independent mentions: +15%, capped so it reorders near-ties only.
407
+ const relevance = bestScore * Math.min(1.15, 1 + (mentions - 1) * 0.15);
408
+ return { relevance, evidence: bestEvidence, best };
409
+ }
410
+ /**
411
+ * Relevance of one entry to a whole user turn.
412
+ *
413
+ * A turn is many sentences and only one of them is usually about any single
414
+ * memory, so scoring the turn as one string buries a precise hit inside a wall
415
+ * of unrelated words. Each sentence is scored on its own and the best one wins;
416
+ * an entry that several sentences mention earns a small bonus, because two
417
+ * independent mentions is stronger evidence than one.
418
+ *
419
+ * @param entry - candidate entry.
420
+ * @param query - the raw turn or search text.
421
+ * @returns a non-negative score; `0` means no match.
422
+ */
423
+ export function relevanceOf(entry, query) {
424
+ return bestMatch(entry, query).relevance;
425
+ }
426
+ /**
427
+ * Half-life of a memory's recency weight, in days.
428
+ *
429
+ * Deliberately short next to the store's own lifetime. It was 90 days, which on
430
+ * an eleven-day-old store distinguishes almost nothing: the recency term spanned
431
+ * 0.94–1.00 while the use-count term spanned 1.0–4.5, so the injected summary
432
+ * was decided by how often a memory had been read before. Measured on a real
433
+ * store that pinned the same six entries — a plugin's logger threshold, a
434
+ * sidebar adapter, a model catalog — into every unrelated session, because those
435
+ * are the memories the harness's own plugin work kept reading. Thirty days keeps
436
+ * recency meaningful against the use term without letting a quarter-old
437
+ * convention fall out of reach.
438
+ */
439
+ export const RECENCY_HALF_LIFE_DAYS = 30;
440
+ /**
441
+ * Floor on the recency weight.
442
+ *
443
+ * Without it a two-year-old memory scores essentially zero and can never
444
+ * outrank a fresh, weaker match, however exact its own — the opposite of what
445
+ * durable memory is for.
446
+ */
447
+ export const DECAY_FLOOR = 0.25;
448
+ /**
449
+ * The most recent moment an entry was written or actually read.
450
+ *
451
+ * Being *surfaced* is deliberately not part of this. The summary lists a bounded
452
+ * number of entries, and counting "listed in the summary" as fresh attention
453
+ * turns that bound into a lock: an entry that makes the cut refreshes its own
454
+ * recency on every injection and keeps every newcomer out. Measured on a real
455
+ * store, the injected set sat at exactly the 12-per-scope cap, every member at
456
+ * maximum recency, while two thirds of the store had never been read at all —
457
+ * including the entry that explicitly corrected one of the listed ones.
458
+ *
459
+ * Surfacing still counts where the question is "does this memory still earn its
460
+ * place on disk"; that rule is `lastAttention` in `retention.ts`, which is the
461
+ * only thing that ever archives a memory.
462
+ *
463
+ * @param entry - candidate entry.
464
+ * @returns Unix epoch milliseconds.
465
+ */
466
+ export function recencyOf(entry) {
467
+ return Math.max(entry.updatedAt, entry.lastUsedAt);
468
+ }
469
+ /**
470
+ * How fast an entry's recency weight decays.
471
+ *
472
+ * A memory not read or rewritten for a quarter is worth half as much as one
473
+ * touched today, and the weight never falls below {@link DECAY_FLOOR}: recency
474
+ * orders memories, it does not erase them.
475
+ * @param entry - candidate entry.
476
+ * @param now - injected clock.
477
+ * @returns a weight in `[DECAY_FLOOR, 1]`.
478
+ */
479
+ export function decayOf(entry, now = Date.now()) {
480
+ const ageDays = Math.max(0, (now - recencyOf(entry)) / 86_400_000);
481
+ return Math.max(DECAY_FLOOR, 0.5 ** (ageDays / RECENCY_HALF_LIFE_DAYS));
482
+ }
483
+ /**
484
+ * Multiplier for a memory a person or the model wrote deliberately.
485
+ *
486
+ * `auto` entries are a background extractor's guess about a transcript;
487
+ * `tool`/`user` entries are somebody's statement. When they disagree the
488
+ * explicit one is the newer truth, and without a thumb on the scale the guess
489
+ * wins purely because it has been around long enough to collect reads.
490
+ *
491
+ * Raised from 1.25 because that was not enough to matter: against a use term
492
+ * spanning 1.0–4.5 with a ten-use cap, a deliberately written entry lost to a
493
+ * heavily-read extracted one every time. Measured on a real store, all six
494
+ * hand-written global rules — including "never break the prompt cache" and
495
+ * "reconnaissance is read-only GET" — failed to reach any session's summary,
496
+ * while the twelve that did were all extracted notes.
497
+ *
498
+ * Two, because the bonus has to clear {@link AUTO_IMPORTANCE_CEILING} rather
499
+ * than merely approach it: at 1.6 a written rule still tied with a note that had
500
+ * been read five times, and the measured global half kept preferring the note.
501
+ */
502
+ export const EXPLICIT_SOURCE_BONUS = 2;
503
+ /**
504
+ * How much one recorded read is worth, and the cap on how far it can climb.
505
+ *
506
+ * Previously `1 + min(uses, 10) * 0.35`, which let a single read-count term
507
+ * outrank recency by four to one and flattened the top of the ranking into a
508
+ * four-way tie at the cap. The slope is smaller and the cap lower so that
509
+ * recency, explicitness and use count each still move the order.
510
+ */
511
+ export const USE_BONUS = 0.15;
512
+ /** @see USE_BONUS */
513
+ export const USE_CAP = 5;
514
+ /**
515
+ * Ceiling a purely read-accumulated entry can reach (see {@link importanceOf}).
516
+ *
517
+ * Exported because {@link EXPLICIT_SOURCE_BONUS} has to clear it for a hand
518
+ * written rule to outrank the busiest extracted note: with the bonus below
519
+ * `1 + USE_CAP * USE_BONUS` the injected global half stays a list of whatever
520
+ * the harness's own tooling happened to read most, which is exactly the state
521
+ * the slot audit measured.
522
+ */
523
+ export const AUTO_IMPORTANCE_CEILING = 1 + USE_CAP * USE_BONUS;
524
+ /**
525
+ * How much an entry has earned its place: a small bonus per recorded use, and a
526
+ * larger one for having been written deliberately rather than inferred.
527
+ */
528
+ export function importanceOf(entry) {
529
+ const used = 1 + Math.min(entry.uses, USE_CAP) * USE_BONUS;
530
+ // A memory built from the user's own statement outranks one the assistant
531
+ // concluded, at equal use. Same argument as the explicit-source bonus — a
532
+ // person said it, so it is a constraint rather than a guess — and it is what
533
+ // lets the profile's rules win a slot against heavily-read notes about the
534
+ // plugin itself.
535
+ const voiced = entry.voice === 'user' ? USER_VOICE_BONUS : 1;
536
+ return (entry.source === 'auto' ? used : used * EXPLICIT_SOURCE_BONUS) * voiced;
537
+ }
538
+ /**
539
+ * Lift for a memory whose claim came from the user.
540
+ *
541
+ * Deliberately smaller than {@link EXPLICIT_SOURCE_BONUS}: it breaks ties among
542
+ * memories that already matched the turn's words, it does not put somebody's
543
+ * preferences in front of the code they asked about — the lexical gate still
544
+ * decides reachability.
545
+ */
546
+ export const USER_VOICE_BONUS = 1.35;
547
+ /**
548
+ * How much a turn's time window lifts an entry whose *measurement* falls in it.
549
+ *
550
+ * A `snapshot` carries `asOf` — the day the number was read — and that is the
551
+ * one timestamp in the store that answers a date question exactly. The lift is
552
+ * roughly a body hit's worth: enough to reorder memories that all match the
553
+ * words of the turn, never enough to outrank a memory that matches them better.
554
+ * It multiplies relevance rather than joining it, so a time match alone can
555
+ * never recall an entry — the lexical gate still runs first.
556
+ */
557
+ export const TIME_MEASURED_BOOST = 1.5;
558
+ /**
559
+ * How much the window lifts an entry that was *learned* inside it.
560
+ *
561
+ * Weaker than {@link TIME_MEASURED_BOOST} on purpose: `createdAt` is when the
562
+ * memory was written, which for a conversation-derived memory is a good proxy
563
+ * for when the thing happened, but for a hand-written rule it is just when
564
+ * somebody typed it. Measured on the real store, 306 of 613 entries carry a
565
+ * session pointer, so the proxy holds for the extracted half and is a
566
+ * tie-breaker for the rest.
567
+ */
568
+ export const TIME_CREATED_BOOST = 1.15;
569
+ /**
570
+ * The multiplier a turn's time window applies to one entry.
571
+ *
572
+ * `undefined` (no time expression, or an entry with no timestamps) returns 1, so
573
+ * turns that name no date are scored exactly as before. An entry is never
574
+ * *penalised* for falling outside the window: a durable fact learned in March
575
+ * can still be the answer to a question about last week, and punishing it would
576
+ * hide the answer more often than it would sharpen the list.
577
+ *
578
+ * @param entry - candidate entry.
579
+ * @param range - the turn's window, when it named one.
580
+ * @returns a multiplier of at least 1.
581
+ */
582
+ export function timeBoost(entry, range) {
583
+ if (range === undefined)
584
+ return 1;
585
+ if (within(entry.asOf, range))
586
+ return TIME_MEASURED_BOOST;
587
+ if (within(entry.createdAt, range))
588
+ return TIME_CREATED_BOOST;
589
+ return 1;
590
+ }
591
+ /**
592
+ * Score one entry against a query: relevance × importance × recency decay × time.
593
+ *
594
+ * One formula for every ordering in the plugin — tool search, the injected
595
+ * summary, and the on-demand recall threshold — so "worth recalling" means the
596
+ * same thing everywhere and a knob tuned in one place holds in the others.
597
+ *
598
+ * @param entry - candidate entry.
599
+ * @param query - raw user/model query.
600
+ * @param now - clock used for the decay.
601
+ * @param range - the turn's time window, or `undefined` to resolve it from the
602
+ * query. Callers that score many entries for one turn should parse once with
603
+ * {@link parseTimeRange} and pass it in.
604
+ * @returns a non-negative score; `0` means the entry does not match.
605
+ */
606
+ export function scoreEntry(entry, query, now = Date.now(), range) {
607
+ return rankEntry(entry, query, now, range).score;
608
+ }
609
+ /**
610
+ * Both halves of one entry's number: what it matches, and what it deserves.
611
+ *
612
+ * They are multiplied together everywhere else, which makes a loss impossible to
613
+ * attribute by reading the output — and the two surfaces want opposite orders.
614
+ * Measured on the real store, ranking by `relevance` alone puts the expected
615
+ * entry in the top eight for **every** probe (7/7), while the multiplied score
616
+ * manages 5/7: 「怎么给 dsh 插件加日志才看得到」 loses to eight heavily-read
617
+ * explicit memories that share the word `dsh`, which 100 of the scope's 176
618
+ * entries carry. A caller that asked a *question* wants the first; a caller
619
+ * deciding what to volunteer unasked wants the second.
620
+ *
621
+ * @param entry - candidate entry.
622
+ * @param query - raw user/model query.
623
+ * @param now - clock used for the decay.
624
+ * @param range - the turn's time window, or `undefined` to resolve it.
625
+ * @returns relevance (`0` when the entry does not match) and the attention score.
626
+ */
627
+ export function rankEntry(entry, query, now = Date.now(), range) {
628
+ const relevance = relevanceOf(entry, query);
629
+ if (relevance === 0)
630
+ return { relevance: 0, score: 0 };
631
+ const window = range === undefined ? parseTimeRange(query, now) : range ?? undefined;
632
+ return { relevance, score: relevance * importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window) };
633
+ }
634
+ /**
635
+ * Rank one entry against a query, reporting the evidence behind the number.
636
+ *
637
+ * The recall gate compares relevance AND evidence, so a caller that has to
638
+ * explain a decision ("why was nothing recalled?") needs both parts plus the
639
+ * sentence that produced them.
640
+ *
641
+ * @param entry - candidate entry.
642
+ * @param query - raw turn or search text.
643
+ * @param now - clock used for the decay.
644
+ * @param range - the turn's time window, or `undefined` to resolve it.
645
+ * @returns relevance, the decayed score, the matching sentence, and evidence.
646
+ */
647
+ export function explainEntry(entry, query, now = Date.now(), range) {
648
+ const match = bestMatch(entry, query);
649
+ const window = range === undefined ? parseTimeRange(query, now) : range ?? undefined;
650
+ return {
651
+ relevance: match.relevance,
652
+ score: match.relevance * importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window),
653
+ best: match.best,
654
+ evidence: match.evidence,
655
+ };
656
+ }
657
+ /**
658
+ * How much clearer than the floor a single strong term has to be on its own.
659
+ *
660
+ * One substantive term is half the evidence two are, so it only counts when the
661
+ * score it produced is decisive rather than marginal. Without this the structural
662
+ * gate would admit a memory that shares one distinctive word with the turn.
663
+ */
664
+ export const QUALIFIED_SCORE_FACTOR = 2;
665
+ /**
666
+ * Whether one entry is genuinely about one turn — the single decision behind
667
+ * both the injected summary's topical tier and the on-demand recall gate.
668
+ *
669
+ * Two gates that answer different questions, and neither replaces the other:
670
+ *
671
+ * - **FLOOR** (`minScore`) is the caller's strictness knob: the relevance an
672
+ * entry has to reach at all.
673
+ * - **CREDIT** is structural, and a score threshold cannot replace it for
674
+ * Chinese. Measured on a real 54-memory store, 「该插件是否有日志」 shares the
675
+ * isolated bigram 插件 with a memory about an unrelated cost-meter bug and
676
+ * scores 12 — above any floor low enough to admit a paraphrase. Credit asks
677
+ * instead for substantive terms: a Latin word of three characters or more, or
678
+ * a CJK pair inside a shared run of three or more, which is the only Chinese
679
+ * term a merely common pair cannot fake.
680
+ *
681
+ * A whole-query hit stands alone; otherwise `minTerms` are required, with one
682
+ * allowed when the score is {@link QUALIFIED_SCORE_FACTOR} times the floor and
683
+ * {@link CreditOptions.singleTerm} leaves that escape hatch open.
684
+ *
685
+ * This lives here, once, because the summary and the recall path used to spell
686
+ * the rule out separately and the two copies had already drifted apart.
687
+ *
688
+ * @param entry - candidate entry.
689
+ * @param query - the raw turn or search text.
690
+ * @param minScore - the relevance floor.
691
+ * @param minTerms - strong terms required when the score is not decisive.
692
+ * @param options - gate strictness and clock.
693
+ * @returns the verdict with the evidence behind it.
694
+ */
695
+ export function matchCredit(entry, query, minScore, minTerms, options = {}) {
696
+ const now = options.now ?? Date.now();
697
+ const singleTerm = options.singleTerm ?? true;
698
+ const window = options.range === undefined ? parseTimeRange(query, now) : options.range ?? undefined;
699
+ const match = bestMatch(entry, query, options.hub);
700
+ const distinctive = match.relevance >= minScore * QUALIFIED_SCORE_FACTOR;
701
+ const credited = match.evidence.phrase
702
+ || match.evidence.strongTerms >= minTerms
703
+ || (singleTerm && match.evidence.strongTerms >= 1 && distinctive);
704
+ return {
705
+ about: match.relevance >= minScore && credited,
706
+ distinctive,
707
+ credited,
708
+ relevance: match.relevance,
709
+ best: match.best,
710
+ evidence: match.evidence,
711
+ score: match.relevance * importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window),
712
+ };
713
+ }
714
+ /**
715
+ * Query terms too common in one scope to count as evidence.
716
+ *
717
+ * Document frequency, computed over the same strong fields the evidence rule
718
+ * reads (title, keys, tags, `appliesTo`) so the two agree on what "this memory is
719
+ * about the term" means. A term present in more than `maxDf` of the scope is a
720
+ * hub: `dsh` in a DSH-plugin store, `插件` in any store written by an agent that
721
+ * keeps talking about its own plugins.
722
+ *
723
+ * This is deliberately NOT the ranking's document-frequency discount the README
724
+ * records as measured-and-rejected. That one tried to change which memory wins;
725
+ * this one only decides what counts as evidence, and the two failures are
726
+ * different: a hub term never made a bad memory rank first, it made two unrelated
727
+ * memories look like two independent signals.
728
+ *
729
+ * @param entries - every entry in the scope.
730
+ * @param maxDf - share of the scope above which a term is a hub; `0` disables.
731
+ * @returns a predicate over lowercase terms.
732
+ */
733
+ export function hubTerms(entries, maxDf) {
734
+ if (maxDf <= 0 || entries.length === 0)
735
+ return () => false;
736
+ const counts = new Map();
737
+ for (const entry of entries) {
738
+ const seen = new Set();
739
+ for (const field of [entry.title, ...entry.keys, ...entry.tags, entry.appliesTo ?? '']) {
740
+ for (const term of tokenize(field)) {
741
+ if (isNoise(term))
742
+ continue;
743
+ seen.add(term);
744
+ }
745
+ }
746
+ for (const term of seen)
747
+ counts.set(term, (counts.get(term) ?? 0) + 1);
748
+ }
749
+ const limit = Math.max(1, Math.ceil(entries.length * Math.min(1, maxDf)));
750
+ const hubs = new Set();
751
+ for (const [term, count] of counts)
752
+ if (count >= limit)
753
+ hubs.add(term);
754
+ return (term) => hubs.has(term);
755
+ }
756
+ /**
757
+ * Most direct hits used as seeds for the one-hop expansion.
758
+ *
759
+ * Three, because a hop from a weak match is a guess about a guess: the seeds are
760
+ * the entries the turn actually matched, and only their own links are followed.
761
+ */
762
+ export const EXPAND_SEEDS = 3;
763
+ /**
764
+ * Keys or tags two entries must share before either can pull the other in.
765
+ *
766
+ * Two, for the same reason the recall gate asks for two substantive terms: one
767
+ * shared tag is the memory equivalent of a common word. `sqlite` alone links
768
+ * every database note in the store; `sqlite` plus `state.db` is a claim that the
769
+ * two entries are about the same thing.
770
+ */
771
+ export const EXPAND_MIN_SHARED = 2;
772
+ /**
773
+ * A related entry's score, as a fraction of the seed it was reached from.
774
+ *
775
+ * Spreading activation, in one line: a neighbour inherits a fixed fraction of
776
+ * the activation of the node that lit it up. It was first written as a fraction
777
+ * of the WEAKEST direct hit, so that a hop could never displace a real match —
778
+ * which sounds safe and is useless. The real-store eval showed why: a query can
779
+ * match forty entries on one shared word each, and every one of them outranks a
780
+ * hop that is pegged to the weakest of the top three. 「注入相关性的排查一共分了
781
+ * 几轮」 left all four rounds out of the top five in every configuration.
782
+ *
783
+ * Tying the score to its own seed keeps the useful part of the old property —
784
+ * a hop never outranks the node it came from — while letting a neighbour of the
785
+ * *best* match beat entries that merely share a common word with the turn.
786
+ */
787
+ export const EXPAND_FACTOR = 0.4;
788
+ /**
789
+ * Share of a scope that may carry a link before it stops being an edge.
790
+ *
791
+ * A key or tag on more than half the entries is the scope's own name, not a
792
+ * relationship: in the plugin's own project scope `dsh-cross-memory` sits on 22 of
793
+ * 29 entries, and `--links` measured 18 of that scope's 48 hop-able pairs
794
+ * sharing nothing but such links (against 0 of 785 in the global scope). Those
795
+ * hops fired, scored like real ones, and carried no information. Ignoring the
796
+ * ubiquitous links removes them without a rarity threshold that would have
797
+ * silently disabled the mechanism in small scopes, where every link looks
798
+ * common because the scope has four entries.
799
+ */
800
+ export const EXPAND_GENERIC_SHARE = 0.5;
801
+ /**
802
+ * The link information that earns the full allowance.
803
+ *
804
+ * Two, because that is what two wholly specific links are worth (`1 - 1/N` each
805
+ * in a scope of any size). A hop backed by one rare alias and one common tag
806
+ * lands around half; a hop backed by two broad tags lands at a quarter and
807
+ * stays behind everything else.
808
+ */
809
+ export const EXPAND_WEIGHT_FULL = 2;
810
+ /** Most related entries one search may add. */
811
+ export const EXPAND_MAX = 3;
812
+ /**
813
+ * The words an entry is filed under: its keys and its tags.
814
+ *
815
+ * Only these two fields, deliberately. The body mentions many things, and a hop
816
+ * through a body word would link entries that merely share vocabulary; `keys`
817
+ * exists to hold the *other names* for a memory, which is exactly the edge a
818
+ * graph walk should follow.
819
+ *
820
+ * @param entry - candidate entry.
821
+ * @returns lowercased, non-empty link words.
822
+ */
823
+ function linksOf(entry) {
824
+ const links = new Set();
825
+ for (const value of [...entry.keys, ...entry.tags]) {
826
+ const link = value.trim().toLowerCase();
827
+ if (link.length > 0)
828
+ links.add(link);
829
+ }
830
+ return links;
831
+ }
832
+ /**
833
+ * Entries reachable from the direct hits by following shared keys/tags.
834
+ *
835
+ * The deterministic stand-in for the graph channel in a memory architecture like
836
+ * Hindsight's: instead of embedding entities, it uses the aliases a memory is
837
+ * already filed under as edges. 「你了解我的账户吗」 matches one fragment about
838
+ * the account; the other three carry the same `keys`, and this is what surfaces
839
+ * them together — without a model call and without an index.
840
+ *
841
+ * @param groups - per-scope entry lists, broadest first.
842
+ * @param seeds - the direct hits whose links are followed.
843
+ * @param options - the same filters as {@link searchMemories}, plus the ids to
844
+ * exclude (the seeds themselves: an entry is not its own neighbour).
845
+ * @returns related hits, strongest first, with the seed each came from.
846
+ */
847
+ export function relatedHits(groups, seeds, options = {}) {
848
+ const limit = options.limit ?? EXPAND_MAX;
849
+ if (seeds.length === 0 || limit <= 0)
850
+ return [];
851
+ const wantedScopes = options.scopes;
852
+ const wantedTags = (options.tags ?? []).map((tag) => tag.toLowerCase());
853
+ const wantedKinds = options.kinds;
854
+ const exclude = options.exclude ?? new Set();
855
+ // How many entries carry each link, over exactly the entries this search can
856
+ // see. One pass, and it is what turns "shared two links" into "shares two
857
+ // links that mean something here": `dsh-cross-memory` on 22 of 29 entries is the
858
+ // scope's own name, and a hop built on it carries nothing.
859
+ const carried = new Map();
860
+ let considered = 0;
861
+ for (const group of groups) {
862
+ if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
863
+ continue;
864
+ for (const entry of group.entries) {
865
+ if (wantedKinds !== undefined && !wantedKinds.includes(entry.kind))
866
+ continue;
867
+ if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
868
+ continue;
869
+ considered += 1;
870
+ for (const link of linksOf(entry))
871
+ carried.set(link, (carried.get(link) ?? 0) + 1);
872
+ }
873
+ }
874
+ /** A ubiquitous link is not an edge; a rare one is worth nearly all of itself. */
875
+ const information = (link) => {
876
+ if (considered <= 0)
877
+ return 0;
878
+ const share = (carried.get(link) ?? 0) / considered;
879
+ return share > EXPAND_GENERIC_SHARE ? 0 : 1 - share;
880
+ };
881
+ const links = seeds.map((seed) => ({ id: seed.entry.id, score: seed.score, words: linksOf(seed.entry) }));
882
+ const best = new Map();
883
+ for (const group of groups) {
884
+ if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
885
+ continue;
886
+ for (const entry of group.entries) {
887
+ if (exclude.has(entry.id))
888
+ continue;
889
+ if (wantedKinds !== undefined && !wantedKinds.includes(entry.kind))
890
+ continue;
891
+ if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
892
+ continue;
893
+ const own = linksOf(entry);
894
+ if (own.size === 0)
895
+ continue;
896
+ let shared = 0;
897
+ let weight = 0;
898
+ let via = '';
899
+ let from = 0;
900
+ for (const seed of links) {
901
+ let here = 0;
902
+ let hereWeight = 0;
903
+ for (const word of own) {
904
+ if (!seed.words.has(word))
905
+ continue;
906
+ const value = information(word);
907
+ if (value <= 0)
908
+ continue;
909
+ here += 1;
910
+ hereWeight += value;
911
+ }
912
+ // The seed that lights this entry up is the one carrying the most
913
+ // information into it; ties keep the better-ranked seed.
914
+ if (hereWeight > weight || (hereWeight === weight && here > shared && here > 0)) {
915
+ shared = here;
916
+ weight = hereWeight;
917
+ via = seed.id;
918
+ from = seed.score;
919
+ }
920
+ }
921
+ if (shared < EXPAND_MIN_SHARED)
922
+ continue;
923
+ // Two fully specific links earn half the allowance, four or more earn all
924
+ // of it; a pair of broad tags lands at a quarter and stays behind every
925
+ // entry the turn actually matched.
926
+ const score = from * EXPAND_FACTOR * Math.min(1, weight / EXPAND_WEIGHT_FULL);
927
+ const previous = best.get(entry.id);
928
+ if (previous === undefined || score > previous.score)
929
+ best.set(entry.id, { entry, score, shared, via });
930
+ }
931
+ }
932
+ return [...best.values()]
933
+ .sort((left, right) => right.score - left.score
934
+ || right.shared - left.shared
935
+ || right.entry.updatedAt - left.entry.updatedAt
936
+ || left.entry.title.localeCompare(right.entry.title))
937
+ .slice(0, limit)
938
+ .map((hit) => ({ entry: hit.entry, score: hit.score, via: hit.via }));
939
+ }
940
+ /**
941
+ * Rank stored entries against a query across the supplied scopes.
942
+ * @param groups - per-scope entry lists, broadest first.
943
+ * @param query - raw query; empty returns nothing.
944
+ * @param options - scope, tag, and limit filters.
945
+ * @returns hits ordered by descending relevance, the attention score breaking ties.
946
+ */
947
+ export function searchMemories(groups, query, options = {}) {
948
+ const limit = options.limit ?? 10;
949
+ const wantedScopes = options.scopes;
950
+ const wantedTags = (options.tags ?? []).map((tag) => tag.toLowerCase());
951
+ const wantedKinds = options.kinds;
952
+ const now = options.now ?? Date.now();
953
+ const window = parseTimeRange(query, now);
954
+ // The search surface orders by the WORDS, not by the attention model. The
955
+ // caller asked a question; the entry that matches it best is the answer, and
956
+ // an entry that merely gets read a lot is not. Measured on the real store:
957
+ // ordering by relevance puts the expected entry in the top eight for 7 of 7
958
+ // probes, the multiplied score for 5 of 7 — the difference is entirely
959
+ // 「怎么给 dsh 插件加日志才看得到」 losing to eight tool-written notes that
960
+ // share `dsh` (100 of 176 entries) and have been read five times each.
961
+ //
962
+ // The injector keeps the opposite order on purpose: it volunteers memories
963
+ // nobody asked for, and there the track record is the point. Both numbers are
964
+ // computed here, so neither surface has to guess.
965
+ const hits = [];
966
+ for (const group of groups) {
967
+ if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
968
+ continue;
969
+ for (const entry of group.entries) {
970
+ if (wantedKinds !== undefined && !wantedKinds.includes(entry.kind))
971
+ continue;
972
+ if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
973
+ continue;
974
+ const { relevance, score } = rankEntry(entry, query, now, window);
975
+ if (relevance <= 0)
976
+ continue;
977
+ hits.push({ entry, score, relevance });
978
+ }
979
+ }
980
+ const byWords = (left, right) => right.relevance - left.relevance
981
+ || right.score - left.score
982
+ || right.entry.updatedAt - left.entry.updatedAt
983
+ || left.entry.title.localeCompare(right.entry.title);
984
+ hits.sort(byWords);
985
+ if (options.expand !== true)
986
+ return hits.slice(0, limit);
987
+ // One hop, never two: a second hop from a guess is a different guess.
988
+ //
989
+ // Only the seeds are excluded, and for one reason: an entry cannot be its own
990
+ // neighbour. Two narrower-looking rules were tried first and both were wrong
991
+ // on the real store — excluding every entry with any lexical score at all
992
+ // (a memory that shares one word scores 2 and lands at rank 40, so the hop
993
+ // could never reach the case it exists for), and excluding the top `limit`
994
+ // (the eighth direct hit is exactly the entry a hop can lift; its rank went
995
+ // 8 → 9, the one entry that would have benefited being the one removed).
996
+ //
997
+ // The seeds are handed over in RELEVANCE units, because that is the currency
998
+ // this surface ranks in: a hop scored against the seed's attention score would
999
+ // be sorting apples against oranges. The injector passes attention scores
1000
+ // instead, for the same reason.
1001
+ const seeds = hits.slice(0, EXPAND_SEEDS);
1002
+ const related = relatedHits(groups, seeds.map((hit) => ({ entry: hit.entry, score: hit.relevance })), {
1003
+ ...options,
1004
+ limit: EXPAND_MAX,
1005
+ exclude: new Set(seeds.map((hit) => hit.entry.id)),
1006
+ });
1007
+ // An entry the query did match keeps its own relevance when that is the higher
1008
+ // one, and never carries `via`: it matched, and saying otherwise would be a
1009
+ // lie about the one thing the marker exists to state.
1010
+ const directById = new Map(hits.map((hit) => [hit.entry.id, hit]));
1011
+ const merged = [...hits];
1012
+ for (const hit of related) {
1013
+ const direct = directById.get(hit.entry.id);
1014
+ // A hop ranks in word units too (`hit.score`), but reports an attention
1015
+ // score like every other hit: `score` means one thing on every row, and the
1016
+ // row's *place* is decided by the other number.
1017
+ const attention = hit.score * importanceOf(hit.entry) * decayOf(hit.entry, now);
1018
+ if (direct === undefined) {
1019
+ merged.push({
1020
+ entry: hit.entry,
1021
+ score: attention,
1022
+ relevance: hit.score,
1023
+ ...hit.via === undefined ? {} : { via: hit.via },
1024
+ });
1025
+ }
1026
+ else if (hit.score > direct.relevance) {
1027
+ merged.push({ entry: direct.entry, score: direct.score, relevance: hit.score });
1028
+ }
1029
+ }
1030
+ // Keep the best record per id. The direct list comes first, so keeping the
1031
+ // first occurrence would silently discard every upgrade — which is exactly
1032
+ // what the first version of this did, and what the eval caught.
1033
+ const unique = new Map();
1034
+ for (const hit of merged) {
1035
+ const previous = unique.get(hit.entry.id);
1036
+ if (previous === undefined || hit.relevance > previous.relevance)
1037
+ unique.set(hit.entry.id, hit);
1038
+ }
1039
+ return [...unique.values()].sort(byWords).slice(0, limit);
1040
+ }
1041
+ /**
1042
+ * Select entries without a text query — used by `memory_search`'s browse mode
1043
+ * and by the injector.
1044
+ * @param groups - per-scope entry lists, broadest first.
1045
+ * @param options - scope, tag, and limit filters.
1046
+ * @returns entries ordered by descending update time.
1047
+ */
1048
+ export function browseMemories(groups, options = {}) {
1049
+ const limit = options.limit ?? 10;
1050
+ const wantedScopes = options.scopes;
1051
+ const wantedTags = (options.tags ?? []).map((tag) => tag.toLowerCase());
1052
+ const wantedKinds = options.kinds;
1053
+ const hits = [];
1054
+ for (const group of groups) {
1055
+ if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
1056
+ continue;
1057
+ for (const entry of group.entries) {
1058
+ if (wantedKinds !== undefined && !wantedKinds.includes(entry.kind))
1059
+ continue;
1060
+ if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
1061
+ continue;
1062
+ hits.push({ entry, score: 0 });
1063
+ }
1064
+ }
1065
+ hits.sort((left, right) => right.entry.updatedAt - left.entry.updatedAt
1066
+ || left.entry.title.localeCompare(right.entry.title));
1067
+ return hits.slice(0, limit);
1068
+ }