dsh-knit 0.5.1 → 0.11.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.
@@ -2,16 +2,59 @@
2
2
  * Knit · 相关性引擎(纯本地,零模型、零网络)
3
3
  *
4
4
  * 输入:当前对话最近几条消息的文本 + 每个文档的可搜索文本
5
- * 输出:每个文档一个 0-100 的相关度,以及一个「当前话题」标签
5
+ * 输出:每个文档一个 0-100 的相关度、一个「当前话题」标签,以及实际命中的词
6
6
  *
7
- * 算法(TF-IDF 的简化版,但不做全局 df 统计以保持 O(docs×keywords)):
8
- * 1. 从对话里抽关键词:ASCII 词 + 中文 2/3-gram,按 出现次数×长度² 排序,
9
- * 贪心去重叠,取前 N 个。越新的消息权重越高。
10
- * 2. 每个文档算加权命中分:标题×4 + 摘要×2 + 正文头部×1,命中数封顶 6 次。
11
- * 3. 加 10% 的时间新鲜度奖励(相关性为主,新鲜度只做微调)。
12
- * 4. 以最高分为 100 归一化。
7
+ * ── 两层,各自的词表来源不同 ─────────────────────────
13
8
  *
14
- * 全部是确定性字符串运算,没有模型调用,没有网络请求。
9
+ * **查询侧**用 `tokenize()` 生成候选词:ASCII 词 + 中文 2/3-gram。
10
+ * **文档侧**不做分词,直接用 `indexOf` 数子串出现次数。
11
+ *
12
+ * 为什么文档侧不分词:分词要为每篇文档生成全部 2/3-gram,
13
+ * 500 篇 × 2500 字实测 **114ms**,而 `indexOf` 是原生实现、只找那几十个候选词。
14
+ * 两者语义也一致 —— 候选词本身就是子串,子串计数就是它的词频。
15
+ *
16
+ * ── 打分:BM25(字段加权) ───────────────────────────
17
+ *
18
+ * 1. 从对话里抽关键词(见下方「抽取」的说明)。
19
+ * 2. 对语料做一次统计:每个词在每篇文档、每个字段的出现次数(tf)、
20
+ * 字段长度、以及**文档频率** df。
21
+ * 3. BM25 打分,字段加权求和:
22
+ *
23
+ * raw(d) = Σ_t qw(t) · idf(t) · Σ_f w_f · sat_f(t, d)
24
+ *
25
+ * sat_f(t,d) = tf·(k1+1) / ( tf + k1·(1 - b_f + b_f·len_f/avgdl_f) )
26
+ * idf(t) = ln(1 + (N - df + 0.5) / (df + 0.5))
27
+ * qw(t) = weight(t) / max(weight) (查询侧相对权重)
28
+ *
29
+ * 4. 叠 10% 的时间新鲜度微调(主排序仍是相关性)。
30
+ * 5. 以最高分为 100 归一化。
31
+ *
32
+ * `len_f` 用的是**字段字符数**而不是「分词后的词数」—— 那需要分词,见上。
33
+ * 长度归一化只要求长度尺度和文档长度单调相关,字符数满足这一点。
34
+ *
35
+ * ── 为什么不再用 v0.5.2 的「加权命中」 ─────────────────
36
+ *
37
+ * - 旧做法**没有 IDF** —— 语料里到处都是的词(比如项目名)和罕见词同权,
38
+ * 高频词于是不产生任何区分度,还把罕见词的区分度稀释掉。
39
+ * - 旧做法**没有长度归一化** —— 长文档天然命中次数多,靠堆词就能赢。
40
+ * - 旧做法的饱和曲线是手写硬拐点(命中封顶 6 次);`k1` / `b` 才是为这件事设计的。
41
+ *
42
+ * **候选要丢掉跨词边界的碎片**(`CN_EDGE_STOP`):中文没有词边界,n-gram 会把相邻
43
+ * 两个词的字粘起来(「图片和」「片和视」「个插」)。它们分数还高(`词长²`),
44
+ * 去重叠时会把「图片」「视频」「面板」这些真实存在的词全部挤掉 ——
45
+ * 结果是查询词里几乎没有一个是文档里真有的词。
46
+ *
47
+ * 实测(`test/eval/fixture.mjs`,21 个用例):
48
+ *
49
+ * | 配置 | top-1 | MRR |
50
+ * |----------------------------------|-----------|-----------|
51
+ * | v0.5.2(加权命中 + 不去碎片) | 76.2% | 0.830 |
52
+ * | BM25,但抽取仍不去碎片 | 81.0% | 0.870 |
53
+ * | **BM25 + 去掉首尾虚词的碎片** | **95.2%** | **0.976** |
54
+ *
55
+ * 输出顺序仍是分数降序 —— 面板那行「按「xxx」排序」显示的是最重要的词。
56
+ *
57
+ * 全部是确定性字符串运算,没有模型调用,没有网络请求,没有任何依赖。
15
58
  */
