dsh-knit 0.19.1 → 0.20.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.
@@ -363,6 +363,10 @@ export function buildContext(input = {}) {
363
363
  terms: terms.map((t) => t.term),
364
364
  // 逐词的字段位图,原样留着给 `explainContext()` 用(合并后的 `fields` 只服务分层判断)
365
365
  termFields: terms.map((t) => ({ term: t.term, fields: t.fields || {} })),
366
+ // v0.20(D5):逐词的「单窗口内最大字频」,由宿主(`passage.js` 的
367
+ // `passageTfOf()`)算好带进来。**只在函数内部用来判 `isDocHit`**,不出现在
368
+ // 任何返回值里;缺失(合成夹具、老的调用方)时 `isDocHit` 退回整篇字频。
369
+ passageTf: doc.passageTf && typeof doc.passageTf === 'object' ? doc.passageTf : null,
366
370
  fields,
367
371
  raw,
368
372
  // 相关度带宽(占本批最高 raw 的比例)。**只在函数内部用来判 Primary 的强度下限**,
@@ -406,19 +410,43 @@ export function buildContext(input = {}) {
406
410
  * 没有它,那篇长文会出现在每一条任务的 Supporting 里。
407
411
  *
408
412
  * 用的是**正文字频**(不是 BM25 分数),不进对外输出,只决定资格。
413
+ *
414
+ * ⚠️ v0.20(D5)改了「字频」的口径:优先用**单窗口内最大字频**
415
+ * (`record.passageTf`,由 `passage.js` 的 `windowTf()` 算),只有在没有这份
416
+ * 数据时才退回整篇字频。原因是整篇字频**不是长度无关的**:v0.19 里正文只取
417
+ * 前 2500 字,这个缺陷被窗口意外掩盖;v0.20 打开窗口后,29000 字的 CHANGELOG
418
+ * 里一个词出现 3 次就会压过真正聚焦的短文,于是它对**每个**任务都满足闸门 ——
419
+ * 正是这段注释开头说的那个要防的场景(需求 §9)。
409
420
  */
421
+ const passageTfIn = (record, term) => {
422
+ const tf = record.passageTf
423
+ if (!tf || typeof tf !== 'object') return null
424
+ const v = tf[term]
425
+ return Number.isFinite(v) ? v : null
426
+ }
427
+
410
428
  const maxBodyTf = new Map()
429
+ const maxPassageTf = new Map()
411
430
  for (const record of records) {
412
431
  for (const entry of record.termFields) {
413
432
  const f = entry.fields || {}
414
433
  if (!f.body) continue
434
+ const tf = f.bodyTf || 0
415
435
  const best = maxBodyTf.get(entry.term) || 0
416
- if ((f.bodyTf || 0) > best) maxBodyTf.set(entry.term, f.bodyTf || 0)
436
+ if (tf > best) maxBodyTf.set(entry.term, tf)
437
+ const pt = passageTfIn(record, entry.term)
438
+ if (pt != null) {
439
+ const bestPt = maxPassageTf.get(entry.term) || 0
440
+ if (pt > bestPt) maxPassageTf.set(entry.term, pt)
441
+ }
417
442
  }
418
443
  }
419
444
  const isDocHit = (record) => record.termFields.some((entry) => {
420
445
  const f = entry.fields || {}
421
446
  if (!f.body) return false
447
+ // v0.20:有片段数据就按「单窗口内最大字频」比,没有就退回整篇字频(v0.19 口径)。
448
+ const pt = passageTfIn(record, entry.term)
449
+ if (pt != null) return pt >= STRONG_BODY_TF && pt >= (maxPassageTf.get(entry.term) || 0)
422
450
  const tf = f.bodyTf || 0
423
451
  return tf >= STRONG_BODY_TF && tf >= (maxBodyTf.get(entry.term) || 0)
424
452
  })
package/src/host/index.js CHANGED
@@ -26,6 +26,9 @@ import { buildLinkGraph, linksOf } from './links.js'
26
26
  // `renderToolText()` 里发生(模型看到的是那段文本,不是结构化 JSON)。曾经多导出一个
27
27
  // `renderContextText` 却没人调用 —— 那是个会与 `tool.js` 漂移的第二渲染器,已删。
28
28
  import { buildContext } from './context.js'
29
+ // v0.20:内容片段层(Deep Context Retrieval)。**纯函数、不读盘**,
30
+ // 目录遍历与缓存全在本文件 —— 它只回答「这篇正文里哪几段相关」。
31
+ import { passageMatchesFor, passageTfOf, PASSAGE_WINDOW } from './passage.js'
29
32
  // v0.19:文件分类层。**所有「这个文件是什么、能不能预览/检索/进上下文」的判断都在这里**,
30
33
  // 本文件(以及 retrieval / preview / UI)不再自己看扩展名 —— 见 `classification.js` 的文件头。
31
34
  import {
@@ -69,17 +72,33 @@ const MAX_CODE = 300
69
72
  const SCAN_BUDGET_MS = 4000
70
73
  const HEAD_BYTES = 16 * 1024
71
74
  /**
72
- * 代码文件参与扫描时读取的头部字节数(v0.19)。
75
+ * 代码文件参与扫描时读取的**头部**字节数(v0.19)。
73
76
  *
74
- * 比 Markdown 的 16KB 更小是**刻意的**:代码的 haystack 只需要前 `HAYSTACK_CHARS`
75
- * 个字符,而真实项目里 `.ts` / `.js` 的数量可能非常高 —— 这是「bounded content read」
77
+ * 比 Markdown 的 16KB 更小是**刻意的**:头部只服务于引用关系与摘要渲染,
78
+ * 而真实项目里 `.ts` / `.js` 的数量可能非常高 —— 这是「bounded content read」
76
79
  * 那条要求(需求 §16)唯一的落地点。
80
+ *
81
+ * ⚠️ v0.20 之后它**不再**限制检索:参与打分的正文是 `MAX_BODY_BYTES` 那份,
82
+ * 与本常量彻底解耦(见 `readCode()`)。
77
83
  */
78
84
  const CODE_HEAD_BYTES = 8 * 1024
79
85
  /** 单次内联预览返回的正文上限(超出截断,面板只做预览不做全量阅读)。 */
80
86
  const DOC_MAX_BYTES = 512 * 1024
81
- /** 参与相关性打分的正文长度(不需要整篇)。 */
82
- const HAYSTACK_CHARS = 2500
87
+ /**
88
+ * 参与相关性打分的正文字节上限(v0.20)。
89
+ *
90
+ * v0.19 之前这里是「正文前 2500 个字符」,于是正文命中只可能发生在前 2500 字里 ——
91
+ * 而真实案例里目标词出现在第 29 033 字(`CHANGELOG.md` 那条「不改窗口」的记录)。
92
+ * v0.20 取消这个窗口:**整篇正文都参与打分**,剩下的只是内存兜底。
93
+ *
94
+ * 单位是**字节**而不是字符:它是一道内存闸门,按字节量才是诚实的
95
+ * (中文文件因此拿到更少的字符数 —— 偏差方向是安全的那一侧)。
96
+ */
97
+ const MAX_BODY_BYTES = 256 * 1024
98
+ /** 解析结果缓存的条目上限(v0.20:缓存里现在留着整篇正文,必须封顶)。 */
99
+ const MAX_CACHE_ENTRIES = 1200
100
+ /** 解析结果缓存里正文的总字节上限 —— 比条目数更硬的那道闸门。 */
101
+ const MAX_CACHE_BYTES = 24 * 1024 * 1024
83
102
 
84
103
  /** 相关性输入:最多回看几条消息、总字符上限。 */
85
104
  const CONV_MAX_MESSAGES = 6
@@ -175,6 +194,36 @@ const SKIP_DIRS = new Set([
175
194
  /** @type {Map<string, object>} */
176
195
  const cache = new Map()
177
196
 
197
+ /** 缓存里正文的总字节数(配合 `MAX_CACHE_BYTES` 淘汰)。 */
198
+ let cacheBodyBytes = 0
199
+
200
+ /**
201
+ * 写缓存并做容量淘汰(v0.20)。
202
+ *
203
+ * 淘汰顺序是**插入序**(`Map` 的迭代序),命中时不重排 —— 也就是 FIFO,不是严格的 LRU。
204
+ * 对本插件的访问模式这是合适的:每次轮询扫的是同一批文件,FIFO 足够;
205
+ * 更重要的是它**完全确定**,不会引入「同一输入两次跑出不同结果」的风险(§20)。
206
+ *
207
+ * @param {string} key - 绝对路径
208
+ * @param {object} entry - 解析结果(`bodyBytes` 为正文占用)
209
+ */
210
+ function cacheSet(key, entry) {
211
+ const prev = cache.get(key)
212
+ if (prev) {
213
+ cacheBodyBytes -= prev.bodyBytes || 0
214
+ cache.delete(key)
215
+ }
216
+ cache.set(key, entry)
217
+ cacheBodyBytes += entry.bodyBytes || 0
218
+ while (cache.size > MAX_CACHE_ENTRIES || (cacheBodyBytes > MAX_CACHE_BYTES && cache.size > 1)) {
219
+ const oldest = cache.keys().next()
220
+ if (oldest.done) break
221
+ const dropped = cache.get(oldest.value)
222
+ cacheBodyBytes -= (dropped && dropped.bodyBytes) || 0
223
+ cache.delete(oldest.value)
224
+ }
225
+ }
226
+
178
227
  /* ── 对话关键词缓存:key = sessionId,seq 未变则直接复用 ─────── */
179
228
  /** @type {Map<string, {seq:number, keywords:Array<{term:string,weight:number}>}>} */
180
229
  const convCache = new Map()
@@ -271,9 +320,18 @@ async function readDoc(absPath) {
271
320
  if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit
272
321
 
273
322
  let head = ''
323
+ let body = ''
324
+ let bodyBytes = 0
325
+ let bodyTruncated = false
274
326
  try {
275
327
  const buf = await readFile(absPath)
276
328
  head = buf.subarray(0, HEAD_BYTES).toString('utf8')
329
+ // v0.20:**整篇正文**参与打分。只解码前 `MAX_BODY_BYTES` 个字节 ——
330
+ // `toString(enc, start, end)` 在字节边界解码,超出部分从不变成字符串,
331
+ // 所以「巨文件」这条路径上的内存占用是有界的。
332
+ bodyBytes = Math.min(buf.length, MAX_BODY_BYTES)
333
+ body = buf.toString('utf8', 0, bodyBytes)
334
+ bodyTruncated = buf.length > MAX_BODY_BYTES
277
335
  } catch {
278
336
  return null
279
337
  }
@@ -288,11 +346,19 @@ async function readDoc(absPath) {
288
346
  // ⚠️ 原文首部**留在缓存里**(v0.14):上下文装配要用它抽引用关系。
289
347
  // 它已经在内存里了 —— 再读一遍盘才是浪费。`publicDoc()` 不会把它发出去。
290
348
  head,
349
+ // v0.20:正文(截到上限)也留在缓存里 —— 片段切分与全文打分的输入。
350
+ // 语义上 `head` 是「首部」(引用关系用,16KB),`body` 是「全文」,
351
+ // 两者**不许互相挪用**(实现说明 D4)。
352
+ body,
353
+ bodyBytes,
354
+ bodyTruncated,
291
355
  hayTitle: title.toLowerCase(),
292
356
  haySummary: summary.toLowerCase(),
293
- hayBody: head.slice(0, HAYSTACK_CHARS).toLowerCase(),
357
+ // v0.20:**不再截前 2500 字**。文件级 BM25 现在看得到整篇正文,
358
+ // 于是 `avgdl[body]` 是真实长度,长文件被 `b = 0.75` 直接惩罚(D3)。
359
+ hayBody: body.toLowerCase(),
294
360
  }
295
- cache.set(absPath, entry)
361
+ cacheSet(absPath, entry)
296
362
  return entry
297
363
  }
298
364
 
@@ -307,7 +373,7 @@ async function readDoc(absPath) {
307
373
  *
308
374
  * - `title` ← 文件名(权重 4,最高价值字段:`plugin-loader.js` 本身就带任务语义)
309
375
  * - `summary` ← 工作区相对路径的目录部分(权重 2)
310
- * - `body` ← 正文前 `HAYSTACK_CHARS` 个字符(权重 1)
376
+ * - `body` ← **整篇正文**(权重 1;v0.20 起不再截前 2500 字)
311
377
  *
312
378
  * 于是 `FIELD_WEIGHTS` 现成的 4 / 2 / 1 恰好等于
313
379
  * 「filename × 4 / path × 2 / content × 1」,排序器零改动。
@@ -329,9 +395,16 @@ async function readCode(absPath, root) {
329
395
  if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit
330
396
 
331
397
  let head = ''
398
+ let body = ''
399
+ let bodyBytes = 0
400
+ let bodyTruncated = false
332
401
  try {
333
402
  const buf = await readFile(absPath)
334
403
  head = buf.subarray(0, CODE_HEAD_BYTES).toString('utf8')
404
+ // v0.20:与 `readDoc` 同一条口径 —— 头部只服务引用关系,打分看整篇正文。
405
+ bodyBytes = Math.min(buf.length, MAX_BODY_BYTES)
406
+ body = buf.toString('utf8', 0, bodyBytes)
407
+ bodyTruncated = buf.length > MAX_BODY_BYTES
335
408
  } catch {
336
409
  return null
337
410
  }
@@ -347,6 +420,9 @@ async function readCode(absPath, root) {
347
420
  mtimeMs: st.mtimeMs,
348
421
  size: st.size,
349
422
  head,
423
+ body,
424
+ bodyBytes,
425
+ bodyTruncated,
350
426
  // ⚠️ 标题是**带扩展名的文件名**,不是去扩展名的 stem。
351
427
  // 代码的文件名里扩展名是信息的一部分(`plugin-loader.js` vs `plugin.json`),
352
428
  // 去掉它反而丢掉了最能区分两个候选的那个字符。
@@ -355,9 +431,9 @@ async function readCode(absPath, root) {
355
431
  summary: dir,
356
432
  hayTitle: name.toLowerCase(),
357
433
  haySummary: dir.toLowerCase(),
358
- hayBody: head.slice(0, HAYSTACK_CHARS).toLowerCase(),
434
+ hayBody: body.toLowerCase(),
359
435
  }
360
- cache.set(absPath, entry)
436
+ cacheSet(absPath, entry)
361
437
  return entry
362
438
  }
363
439
 
@@ -503,10 +579,14 @@ async function readMediaMeta(root, { abs, kind }) {
503
579
  export async function collectDocs(root) {
504
580
  const found = await collectEntries(root)
505
581
  const docs = []
582
+ // v0.20:被 `MAX_BODY_BYTES` 截掉尾巴的文件数。**只是计数**,用来在规模报告里
583
+ // 诚实说出「有多大比例的文件没有全量参与打分」,不参与任何排序。
584
+ let bodyTruncated = 0
506
585
 
507
586
  for (const abs of found.md) {
508
587
  const meta = await readDoc(abs)
509
588
  if (!meta) continue
589
+ if (meta.bodyTruncated) bodyTruncated += 1
510
590
  docs.push({
511
591
  kind: KIND_DOC,
512
592
  path: abs,
@@ -518,6 +598,9 @@ export async function collectDocs(root) {
518
598
  mtimeMs: meta.mtimeMs,
519
599
  // 原文首部:`buildContextFor()` 抽引用关系用(v0.14)。内部字段,不下发。
520
600
  head: meta.head,
601
+ // v0.20:整篇正文随记录走 —— 片段切分与 `matches` 的输入。
602
+ // 它是**内部字段**:`publicDoc()` 不转发正文,只转发派生出的行号与摘要。
603
+ body: meta.body,
521
604
  haystack: { title: meta.hayTitle, summary: meta.haySummary, body: meta.hayBody },
522
605
  })
523
606
  }
@@ -530,6 +613,7 @@ export async function collectDocs(root) {
530
613
  for (const abs of found.code) {
531
614
  const meta = await readCode(abs, root)
532
615
  if (!meta) continue
616
+ if (meta.bodyTruncated) bodyTruncated += 1
533
617
  code.push({
534
618
  kind: KIND_CODE,
535
619
  path: abs,
@@ -540,6 +624,7 @@ export async function collectDocs(root) {
540
624
  size: meta.size,
541
625
  mtimeMs: meta.mtimeMs,
542
626
  head: meta.head,
627
+ body: meta.body,
543
628
  haystack: { title: meta.hayTitle, summary: meta.haySummary, body: meta.hayBody },
544
629
  })
545
630
  }
@@ -559,7 +644,7 @@ export async function collectDocs(root) {
559
644
  truncated: found.mdTruncated,
560
645
  codeTruncated: found.codeTruncated,
561
646
  mediaTruncated: found.mediaTruncated,
562
- stats: found.stats,
647
+ stats: { ...found.stats, bodyTruncated },
563
648
  scanMs: found.scanMs,
564
649
  }
565
650
  }
@@ -718,7 +803,7 @@ function conversationFor(session, sessionId) {
718
803
  * @returns {object} 公开记录
719
804
  */
720
805
  function publicDoc(doc) {
721
- return {
806
+ const out = {
722
807
  kind: doc.kind || KIND_DOC,
723
808
  path: doc.path,
724
809
  rel: doc.rel,
@@ -729,6 +814,11 @@ function publicDoc(doc) {
729
814
  mtimeMs: doc.mtimeMs,
730
815
  score: typeof doc.score === 'number' ? doc.score : null,
731
816
  }
817
+ // v0.20:命中片段(§11)。只下发**派生结果** —— 行号区间、命中词、片段摘要;
818
+ // `body` 与 `passage.text` 一律不出宿主(§16:不准把大文件正文塞进载荷)。
819
+ // 没有片段的记录**不带这个键**(v0.19 的响应形状因此逐字不变)。
820
+ if (Array.isArray(doc.matches) && doc.matches.length > 0) out.matches = doc.matches
821
+ return out
732
822
  }
733
823
 
734
824
  /**
@@ -817,8 +907,29 @@ export async function scan(root, limit, options = {}) {
817
907
  let ordered
818
908
  let topic = ''
819
909
  if (mode === 'relevance') {
820
- const ranked = rankByRelevance(pool, keywords, Date.now())
910
+ // 一个 `now` 贯到底(打分与片段用同一个时间基准)—— 同一批输入两次跑出的
911
+ // 结果因此逐字相同(§20 的确定性要求)。
912
+ const now = Date.now()
913
+ const ranked = rankByRelevance(pool, keywords, now)
821
914
  ordered = ranked.docs
915
+ // v0.20(D5):给每条命中记录附上逐词的「单窗口内最大字频」。
916
+ // 分层闸门 `isDocHit` 原来用**整篇**字频,而整篇字频会随文件变长而虚高 ——
917
+ // 窗口一开,29000 字的 CHANGELOG 就能对**每个**任务满足闸门(需求 §9 明令禁止)。
918
+ // 这一步只算「正文真的命中」的词,成本是几次 `indexOf`,不改名次、也不进 payload。
919
+ for (const doc of ordered) {
920
+ const tf = passageTfOf(doc)
921
+ if (tf) doc.passageTf = tf
922
+ }
923
+ // v0.20:给排名最前的 `PASSAGE_WINDOW` 条挂上命中片段(§11)。
924
+ // ⚠️ 这一步**不改名次**:片段是文件名的投影(实现说明 D3)。
925
+ // 窗口之外的记录只是「没有片段」,不是「不相关」—— `limit` 才管分页,
926
+ // 这里是宿主侧的成本上限(切段是 O(全文),不该为 400 篇文件各做一遍)。
927
+ // `rankByRelevance` 返回的是浅拷贝,所以挂 `matches` 不会污染 `pool`。
928
+ const stop = Math.min(ordered.length, PASSAGE_WINDOW)
929
+ for (let i = 0; i < stop; i++) {
930
+ const matches = passageMatchesFor(ordered[i], keywords, now)
931
+ if (matches.length > 0) ordered[i].matches = matches
932
+ }
822
933
  // 话题标签用 `label`(把命中词的**原文区间合并**后的可读结果),不是 `matched`。
823
934
  // 后者是「语料里真实存在的词」,但仍可能是一堆碎片:
824
935
  // 「项目文档」的候选是 `项目文` / `目文档`,直接显示就成了「按「目文档、项目文」排序」。