dsh-memu-memory 1.2.6 → 1.2.8
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/AGENTS.md +1 -1
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/contributing.md +1 -1
- package/docs/host-adaptation.md +1 -1
- package/docs/memory-semantics.md +26 -4
- package/docs/troubleshooting.md +3 -1
- package/lib/backup.js +1 -1
- package/lib/binding-diagnostics.js +2 -2
- package/lib/budget.js +31 -0
- package/lib/client.js +276 -28
- package/lib/commitment.js +138 -0
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +98 -0
- package/lib/fork-model.js +312 -0
- package/lib/freshness.js +24 -0
- package/lib/inject.js +117 -10
- package/lib/lexicon.js +1 -1
- package/lib/local-vector-service.js +4 -1
- package/lib/memory.js +600 -43
- package/lib/memu.js +4 -0
- package/lib/private.js +49 -8
- package/lib/prompts/private-consolidation.mixed.md +3 -2
- package/lib/prompts/private-consolidation.rp.md +7 -1
- package/lib/prompts/private-policy.mixed.md +1 -0
- package/lib/prompts/private-policy.rp.md +5 -1
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/recall-cache.js +212 -0
- package/lib/rpc.js +44 -6
- package/lib/snippet.js +25 -0
- package/lib/state.js +43 -1
- package/lib/temporal.js +329 -0
- package/lib/text-retrieval.js +292 -28
- package/lib/tokenizer-v2.js +295 -0
- package/lib/tools.js +81 -4
- package/lib/webui/standalone.css +17 -1
- package/package.json +1 -1
- package/scripts/bench-recall.mjs +142 -0
- package/scripts/check-seed-compat.mjs +118 -0
- package/tests/backup.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +122 -5
- package/tests/curator-clusters.test.mjs +7 -1
- package/tests/curator-pairing.test.mjs +52 -8
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +179 -0
- package/tests/fact-version.test.mjs +128 -0
- package/tests/fork-model.test.mjs +345 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +94 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexicon-frequency.test.mjs +1 -1
- package/tests/loader.mjs +3 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/negation-polarity.test.mjs +135 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +292 -0
- package/tests/recall-intent.test.mjs +100 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/stubs/dsh-llm-pi-ai.js +13 -0
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +142 -0
package/lib/text-retrieval.js
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
// duplicate/conflict gate — one ruler from blocking to commit.
|
|
9
9
|
//
|
|
10
10
|
// Dependency discipline: this module imports only lib/text-similarity.js (the
|
|
11
|
-
// shared similarity ruler)
|
|
12
|
-
//
|
|
11
|
+
// shared similarity ruler), lib/curator-policy.js (the single constant table)
|
|
12
|
+
// and lib/tokenizer-v2.js (the V2 tokenizer delegated to by the TOKENIZER_V2
|
|
13
|
+
// switch). No state, no IO, no clock — same input, same output, always.
|
|
13
14
|
|
|
14
15
|
import {
|
|
15
16
|
bigrams,
|
|
@@ -38,21 +39,33 @@ import {
|
|
|
38
39
|
PAIR_W_LEXICAL,
|
|
39
40
|
PAIR_W_TITLE,
|
|
40
41
|
PAIR_W_TOKEN,
|
|
42
|
+
RRF_DYNAMIC,
|
|
41
43
|
RRF_K,
|
|
44
|
+
RRF_SLICE_BAND,
|
|
45
|
+
RRF_SLICE_BAND_CAP,
|
|
42
46
|
RRF_W_BM25,
|
|
43
47
|
RRF_W_DICE,
|
|
44
48
|
RRF_W_ENTITY,
|
|
49
|
+
TOKENIZER_V2,
|
|
50
|
+
computeRRFWeights,
|
|
45
51
|
} from './curator-policy.js'
|
|
52
|
+
import {
|
|
53
|
+
tokenStreamV2,
|
|
54
|
+
tokenize as tokenizeV2,
|
|
55
|
+
} from './tokenizer-v2.js'
|
|
56
|
+
import { hasTemporalHint, resolveQueryDates, DEFAULT_TIME_ZONE } from './temporal.js'
|
|
46
57
|
|
|
47
58
|
// —— §4.1 分词 ——
|
|
48
59
|
|
|
49
60
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
61
|
+
* V1 分词原实现(双角色):TOKENIZER_V2 关时的回退路径;开时是本模块内
|
|
62
|
+
* **idf 盲集合运算**(blocking 共享计数、tokenJaccard)的固定口径。
|
|
63
|
+
* NFKC + lowercase; latin runs of ≥2 chars keep `._-` joins as one token; CJK
|
|
64
|
+
* runs become single chars when isolated, otherwise overlapping bigrams; the
|
|
65
|
+
* result is deduplicated (a set — Jaccard/blocking only care about presence).
|
|
66
|
+
* Build tf from tokenStream below, never from this.
|
|
54
67
|
*/
|
|
55
|
-
|
|
68
|
+
function tokenizeV1(text) {
|
|
56
69
|
const s = String(text || '').normalize('NFKC').toLowerCase()
|
|
57
70
|
const out = []
|
|
58
71
|
for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
|
|
@@ -66,8 +79,8 @@ export function tokenize(text) {
|
|
|
66
79
|
return [...new Set(out)]
|
|
67
80
|
}
|
|
68
81
|
|
|
69
|
-
/**
|
|
70
|
-
function
|
|
82
|
+
/** V1 token stream 原实现(无去重)——BM25 tf 的频率来源(回退路径)。 */
|
|
83
|
+
function tokenStreamV1(text) {
|
|
71
84
|
const s = String(text || '').normalize('NFKC').toLowerCase()
|
|
72
85
|
const out = []
|
|
73
86
|
for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
|
|
@@ -81,6 +94,33 @@ function tokenStream(text) {
|
|
|
81
94
|
return out
|
|
82
95
|
}
|
|
83
96
|
|
|
97
|
+
/**
|
|
98
|
+
* 对外分词入口(双轨制,P0-1):TOKENIZER_V2 开 → 委托 lib/tokenizer-v2.js
|
|
99
|
+
* (CJK unigram+bigram+trigram 三层 + 实体保护,Set 插入序数组);关 → V1
|
|
100
|
+
* 原路径。签名与语义兼容,返回去重 token 数组(插入序)。
|
|
101
|
+
*
|
|
102
|
+
* 消费口径分层(P0 基准回归修复):V2 的增量 token **只进 BM25 流**(idf
|
|
103
|
+
* 加权通道,unigram 的低 idf 由权重自然压掉,子词命中是纯收益);idf 盲的
|
|
104
|
+
* 集合运算——blocking 共享计数、tokenJaccard——固定 tokenizeV1(bigram+latin)。
|
|
105
|
+
* unigram 同时喂给集合运算会把高频单字灌进倒排/共享计数(候选池被灌爆、
|
|
106
|
+
* 集合重叠被拉平,Recall@10 0.7675→0.6375 的定量根因)。开关关时本入口
|
|
107
|
+
* 本来就是 V1,关闭路径字节级不变。
|
|
108
|
+
*/
|
|
109
|
+
export function tokenize(text) {
|
|
110
|
+
if (TOKENIZER_V2) return tokenizeV2(text)
|
|
111
|
+
return tokenizeV1(text)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Raw token stream (no dedupe) — the frequency source for BM25's tf.
|
|
116
|
+
* 与 tokenize 同一开关:V2 → tokenStreamV2(与 tokenizeV2 同一生成器);V1 →
|
|
117
|
+
* tokenStreamV1。
|
|
118
|
+
*/
|
|
119
|
+
function tokenStream(text) {
|
|
120
|
+
if (TOKENIZER_V2) return tokenStreamV2(text)
|
|
121
|
+
return tokenStreamV1(text)
|
|
122
|
+
}
|
|
123
|
+
|
|
84
124
|
// —— §4.1 语料与 BM25 ——
|
|
85
125
|
|
|
86
126
|
/**
|
|
@@ -176,7 +216,8 @@ function normalizedTitle(entry) {
|
|
|
176
216
|
* charDice — similarTexts(title+\n+content):length-prune + containment floor
|
|
177
217
|
* containment — the probe floor when the length prune fired, else 0
|
|
178
218
|
* lexical — max(charDice, containment)
|
|
179
|
-
* tokenJaccard — tokenize
|
|
219
|
+
* tokenJaccard — V1 口径 tokenize set Jaccard over title+content(idf 盲集合
|
|
220
|
+
* 运算固定 V1;V2 三层只服务 BM25,见 tokenize 的 JSDoc)
|
|
180
221
|
* titleDice — bigram Dice over the raw titles
|
|
181
222
|
* titleExact — trimmed/lowercase title equality (non-empty)
|
|
182
223
|
* entityJaccard — appliesTo set Jaccard; both empty → 0.5 neutral
|
|
@@ -189,7 +230,9 @@ export function pairFeatures(a, b) {
|
|
|
189
230
|
charDice: detail.dice,
|
|
190
231
|
containment: detail.containment,
|
|
191
232
|
lexical: Math.max(detail.dice, detail.containment),
|
|
192
|
-
|
|
233
|
+
// idf 盲集合运算固定 V1 口径:unigram 会把跨主题的高频单字重叠拉平
|
|
234
|
+
// tokenJaccard 的区分度。开关关时 tokenize 本就返回 V1,两种写法等价。
|
|
235
|
+
tokenJaccard: jaccard(new Set(tokenizeV1(aText)), new Set(tokenizeV1(bText))),
|
|
193
236
|
titleDice: dice(bigrams(a?.title || ''), bigrams(b?.title || '')),
|
|
194
237
|
titleExact: normalizedTitle(a) !== '' && normalizedTitle(a) === normalizedTitle(b),
|
|
195
238
|
entityJaccard: entityScore(a?.appliesTo, b?.appliesTo),
|
|
@@ -250,7 +293,8 @@ export function pairDecision(a, b, features = pairFeatures(a, b)) {
|
|
|
250
293
|
// —— §4.8 全局冲突预筛 ——
|
|
251
294
|
|
|
252
295
|
// Same pattern as memory.js's NEGATION_RE (not exported there; lib/memory.js is
|
|
253
|
-
// outside this package's edit scope). One ruler for "opposite claim".
|
|
296
|
+
// outside this package's edit scope). One ruler for "opposite claim". 整文本
|
|
297
|
+
// 口径保持原样(P0 前的既有行为,也是无锚点时的回退路径),词典不在此扩。
|
|
254
298
|
const NEGATION_RE = /不|没|别|无|never|not|no longer|doesn't|don't/i
|
|
255
299
|
|
|
256
300
|
/** True when the text carries a negation marker (memory.js findConflict 口径). */
|
|
@@ -258,6 +302,68 @@ export function negationPolarity(text) {
|
|
|
258
302
|
return NEGATION_RE.test(String(text || ''))
|
|
259
303
|
}
|
|
260
304
|
|
|
305
|
+
// —— 子句级否定作用域(P1-2)——
|
|
306
|
+
//
|
|
307
|
+
// 整文本 negationPolarity 有两类误报:无关子句的否定污染(「截止日期是 5 月
|
|
308
|
+
// 1 日,别忘了」整条算否定侧)和双重否定(「不是不喜欢香菜」仍算否定侧)。
|
|
309
|
+
// polarityAt 把判定范围缩到锚点所在的子句,用标记计数 mod 2 近似否定作用域,
|
|
310
|
+
// 不做句法分析——同输入同输出,无 clock。
|
|
311
|
+
|
|
312
|
+
// 子句切分:中西标点一视同仁(连续标点算一次切分)。
|
|
313
|
+
const CLAUSE_SPLIT_RE = /[。!?;,、,.!?;:]+/
|
|
314
|
+
|
|
315
|
+
// 对比结构:「不是 A 而是 B」的 B、「不用 A 改成/换成 B」的 B 都是肯定侧,
|
|
316
|
+
// 前文标记的否定作用到对比词为止。
|
|
317
|
+
const CONTRAST_RE = /而不是|而是|改成|换成/g
|
|
318
|
+
|
|
319
|
+
// 否定标记词典。CJK 没有词边界(\b 对中文无效),靠最长优先的 alternation
|
|
320
|
+
// 保证「不再」「没有」只数一次而不是拆成「不」+「再」;「非常/未来/别的」
|
|
321
|
+
// 与否定标记同形但不是否定(高频词),用 lookahead 排除。英文统一用 \b 包住
|
|
322
|
+
// (缩写以 't 结尾,\b 仍成立;不 \b 的话 'not' 会命中 another/desktop)。
|
|
323
|
+
const NEG_MARKER_RE = /禁止|不得|无法|不能|不再|从不|从未|并不|并非|没有|拒绝|反对|不|没|别(?!的)|无|未(?!来)|勿|莫|非(?!常)|\b(?:not|never|no longer|cannot|without|avoid|refuse|stop|doesn't|don't|won't|can't)\b/gi
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* 一个子句内、锚点所在片段是否为否定侧。对比词把子句切成片段,逐片段判定:
|
|
327
|
+
* 片段自带标记计数(奇数 → 否定);「而不是」引出的片段额外继承 1 个否定
|
|
328
|
+
* (「而不是队列」的队列仍是否定侧,等价于标记紧邻锚点前不被对比词隔断的
|
|
329
|
+
* 场景),「而是/改成/换成」引出的片段从 0 起算。锚点在同片段多次出现只按
|
|
330
|
+
* 片段判定一次,锚点落在多个片段时任一片段否定即为否定(保守)。
|
|
331
|
+
*/
|
|
332
|
+
function segmentNegated(clause, needle) {
|
|
333
|
+
const segments = []
|
|
334
|
+
let last = 0
|
|
335
|
+
let inherit = false
|
|
336
|
+
for (const m of clause.matchAll(CONTRAST_RE)) {
|
|
337
|
+
segments.push({ text: clause.slice(last, m.index), inherit })
|
|
338
|
+
inherit = m[0] === '而不是'
|
|
339
|
+
last = m.index + m[0].length
|
|
340
|
+
}
|
|
341
|
+
segments.push({ text: clause.slice(last), inherit })
|
|
342
|
+
for (const segment of segments) {
|
|
343
|
+
if (!segment.text.includes(needle)) continue
|
|
344
|
+
let markers = 0
|
|
345
|
+
for (const _ of segment.text.matchAll(NEG_MARKER_RE)) markers += 1
|
|
346
|
+
if ((markers + (segment.inherit ? 1 : 0)) % 2 === 1) return true
|
|
347
|
+
}
|
|
348
|
+
return false
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* 子句级否定极性(P1-2):text 里 anchor 所在的每个子句,任一为否定即算否定
|
|
353
|
+
* 侧(锚点多次出现取保守口径)。子句切分与标记匹配都在 NFKC + lowercase 之后
|
|
354
|
+
* 进行——锚点来自 tokenize(同一规范化),latin 大小写/全角差异不会漏匹配。
|
|
355
|
+
* 锚点为空或不在 text 中出现 → false(没有可判定的作用域就不是否定侧)。
|
|
356
|
+
*/
|
|
357
|
+
export function polarityAt(text, anchor) {
|
|
358
|
+
const needle = String(anchor || '').normalize('NFKC').toLowerCase()
|
|
359
|
+
if (!needle) return false
|
|
360
|
+
const s = String(text || '').normalize('NFKC').toLowerCase()
|
|
361
|
+
for (const clause of s.split(CLAUSE_SPLIT_RE)) {
|
|
362
|
+
if (clause.includes(needle) && segmentNegated(clause, needle)) return true
|
|
363
|
+
}
|
|
364
|
+
return false
|
|
365
|
+
}
|
|
366
|
+
|
|
261
367
|
/** 数字、周X/星期X、YYYY-MM-DD、M月D日 —— 抽出来比集合(§4.8 numericSetsDiffer)。 */
|
|
262
368
|
export function numericSet(text) {
|
|
263
369
|
const s = String(text || '')
|
|
@@ -278,17 +384,43 @@ export function numericSetsDiffer(a, b) {
|
|
|
278
384
|
return false
|
|
279
385
|
}
|
|
280
386
|
|
|
387
|
+
/**
|
|
388
|
+
* 冲突锚点:双方 body 的共享 token 里最长者(长度相同取字典序最小,完全确定,
|
|
389
|
+
* 与遍历序无关)。token 来自当前生效的 tokenize(双轨开关自动生效),只要求
|
|
390
|
+
* 子串包含关系(clause.includes(anchor))——锚点本身就是文本的子串,CJK
|
|
391
|
+
* unigram/bigram 与 latin 词都覆盖。无共享词返回 ''(调用方回退整文本口径)。
|
|
392
|
+
*/
|
|
393
|
+
function longestSharedToken(aBody, bBody) {
|
|
394
|
+
const bTokens = new Set(tokenize(bBody))
|
|
395
|
+
let anchor = ''
|
|
396
|
+
for (const token of new Set(tokenize(aBody))) {
|
|
397
|
+
if (!bTokens.has(token)) continue
|
|
398
|
+
if (token.length > anchor.length || (token.length === anchor.length && token < anchor)) anchor = token
|
|
399
|
+
}
|
|
400
|
+
return anchor
|
|
401
|
+
}
|
|
402
|
+
|
|
281
403
|
/**
|
|
282
404
|
* §4.8 全局冲突预筛(同 domain/track 前提由调用方保证)。返回 'same_title' |
|
|
283
405
|
* 'negation' | 'value' 或 null。containment ≥0.92 或 charDice ≥0.95 一票豁免
|
|
284
406
|
* (重复/细化,不是冲突)。预筛只决定“送不送人审”,最终由 LLM + 人审裁决。
|
|
407
|
+
*
|
|
408
|
+
* negation 分支(P1-2):有共享锚点 → 双方 polarityAt(body, anchor) 不同才算
|
|
409
|
+
* 否定冲突(子句级作用域,修掉「无关子句否定污染」与「双重否定」两类误报);
|
|
410
|
+
* 无共享锚点 → 回退整文本 negationPolarity 对比(原口径,行为不变)。
|
|
285
411
|
*/
|
|
286
412
|
export function globalConflictCheck(a, b, features = pairFeatures(a, b)) {
|
|
287
413
|
if (features.containment >= 0.92 || features.charDice >= 0.95) return null
|
|
288
414
|
if (features.titleExact && features.charDice < 0.95) return 'same_title'
|
|
289
415
|
const aBody = String(a?.content || '')
|
|
290
416
|
const bBody = String(b?.content || '')
|
|
291
|
-
if (features.charDice >= 0.55
|
|
417
|
+
if (features.charDice >= 0.55) {
|
|
418
|
+
const anchor = longestSharedToken(aBody, bBody)
|
|
419
|
+
const differs = anchor
|
|
420
|
+
? polarityAt(aBody, anchor) !== polarityAt(bBody, anchor)
|
|
421
|
+
: negationPolarity(aBody) !== negationPolarity(bBody)
|
|
422
|
+
if (differs) return 'negation'
|
|
423
|
+
}
|
|
292
424
|
if (features.titleDice >= 0.8 && features.charDice >= 0.55
|
|
293
425
|
&& numericSetsDiffer(`${a?.title || ''} ${aBody}`, `${b?.title || ''} ${bBody}`)) return 'value'
|
|
294
426
|
return null
|
|
@@ -314,12 +446,19 @@ function idAsc(a, b) {
|
|
|
314
446
|
* 1) blocking:同 track;N ≤ exactPairLimit 时精确两两,否则查询 token 中
|
|
315
447
|
* df ≤ 30%N 的稀有词、共享 ≥2 token,或 exact title。
|
|
316
448
|
* 2) 三路排名 bm25 / charDice / entityJaccard(tiebreak containment)。
|
|
317
|
-
* 3) 加权 RRF(k=60)
|
|
318
|
-
*
|
|
449
|
+
* 3) 加权 RRF(k=60)。RRF_DYNAMIC 开 → 权重来自 computeRRFWeights(proposal,
|
|
450
|
+
* corpus):普通查询退化为静态 0.5/0.3/0.2,近期查询加第四路 recency
|
|
451
|
+
* (候选按 updatedAt 降序排名),coding 域 entity 提权;关 → 恒用静态
|
|
452
|
+
* 0.5/(60+rankBm25) + 0.3/(60+rankDice) + 0.2/(60+rankEntity)。
|
|
453
|
+
* 4) RRF 代理切分 + 边界带 → pairScore 真尺终选:前 max 名进评分集,与切点
|
|
454
|
+
* rrf 之差 ≤ RRF_SLICE_BAND 的候选并入(总量 ≤ max×RRF_SLICE_BAND_CAP),
|
|
455
|
+
* 全部算 pairFeatures/pairScore,按 pairScore 降序截取前 max——近重复簇里
|
|
456
|
+
* rrf 平刀锋时 len 归一噪声不再决定准入。
|
|
319
457
|
* 5) 不足 limit 用同域最近条目补齐(“多看几眼”,不降低门槛)。
|
|
320
458
|
*
|
|
321
459
|
* 返回 [{ id, entry, score, decision, features, rrf, fallback }],score 降序,
|
|
322
|
-
* 平手 rrf 降序 → id
|
|
460
|
+
* 平手 rrf 降序 → id 升序——完全确定(动态路径的 recency 排名同样带
|
|
461
|
+
* idAsc tiebreak,不引入任何 clock/随机性)。
|
|
323
462
|
*/
|
|
324
463
|
export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }) {
|
|
325
464
|
const max = Number(limit) > 0 ? Math.floor(Number(limit)) : PAIR_SCAN_LIMIT
|
|
@@ -330,7 +469,10 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
|
|
|
330
469
|
const proposalDomain = proposal?.domain || 'unknown'
|
|
331
470
|
const proposalTitle = normalizedTitle(proposal)
|
|
332
471
|
const proposalId = proposal?.id ?? null
|
|
333
|
-
const
|
|
472
|
+
const queryText = `${proposal.title || ''} ${proposal.content || ''}`
|
|
473
|
+
// BM25 查询词用当前生效分词(V2 三层在这里是收益);blocking 是 idf 盲的
|
|
474
|
+
// 共享计数,走下面的 V1 口径。
|
|
475
|
+
const queryTokens = tokenize(queryText)
|
|
334
476
|
|
|
335
477
|
// 1) blocking
|
|
336
478
|
const candidates = new Map()
|
|
@@ -343,7 +485,11 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
|
|
|
343
485
|
} else {
|
|
344
486
|
const dfCap = Math.ceil(BLOCK_DF_RATIO * n)
|
|
345
487
|
const shared = new Map()
|
|
346
|
-
|
|
488
|
+
// blocking 固定 V1 口径(bigram+latin):V1 token ⊆ V2 token,V2 建的
|
|
489
|
+
// corpus.inverted 照样命中,bigram 的 posting/df 也不受 unigram 膨胀影响;
|
|
490
|
+
// 若用 V2 查询,高频单字会让无关条目凑满 ≥2 共享词,候选池被灌爆、
|
|
491
|
+
// target 被挤出 RRF 前 limit 切片(基准 Recall 池命中 0.985→0.8625 的主因)。
|
|
492
|
+
for (const term of tokenizeV1(queryText)) {
|
|
347
493
|
const posting = corpus.inverted.get(term)
|
|
348
494
|
if (!posting || posting.size === 0 || posting.size > dfCap) continue
|
|
349
495
|
for (const id of posting) {
|
|
@@ -391,18 +537,57 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
|
|
|
391
537
|
const rankEntity = new Map()
|
|
392
538
|
entityOrder.forEach((item, index) => rankEntity.set(item.id, index + 1))
|
|
393
539
|
|
|
394
|
-
// 3) weighted RRF
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
540
|
+
// 3) weighted RRF。开关关 → 静态三路原式(字节级回退路径);开 → 权重来自
|
|
541
|
+
// computeRRFWeights,含 recency 键时加第四路 updatedAt 降序排名。
|
|
542
|
+
let rrf
|
|
543
|
+
if (!RRF_DYNAMIC) {
|
|
544
|
+
rrf = new Map()
|
|
545
|
+
for (const id of ids) {
|
|
546
|
+
rrf.set(id, RRF_W_BM25 / (RRF_K + rankBm25.get(id))
|
|
547
|
+
+ RRF_W_DICE / (RRF_K + rankDice.get(id))
|
|
548
|
+
+ RRF_W_ENTITY / (RRF_K + rankEntity.get(id)))
|
|
549
|
+
}
|
|
550
|
+
} else {
|
|
551
|
+
const weights = computeRRFWeights(proposal, corpus)
|
|
552
|
+
const rankRecency = new Map()
|
|
553
|
+
if (weights.recency != null) {
|
|
554
|
+
// 第四路:updatedAt 字符串降序(updatedDesc + idAsc tiebreak,与 backfill
|
|
555
|
+
// 同一确定性口径);rank 为 1 起的稠密序,只覆盖 blocking 后的候选集。
|
|
556
|
+
const recencyOrder = ids
|
|
557
|
+
.map((id) => ({ id, entry: corpus.docs.get(id).entry }))
|
|
558
|
+
.sort((a, b) => updatedDesc(a.entry, b.entry) || idAsc(a, b))
|
|
559
|
+
recencyOrder.forEach((item, index) => rankRecency.set(item.id, index + 1))
|
|
560
|
+
}
|
|
561
|
+
rrf = new Map()
|
|
562
|
+
for (const id of ids) {
|
|
563
|
+
let value = weights.bm25 / (RRF_K + rankBm25.get(id))
|
|
564
|
+
+ weights.dice / (RRF_K + rankDice.get(id))
|
|
565
|
+
+ weights.entity / (RRF_K + rankEntity.get(id))
|
|
566
|
+
if (weights.recency != null) value += weights.recency / (RRF_K + rankRecency.get(id))
|
|
567
|
+
rrf.set(id, value)
|
|
568
|
+
}
|
|
400
569
|
}
|
|
401
570
|
ids.sort((a, b) => rrf.get(b) - rrf.get(a) || idAsc(a, b))
|
|
402
571
|
|
|
403
|
-
// 4) features for the
|
|
572
|
+
// 4) features for the scored slice(P0-1 回归修复:准入从 RRF 代理换成
|
|
573
|
+
// pairScore 真尺)。pre-cut 用 RRF 代理决定谁进入完整 pairFeatures/pairScore
|
|
574
|
+
// 评分;近重复簇里 rrf 平刀锋时(bench 实测缝 3.6e-5),len 归一噪声决定
|
|
575
|
+
// 准入,pairScore 更准的候选反而落榜。修法:与切点 rrf 之差 ≤
|
|
576
|
+
// RRF_SLICE_BAND 的候选并入评分集(总量 ≤ max×RRF_SLICE_BAND_CAP,防病态
|
|
577
|
+
// 全带,超限按 rrf 降序 + idAsc 截断),评分集全部评分后按 pairScore 降序
|
|
578
|
+
// 截取前 max——准入决策从代理换真尺,返回数量语义不变(≤max)。开关关/开
|
|
579
|
+
// 同轨生效(这是准入结构的改进,不分轨)。
|
|
580
|
+
const cutIndex = Math.min(max, ids.length) - 1
|
|
581
|
+
const bandFloor = rrf.get(ids[cutIndex]) - RRF_SLICE_BAND
|
|
582
|
+
let scoredIds = []
|
|
583
|
+
for (const id of ids) {
|
|
584
|
+
if (rrf.get(id) < bandFloor) break // ids 已按 (rrf desc, idAsc) 排序,后面只会更低
|
|
585
|
+
scoredIds.push(id)
|
|
586
|
+
}
|
|
587
|
+
const bandCap = max * RRF_SLICE_BAND_CAP
|
|
588
|
+
if (scoredIds.length > bandCap) scoredIds = scoredIds.slice(0, bandCap)
|
|
404
589
|
const taken = new Set()
|
|
405
|
-
for (const id of
|
|
590
|
+
for (const id of scoredIds) {
|
|
406
591
|
const doc = corpus.docs.get(id)
|
|
407
592
|
const features = pairFeatures(proposal, doc.entry)
|
|
408
593
|
const score = pairScore(features)
|
|
@@ -410,6 +595,8 @@ export function rankPairCandidates({ corpus, proposal, limit = PAIR_SCAN_LIMIT }
|
|
|
410
595
|
out.push({ id, entry: doc.entry, score, decision: pairDecision(proposal, doc.entry, features), features, rrf: rrf.get(id), fallback: false })
|
|
411
596
|
}
|
|
412
597
|
out.sort((a, b) => b.score - a.score || b.rrf - a.rrf || idAsc(a, b))
|
|
598
|
+
// 真尺终选:评分集可能因边界带超过 max,按 pairScore 降序截取前 max
|
|
599
|
+
if (out.length > max) out.length = max
|
|
413
600
|
// 5) same-domain recent backfill — extra eyes, never a lower bar
|
|
414
601
|
return backfill({ corpus, proposal, proposalDomain, proposalId, max, out, taken, queryTokens })
|
|
415
602
|
}
|
|
@@ -494,7 +681,10 @@ export function buildCandidateClusters(index, options = {}) {
|
|
|
494
681
|
const tokenSets = new Map()
|
|
495
682
|
const inverted = new Map()
|
|
496
683
|
for (const item of items) {
|
|
497
|
-
|
|
684
|
+
// blocking 倒排固定 V1 口径(idf 盲集合运算):unigram 会把高频单字灌大
|
|
685
|
+
// 倒排与两两共享计数(N=500 簇延迟 +60% 的根因),对成簇质量无收益。
|
|
686
|
+
// 边打分的 BM25 路由(下方 bm25Route/buildCorpus)仍走 V2 流。
|
|
687
|
+
const tokens = tokenizeV1(`${item.entry?.title || ''} ${item.entry?.content || ''}`)
|
|
498
688
|
tokenSets.set(item.id, new Set(tokens))
|
|
499
689
|
for (const term of tokens) {
|
|
500
690
|
if (!inverted.has(term)) inverted.set(term, [])
|
|
@@ -535,7 +725,11 @@ export function buildCandidateClusters(index, options = {}) {
|
|
|
535
725
|
}).filter((pair) => pair.score >= minPair)
|
|
536
726
|
if (pairList.length === 0) continue
|
|
537
727
|
|
|
538
|
-
// three route rankings for edge order only
|
|
728
|
+
// three route rankings for edge order only。
|
|
729
|
+
// 刻意不做动态权重(P0-2 只落在 rankPairCandidates):buildCandidateClusters
|
|
730
|
+
// 没有 proposal/查询上下文——它是无监督的全库成簇,三路 RRF 只决定贪心
|
|
731
|
+
// 长簇的边访问顺序;引入「查询类型」没有语义落点,静态三路保证簇构建
|
|
732
|
+
// 与查询无关、完全可复现。
|
|
539
733
|
const bm25Route = pairList.map((pair) => ({
|
|
540
734
|
key: pair.key,
|
|
541
735
|
s: bm25(tokenStream(`${pair.aItem.entry?.title || ''} ${pair.aItem.entry?.content || ''}`), corpus.docs.get(pair.bId), corpus)
|
|
@@ -659,3 +853,73 @@ export function buildCandidateClusters(index, options = {}) {
|
|
|
659
853
|
for (let i = 0; i < out.length; i++) out[i].cluster_id = `cl-${i + 1}`
|
|
660
854
|
return { clusters: out.slice(0, maxClusters), truncated, scanned: pool.length }
|
|
661
855
|
}
|
|
856
|
+
|
|
857
|
+
// —— S5 查询意图与分解 ——
|
|
858
|
+
//
|
|
859
|
+
// 召回入口只需要知道“这句话在问哪一类事”,然后决定过滤与取数策略:
|
|
860
|
+
// date 时间题:先解析相对日期,按 absolute_date 过滤/排序
|
|
861
|
+
// entity 实体题:抽出实体名/别名,按实体索引扩展一跳
|
|
862
|
+
// conflict 冲突题:按 fact_key / conflicts_with 成对取
|
|
863
|
+
// commitment 约定题:未完成/到期承诺优先
|
|
864
|
+
// boundary 边界题:只有用户明确问到时才注入 only_if_asked
|
|
865
|
+
// general 普通题
|
|
866
|
+
// 纯规则,无外部模型,无网络;识别不出来就是 general,不猜。
|
|
867
|
+
|
|
868
|
+
const CONFLICT_RE = /矛盾|冲突|到底|哪一版|哪个版本|哪边|前后说法|说法不一|改口|不一致|不是说|谁对|真的吗|相反|contradict|conflict|which version/i
|
|
869
|
+
const COMMITMENT_RE = /答应|承诺|约定|说好|欠|兑现|到期|还没|什么时候还|做到|提醒我|promise|commitment|owe/i
|
|
870
|
+
const BOUNDARY_RE = /秘密|保密|别说|别告诉|不要告诉|不能说|不能提|隐私|瞒着|never[-_ ]?say|only if asked|secret/i
|
|
871
|
+
const DATE_QUERY_RE = /什么时候|哪天|几号|日期|时间|多久|几点|星期几|上次|之前|后来|最近|when|what time|which day/i
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* @returns {'date'|'entity'|'conflict'|'commitment'|'boundary'|'general'}
|
|
875
|
+
*/
|
|
876
|
+
export function detectQueryIntent(query, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
|
|
877
|
+
const text = String(query || '').trim()
|
|
878
|
+
if (!text) return 'general'
|
|
879
|
+
if (CONFLICT_RE.test(text)) return 'conflict'
|
|
880
|
+
if (COMMITMENT_RE.test(text)) return 'commitment'
|
|
881
|
+
if (BOUNDARY_RE.test(text)) return 'boundary'
|
|
882
|
+
if (hasTemporalHint(text) || DATE_QUERY_RE.test(text) || /\d{4}[-/]\d{1,2}[-/]\d{1,2}/.test(text)) return 'date'
|
|
883
|
+
if (extractQueryEntities(text, { knownEntities }).length > 0) return 'entity'
|
|
884
|
+
return 'general'
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
const QUOTED_RE = /["“”「」『』]([^"“”「」『』]{2,30})["“”「」『』]/g
|
|
888
|
+
const AT_RE = /@([\w\u4e00-\u9fff-]{2,30})/g
|
|
889
|
+
|
|
890
|
+
/** 实体抽取只用“明确标注”的名字:引号、@、已知实体表。宁缺毋滥。 */
|
|
891
|
+
export function extractQueryEntities(query, { knownEntities = [] } = {}) {
|
|
892
|
+
const text = String(query || '')
|
|
893
|
+
const found = []
|
|
894
|
+
const add = (value) => {
|
|
895
|
+
const name = String(value || '').trim()
|
|
896
|
+
if (name.length < 2 || name.length > 30) return
|
|
897
|
+
if (!found.includes(name)) found.push(name)
|
|
898
|
+
}
|
|
899
|
+
for (const match of text.matchAll(QUOTED_RE)) add(match[1])
|
|
900
|
+
for (const match of text.matchAll(AT_RE)) add(match[1])
|
|
901
|
+
for (const name of Array.isArray(knownEntities) ? knownEntities : []) {
|
|
902
|
+
if (typeof name === 'string' && name.trim().length >= 2 && text.includes(name)) add(name)
|
|
903
|
+
}
|
|
904
|
+
return found.slice(0, 6)
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* 把查询拆成召回能直接用的零件。`expanded` 是拼给词法/向量检索的查询,
|
|
909
|
+
* `dates`/`entities` 同时供过滤与排序使用。
|
|
910
|
+
*/
|
|
911
|
+
export function decomposeQuery(query, intent = null, { now = new Date(), timeZone = DEFAULT_TIME_ZONE, knownEntities = [] } = {}) {
|
|
912
|
+
const text = String(query || '')
|
|
913
|
+
const resolvedIntent = intent || detectQueryIntent(text, { now, timeZone, knownEntities })
|
|
914
|
+
const dates = resolveQueryDates(text, { now, timeZone })
|
|
915
|
+
const entities = extractQueryEntities(text, { knownEntities })
|
|
916
|
+
const terms = [...new Set([...dates, ...entities])]
|
|
917
|
+
return {
|
|
918
|
+
query: text,
|
|
919
|
+
intent: resolvedIntent,
|
|
920
|
+
dates,
|
|
921
|
+
entities,
|
|
922
|
+
terms,
|
|
923
|
+
expanded: [text, ...terms].filter(Boolean).join(' ').trim(),
|
|
924
|
+
}
|
|
925
|
+
}
|