16
59
 
17
60
  /* ── 停用词 ─────────────────────────────────────────── */
@@ -49,7 +92,43 @@ const CN_STOP_BIGRAMS = new Set([
49
92
  '一些', '有点', '有点', '有点', '以后', '以前', '之后', '之前', '的话', '来说', '方面',
50
93
  ])
51
94
 
52
- /* ── 关键词抽取 ─────────────────────────────────────── */
95
+ /**
96
+ * **首尾出现即判定为「跨词边界碎片」**的虚词集合。
97
+ *
98
+ * 中文没有词边界,n-gram 会把相邻两个词的字粘在一起(「图片和」「个插」「的排」)。
99
+ * 这类碎片有两个共同特征:**首字或尾字是纯虚词**。它们几乎不可能是真词,
100
+ * 却会占满候选位,把「图片」「排序」这种真实存在的词挤掉。
101
+ *
102
+ * 这是**窄集**,不是 `CN_STOP_CHARS` 全表 —— 后者含「上/中/里/前/后/大/小/一…」,
103
+ * 那些是常见**构词成分**(上传、上下文、中间、下游…),拿它们做首尾判定会误杀真词。
104
+ * 实测:窄集与宽集在评测集上表现完全相同(top-1 95.2% / MRR 0.976),
105
+ * 但窄集保住了上面那些词。
106
+ *
107
+ * ⚠️ **「对」在 v0.8 被移出这个集合。** 它是介词,但也是**构词成分**:
108
+ * 对比、对话、对象、对齐 都是真词,判在首字会把它们全部误杀
109
+ * (实测:「对比度」被切成了碎片「比度」)。
110
+ * 移出之后评测四项指标**一个都没变**(top-1 95.2% / MRR 0.976 / 陷阱 0)。
111
+ * 移除是免费的,所以做了;**再往下裁就没有额外收益**(试过 以/从/到/及/或/为/之/于/并/等/着/过/来/去,
112
+ * 标签一个都没变好),所以停在这里,不再扩大。
113
+ */
114
+ const CN_EDGE_STOP = new Set([
115
+ '的', '了', '是', '在', '和', '与', '就', '都', '也', '很', '把', '被', '让', '给',
116
+ '从', '到', '为', '以', '及', '或', '但', '而', '之', '于', '并', '等', '着',
117
+ '过', '呢', '吗', '吧', '啊', '哦', '嗯', '呀', '么', '些', '嘛', '啦',
118
+ '我', '你', '他', '她', '它', '们', '这', '那', '有', '没', '会', '能', '要', '不',
119
+ '说', '做', '用', '好', '多', '少', '来', '去', '出', '入', '时', '话', '个',
120
+ ])
121
+
122
+ /* ── 分词(只用于查询侧) ───────────────────────────── */
123
+
124
+ /** 单个 CJK 字符。用来扫出连续的汉字段,同时保留原文位置。 */
125
+ const CJK_RE = /[\u4e00-\u9fff]/
126
+
127
+ /** 一个词最多留几个位置(只用于合并话题标签,不需要穷举)。 */
128
+ const MAX_SPANS_PER_TERM = 8
129
+
130
+ /** 合并后的标签最长几个字。真词一般不超过这个长度(扩展名白名单 = 6)。 */
131
+ const MAX_LABEL_CHARS = 6
53
132
 
