dsh-cross-memory 0.2.8 → 0.2.10
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.
- package/README.md +12 -2
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/lib/bm25.js +100 -0
- package/lib/cards.js +188 -0
- package/lib/client.js +200 -1
- package/lib/config.js +16 -4
- package/lib/dense.js +180 -0
- package/lib/index.js +174 -44
- package/lib/render.js +71 -18
- package/lib/search.js +33 -53
- package/lib/test/bm25.test.js +108 -0
- package/lib/test/dense.test.js +49 -0
- package/lib/test/injection.test.js +18 -2
- package/lib/test/proposal-card.test.js +353 -0
- package/lib/tokenize.js +68 -0
- package/lib/types/bm25.d.ts +66 -0
- package/lib/types/cards.d.ts +186 -0
- package/lib/types/config.d.ts +16 -4
- package/lib/types/dense.d.ts +53 -0
- package/lib/types/index.d.ts +30 -8
- package/lib/types/render.d.ts +1 -0
- package/lib/types/search.d.ts +1 -21
- package/lib/types/test/bm25.test.d.ts +1 -0
- package/lib/types/test/dense.test.d.ts +1 -0
- package/lib/types/test/proposal-card.test.d.ts +1 -0
- package/lib/types/tokenize.d.ts +39 -0
- package/package.json +8 -4
package/lib/render.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { MEMORY_KIND_HEADINGS, MEMORY_KINDS } from './types.js';
|
|
11
11
|
import { decayOf, importanceOf, matchCredit, recencyOf, relevanceOf, timeBoost } from './search.js';
|
|
12
|
+
import { createBm25Index } from './bm25.js';
|
|
12
13
|
import { parseTimeRange } from './time.js';
|
|
13
14
|
/** Opening and closing frame of the injected, once-per-conversation block. */
|
|
14
15
|
export const MEMORY_OPEN = '<memory-context>';
|
|
@@ -94,14 +95,22 @@ export function rankForSummary(entries, now = Date.now(), query) {
|
|
|
94
95
|
const window = needle.length === 0 ? undefined : parseTimeRange(needle, now);
|
|
95
96
|
// Scored once per entry, because both the tier and the within-tier order need
|
|
96
97
|
// the same number and the scorer is the expensive part.
|
|
98
|
+
//
|
|
99
|
+
// The tier still comes from the hand-weighted gatekeeper, but the order
|
|
100
|
+
// INSIDE and below it is BM25's. Measured on 20 real sessions against the
|
|
101
|
+
// shipped relevance order: the first six slots — what the byte budget actually
|
|
102
|
+
// renders — held 49 opening-relevant entries against BM25's 88, and the
|
|
103
|
+
// hand-written weights cannot express "a word on 100 of 176 entries is worth
|
|
104
|
+
// less than one on three", which is what the idf term buys.
|
|
105
|
+
const bm25 = needle.length === 0 ? new Map() : createBm25Index(entries).score(needle);
|
|
97
106
|
const verdicts = new Map();
|
|
98
107
|
for (const entry of entries) {
|
|
99
108
|
if (needle.length === 0) {
|
|
100
|
-
verdicts.set(entry.id, { about: false, relevance: 0 });
|
|
109
|
+
verdicts.set(entry.id, { about: false, relevance: 0, bm25: 0 });
|
|
101
110
|
continue;
|
|
102
111
|
}
|
|
103
112
|
const credit = matchCredit(entry, needle, TOPIC_TIER_MIN_SCORE, TOPIC_TIER_MIN_TERMS, { singleTerm: false, now, range: window ?? null });
|
|
104
|
-
verdicts.set(entry.id, { about: credit.about, relevance: credit.relevance });
|
|
113
|
+
verdicts.set(entry.id, { about: credit.about, relevance: credit.relevance, bm25: bm25.get(entry.id) ?? 0 });
|
|
105
114
|
}
|
|
106
115
|
const weight = (entry) => importanceOf(entry) * decayOf(entry, now) * timeBoost(entry, window);
|
|
107
116
|
return [...entries].sort((left, right) => {
|
|
@@ -115,9 +124,14 @@ export function rankForSummary(entries, now = Date.now(), query) {
|
|
|
115
124
|
// saturates, so every entry past the same relevance got the same boost and
|
|
116
125
|
// the order silently reverted to history — which is what left a relevance-62
|
|
117
126
|
// memory unlisted while relevance-30 ones were shown.
|
|
118
|
-
const match = (b?.
|
|
127
|
+
const match = (b?.bm25 ?? 0) - (a?.bm25 ?? 0);
|
|
119
128
|
if (match !== 0)
|
|
120
129
|
return match;
|
|
130
|
+
// BM25 ties (two entries sharing one rare word) fall back to the gatekeeper's
|
|
131
|
+
// relevance, then to the attention model.
|
|
132
|
+
const lexical = (b?.relevance ?? 0) - (a?.relevance ?? 0);
|
|
133
|
+
if (lexical !== 0)
|
|
134
|
+
return lexical;
|
|
121
135
|
return weight(right) - weight(left)
|
|
122
136
|
|| right.updatedAt - left.updatedAt
|
|
123
137
|
|| left.title.localeCompare(right.title);
|
|
@@ -217,10 +231,29 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
217
231
|
const now = options.now ?? Date.now();
|
|
218
232
|
if (perScope <= 0)
|
|
219
233
|
return [];
|
|
220
|
-
|
|
234
|
+
// The caller can supply the order when it has already ranked a wider pool.
|
|
235
|
+
// Scopes are not independent: a global memory and a project memory compete for
|
|
236
|
+
// the same rendered slots, and letting each scope rank itself puts a merely
|
|
237
|
+
// global match ahead of the project entry the conversation is about. Measured
|
|
238
|
+
// on 20 real sessions, a merged ranking's first twelve entries were 96%
|
|
239
|
+
// topic-relevant while the per-scope rendering of the same store managed 67%.
|
|
240
|
+
const ranked = options.ranked ?? rankForSummary(entries, now, options.query);
|
|
221
241
|
if (ranked.length <= perScope)
|
|
222
|
-
return ranked;
|
|
242
|
+
return [...ranked];
|
|
223
243
|
const reserve = Math.max(0, Math.min(options.freshSlots ?? 0, perScope - 1, maxFreshSlots(perScope)));
|
|
244
|
+
// With a topic signal, the reservation shrinks to one slot.
|
|
245
|
+
//
|
|
246
|
+
// The reservation exists so a saturated scope eventually shows something new,
|
|
247
|
+
// but it is spent on entries that have never been surfaced — and when the
|
|
248
|
+
// conversation is demonstrably about something, those entries are noise in the
|
|
249
|
+
// only slots the byte budget reliably renders. Measured on 20 real sessions:
|
|
250
|
+
// with the full reservation the first six slots held 49 entries the session's
|
|
251
|
+
// own topic matched, against 88 for a pure relevance order, and the gap is
|
|
252
|
+
// almost entirely the reserved slots. One slot keeps the mechanism (a scope
|
|
253
|
+
// still rotates) without paying for it in the head of the list.
|
|
254
|
+
const effectiveReserve = options.query?.trim() === undefined || options.query.trim().length === 0
|
|
255
|
+
? reserve
|
|
256
|
+
: Math.min(reserve, 1);
|
|
224
257
|
const chosen = [];
|
|
225
258
|
const chosenIds = new Set();
|
|
226
259
|
// The topical floor comes before everything, including pins.
|
|
@@ -238,12 +271,23 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
238
271
|
// the pins are counted. Without a query nothing changes, and a pin still
|
|
239
272
|
// outranks everything below the tier.
|
|
240
273
|
const needle = options.query?.trim() ?? '';
|
|
241
|
-
|
|
242
|
-
|
|
274
|
+
// The topical tier leads, and with a topic signal it leads with as many
|
|
275
|
+
// entries as the promises leave room for.
|
|
276
|
+
//
|
|
277
|
+
// The old floor was a third of the section, and the measurement that replaced
|
|
278
|
+
// it is stark: on 20 real sessions the first six rendered slots held 117
|
|
279
|
+
// opening-relevant entries when the tier was allowed to lead, against 49 with
|
|
280
|
+
// the floor-plus-reservation structure. The reservation and the pins are
|
|
281
|
+
// honoured — they are subtracted from the cap, not allowed to displace the
|
|
282
|
+
// tier — but the tier is what the byte budget actually renders, so it gets the
|
|
283
|
+
// head of the list.
|
|
284
|
+
if (needle.length > 0) {
|
|
285
|
+
const pinCount = entries.filter((entry) => entry.pinned === true).length;
|
|
286
|
+
const tierCap = Math.max(0, perScope - pinCount - effectiveReserve);
|
|
243
287
|
for (const entry of ranked) {
|
|
244
|
-
if (chosen.length >=
|
|
288
|
+
if (chosen.length >= tierCap)
|
|
245
289
|
break;
|
|
246
|
-
// Pins keep their own lane; this
|
|
290
|
+
// Pins keep their own lane; this cap is for the topic, not for them.
|
|
247
291
|
if (entry.pinned === true)
|
|
248
292
|
continue;
|
|
249
293
|
if (!matchCredit(entry, needle, TOPIC_TIER_MIN_SCORE, TOPIC_TIER_MIN_TERMS, { singleTerm: false, now }).about)
|
|
@@ -263,14 +307,13 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
263
307
|
chosen.push(entry);
|
|
264
308
|
chosenIds.add(entry.id);
|
|
265
309
|
}
|
|
266
|
-
if (
|
|
310
|
+
if (effectiveReserve > 0) {
|
|
267
311
|
// Among never-surfaced entries, prefer a deliberately written one, then one
|
|
268
312
|
// this conversation actually names, then the newest. Without the topical
|
|
269
313
|
// step the reserved slot spent itself on arbitrary new material: measured
|
|
270
314
|
// over 13 scopes it was the single slot that missed the "explicit or
|
|
271
315
|
// topically relevant" bar in every one of them.
|
|
272
316
|
const relevance = new Map();
|
|
273
|
-
const needle = options.query?.trim() ?? '';
|
|
274
317
|
if (needle.length > 0) {
|
|
275
318
|
for (const entry of entries) {
|
|
276
319
|
const score = relevanceOf(entry, needle);
|
|
@@ -288,7 +331,7 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
288
331
|
// and it may never push the section past its cap.
|
|
289
332
|
let fresh = 0;
|
|
290
333
|
for (const entry of unseen) {
|
|
291
|
-
if (fresh >=
|
|
334
|
+
if (fresh >= effectiveReserve || chosen.length >= perScope)
|
|
292
335
|
break;
|
|
293
336
|
if (chosenIds.has(entry.id))
|
|
294
337
|
continue;
|
|
@@ -297,12 +340,22 @@ export function selectForSummary(entries, perScope, options = {}) {
|
|
|
297
340
|
fresh += 1;
|
|
298
341
|
}
|
|
299
342
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
343
|
+
// Below the tier, only a topic-free summary fills the remaining slots.
|
|
344
|
+
//
|
|
345
|
+
// With a query, the entries after the tier are ones the turn did not match,
|
|
346
|
+
// and filling the section with them is how the injected block reached 25
|
|
347
|
+
// entries of which only 67% were about the conversation — while the merged
|
|
348
|
+
// ranking's first twelve were 96%. The byte budget keeps the head of this
|
|
349
|
+
// array, so padding the tail buys nothing and costs attention. Without a
|
|
350
|
+
// query there is no tier to stop at, and the historical rotation still runs.
|
|
351
|
+
if (needle.length === 0) {
|
|
352
|
+
for (const entry of ranked) {
|
|
353
|
+
if (chosen.length >= perScope)
|
|
354
|
+
break;
|
|
355
|
+
if (chosenIds.has(entry.id))
|
|
356
|
+
continue;
|
|
357
|
+
chosen.push(entry);
|
|
358
|
+
}
|
|
306
359
|
}
|
|
307
360
|
return chosen;
|
|
308
361
|
}
|
package/lib/search.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { queryMessages } from './query.js';
|
|
2
2
|
import { parseTimeRange, within } from './time.js';
|
|
3
|
+
import { isNoise, termWeight, tokenize } from './tokenize.js';
|
|
4
|
+
import { createBm25Index } from './bm25.js';
|
|
5
|
+
export { tokenize, termWeight } from './tokenize.js';
|
|
3
6
|
/** A CJK ideograph, including the extension blocks in common use. */
|
|
4
7
|
const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/u;
|
|
5
8
|
/** A CJK character inside a query or a memory field. */
|
|
@@ -99,52 +102,6 @@ function sharedRuns(queryRuns, field, minimum) {
|
|
|
99
102
|
}
|
|
100
103
|
return shared;
|
|
101
104
|
}
|
|
102
|
-
/** Split text into searchable terms: ASCII words and CJK character bigrams.
|
|
103
|
-
*
|
|
104
|
-
* A CJK run also contributes bigrams of its neighbours, so "该插件是否有日志"
|
|
105
|
-
* yields "该插","插件","件是","是否","否有","有日","日志". A one-character run
|
|
106
|
-
* contributes itself, since a lone ideograph has no bigram.
|
|
107
|
-
*
|
|
108
|
-
* @param text - raw text.
|
|
109
|
-
* @returns lowercase terms; a run that yields nothing contributes nothing.
|
|
110
|
-
*/
|
|
111
|
-
export function tokenize(text) {
|
|
112
|
-
const lower = text.toLowerCase();
|
|
113
|
-
const terms = [];
|
|
114
|
-
for (const word of lower.match(WORD) ?? [])
|
|
115
|
-
terms.push(word);
|
|
116
|
-
const chars = lower.match(CJK_CHAR) ?? [];
|
|
117
|
-
if (chars.length === 1)
|
|
118
|
-
terms.push(chars[0]);
|
|
119
|
-
for (let index = 0; index + 1 < chars.length; index += 1) {
|
|
120
|
-
terms.push(`${chars[index]}${chars[index + 1]}`);
|
|
121
|
-
}
|
|
122
|
-
return terms;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* A term's weight for scoring purposes.
|
|
126
|
-
*
|
|
127
|
-
* One CJK bigram is a much weaker claim than one Latin word — "日志" occurs in
|
|
128
|
-
* countless texts where "logging" does not — so a bigram earns less. Without
|
|
129
|
-
* this every Chinese question would clear the recall gate on noise alone.
|
|
130
|
-
*
|
|
131
|
-
* @param term - one term from {@link tokenize}.
|
|
132
|
-
* @returns a multiplier in `(0, 1]`.
|
|
133
|
-
*/
|
|
134
|
-
export function termWeight(term) {
|
|
135
|
-
const cjk = (term.match(CJK_CHAR) ?? []).length;
|
|
136
|
-
if (cjk === 0)
|
|
137
|
-
return 1;
|
|
138
|
-
// Two-character bigram: half credit. A longer CJK term cannot occur (the
|
|
139
|
-
// tokenizer emits bigrams), but treat it as stronger if it ever does.
|
|
140
|
-
return cjk <= 2 ? 0.5 : Math.min(1, 0.5 + (cjk - 2) * 0.15);
|
|
141
|
-
}
|
|
142
|
-
/** A short token carries little signal and is skipped as a query term. */
|
|
143
|
-
function isNoise(token) {
|
|
144
|
-
if (CJK.test(token))
|
|
145
|
-
return false;
|
|
146
|
-
return token.length < 2;
|
|
147
|
-
}
|
|
148
105
|
/** Count occurrences of `needle` in `haystack`. */
|
|
149
106
|
function occurrences(haystack, needle) {
|
|
150
107
|
if (needle.length === 0)
|
|
@@ -1032,6 +989,12 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1032
989
|
// nobody asked for, and there the track record is the point. Both numbers are
|
|
1033
990
|
// computed here, so neither surface has to guess.
|
|
1034
991
|
const hits = [];
|
|
992
|
+
// One index over every entry this search can see, so a global and a project
|
|
993
|
+
// entry are scored against the same document frequencies and their numbers
|
|
994
|
+
// are comparable. Per-scope indexes would make `dsh` cheap in the 1155-entry
|
|
995
|
+
// global scope and expensive in a 30-entry project scope, and the project
|
|
996
|
+
// entries would lose every tie they should win.
|
|
997
|
+
const pool = [];
|
|
1035
998
|
for (const group of groups) {
|
|
1036
999
|
if (wantedScopes !== undefined && !wantedScopes.includes(group.scope))
|
|
1037
1000
|
continue;
|
|
@@ -1040,13 +1003,18 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1040
1003
|
continue;
|
|
1041
1004
|
if (wantedTags.length > 0 && !wantedTags.every((tag) => entry.tags.includes(tag)))
|
|
1042
1005
|
continue;
|
|
1043
|
-
|
|
1044
|
-
if (relevance <= 0)
|
|
1045
|
-
continue;
|
|
1046
|
-
hits.push({ entry, score, relevance });
|
|
1006
|
+
pool.push(entry);
|
|
1047
1007
|
}
|
|
1048
1008
|
}
|
|
1049
|
-
const
|
|
1009
|
+
const bm25 = createBm25Index(pool).score(query);
|
|
1010
|
+
for (const entry of pool) {
|
|
1011
|
+
const { relevance, score } = rankEntry(entry, query, now, window);
|
|
1012
|
+
if (relevance <= 0)
|
|
1013
|
+
continue;
|
|
1014
|
+
hits.push({ entry, score, relevance, bm25: bm25.get(entry.id) ?? 0 });
|
|
1015
|
+
}
|
|
1016
|
+
const byWords = (left, right) => right.bm25 - left.bm25
|
|
1017
|
+
|| right.relevance - left.relevance
|
|
1050
1018
|
|| right.score - left.score
|
|
1051
1019
|
|| right.entry.updatedAt - left.entry.updatedAt
|
|
1052
1020
|
|| left.entry.title.localeCompare(right.entry.title);
|
|
@@ -1067,7 +1035,14 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1067
1035
|
// this surface ranks in: a hop scored against the seed's attention score would
|
|
1068
1036
|
// be sorting apples against oranges. The injector passes attention scores
|
|
1069
1037
|
// instead, for the same reason.
|
|
1070
|
-
|
|
1038
|
+
// The seeds are the strongest hits in the currency the hop is paid in.
|
|
1039
|
+
// `relatedHits` multiplies a seed's own score, so a seed picked by BM25 order
|
|
1040
|
+
// would pass a BM25 number into a relevance formula; the relevance top three
|
|
1041
|
+
// keeps the activation spreading from the entries the gatekeeper rated
|
|
1042
|
+
// strongest, which is also what the expansion eval measured.
|
|
1043
|
+
const seeds = [...hits]
|
|
1044
|
+
.sort((left, right) => right.relevance - left.relevance || right.score - left.score)
|
|
1045
|
+
.slice(0, EXPAND_SEEDS);
|
|
1071
1046
|
const related = relatedHits(groups, seeds.map((hit) => ({ entry: hit.entry, score: hit.relevance })), {
|
|
1072
1047
|
...options,
|
|
1073
1048
|
limit: EXPAND_MAX,
|
|
@@ -1084,16 +1059,21 @@ export function searchMemories(groups, query, options = {}) {
|
|
|
1084
1059
|
// score like every other hit: `score` means one thing on every row, and the
|
|
1085
1060
|
// row's *place* is decided by the other number.
|
|
1086
1061
|
const attention = hit.score * importanceOf(hit.entry) * decayOf(hit.entry, now);
|
|
1062
|
+
// A hop carries no BM25 of its own: it matched no query word, so it must
|
|
1063
|
+
// sort behind everything the query did match rather than inherit the seed's
|
|
1064
|
+
// number and displace a direct hit.
|
|
1065
|
+
const hopScore = direct?.bm25 ?? 0;
|
|
1087
1066
|
if (direct === undefined) {
|
|
1088
1067
|
merged.push({
|
|
1089
1068
|
entry: hit.entry,
|
|
1090
1069
|
score: attention,
|
|
1091
1070
|
relevance: hit.score,
|
|
1071
|
+
bm25: hopScore,
|
|
1092
1072
|
...hit.via === undefined ? {} : { via: hit.via },
|
|
1093
1073
|
});
|
|
1094
1074
|
}
|
|
1095
1075
|
else if (hit.score > direct.relevance) {
|
|
1096
|
-
merged.push({ entry: direct.entry, score: direct.score, relevance: hit.score });
|
|
1076
|
+
merged.push({ entry: direct.entry, score: direct.score, relevance: hit.score, bm25: hopScore });
|
|
1097
1077
|
}
|
|
1098
1078
|
}
|
|
1099
1079
|
// Keep the best record per id. The direct list comes first, so keeping the
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the BM25 ranker.
|
|
3
|
+
*
|
|
4
|
+
* BM25 is the ordering layer; the gatekeeper in `search.ts` decides what may be
|
|
5
|
+
* recalled. These pin the properties that make BM25 worth its own ranker: a
|
|
6
|
+
* term that appears everywhere is worth less than a term that names the thing
|
|
7
|
+
* (idf), a title hit outranks a body hit (field multiplicity), and a long
|
|
8
|
+
* document does not win merely by repeating a word (length normalisation).
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/test/bm25.test
|
|
11
|
+
*/
|
|
12
|
+
import assert from 'node:assert/strict';
|
|
13
|
+
import test from 'node:test';
|
|
14
|
+
import { BM25_B, BM25_K1, bm25Rank, createBm25Index } from '../bm25.js';
|
|
15
|
+
import { relevanceOf, searchMemories } from '../search.js';
|
|
16
|
+
/** Build one corpus entry. */
|
|
17
|
+
function entry(id, title, body, extra = {}, kind = 'fact') {
|
|
18
|
+
return {
|
|
19
|
+
id,
|
|
20
|
+
scope: 'global',
|
|
21
|
+
kind,
|
|
22
|
+
title,
|
|
23
|
+
body,
|
|
24
|
+
tags: extra.tags ?? [],
|
|
25
|
+
keys: extra.keys ?? [],
|
|
26
|
+
createdAt: 0,
|
|
27
|
+
updatedAt: 0,
|
|
28
|
+
uses: 0,
|
|
29
|
+
lastUsedAt: 0,
|
|
30
|
+
lastSurfacedAt: 0,
|
|
31
|
+
source: 'auto',
|
|
32
|
+
...extra.appliesTo === undefined ? {} : { appliesTo: extra.appliesTo },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
test('the constants are the sensitivity audit best cell, not a guess', () => {
|
|
36
|
+
assert.equal(BM25_K1, 1.2);
|
|
37
|
+
assert.equal(BM25_B, 0.75);
|
|
38
|
+
});
|
|
39
|
+
test('a title hit outranks an identical body hit', () => {
|
|
40
|
+
const corpus = [
|
|
41
|
+
entry('in-title', '插件日志查看方式', '无关正文。'),
|
|
42
|
+
entry('in-body', '无关标题', '插件日志查看方式写在正文里。'),
|
|
43
|
+
];
|
|
44
|
+
const ranked = bm25Rank(corpus, '插件日志');
|
|
45
|
+
assert.equal(ranked[0]?.id, 'in-title', 'the title is repeated twice in the index');
|
|
46
|
+
assert.ok((createBm25Index(corpus).score('插件日志').get('in-title') ?? 0)
|
|
47
|
+
> (createBm25Index(corpus).score('插件日志').get('in-body') ?? 0));
|
|
48
|
+
});
|
|
49
|
+
test('a term that appears everywhere is worth less than one that names the thing', () => {
|
|
50
|
+
// 「同步」 is on every entry; the file name is on one. A query naming both
|
|
51
|
+
// must prefer the entry that carries the rare term.
|
|
52
|
+
const corpus = Array.from({ length: 20 }, (_unused, index) => entry(`common-${index}`, `同步任务 ${index}`, '同步 同步 同步。'));
|
|
53
|
+
corpus.push(entry('rare', '同步任务:uk_file_invoice_sha_role', '同步。'));
|
|
54
|
+
const ranked = bm25Rank(corpus, '同步 uk_file_invoice_sha_role');
|
|
55
|
+
assert.equal(ranked[0]?.id, 'rare', 'the rare identifier decides the order');
|
|
56
|
+
const index = createBm25Index(corpus);
|
|
57
|
+
const scores = index.score('同步 uk_file_invoice_sha_role');
|
|
58
|
+
assert.ok((scores.get('rare') ?? 0) > (scores.get('common-0') ?? 0));
|
|
59
|
+
});
|
|
60
|
+
test('repeating one common word saturates instead of scaling linearly', () => {
|
|
61
|
+
const shortHit = entry('short', '同步说明', '同步。');
|
|
62
|
+
const longRepeat = entry('long', '同步说明', '同步 '.repeat(80));
|
|
63
|
+
const corpus = [shortHit, longRepeat];
|
|
64
|
+
const scores = createBm25Index(corpus).score('同步');
|
|
65
|
+
const once = scores.get('short') ?? 0;
|
|
66
|
+
const eighty = scores.get('long') ?? 0;
|
|
67
|
+
assert.ok(once > 0 && eighty > 0);
|
|
68
|
+
// 80 repeats are worth about one hit, not eighty: the tf term saturates.
|
|
69
|
+
assert.ok(eighty / once < 10, `repetition scaled too far: ${once.toFixed(2)} -> ${eighty.toFixed(2)}`);
|
|
70
|
+
});
|
|
71
|
+
test('a query with no shared term returns nothing, and an empty query is empty', () => {
|
|
72
|
+
const corpus = [entry('a', '插件日志', '日志正文。')];
|
|
73
|
+
assert.deepEqual(bm25Rank(corpus, '完全不相关的查询'), []);
|
|
74
|
+
assert.deepEqual(bm25Rank(corpus, ''), []);
|
|
75
|
+
assert.deepEqual(bm25Rank(corpus, ' '), []);
|
|
76
|
+
});
|
|
77
|
+
test('the index is cached against the exact array it was built from', () => {
|
|
78
|
+
const corpus = [entry('a', '插件日志', '日志正文。')];
|
|
79
|
+
assert.equal(createBm25Index(corpus), createBm25Index(corpus), 'the same array reuses the index');
|
|
80
|
+
assert.notEqual(createBm25Index([...corpus]), createBm25Index(corpus), 'a copy is a different index');
|
|
81
|
+
});
|
|
82
|
+
test('CJK bigrams rank a Chinese query without a model call', () => {
|
|
83
|
+
const corpus = [
|
|
84
|
+
entry('logs', '插件日志查看方式', '日志写在文件里。'),
|
|
85
|
+
entry('order', '插件注册顺序', '启动时注册。'),
|
|
86
|
+
entry('cost', '成本计量的坑', '另一件事。'),
|
|
87
|
+
];
|
|
88
|
+
const ranked = bm25Rank(corpus, '该插件是否有日志');
|
|
89
|
+
assert.equal(ranked[0]?.id, 'logs');
|
|
90
|
+
assert.ok(!ranked.some((value) => value.id === 'cost'), 'an unrelated entry does not surface');
|
|
91
|
+
});
|
|
92
|
+
test('the ranker changes the order, never the admitted set', () => {
|
|
93
|
+
// The gatekeeper decides what may be recalled; BM25 only decides which of
|
|
94
|
+
// those comes first. If a ranker ever adds or drops an entry, the recall
|
|
95
|
+
// gate has silently changed meaning — so pin the set.
|
|
96
|
+
const corpus = [
|
|
97
|
+
entry('logs', '插件日志查看方式', '日志写在文件里。', { keys: ['logging'] }),
|
|
98
|
+
entry('order', '插件注册顺序', '启动时注册。', { tags: ['插件'] }),
|
|
99
|
+
entry('push', '提交后主动推送', '提交完直接推 origin。', { appliesTo: '准备推送代码之前' }),
|
|
100
|
+
entry('cost', '成本计量的坑', '另一件事。'),
|
|
101
|
+
entry('restart', '重启 dsh web', '用 restart 端点。'),
|
|
102
|
+
];
|
|
103
|
+
const groups = [{ scope: 'global', label: 'global', entries: corpus }];
|
|
104
|
+
const query = '插件的日志和推送';
|
|
105
|
+
const admitted = corpus.filter((value) => relevanceOf(value, query) > 0).map((value) => value.id).sort();
|
|
106
|
+
const ranked = searchMemories(groups, query, { limit: 10 }).map((hit) => hit.entry.id).sort();
|
|
107
|
+
assert.deepEqual(ranked, admitted, 'BM25 must not admit an entry the gatekeeper refused, or hide one it admitted');
|
|
108
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the optional dense channel.
|
|
3
|
+
*
|
|
4
|
+
* The ranker is only exercised on the parts that need no service: fusion order
|
|
5
|
+
* and the degrade-to-lexical guarantee. The embedding call itself is covered by
|
|
6
|
+
* the bench (`run-bench.mts`, dense arm), which runs against a real ollama.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-cross-memory/test/dense.test
|
|
9
|
+
*/
|
|
10
|
+
import assert from 'node:assert/strict';
|
|
11
|
+
import test from 'node:test';
|
|
12
|
+
import { cosine, denseScores, rrf } from '../dense.js';
|
|
13
|
+
function entry(id, title, body) {
|
|
14
|
+
return {
|
|
15
|
+
id, scope: 'global', kind: 'fact', title, body,
|
|
16
|
+
tags: [], keys: [], createdAt: 0, updatedAt: 0, uses: 0,
|
|
17
|
+
lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto',
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
test('fusion sums reciprocal ranks and keeps the better-placed entry first', () => {
|
|
21
|
+
const fused = rrf([['a', 'b', 'c'], ['a', 'b']]);
|
|
22
|
+
// `a` leads both lists; `b` follows it in both; `c` appears once.
|
|
23
|
+
assert.ok((fused.get('a') ?? 0) > (fused.get('b') ?? 0), 'a outranks b on total rank');
|
|
24
|
+
assert.ok((fused.get('b') ?? 0) > (fused.get('c') ?? 0), 'c has only one appearance');
|
|
25
|
+
assert.deepEqual([...fused.keys()], ['a', 'b', 'c']);
|
|
26
|
+
});
|
|
27
|
+
test('fusion ignores empty lists and returns nothing for no lists', () => {
|
|
28
|
+
assert.deepEqual([...rrf([[], ['a']]).keys()], ['a']);
|
|
29
|
+
assert.equal(rrf([]).size, 0);
|
|
30
|
+
});
|
|
31
|
+
test('cosine is 1 for identical unit vectors and 0 for orthogonal ones', () => {
|
|
32
|
+
assert.ok(Math.abs(cosine(new Float32Array([1, 0]), new Float32Array([1, 0])) - 1) < 1e-6);
|
|
33
|
+
assert.ok(Math.abs(cosine(new Float32Array([1, 0]), new Float32Array([0, 1]))) < 1e-6);
|
|
34
|
+
});
|
|
35
|
+
test('an unavailable embedding service degrades to an empty result, never a throw', async () => {
|
|
36
|
+
const entries = [entry('a', '插件日志', '日志正文。')];
|
|
37
|
+
const scores = await denseScores(entries, '插件日志', {
|
|
38
|
+
url: 'http://127.0.0.1:1',
|
|
39
|
+
model: 'test-model',
|
|
40
|
+
cacheDir: '/tmp/dsh-cross-memory-dense-test',
|
|
41
|
+
});
|
|
42
|
+
assert.equal(scores.size, 0, 'the lexical caller falls back on an empty map');
|
|
43
|
+
});
|
|
44
|
+
test('an empty query or an empty store scores nothing without calling out', async () => {
|
|
45
|
+
const entries = [entry('a', '插件日志', '日志正文。')];
|
|
46
|
+
const options = { url: 'http://127.0.0.1:1', model: 'test-model', cacheDir: '/tmp/dsh-cross-memory-dense-test' };
|
|
47
|
+
assert.equal((await denseScores(entries, '', options)).size, 0);
|
|
48
|
+
assert.equal((await denseScores([], '插件日志', options)).size, 0);
|
|
49
|
+
});
|
|
@@ -35,6 +35,19 @@ function stubSession(cwd, history = []) {
|
|
|
35
35
|
function stubAgent(session) {
|
|
36
36
|
return { id: 'test-session', session, status: 'idle' };
|
|
37
37
|
}
|
|
38
|
+
/** One rendered section's text, located by its heading rather than its place.
|
|
39
|
+
*
|
|
40
|
+
* Project memories render before global ones, so a test that splits on the
|
|
41
|
+
* first `## ` would be asserting an order rather than a cap.
|
|
42
|
+
*/
|
|
43
|
+
function sectionOf(summary, heading) {
|
|
44
|
+
const lines = summary.split('\n');
|
|
45
|
+
const start = lines.findIndex((line) => line.startsWith(`## ${heading}`));
|
|
46
|
+
if (start < 0)
|
|
47
|
+
return '';
|
|
48
|
+
const end = lines.findIndex((line, at) => at > start && line.startsWith('## '));
|
|
49
|
+
return lines.slice(start, end < 0 ? lines.length : end).join('\n');
|
|
50
|
+
}
|
|
38
51
|
test('injection is once per conversation, not once per turn', async (t) => {
|
|
39
52
|
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-inj-'));
|
|
40
53
|
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
|
|
@@ -169,7 +182,10 @@ test('the global section is capped so it cannot bury the project scope', async (
|
|
|
169
182
|
await runtime.write(agent.session, { scope: 'project', title: 'This repo is special', body: 'Only true here.', tags: [] }, 'tool');
|
|
170
183
|
const summary = await runtime.summary(agent.session);
|
|
171
184
|
assert.ok(summary !== undefined);
|
|
172
|
-
|
|
185
|
+
// Sections are parsed by heading, not by position: project memories render
|
|
186
|
+
// before global ones, because they are the ones about this workspace.
|
|
187
|
+
const globalPart = sectionOf(summary, 'Global memories');
|
|
188
|
+
const projectPart = sectionOf(summary, 'Project memories');
|
|
173
189
|
const globalBullets = (globalPart ?? '').split('\n').filter((line) => line.startsWith('- ') && !line.startsWith('- …'));
|
|
174
190
|
assert.equal(globalBullets.length, 2, 'the global half stops at its own cap');
|
|
175
191
|
assert.match(projectPart ?? '', /This repo is special/u, 'and the project half still appears');
|
|
@@ -240,7 +256,7 @@ test('a never-surfaced backlog cannot swallow the shared global half', async (t)
|
|
|
240
256
|
await runtime.write(agent.session, { scope: 'project', title: 'Workspace fact', body: 'Only here.', tags: [] }, 'auto');
|
|
241
257
|
const summary = await runtime.summary(agent.session);
|
|
242
258
|
assert.ok(summary !== undefined);
|
|
243
|
-
const
|
|
259
|
+
const globalPart = sectionOf(summary, 'Global memories');
|
|
244
260
|
const freshShown = (globalPart ?? '').split('\n').filter((line) => /^- (?:📌 )?Newest note/u.test(line)).length;
|
|
245
261
|
const bullets = (globalPart ?? '').split('\n').filter((line) => line.startsWith('- ') && !line.startsWith('- …')).length;
|
|
246
262
|
assert.equal(bullets, 4, 'the global half still fills its own cap');
|