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.
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import test from 'node:test'
9
9
  import assert from 'node:assert/strict'
10
+ import { readFileSync } from 'node:fs'
10
11
 
11
12
  import { makeWorkspace } from './fixture.mjs'
12
13
  import {
@@ -21,6 +22,7 @@ import {
21
22
  registerKnitDocsTool,
22
23
  } from '../src/host/tool.js'
23
24
  import { scan, apply, readDocument, buildContextFor, publicScanPayload } from '../src/host/index.js'
25
+ import { SNIPPET_CHARS } from '../src/host/passage.js'
24
26
  // 校验器与真机探针**共用同一份** —— 两边各写一份必然漂移,
25
27
  // 而它锁的恰恰是「工具返回值 vs 它自己的 schema」这件最容易腐坏的事。
26
28
  import { validateAgainst } from '../tools/json-schema-subset.mjs'
@@ -72,14 +74,37 @@ function fakeExec(session) {
72
74
  *
73
75
  * @param {object} exec - 执行上下文
74
76
  * @param {object} args - 参数
75
- * @param {{read?: Function, contextFor?: Function, audit?: object}} [deps] - 覆盖注入的依赖
77
+ * @param {{read?: Function, scan?: Function, contextFor?: Function, audit?: object}} [deps] - 覆盖注入的依赖
76
78
  * @returns {Promise<object>} 工具结果
77
79
  */
78
80
  async function runTool(exec, args = {}, deps = {}) {
79
81
  const read = 'read' in deps ? deps.read : undefined
82
+ const scanFn = 'scan' in deps ? deps.scan : scan
80
83
  const contextFor = 'contextFor' in deps ? deps.contextFor : buildContextFor
81
84
  const audit = 'audit' in deps ? deps.audit : undefined
82
- return knitDocsDefinition(scan, read, contextFor, audit).execute(args, exec)
85
+ return knitDocsDefinition(scanFn, read, contextFor, audit).execute(args, exec)
86
+ }
87
+
88
+ /**
89
+ * 包一层 `scan`:把 `ranked` 上的 `matches` 全部剥掉,模拟「没有片段数据」的路径
90
+ * (v0.20 里它意味着老宿主,或者命中名次落在 `PASSAGE_WINDOW` 之外)。
91
+ *
92
+ * 用它来守住那个仍存在的**兜底**分支:`read` + `pickSnippet`。
93
+ *
94
+ * @param {Function} scanImpl - 真的 `scan`
95
+ * @returns {Function} 剥掉 matches 的 `scan`
96
+ */
97
+ function scanWithoutMatches(scanImpl) {
98
+ return async (root, limit, options) => {
99
+ const payload = await scanImpl(root, limit, options)
100
+ return {
101
+ ...payload,
102
+ ranked: (payload.ranked || []).map((doc) => {
103
+ const { matches, ...rest } = doc
104
+ return rest
105
+ }),
106
+ }
107
+ }
83
108
  }
84
109
 
85
110
  /**
@@ -366,6 +391,55 @@ test('limit: 只影响参与分层的候选池,不把 Context Pack 又切一
366
391
  assert.ok(allItems(result).every((item) => typeof item.rel === 'string'))
367
392
  })
368
393
 
394
+ test('集成: 同一条任务下,knit_docs 的命中段与面板载荷逐条一致(v0.20 §15)', async () => {
395
+ // 这条守的是「一个引擎、两个面」这件承诺:面板与工具各有一条补偿路径
396
+ // —— 面板靠客户端按 `rel` 从 `docs[]` 取回 `matches`(三层投影只有 7 个键),
397
+ // 工具靠 `tool.js` 的 `matchesByRel` 从 `payload.ranked` 取回。
398
+ // 两条补偿路径一旦漂移,用户看到的「命中段」和模型读到的行号就会不一样,
399
+ // 而单面的测试**各自都是绿的**。
400
+ const session = fakeSession([userMessage(1, '相关性排序与 BM25 的长度归一化')])
401
+
402
+ // ① 面板路径:客户端真正拿到的那份载荷
403
+ const payload = await scan(PROJECT_ROOT, 40, {
404
+ session, sessionId: 'sess-tool-test', sort: 'relevance', kind: 'doc',
405
+ })
406
+ const panel = publicScanPayload(payload)
407
+ const panelMatches = new Map(
408
+ (panel.docs || []).map((doc) => [doc.rel, Array.isArray(doc.matches) ? doc.matches : []]),
409
+ )
410
+ const panelWithHits = [...panelMatches].filter(([, list]) => list.length > 0)
411
+ assert.ok(panelWithHits.length > 0, '样本里至少该有一篇带命中段,否则这条是空测试')
412
+
413
+ // ② 工具路径:真实的 execute()
414
+ const value = await runTool(fakeExec(session), {}, { read: readDocument })
415
+ const items = allItems(value)
416
+ assert.ok(items.length > 0, '工具应当给出结果')
417
+
418
+ const ranges = (list) => list.map((m) => [m.startLine, m.endLine])
419
+ for (const [rel, list] of panelWithHits) {
420
+ const item = items.find((entry) => entry.rel === rel)
421
+ assert.ok(item, `面板给出了 ${rel} 的命中段,工具也必须给出这一篇`)
422
+ assert.ok(
423
+ Array.isArray(item.matches) && item.matches.length > 0,
424
+ `${rel} 在工具侧也必须有命中段`,
425
+ )
426
+ assert.deepEqual(
427
+ ranges(item.matches),
428
+ ranges(list),
429
+ `${rel} 的命中段行号:工具与面板必须是同一组(同一套判断的两种投影)`,
430
+ )
431
+ }
432
+
433
+ // ③ 反向:工具给了命中段的,面板也不能缺(不许「一边多一边少」)
434
+ for (const item of items) {
435
+ if (!Array.isArray(item.matches) || item.matches.length === 0) continue
436
+ assert.ok(
437
+ (panelMatches.get(item.rel) || []).length > 0,
438
+ `工具给出了 ${item.rel} 的命中段,面板载荷里也必须带`,
439
+ )
440
+ }
441
+ })
442
+
369
443
  test('agentScope: 从 exec 里取出的三个字段都可用', () => {
370
444
  const session = fakeSession([])
371
445
  const scope = agentScope(fakeExec(session))
@@ -519,15 +593,20 @@ test('renderToolText: 三层都空时才说「没找到」', () => {
519
593
  })
520
594
 
521
595
  test('renderToolText: 工作区有文档或代码、但话题一个词都没命中 —— 不许说成「工作区里是空的」', () => {
522
- // 真机实测的场景:问「路径越界怎么防」,49 篇一篇都没命中(文档侧只看每篇前 2500 字,
523
- // 而这个词在 5 篇 .md 里全部出现在 2500 字之后)。原先这里打印的是
524
- // "No Markdown documents found in the workspace." —— 工作区里明明有 49 篇。
596
+ // 真机实测的场景(v0.19 的时代):问「路径越界怎么防」,49 篇一篇都没命中,因为文档侧
597
+ // 只看每篇前 2500 字,而这个词在 5 篇 .md 里全部出现在 2500 字之后。v0.20 取消了这个
598
+ // 窗口,所以「0 命中」现在是句更强的话 —— 但**边界仍要说实话**(单文件大小上限、媒体无正文)。
525
599
  const text = renderToolText(packOf({ total: 49 }))
526
600
  assert.ok(!text.includes('No documents or code files found'), '总数为 49 时不能说「一篇都没有」')
527
601
  assert.match(text, /No document or code file matched the current topic/)
528
602
  assert.match(text, /0 of 49 documents and code files/)
529
- assert.match(text, /2500 characters/) // 窗口限制必须说出来
530
- assert.match(text, /grep/) // 并给下一步
603
+ assert.match(text, /searched in full/) // v0.20:全文都搜过了
604
+ assert.match(text, /256 KB/) // 单文件上限(必须与 index.js 的 MAX_BODY_BYTES 一致)
605
+ assert.match(text, /images and videos have no searchable text/) // 媒体没有正文
606
+ // ⚠️ 这两条是 v0.20 的**反向**守卫:窗口没了,那句「更深的用 grep」就是假话,
607
+ // 留着还会让模型为一件不存在的事去做多余的 grep。
608
+ assert.ok(!/2500/.test(text), '不许再提 2500 字的窗口')
609
+ assert.ok(!/grep/.test(text), '不许再叫模型去 grep「更深的」内容')
531
610
 
532
611
  // 真的空工作区仍然走原来那句
533
612
  assert.match(renderToolText(packOf({ total: 0 })), /No documents or code files found in the workspace\./)
@@ -585,10 +664,11 @@ test('pickSnippet: 超长块**以命中词为中心**截,不是从头截', ()
585
664
  assert.match(snippet, /…$/, '右边被截掉要有省略号')
586
665
  })
587
666
 
588
- test('pickSnippet: 只看评分窗口内的正文(2500 字之后不算)', () => {
589
- // 与 index.js 的 HAYSTACK_CHARS 对齐;否则会出现「排上来但段落里没有命中词」
667
+ test('pickSnippet: 全文分块 —— 2500 字之后的内容同样抽得出来(v0.20 取消了窗口)', () => {
668
+ // v0.19 这条断言的是**空串**(只看每篇前 2500 字,与 HAYSTACK_CHARS 对齐)。
669
+ // 需求 §3 取消窗口后,评分看全文,抽段落也必须看全文 —— 否则「排上来了却没有片段」。
590
670
  const text = `${'甲'.repeat(3000)}\n\nBM25 在很后面。`
591
- assert.equal(pickSnippet(text, ['bm25']), '')
671
+ assert.equal(pickSnippet(text, ['bm25']), 'BM25 在很后面。')
592
672
  })
593
673
 
594
674
  test('execute: 传了 read 时命中的那篇带 snippet;没有命中词的篇**不带这个字段**', async () => {
@@ -606,29 +686,47 @@ test('execute: 传了 read 时命中的那篇带 snippet;没有命中词的篇
606
686
  }
607
687
  })
608
688
 
609
- test('execute: 不传 read → 只是不带段落,分层照常给', async () => {
689
+ test('execute: 不传 read → 命中的那篇照样带 matches(v0.20 起片段来自扫描,不再读盘)', async () => {
610
690
  const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
611
691
  const out = await runTool(exec, { query: 'sidebar', limit: 3 })
612
692
  assert.ok(allItems(out).length > 0, '不给 read 也要照常分层')
613
- for (const doc of allItems(out)) {
614
- assert.equal('snippet' in doc, false, '没给 read 就不该带段落')
693
+ const readme = allItems(out).find((d) => d.rel === 'README.md')
694
+ assert.ok(readme, '样本里应当有 README.md')
695
+ assert.ok(Array.isArray(readme.matches) && readme.matches.length > 0, '片段由 scan() 提供')
696
+ for (const m of readme.matches) {
697
+ assert.ok(Number.isInteger(m.startLine) && Number.isInteger(m.endLine), '片段必须带行号')
698
+ assert.ok(Number.isInteger(m.startOffset) && Number.isInteger(m.endOffset), '片段必须带偏移量')
699
+ assert.ok(Array.isArray(m.terms) && m.terms.length > 0, '片段必须说清命中了哪些词')
700
+ assert.equal(typeof m.snippet, 'string')
615
701
  }
702
+ // 没有命中词的篇仍然**字段缺省**(不编造)
703
+ const other = allItems(out).find((d) => !d.matches)
704
+ if (other) assert.equal('snippet' in other, false)
616
705
  })
617
706
 
618
- test('execute: read 抛错时**不影响**整次调用(只是少一段)', async () => {
707
+ test('execute: read 抛错时**不影响**整次调用(兜底路径也只是少一段)', async () => {
619
708
  const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
620
709
  const boom = async () => { throw new Error('读盘炸了') }
621
- const out = await runTool(exec, { query: 'sidebar', limit: 3 }, { read: boom })
710
+ // 剥掉 matches ⇒ 走 v0.19 的兜底(read + pickSnippet),这里让它炸
711
+ const out = await runTool(exec, { query: 'sidebar', limit: 3 },
712
+ { read: boom, scan: scanWithoutMatches(scan) })
622
713
  assert.ok(allItems(out).length > 0, '排序结果照常返回')
623
- for (const doc of allItems(out)) assert.equal('snippet' in doc, false)
714
+ for (const doc of allItems(out)) {
715
+ assert.equal('snippet' in doc, false)
716
+ assert.equal('matches' in doc, false)
717
+ }
624
718
  })
625
719
 
626
720
  test('execute: read 返回失败信封时也只是少一段,不抛', async () => {
627
721
  const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
628
722
  const denied = async () => ({ ok: false, code: 'knit/outside-workspace' })
629
- const out = await runTool(exec, { query: 'sidebar', limit: 3 }, { read: denied })
723
+ const out = await runTool(exec, { query: 'sidebar', limit: 3 },
724
+ { read: denied, scan: scanWithoutMatches(scan) })
630
725
  assert.ok(allItems(out).length > 0)
631
- for (const doc of allItems(out)) assert.equal('snippet' in doc, false)
726
+ for (const doc of allItems(out)) {
727
+ assert.equal('snippet' in doc, false)
728
+ assert.equal('matches' in doc, false)
729
+ }
632
730
  })
633
731
 
634
732
  test('execute: 时间序(无命中词)时不抽段落,也不硬凑三层', async () => {
@@ -666,6 +764,137 @@ test('renderToolText: 有段落时多一行 `match:`,且行序是 标题 / 摘
666
764
  assert.ok(!text.includes('match: \n'), '没有段落时不该出现空的 match 行')
667
765
  })
668
766
 
767
+ test('renderToolText: v0.20 命中片段带行号,且**只渲染第一段**(第二、三段都不给)', () => {
768
+ const match = (startLine, endLine, snippet) => ({
769
+ startLine, endLine, startOffset: startLine * 10, endOffset: endLine * 10 + 5, terms: ['排序'], snippet,
770
+ })
771
+ const value = {
772
+ mode: 'relevance', topic: '排序', total: 1,
773
+ primary: [{
774
+ rel: 'a.md',
775
+ title: '甲',
776
+ summary: '',
777
+ mtimeMs: 1,
778
+ source: 'doc',
779
+ reason: { code: 'bodyMatch', terms: ['排序'], fields: 1 },
780
+ matches: [match(147, 163, '片段甲'), match(900, 912, '片段乙'), match(2000, 2010, '片段丙')],
781
+ }],
782
+ supporting: [], related: [], totals: { matched: 1, total: 1 },
783
+ }
784
+ const lines = renderToolText(value).split('\n')
785
+ const at = lines.findIndex((l) => l.startsWith(' match: '))
786
+ assert.ok(at > 0, '应当有 match 行')
787
+ assert.equal(lines[at], ' match: lines 147–163 — 片段甲', '第一段带行号')
788
+ // 需求 §16 的预算实测(R2:两段 4614 字符 = 1.71× > 1.4×)⇒ 工具侧只留一段。
789
+ const matchLines = lines.filter((l) => l.startsWith(' match: '))
790
+ assert.equal(matchLines.length, 1, `一条结果只渲染一段:${matchLines.join(' | ')}`)
791
+ assert.ok(!lines.some((l) => l.includes('片段乙')), '第二段不许出现')
792
+ assert.ok(!lines.some((l) => l.includes('片段丙')), '第三段不许出现')
793
+ assert.ok(!lines.some((l) => l.startsWith(' also:')), '不再有 also: 行')
794
+ })
795
+
796
+ test('renderToolText: 没有 matches 时才走注入的 readSnippet(v0.19 兜底路径)', () => {
797
+ const item = {
798
+ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1, source: 'doc',
799
+ reason: { code: 'bodyMatch', terms: ['排序'], fields: 1 },
800
+ }
801
+ const value = {
802
+ mode: 'relevance', topic: '排序', total: 1,
803
+ primary: [item], supporting: [], related: [], totals: { matched: 1, total: 1 },
804
+ }
805
+ // 没有 matches ⇒ 用注入的 readSnippet(不带行号,因为兜底路径不知道行号)
806
+ const withRead = renderToolText(value, () => '兜底片段')
807
+ assert.ok(withRead.includes(' match: 兜底片段'), `兜底路径要渲染:${withRead}`)
808
+ assert.ok(!withRead.includes('lines '), '兜底路径没有行号,不许编一个')
809
+ // 有 matches ⇒ 用 matches,**不读** readSnippet
810
+ const withBoth = renderToolText({
811
+ ...value,
812
+ primary: [{
813
+ ...item,
814
+ matches: [{ startLine: 3, endLine: 4, startOffset: 0, endOffset: 9, terms: ['排序'], snippet: '片段' }],
815
+ }],
816
+ }, () => '兜底片段')
817
+ assert.ok(withBoth.includes(' match: lines 3–4 — 片段'), `优先用 matches:${withBoth}`)
818
+ assert.ok(!withBoth.includes('兜底片段'), '有 matches 就不该再读盘抽段落')
819
+ })
820
+
821
+ test('R2 预算:片段只带来有界增量 —— 每条结果一行 `match:`,且长度 ≤ SNIPPET_CHARS + 24', async () => {
822
+ // 需求 §16:进模型上下文的**要更精准,不是更多**。实现说明 §7 的 R2 定的上界是
823
+ // 「相对 v0.19 同一次调用不超过 1.4×」。这里把它落成一条**可复现**的守卫:
824
+ // · v0.19 基线 = 剥掉 `matches` ⇒ 走 `read` + `pickSnippet` 兜底(老宿主的行为)
825
+ // · v0.20 = 带 `matches` ⇒ 每篇渲染 `match:` 一行(**只有一行**:第二段已在
826
+ // 2026-10-07 的实测后砍掉,当时两段 = 1.71× > 1.4×)
827
+ // 比的是**整条增量**与**每条结果的增量**,不是比值 —— 比值会随 v0.19 兜底片段
828
+ // 的长短飘(pickSnippet 对短段落只给几十字符,那时比值天然高,并不代表膨胀)。
829
+ const para = (n, word) => `第 ${n} 段:关于 ${word} 的说明放在这里,后面跟着一些不重要的叙述,`
830
+ + '用来把这一段撑到接近一个正常段落该有的长度,免得测试量到的是一个玩具样本。'.repeat(4)
831
+ const extra = []
832
+ for (let i = 1; i <= 6; i += 1) {
833
+ extra.push([`docs/budget-${i}.md`, [
834
+ `# 预算 ${i}`,
835
+ '',
836
+ para(1, '无关内容'),
837
+ '',
838
+ `命中:woollybear 的处理入口在预算 ${i} 这一段的开头,${'后面继续展开细节,'.repeat(8)}`,
839
+ '',
840
+ para(3, '无关内容'),
841
+ '',
842
+ `再次提到 woollybear 是作为对照。`,
843
+ '',
844
+ ].join('\n')])
845
+ }
846
+ const root = makeWorkspace(extra)
847
+ const exec = fakeExec(fakeSession([{ role: 'user', text: 'woollybear 怎么处理' }], { cwd: root }))
848
+ const args = { query: 'woollybear', limit: 5 }
849
+ // ⚠️ 要比的是**模型读到的那个字符串**:工具的 `execute()` 返回结构化 value,
850
+ // 模型看到的是 `output.render()` 的产物。直接 `renderToolText(value)` 会漏掉
851
+ // 注册在 `output.render` 里的那个 `readSnippet` 兜底(`(item) => item.snippet`),
852
+ // 于是 v0.19 那条会因为「没有片段来源」而变空 —— 第一次就踩了这个坑。
853
+ const render = async (def) => {
854
+ const value = await def.execute(args, exec)
855
+ return def.output.render({}, value)[0].text
856
+ }
857
+ const v020 = await render(knitDocsDefinition(scan, readDocument, buildContextFor, undefined))
858
+ const v019 = await render(knitDocsDefinition(scanWithoutMatches(scan), readDocument, buildContextFor, undefined))
859
+ const items = v020.split('\n').filter((l) => /^\d+\. /.test(l)).length
860
+ const matchLines = v020.split('\n').filter((l) => l.startsWith(' match: '))
861
+ assert.ok(items > 0, `要有结果才量得到:${v020}`)
862
+ assert.ok(matchLines.length > 0, `v0.20 要带行号片段:${v020}`)
863
+ assert.ok(matchLines.length <= items, `一条结果最多一行 match:,实测 ${matchLines.length} 行 / ${items} 条`)
864
+ for (const line of matchLines) {
865
+ // ` match: lines 147–163 — ` 是 24 个字符的固定前缀,片段本体 ≤ SNIPPET_CHARS
866
+ assert.ok(line.length <= SNIPPET_CHARS + 24, `单条片段超长(${line.length}):${line}`)
867
+ }
868
+ assert.ok(v019.includes(' match: '), `v0.19 兜底也要有片段,否则这个对比没意义:${v019}`)
869
+ assert.equal(v019.includes('lines '), false, '兜底路径不许有行号')
870
+ const perItem = (v020.length - v019.length) / items
871
+ assert.ok(v020.length > v019.length, 'v0.20 应当多出片段信息(否则守卫是假的)')
872
+ assert.ok(
873
+ perItem <= SNIPPET_CHARS + 24,
874
+ `R2 超预算:每条结果多出 ${perItem.toFixed(0)} 字符 > ${SNIPPET_CHARS + 24}`,
875
+ )
876
+ // 实测比值只作为**记录**(真机压力语料上是 1.35×),不作门槛 —— 见上面的理由。
877
+ console.log(` R2 实测:v0.20 ${v020.length} 字符 / v0.19 ${v019.length} 字符 = `
878
+ + `${(v020.length / v019.length).toFixed(2)}×(${items} 条结果)`)
879
+ })
880
+
881
+ test('镜像常量:工具里的单文件上限与片段长度必须和宿主一致', () => {
882
+ // 这两对常量是「两处各写一份、必然漂移」的典型:
883
+ // · `MAX_INDEXED_KB`(工具对模型说的话)vs `index.js` 的 `MAX_BODY_BYTES`(真读多少)
884
+ // · `SNIPPET_CHARS`(工具渲染上限)vs `passage.js` 的 `SNIPPET_CHARS`(评分侧片段上限)
885
+ // 漂了不会报错,只会让工具**对模型说假话**(说 256 KB、实际读 128 KB),
886
+ // 所以按源码文本断言 —— 两个文件都真实存在,改一边忘另一边就红。
887
+ const src = (rel) => readFileSync(new URL(rel, import.meta.url), 'utf8')
888
+ const toolSrc = src('../src/host/tool.js')
889
+ const indexSrc = src('../src/host/index.js')
890
+ const kb = Number((toolSrc.match(/const MAX_INDEXED_KB = (\d+)/) || [])[1])
891
+ const bytesKb = Number((indexSrc.match(/const MAX_BODY_BYTES = (\d+) \* 1024/) || [])[1])
892
+ assert.ok(Number.isFinite(kb) && Number.isFinite(bytesKb), '两处常量都要能解析出来')
893
+ assert.equal(kb, bytesKb, `工具说 ${kb} KB,宿主实际读 ${bytesKb} KB`)
894
+ const toolSnippet = Number((toolSrc.match(/const SNIPPET_CHARS = (\d+)/) || [])[1])
895
+ assert.equal(toolSnippet, SNIPPET_CHARS, `工具渲染上限 ${toolSnippet} vs 评分侧 ${SNIPPET_CHARS}`)
896
+ })
897
+
669
898
  test('renderToolText: 不传 readSnippet → 段落字段被忽略(渲染函数无副作用)', () => {
670
899
  const value = {
671
900
  mode: 'relevance', topic: '', total: 1,