54
133
  /**
55
134
  * 给一个 n-gram 打分用的字符集检查。
@@ -64,7 +143,78 @@ function allStopChars(gram) {
64
143
  }
65
144
 
66
145
  /**
67
- * 从一段文本里累计 n-gram。
146
+ * 把一段对话文本切成候选词,**并带上每个词在原文里的位置**。
147
+ *
148
+ * 位置是给「当前话题」标签用的:候选里难免有跨词边界的碎片
149
+ * (`项目文` / `目文档` 都是「项目文档」的碎片),但**它们覆盖的区间是重叠的** ——
150
+ * 把重叠区间合并再切原文,就还原出真词「项目文档」。
151
+ * 见 `readableTopics()`。
152
+ *
153
+ * 只在**查询侧**使用。文档侧不调它 —— 那是为了性能,见文件头说明。
154
+ *
155
+ * 规则(与 v0.6 的 `tokenize` 逐字一致,只是多带位置):
156
+ * - ASCII 词 / 标识符:`[A-Za-z][A-Za-z0-9_]{2,29}`,小写后丢掉英文停用词
157
+ * - 中文:按非 CJK 字符切段,每段长度 ≥ 2 时产出**全部 2-gram 与 3-gram**,
158
+ * 2-gram 丢掉中文停用 bigram,全是停用字符的 gram 丢掉
159
+ *
160
+ * @param {string} text - 文本(调用方保证已是小写;中文不受影响)
161
+ * @returns {Array<{term: string, start: number, end: number}>} 词与它在 `text` 里的区间
162
+ */
163
+ export function tokenizeSpans(text) {
164
+ if (!text) return []
165
+ const out = []
166
+
167
+ // ASCII 词 / 标识符(chokidar、TypeScript、ctx.sidebarRightTabs…)
168
+ for (const m of text.matchAll(/[A-Za-z][A-Za-z0-9_]{2,29}/g)) {
169
+ const token = m[0].toLowerCase()
170
+ if (EN_STOP.has(token)) continue
171
+ out.push({ term: token, start: m.index, end: m.index + m[0].length })
172
+ }
173
+
174
+ // 中文 2-gram / 3-gram。
175
+ // **不能用 replace + split 找 run** —— 那会丢掉原文位置,只能自己扫。
176
+ let i = 0
177
+ while (i < text.length) {
178
+ if (!CJK_RE.test(text[i])) {
179
+ i += 1
180
+ continue
181
+ }
182
+ let j = i
183
+ while (j < text.length && CJK_RE.test(text[j])) j += 1
184
+ const runLen = j - i
185
+ if (runLen >= 2) {
186
+ for (let n = 2; n <= 3; n += 1) {
187
+ for (let k = 0; k + n <= runLen; k += 1) {
188
+ const gram = text.slice(i + k, i + k + n)
189
+ if (n === 2 && CN_STOP_BIGRAMS.has(gram)) continue
190
+ if (allStopChars(gram)) continue
191
+ out.push({ term: gram, start: i + k, end: i + k + n })
192
+ }
193
+ }
194
+ }
195
+ i = j
196
+ }
197
+
198
+ return out
199
+ }
200
+
201
+ /**
202
+ * 把一段对话文本切成候选词(只要词,不要位置)。
203
+ *
204
+ * 与 `tokenizeSpans` 产出的词表**逐字一致**,只是把位置丢掉了。
205
+ * 保留这个导出是因为 v0.6 的「抽词零变化」守卫测试直接对着它断言。
206
+ *
207
+ * @param {string} text - 文本
208
+ * @returns {string[]} 词表,含重复
209
+ */
210
+ export function tokenize(text) {
211
+ return tokenizeSpans(text).map((tok) => tok.term)
212
+ }
213
+
214
+ /* ── 关键词抽取 ─────────────────────────────────────── */
215
+
216
+ /**
217
+ * 把一段文本的词频累加进两张表,并记下每个词在原文里的位置。
68
218
  *
69
219
  * **原始次数与加权分数分开记**:权重只影响排序,不影响「够不够格」。
70
220
  * 否则一条消息权重 3,里面出现一次的词也会被当成出现 3 次,噪音全进来了。
@@ -73,40 +223,21 @@ function allStopChars(gram) {
73
223
  * @param {number} weight - 这段话的权重倍数
74
224
  * @param {Map<string, number>} raw - 原始出现次数
75
225
  * @param {Map<string, number>} weighted - 加权分数
226
+ * @param {Map<string, Array<{text: string, start: number, end: number}>>} spans - 词 → 它在原文里的区间
76
227
  * @returns {void}
77
228
  */
78
- function accumulate(text, weight, raw, weighted) {
79
- if (!text) return
80
-
81
- /**
82
- * 记一次命中。
83
- * @param {string} term - 词
84
- * @returns {void}
85
- */
86
- const bump = (term) => {
229
+ function accumulate(text, weight, raw, weighted, spans) {
230
+ for (const tok of tokenizeSpans(text)) {
231
+ const term = tok.term
87
232
  raw.set(term, (raw.get(term) || 0) + 1)
88
233
  weighted.set(term, (weighted.get(term) || 0) + weight)
89
- }
90
-
91
- // ASCII 词 / 标识符(chokidar、TypeScript、ctx.sidebarRightTabs…)
92
- for (const m of text.matchAll(/[A-Za-z][A-Za-z0-9_]{2,29}/g)) {
93
- const token = m[0].toLowerCase()
94
- if (EN_STOP.has(token)) continue
95
- bump(token)
96
- }
97
-
98
- // 中文 2-gram / 3-gram
99
- const cjkRuns = text.replace(/[^\u4e00-\u9fff]+/g, ' ').split(' ')
100
- for (const run of cjkRuns) {
101
- if (run.length < 2) continue
102
- for (let n = 2; n <= 3; n += 1) {
103
- for (let i = 0; i + n <= run.length; i += 1) {
104
- const gram = run.slice(i, i + n)
105
- if (n === 2 && CN_STOP_BIGRAMS.has(gram)) continue
106
- if (allStopChars(gram)) continue
107
- bump(gram)
108
- }
234
+ if (!spans) continue
235
+ let list = spans.get(term)
236
+ if (list === undefined) {
237
+ list = []
238
+ spans.set(term, list)
109
239
  }
240
+ if (list.length < MAX_SPANS_PER_TERM) list.push({ text, start: tok.start, end: tok.end })
110
241
  }
111
242
  }
112
243
 
@@ -121,27 +252,41 @@ function accumulate(text, weight, raw, weighted) {
121
252
  * 后者权重为 3,是当下正在聊什么的最强信号,不该因为只出现一次被丢掉;
122
253
  * 而只在旧消息里露过一次的中文片段基本是噪音,滤掉。
123
254
  *
255
+ * **候选会丢掉跨词边界的碎片**(见 `CN_EDGE_STOP`):首字或尾字是虚词的 n-gram
256
+ * 几乎都是两个词粘起来的产物,不是词。不丢的话它们会占满候选位,
257
+ * 把真实存在的词全挤出去。
258
+ *
259
+ * 输出仍按分数降序。
260
+ *
261
+ * **每个词还会带上它在原文里的位置**(`spans`)。位置不参与排序,
262
+ * 只用来把「当前话题」标签还原成可读的词 —— 见 `readableTopics()`。
263
+ *
124
264
  * @param {readonly string[]} messages - 对话文本,最新在前
125
265
  * @param {number} limit - 最多返回多少个关键词
126
- * @returns {Array<{term: string, weight: number}>} 关键词及其权重,权重降序
266
+ * @returns {Array<{term: string, weight: number, spans: Array<{text: string, start: number, end: number}>}>}
267
+ * 关键词及其权重,权重降序
127
268
  */
128
269
  export function extractKeywords(messages, limit = 30) {
129
270
  const raw = new Map()
130
271
  const weighted = new Map()
272
+ const spans = new Map()
131
273
 
132
274
  messages.forEach((text, index) => {
133
275
  const weight = index === 0 ? 3 : index === 1 ? 2 : 1
134
- accumulate(text, weight, raw, weighted)
276
+ accumulate(text, weight, raw, weighted, spans)
135
277
  })
136
278
 
137
279
  const ranked = [...weighted.entries()]
138
280
  .map(([term, weight]) => ({ term, weight, seen: raw.get(term) || 0 }))
139
281
  .filter((entry) => {
140
282
  if (/^[a-z]/.test(entry.term)) return entry.seen >= 1
283
+ // 跨词边界的碎片:首字或尾字是纯虚词。判在门槛之前 —— 它比「出现几次」更根本。
284
+ if (CN_EDGE_STOP.has(entry.term[0])) return false
285
+ if (CN_EDGE_STOP.has(entry.term[entry.term.length - 1])) return false
141
286
  return entry.seen >= 2 || entry.weight >= 3
142
287
  })
143
288
  .map((entry) => ({ ...entry, score: entry.weight * entry.term.length * entry.term.length }))
144
- .sort((a, b) => b.score - a.score)
289
+ .sort((a, b) => (b.score - a.score) || a.term.localeCompare(b.term))
145
290
 
146
291
  const picked = []
147
292
  for (const entry of ranked) {
@@ -151,16 +296,167 @@ export function extractKeywords(messages, limit = 30) {
151
296
  picked.push(entry)
152
297
  }
153
298
 
154
- return picked.map((entry) => ({ term: entry.term, weight: entry.score }))
299
+ return picked.map((entry) => ({
300
+ term: entry.term,
301
+ weight: entry.score,
302
+ spans: spans.get(entry.term) || [],
303
+ }))
155
304
  }
156
305
 
157
- /* ── 文档打分 ───────────────────────────────────────── */
306
+ /* ── 当前话题标签(v0.8) ───────────────────────────── */
158
307
 
159
308
  /**
160
- * 数一个词在文本里出现几次(封顶,避免长文档靠堆词刷分)。
309
+ * 把「语料里真实存在」的那批候选词还原成人能读的标签。
310
+ *
311
+ * **问题**:候选分是 `出现次数 × 词长²`,所以每个 3-gram 都压过所有 2-gram。
312
+ * 对「项目文档」这种输入,`项目文` 与 `目文档` 先被选中,
313
+ * 真实的 `项目` / `文档` 作为它们的子串在去重叠时被吞掉 ——
314
+ * 面板那行就成了「按「目文档、项目文」排序」。
315
+ *
316
+ * **修法**:不动排序(`extractKeywords` 的候选与顺序一字不改),
317
+ * 只把命中词的**原文区间**拿来合并 —— `项目文[0,3)` 与 `目文档[1,4)` 是**重叠**的,
318
+ * 合并后切原文得到 `项目文档`,正好是真词。
319
+ *
320
+ * 三个细节:
321
+ * - **只有严格重叠才合并**,相邻不算。否则 `相关[0,2)` + `性排[2,4)` 会被粘成
322
+ * 更难看的「相关性排」。
323
+ * - **合并结果必须在语料里真的出现过**(`isPresent`)。这一条是必需的:
324
+ * 3-gram 逐个错位、彼此都重叠,所以**传递性合并会一路串下去** ——
325
+ * 实测「悬停浮层是怎么做的」会串成「悬停浮层是怎」、「扩展名白名单都放行什么」
326
+ * 会串成「扩展名白名单都放行什」。光靠长度上限没用(链条会一直长到上限为止)。
327
+ * 「项目文档」「悬停浮层」「扩展名白名单」都真的在项目里出现过,而串出来的那几句没有。
328
+ * - 拿不到 `spans`(调用方直接传了 `{term, weight}`)时返回空数组,
329
+ * 由调用方回落成原来的词表。
330
+ *
331
+ * @param {readonly {term: string, weight: number, spans?: Array<{text: string, start: number, end: number}>}[]} keywords -
332
+ * 已经过滤到「语料里真实存在」的那批词
333
+ * @param {number} limit - 最多返回几个标签
334
+ * @param {(label: string) => boolean} [isPresent] - 判断一段文本是否在语料里出现过;
335
+ * 不传就只按长度上限取最长的那段(测试用)
336
+ * @returns {string[]} 标签词,按权重降序
337
+ */
338
+ export function readableTopics(keywords, limit = 3, isPresent) {
339
+ const groups = new Map()
340
+ for (const kw of keywords) {
341
+ if (!kw || !Array.isArray(kw.spans)) continue
342
+ for (const span of kw.spans) {
343
+ if (!span || typeof span.text !== 'string') continue
344
+ if (!Number.isInteger(span.start) || !Number.isInteger(span.end)) continue
345
+ let list = groups.get(span.text)
346
+ if (list === undefined) {
347
+ list = []
348
+ groups.set(span.text, list)
349
+ }
350
+ list.push({ start: span.start, end: span.end, weight: kw.weight })
351
+ }
352
+ }
353
+
354
+ const found = []
355
+ for (const [text, list] of groups) {
356
+ list.sort((a, b) => (a.start - b.start) || (a.end - b.end))
357
+
358
+ // 滑动窗口:从每个还没被用掉的区间出发,尽量往后接**仍然与当前并集重叠**的区间,
359
+ // 一旦并集超过长度上限就停(后面只会更长)。
360
+ // 取其中**最长且在语料里真的出现过**的那一段;用掉它覆盖的区间,再处理下一个。
361
+ // 于是一句话里可以有多个标签(互不重叠),而不是只挑一个。
362
+ const used = new Array(list.length).fill(false)
363
+ for (let i = 0; i < list.length; i += 1) {
364
+ if (used[i]) continue
365
+ const start = list[i].start
366
+ let end = list[i].end
367
+ let weight = list[i].weight
368
+ let bestEnd = -1
369
+ let bestWeight = -1
370
+ for (let j = i; j < list.length; j += 1) {
371
+ if (j > i) {
372
+ if (list[j].start >= end) break // 不再重叠 → 链条断了
373
+ end = Math.max(end, list[j].end)
374
+ weight = Math.max(weight, list[j].weight)
375
+ }
376
+ const size = end - start
377
+ if (size < 2) continue
378
+ if (size > MAX_LABEL_CHARS) break
379
+ const label = text.slice(start, end)
380
+ if (isPresent !== undefined && !isPresent(label)) continue
381
+ if (size > bestEnd - start) {
382
+ bestEnd = end
383
+ bestWeight = weight
384
+ }
385
+ }
386
+ if (bestEnd < 0) continue // 这个起点组不出任何真实存在的词
387
+ found.push({ label: text.slice(start, bestEnd), weight: bestWeight })
388
+ for (let j = i; j < list.length; j += 1) {
389
+ if (list[j].start < bestEnd) used[j] = true
390
+ }
391
+ }
392
+ }
393
+
394
+ found.sort((a, b) => (b.weight - a.weight) || a.label.localeCompare(b.label))
395
+ const seen = new Set()
396
+ const out = []
397
+ for (const item of found) {
398
+ if (seen.has(item.label)) continue
399
+ seen.add(item.label)
400
+ out.push(item.label)
401
+ if (out.length >= limit) break
402
+ }
403
+ return out
404
+ }
405
+
406
+ /* ── 文档打分(v0.6 换成 BM25) ─────────────────────── */
407
+
408
+ /**
409
+ * 字段权重。
410
+ *
411
+ * 沿用 v0.5.2 的比例(标题 > 摘要 > 正文)—— 这是已经对外解释过的产品决策,
412
+ * 不是 v0.6 要改的东西;README 里那张表说的就是这三个数。
413
+ */
414
+ const FIELD_WEIGHTS = { title: 4, summary: 2, body: 1 }
415
+
416
+ /**
417
+ * 每个字段的长度归一化强度 `b`:`0` 是不归一化,`1` 是完全按长度归一化。
418
+ *
419
+ * 标题本来就短、长度差异小,过度归一化会惩罚「信息量大的长标题」,所以给小值;
420
+ * 正文差异最大,用 BM25 的经典默认值 0.75。
421
+ */
422
+ const FIELD_B = { title: 0.3, summary: 0.5, body: 0.75 }
423
+
424
+ /** BM25 的词频饱和系数(经典默认值)。 */
425
+ const K1 = 1.2
426
+
427
+ /**
428
+ * 单词频上限。
429
+ *
430
+ * BM25 本身就会饱和(`k1` 越小饱和越快),所以封顶不是为了压制长文档,
431
+ * 纯粹是为了给最坏情况(一个词在 2500 字里出现几百次)定一个成本上界。
432
+ * 取 20 时,与不封顶的分数差已经可以忽略。
433
+ */
434
+ const TF_CAP = 20
435
+
436
+ /** 参与打分的字段名。 */
437
+ const FIELDS = ['title', 'summary', 'body']
438
+
439
+ /** 新鲜度奖励的时间常数(7 天)。 */
440
+ const FRESHNESS_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
441
+
442
+ /**
443
+ * 查询侧相对权重的压缩指数:`qw(t) = (weight(t) / max(weight)) ^ QW_EXPONENT`。
444
+ *
445
+ * 候选分是 `出现次数 × 词长²`,尺度差得很远:一个 4 字英文词出现 10 次是 160 分,
446
+ * 一个中文 2-gram 出现 5 次只有 20 分。直接用比例(指数 1)会让**最强的那一个词**
447
+ * 压过其余所有词,于是「满篇项目名」的文档靠一个词就能霸榜。
448
+ *
449
+ * 实测(21 个用例):指数 1 时高频词陷阱仍然失败;**≤ 0.25 时全部翻正**,
450
+ * 而 top-1 / MRR 不变。取 0.25 —— 保留「越新 / 越长的词更重要」的**次序**,
451
+ * 但把它的**幅度**压到不再压倒其他词。
452
+ */
453
+ const QW_EXPONENT = 0.25
454
+
455
+ /**
456
+ * 数一个词在文本里出现几次,最多 `TF_CAP` 次。
161
457
  * @param {string} hay - 小写后的可搜索文本
162
458
  * @param {string} needle - 关键词(小写)
163
- * @returns {number} 命中次数,最多 6
459
+ * @returns {number} 出现次数
164
460
  */
165
461
  function countOccurrences(hay, needle) {
166
462
  if (!hay || !needle) return 0
@@ -168,40 +464,116 @@ function countOccurrences(hay, needle) {
168
464
  let from = 0
169
465
  for (;;) {
170
466
  const at = hay.indexOf(needle, from)
171
- if (at === -1 || hits >= 6) break
467
+ if (at === -1 || hits >= TF_CAP) break
172
468
  hits += 1
173
469
  from = at + needle.length
174
470
  }
175
471
  return hits
176
472
  }
177
473
 
178
- /** 新鲜度奖励的时间常数(7 天)。 */
179
- const FRESHNESS_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
180
-
181
474
  /**
182
- * 给一批文档算相关度并按相关度重排。
475
+ * 给一批文档算相关度并按相关度重排(BM25 + 字段加权)。
183
476
  *
184
477
  * 每个文档需要 `haystack: { title, summary, body }`(都已小写)。
478
+ * 文档侧不做分词 —— tf 用子串扫描数,长度用字符数,见文件头。
185
479
  *
186
480
  * @param {Array<object>} docs - 文档记录(含 haystack 与 mtimeMs)
187
- * @param {readonly {term: string, weight: number}[]} keywords - 关键词表
481
+ * @param {readonly {term: string, weight: number, spans?: Array<object>}[]} keywords - 关键词表
188
482
  * @param {number} now - 当前时间(epoch ms)
189
- * @returns {{docs: Array<object>, maxRaw: number}} 带 `score` 的文档(相关度降序)
483
+ * @returns {{docs: Array<object>, maxRaw: number, matched: string[], label: string[]}}
484
+ * 带 `score` 的文档(相关度降序);
485
+ * `matched` 是**语料里真实存在**的词,`label` 是给用户看的**可读**话题词
486
+ * (把命中词的原文区间合并后的结果,见 `readableTopics`)。
487
+ * 调用方应该用 `label` 渲染「按「xxx」排序」。
190
488
  */
191
489
  export function rankByRelevance(docs, keywords, now) {
192
490
  if (keywords.length === 0) {
193
- return { docs: docs.map((doc) => ({ ...doc, score: 0 })), maxRaw: 0 }
491
+ return { docs: docs.map((doc) => ({ ...doc, score: 0 })), maxRaw: 0, matched: [], label: [] }
194
492
  }
195
493
 
196
- const raws = docs.map((doc) => {
494
+ const maxWeight = keywords.reduce((max, k) => Math.max(max, k.weight), 0)
495
+
496
+ // 查询侧相对权重:保留「越新 / 越长的词越重要」这个既有语义,
497
+ // 但压缩幅度并去掉绝对尺度 —— 否则 raw 的量级会随对话长度漂移,
498
+ // 而且最强的那个词会压过其余所有词(见 QW_EXPONENT 的说明)。
499
+ const qw = new Map(keywords.map((k) => {
500
+ const ratio = maxWeight > 0 ? k.weight / maxWeight : 0
501
+ return [k.term, Math.pow(ratio, QW_EXPONENT)]
502
+ }))
503
+
504
+ /* ── 第 1 趟:tf、字段长度、文档频率 ───────────────── */
505
+
506
+ const total = docs.length
507
+ const df = new Map()
508
+ const lens = { title: 0, summary: 0, body: 0 }
509
+ const tfList = []
510
+
511
+ for (const doc of docs) {
197
512
  const hay = doc.haystack || { title: '', summary: '', body: '' }
513
+ const tf = { title: new Map(), summary: new Map(), body: new Map() }
514
+ const len = { title: 0, summary: 0, body: 0 }
515
+ const seen = new Set()
516
+
517
+ for (const field of FIELDS) {
518
+ const text = hay[field] || ''
519
+ // 长度代理:字段字符数。只要求与文档长度单调相关,不要求是「词数」。
520
+ len[field] = text.length
521
+ lens[field] += text.length
522
+ for (const { term } of keywords) {
523
+ const hits = countOccurrences(text, term)
524
+ if (hits === 0) continue
525
+ tf[field].set(term, hits)
526
+ seen.add(term)
527
+ }
528
+ }
529
+
530
+ // df 是**文档级**的:一个词在这篇的任一字段出现过就算一次,
531
+ // 同一篇里两个字段都命中不能算两次。
532
+ for (const term of seen) df.set(term, (df.get(term) || 0) + 1)
533
+ tfList.push({ tf, len })
534
+ }
535
+
536
+ const avgdl = {}
537
+ for (const field of FIELDS) {
538
+ avgdl[field] = total > 0 ? lens[field] / total : 0
539
+ }
540
+
541
+ // 概率式 BM25 的 IDF:恒为正,不会出现负值把分数往下拉。
542
+ // 注意语料越小,df 的取值范围越窄 → IDF 的动态范围越窄 → 收益越小(但不会变坏)。
543
+ // 三五篇文档时它几乎不起作用,这是合理预期,不要宣传成「小项目也明显变准」。
544
+ const idf = new Map()
545
+ for (const { term } of keywords) {
546
+ const d = df.get(term) || 0
547
+ idf.set(term, d > 0 ? Math.log(1 + (total - d + 0.5) / (d + 0.5)) : 0)
548
+ }
549
+
550
+ /* ── 第 2 趟:BM25 打分 ────────────────────────────── */
551
+
552
+ const raws = docs.map((doc, index) => {
553
+ const { tf, len } = tfList[index]
198
554
  let raw = 0
199
- for (const { term, weight } of keywords) {
200
- const hits = countOccurrences(hay.title, term) * 4
201
- + countOccurrences(hay.summary, term) * 2
202
- + countOccurrences(hay.body, term)
203
- if (hits > 0) raw += weight * hits
555
+
556
+ for (const { term } of keywords) {
557
+ const weight = qw.get(term) || 0
558
+ if (weight === 0) continue
559
+ const termIdf = idf.get(term) || 0
560
+ if (termIdf === 0) continue // df = 0:语料里没有这个词,直接跳过
561
+
562
+ let fieldSum = 0
563
+ for (const field of FIELDS) {
564
+ const freq = tf[field].get(term) || 0
565
+ if (freq === 0) continue
566
+ // avgdl 为 0 说明这个字段在整个语料里都是空的(例如 kind=media 时
567
+ // 每篇的 summary/body 都为空)—— 此时不做长度归一化。
568
+ // 不短路的话这里会除零,NaN 会顺着 maxRaw 污染全部文档的分数。
569
+ const norm = avgdl[field] > 0 ? len[field] / avgdl[field] : 0
570
+ const denom = freq + K1 * (1 - FIELD_B[field] + FIELD_B[field] * norm)
571
+ fieldSum += (FIELD_WEIGHTS[field] * freq * (K1 + 1)) / denom
572
+ }
573
+
574
+ if (fieldSum > 0) raw += weight * termIdf * fieldSum
204
575
  }
576
+
205
577
  // 时间新鲜度只做 10% 的微调,主排序仍然是相关性
206
578
  const age = Math.max(0, now - (doc.mtimeMs || 0))
207
579
  const freshness = 1 - Math.min(1, age / FRESHNESS_WINDOW_MS)
@@ -218,19 +590,43 @@ export function rankByRelevance(docs, keywords, now) {
218
590
 
219
591
  scored.sort((a, b) => b.raw - a.raw || b.mtimeMs - a.mtimeMs)
220
592
 
221
- return { docs: scored, maxRaw }
593
+ // 语料里真实存在的词,按查询权重降序。
594
+ const present = keywords
595
+ .filter((k) => (df.get(k.term) || 0) > 0)
596
+ .sort((a, b) => b.weight - a.weight)
597
+ const matched = present.map((k) => k.term)
598
+
599
+ // 给「当前话题」用的**可读**标签:把命中词的原文区间合并,还原出真词。
600
+ // 合并结果还要**真的在语料里出现过**才认 —— 否则传递性合并会把整句串起来,
601
+ // 见 `readableTopics` 的说明。用不了 spans 时回落成 matched 本身。
602
+ // ⚠️ 语料的 haystack 是**已小写**的,而标签切的是**原文**(保留大小写)——
603
+ // 所以比对前必须把标签也小写,否则 `BM25` 这种永远匹配不上。
604
+ const isPresent = (label) => {
605
+ const needle = label.toLowerCase()
606
+ return docs.some((doc) => {
607
+ const hay = doc.haystack
608
+ if (!hay) return false
609
+ return (hay.title || '').includes(needle)
610
+ || (hay.summary || '').includes(needle)
611
+ || (hay.body || '').includes(needle)
612
+ })
613
+ }
614
+ const merged = readableTopics(present, 3, isPresent)
615
+ const label = merged.length > 0 ? merged : matched.slice(0, 3)
616
+
617
+ return { docs: scored, maxRaw, matched, label }
222
618
  }
223
619
 
224
620
  /**
225
621
  * 从关键词表里挑一个给人看的「当前话题」标签。
226
- * @param {readonly {term: string, weight: number}[]} keywords - 关键词表
622
+ * @param {readonly (string|{term: string})[]} terms - 词,或含 `term` 的对象
227
623
  * @param {number} count - 取几个
228
624
  * @returns {string} 用「、」连接的标签,没有则空串
229
625
  */
230
- export function topicLabel(keywords, count = 3) {
231
- const terms = keywords
626
+ export function topicLabel(terms, count = 3) {
627
+ const picked = terms
232
628
  .slice(0, count)
233
- .map((entry) => entry.term)
234
- .filter((term) => term.length >= 2)
235
- return terms.join('、')
629
+ .map((entry) => (typeof entry === 'string' ? entry : entry.term))
630
+ .filter((term) => term && term.length >= 2)
631
+ return picked.join('、')
236
632
  }