dsh-knit 0.13.0 → 0.14.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.
@@ -0,0 +1,576 @@
1
+ /**
2
+ * Knit v0.14 · **Context Pack 质量回归**
3
+ *
4
+ * 这个文件的被测对象不是「结构对不对」,而是**分层有没有决策价值**:
5
+ * 该先看的进 Primary 了吗?证据 / 实现支撑进 Supporting 了吗?
6
+ * README / CHANGELOG 这类高频文档有没有霸占 Primary?
7
+ *
8
+ * 六条硬性验收(需求 §十七 / §十八):
9
+ *
10
+ * 1. Primary 命中 —— 期望的主文档必须在 Primary 里
11
+ * 2. Supporting 出现 —— 期望的支撑材料必须在 Supporting 里
12
+ * 3. 无关长文档不许抢占 Primary
13
+ * 4. README / CHANGELOG 的高频词不许污染 Primary
14
+ * 5. 零命中的文档不许混进 Primary / Supporting
15
+ * 6. 相同输入必须产出**完全相同**的顺序(跑两遍逐字比对)
16
+ *
17
+ * 另外三条是**「不是 top-N 换三个名字」的证据**(见 `context-eval: 不是 top-N 换名字`):
18
+ * 层内的东西必须真的来自名次表的不同位置,而且层与层之间不能同序。
19
+ *
20
+ * ⚠️ 这里**不测** BM25 的 top-1 / MRR —— 那是 `test/eval.test.mjs` 的职责,
21
+ * 两套评测必须保持可比(需求 §十九)。
22
+ */
23
+ import test from 'node:test'
24
+ import assert from 'node:assert/strict'
25
+
26
+ import { CORPUS, CASES, NOW, buildFixtureGraph } from './context/fixture.mjs'
27
+ import { extractKeywords, rankByRelevance, topicLabel } from '../src/host/relevance.js'
28
+ import {
29
+ buildContext, explainContext, sourceTypeOf,
30
+ MAX_PRIMARY, MAX_SUPPORTING, MAX_RELATED,
31
+ } from '../src/host/context.js'
32
+ import { buildLinkGraph, extractRefs, createIndex, resolveRef } from '../src/host/links.js'
33
+
34
+ /* ── 一次装配:与宿主里 `scan → rankByRelevance → buildLinkGraph → buildContext`
35
+ 完全同序,只是把 I/O 换成了语料 ───────────────────────── */
36
+
37
+ /**
38
+ * 跑一条用例,返回 `{pack, ranked, order}`。
39
+ * @param {object} testCase - 用例
40
+ * @param {object} graph - 引用图
41
+ * @returns {{pack: object, ranked: object[], order: string[]}} 结果
42
+ */
43
+ function assemble(testCase, graph) {
44
+ const keywords = extractKeywords(testCase.messages, 30)
45
+ const ranked = rankByRelevance(CORPUS, keywords, NOW)
46
+ const pack = buildContext({
47
+ ranked: ranked.docs,
48
+ topic: topicLabel(ranked.label),
49
+ total: CORPUS.length,
50
+ graph,
51
+ })
52
+ return { pack, ranked: ranked.docs, order: ranked.docs.map((d) => d.rel) }
53
+ }
54
+
55
+ /** 图只建一次(它与用例无关)。 */
56
+ const GRAPH = await buildFixtureGraph(buildLinkGraph)
57
+
58
+ /** 每条用例的装配结果,只算一次。 */
59
+ const RESULTS = new Map(CASES.map((testCase) => [testCase.name, assemble(testCase, GRAPH)]))
60
+
61
+ /** 取某一层的 rel 数组。 */
62
+ const rels = (items) => items.map((item) => item.rel)
63
+
64
+ /* ── 0 · 语料自检:引用关系必须真的被解析出来 ─────────── */
65
+
66
+ test('语料自检: 引用图从原文里解析出了预期的边', () => {
67
+ // 这条先跑是有原因的:如果 `text` 里那些路径没被解析成边,
68
+ // 「引用关系能不能把邻居带进 Supporting」这件事就根本没被测到 —— 后面全绿也是假的。
69
+ const out = (rel) => [...(GRAPH.out.get(rel) || new Set())].sort()
70
+ assert.deepEqual(out('README.md'), [
71
+ 'docs/api-contract.md',
72
+ 'docs/eval-benchmark.md',
73
+ 'docs/package-layout.md',
74
+ 'docs/relevance-algorithm.md',
75
+ ])
76
+ assert.deepEqual(out('docs/relevance-algorithm.md'), [
77
+ 'docs/eval-benchmark.md',
78
+ 'docs/sdd-context-assembly.md',
79
+ ])
80
+ assert.deepEqual(out('docs/tool-contract.md'), ['docs/sdd-context-assembly.md'])
81
+ assert.deepEqual(out('docs/path-safety.md'), ['docs/api-contract.md'])
82
+ })
83
+
84
+ test('语料自检: extractRefs 不把外链与 wikilink 当工作区引用', () => {
85
+ assert.deepEqual(extractRefs('见 https://example.com/a.md 和 [[b]]'), [])
86
+ const index = createIndex(['docs/a.md'])
87
+ assert.equal(resolveRef('https://example.com/a.md', index, 'README.md'), null)
88
+ })
89
+
90
+ /* ── 1–4 · 用例:Primary / Supporting / Related 的集合关系 ─ */
91
+
92
+ for (const testCase of CASES) {
93
+ test(`context-eval: ${testCase.name}`, () => {
94
+ const { pack } = RESULTS.get(testCase.name)
95
+ const primary = rels(pack.primary)
96
+ const supporting = rels(pack.supporting)
97
+ const related = rels(pack.related)
98
+
99
+ // 1 · Primary 命中
100
+ for (const want of testCase.expectPrimary || []) {
101
+ assert.ok(primary.includes(want), `Primary 缺少 ${want};实际 Primary = ${JSON.stringify(primary)}`)
102
+ }
103
+ // 1b · 「这一对里有一个就行」—— 用于记录**已知无法判定**的并列(见 fixture 的说明)。
104
+ // 它不是放宽标准:如果 Primary 为空、或者冒出第三篇,照样红。
105
+ if (testCase.expectPrimaryOneOf) {
106
+ assert.equal(primary.length, 1, `Primary 应恰好一篇;实际 = ${JSON.stringify(primary)}`)
107
+ assert.ok(
108
+ testCase.expectPrimaryOneOf.includes(primary[0]),
109
+ `Primary 落在意料之外:${primary[0]};可接受的是 ${JSON.stringify(testCase.expectPrimaryOneOf)}`,
110
+ )
111
+ }
112
+ // 2 · Supporting 出现
113
+ for (const want of testCase.expectSupporting || []) {
114
+ assert.ok(
115
+ supporting.includes(want),
116
+ `Supporting 缺少 ${want};实际 Supporting = ${JSON.stringify(supporting)}`,
117
+ )
118
+ }
119
+ // 3 · Related 出现
120
+ for (const want of testCase.expectRelated || []) {
121
+ assert.ok(related.includes(want), `Related 缺少 ${want};实际 Related = ${JSON.stringify(related)}`)
122
+ }
123
+ // 4 · 污染源不许抢占 Primary(README / CHANGELOG / 长归档)
124
+ for (const bad of testCase.notPrimary || []) {
125
+ assert.ok(!primary.includes(bad), `${bad} 不该出现在 Primary;实际 = ${JSON.stringify(primary)}`)
126
+ }
127
+ // 5 · 三层不许互相重复,也不许出现语料外的路径
128
+ const known = new Set(CORPUS.map((doc) => doc.rel))
129
+ const union = new Set([...primary, ...supporting, ...related])
130
+ assert.equal(
131
+ union.size, primary.length + supporting.length + related.length,
132
+ '同一条不许出现在两层里',
133
+ )
134
+ for (const rel of union) assert.ok(known.has(rel), `${rel} 不在语料里`)
135
+ })
136
+ }
137
+
138
+ /* ── 5 · 零命中不许混进「先看」那两层 ──────────────────── */
139
+
140
+ test('context-eval: Primary 与 Supporting 里不许出现零命中的文档', () => {
141
+ // 这是「不是换个名字」的第一条硬证据:能进 Primary / Supporting 的
142
+ // 必须真的命中了话题,**或者**与 Primary 有引用关系(那时理由会是 linkTarget/linkSource)。
143
+ for (const testCase of CASES) {
144
+ const { pack } = RESULTS.get(testCase.name)
145
+ for (const item of [...pack.primary, ...pack.supporting]) {
146
+ const code = item.reason.code
147
+ const linked = code === 'linkTarget' || code === 'linkSource'
148
+ assert.ok(
149
+ item.reason.terms.length > 0 || linked,
150
+ `${testCase.name}: ${item.rel} 进了「先看」两层却既没命中也没有引用关系(reason=${code})`,
151
+ )
152
+ }
153
+ }
154
+ })
155
+
156
+ test('context-eval: 「什么话题都提一句」的归档长文永远进不了前两层', () => {
157
+ // §十七 案例 3 的加强版:每个话题词各提一句的长文,对任何任务都没有增量信息。
158
+ // 它既不许进 Primary,也不许进 Supporting —— 实测里它一度出现在**每一条**任务里。
159
+ // 分层里挡住它的那条规则是 `isDocHit`(「这一篇是把它讲得最多的那一篇」)。
160
+ for (const testCase of CASES) {
161
+ const { pack } = RESULTS.get(testCase.name)
162
+ const inTop = rels(pack.primary).includes('docs/long-archive.md')
163
+ || rels(pack.supporting).includes('docs/long-archive.md')
164
+ assert.ok(!inTop, `${testCase.name}: docs/long-archive.md 混进了前两层`)
165
+ }
166
+ })
167
+
168
+ test('context-eval: 没有引用的零命中文档永远进不了前两层', () => {
169
+ // 前两层收录零命中条目的**唯一**理由就是引用关系。没有任何引用的零命中条目
170
+ // 只能进 Related —— 否则「先看这几篇」就掺进了纯背景。
171
+ for (const testCase of CASES) {
172
+ const { pack } = RESULTS.get(testCase.name)
173
+ for (const item of [...pack.primary, ...pack.supporting]) {
174
+ if (item.reason.terms.length > 0) continue
175
+ const linked = item.reason.code === 'linkTarget' || item.reason.code === 'linkSource'
176
+ assert.ok(linked, `${testCase.name}: ${item.rel} 零命中又没引用关系却进了前两层`)
177
+ }
178
+ }
179
+ })
180
+
181
+ test('context-eval: Related 里的每一条也都有可核验的理由(不许「工作区里还有这一篇」凑数)', () => {
182
+ // ⚠️ 这条守卫是 2026-09-29 加的,它锁的是一个**真被改掉的缺陷**:
183
+ // 旧实现 Related 遍历 `[...hit, ...noHit]` —— 一个话题词都没命中、又没有任何引用关系的文档
184
+ // 也会被填进 Related,理由码落到兜底的 `related`,客户端把它译成「与当前工作区相关」。
185
+ // 那正是需求 §九 明令禁止的「可能对你有帮助」(无法验证的推断),
186
+ // 也违反 PRD §5 对 Related 的定义(「与当前任务**有关**」)。
187
+ // ⇒ 现在:Related 的每一条**要么真的命中了话题词,要么与 Primary 有引用关系**,二者必居其一。
188
+ // 两条都不满足就**不出场** —— Related 为空是合法结论(见任务 10)。
189
+ for (const testCase of CASES) {
190
+ const { pack } = RESULTS.get(testCase.name)
191
+ for (const item of pack.related) {
192
+ const linked = item.reason.code === 'linkTarget' || item.reason.code === 'linkSource'
193
+ const hasTerms = item.reason.terms.length > 0
194
+ assert.ok(
195
+ linked || hasTerms,
196
+ `${testCase.name}: ${item.rel} 在 Related 里,但既没命中词也没有引用关系(理由码 ${item.reason.code})`,
197
+ )
198
+ assert.notEqual(
199
+ item.reason.code, 'related',
200
+ `${testCase.name}: ${item.rel} 用了兜底理由码 related —— 那等于说「工作区里还有这么一篇」`,
201
+ )
202
+ }
203
+ }
204
+ })
205
+
206
+
207
+ test('context-eval: README 与 CHANGELOG 永远进不了 Primary', () => {
208
+ // 高频词污染的直接防线。它们在**检索**里已经排得不错(IDF 压住了),
209
+ // 但仍然不许霸占 Primary —— 否则「按对话构建上下文」就退化成「列项目门口那几篇」。
210
+ for (const testCase of CASES) {
211
+ const { pack } = RESULTS.get(testCase.name)
212
+ for (const noisy of ['README.md', 'CHANGELOG.md']) {
213
+ assert.ok(
214
+ !rels(pack.primary).includes(noisy),
215
+ `${testCase.name}: ${noisy} 霸占了 Primary;实际 = ${JSON.stringify(rels(pack.primary))}`,
216
+ )
217
+ }
218
+ }
219
+ })
220
+
221
+ test('context-eval: 进 Primary 的每一条都有「落脚点」(标题或摘要命中)', () => {
222
+ // 「落脚点」是 Primary 的硬条件,这条把它钉死:Primary 里的条目的理由码
223
+ // 必须是标题/摘要类,不能是 bodyMatch / linkTarget。
224
+ const groundedCodes = new Set(['direct', 'titleMatch', 'summaryMatch'])
225
+ for (const testCase of CASES) {
226
+ const { pack } = RESULTS.get(testCase.name)
227
+ for (const item of pack.primary) {
228
+ assert.ok(
229
+ groundedCodes.has(item.reason.code),
230
+ `${testCase.name}: ${item.rel} 进了 Primary 但理由是 ${item.reason.code}(没有落脚点)`,
231
+ )
232
+ }
233
+ }
234
+ })
235
+
236
+ test('context-eval: 靠引用关系进前两层的条目,理由必须是 link 而不是假装命中', () => {
237
+ // 任务 3 / 10 / 11 都出现了「零命中、但与主要上下文有引用关系」的条目。
238
+ // 它们的理由必须是 linkTarget / linkSource,而且**不许**带命中词 —— 不许编造。
239
+ const seen = []
240
+ for (const testCase of CASES) {
241
+ const { pack } = RESULTS.get(testCase.name)
242
+ for (const item of [...pack.primary, ...pack.supporting]) {
243
+ const code = item.reason.code
244
+ if (code !== 'linkTarget' && code !== 'linkSource') continue
245
+ seen.push(`${testCase.name}:${item.rel}:${code}`)
246
+ assert.deepEqual(item.reason.terms, [], `${item.rel} 零命中却带了命中词`)
247
+ assert.equal(item.reason.fields, 0, `${item.rel} 零命中却报了字段数`)
248
+ assert.ok(
249
+ item.reason.code === 'linkTarget' ? true : true,
250
+ '理由码只能是 linkTarget / linkSource',
251
+ )
252
+ }
253
+ }
254
+ assert.ok(
255
+ seen.some((entry) => entry.endsWith(':linkTarget')),
256
+ `没有任何「被主要文档引用」的条目 —— 引用关系没被装配层用上。实际:${seen.join(' | ')}`,
257
+ )
258
+ assert.ok(
259
+ seen.some((entry) => entry.endsWith(':linkSource')),
260
+ `没有任何「引用了主要文档」的条目。实际:${seen.join(' | ')}`,
261
+ )
262
+ })
263
+
264
+ /* ── 6 · 真的不是「top-N 换名字」──────────────────────── */
265
+
266
+ test('context-eval: 不是 top-N 换名字 —— 层内条目来自名次表的不同位置', () => {
267
+ // 「换个名字」的意思是:Primary = top-3 改名、Supporting = top 4-8 改名、Related = 其余。
268
+ // 那样的话 Supporting 里每一项的名次都必然紧跟在 Primary 之后。
269
+ // 实测不是:支持材料会从名次表很后面被带上来(引用关系 / 代码角色)。
270
+ let demonstrated = 0
271
+ const detail = []
272
+ for (const testCase of CASES) {
273
+ const { pack, order } = RESULTS.get(testCase.name)
274
+ const primaryRanks = pack.primary.map((item) => order.indexOf(item.rel))
275
+ if (primaryRanks.length === 0) continue
276
+ const lastPrimary = Math.max(...primaryRanks)
277
+ const promoted = pack.supporting
278
+ .map((item) => ({ rel: item.rel, rank: order.indexOf(item.rel) }))
279
+ .filter((entry) => entry.rank > lastPrimary + 1 || entry.rank === -1)
280
+ if (promoted.length > 0) demonstrated += 1
281
+ detail.push({
282
+ name: testCase.name,
283
+ primary: pack.primary.length,
284
+ supporting: pack.supporting.length,
285
+ related: pack.related.length,
286
+ lastPrimary,
287
+ promoted,
288
+ })
289
+ }
290
+ // 只要有一条用例出现了「跨过 Primary 之后的相邻名次被提上来」,分层就不是重新贴标签
291
+ assert.ok(
292
+ demonstrated > 0,
293
+ `没有任何一条用例出现「来自名次表更后面」的支撑条目 —— 那它可能只是 top-N 改名。明细:\n`
294
+ + JSON.stringify(detail, null, 1),
295
+ )
296
+ })
297
+
298
+ test('context-eval: 至少两个用例的三层不是同一个顺序(重排确实发生了)', () => {
299
+ // 若某一层恒等于名次表的某个连续切段,「重排」就没发生。
300
+ let regrouped = 0
301
+ for (const testCase of CASES) {
302
+ const { pack, order } = RESULTS.get(testCase.name)
303
+ const flat = [...rels(pack.primary), ...rels(pack.supporting), ...rels(pack.related)]
304
+ const head = order.slice(0, flat.length)
305
+ if (JSON.stringify(flat) !== JSON.stringify(head)) regrouped += 1
306
+ }
307
+ assert.ok(regrouped >= 2, `只有 ${regrouped} 条用例的顺序与名次表不同 —— 重排幅度太小`)
308
+ })
309
+
310
+ /* ── 7 · 确定性 ─────────────────────────────────────── */
311
+
312
+ test('context-eval: 相同输入产出完全相同的顺序(跑两遍逐字比对)', () => {
313
+ const fresh = CASES.map((testCase) => assemble(testCase, GRAPH).pack)
314
+ const cached = CASES.map((testCase) => RESULTS.get(testCase.name).pack)
315
+ assert.deepEqual(
316
+ JSON.parse(JSON.stringify(fresh)),
317
+ JSON.parse(JSON.stringify(cached)),
318
+ '两次装配的结果必须逐字相同',
319
+ )
320
+ })
321
+
322
+ test('context-eval: 打乱语料输入顺序,分层结果不变', () => {
323
+ // `collectDocs` 是按 mtime 倒序给出的,同一份语料换个扫描顺序不该换序。
324
+ // 这条钉的是 `rankByRelevance` 里那个 `__index` 兜底键。
325
+ const shuffled = [...CORPUS].reverse()
326
+ const keywords = extractKeywords(CASES[0].messages, 30)
327
+ const a = rankByRelevance(CORPUS, keywords, NOW)
328
+ const b = rankByRelevance(shuffled, keywords, NOW)
329
+ const packA = buildContext({ ranked: a.docs, topic: topicLabel(a.label), total: CORPUS.length, graph: GRAPH })
330
+ const packB = buildContext({ ranked: b.docs, topic: topicLabel(b.label), total: CORPUS.length, graph: GRAPH })
331
+ assert.deepEqual(rels(packA.primary), rels(packB.primary))
332
+ assert.deepEqual(rels(packA.supporting), rels(packB.supporting))
333
+ })
334
+
335
+ /* ── 8 · 结构与纪律 ─────────────────────────────────── */
336
+
337
+ test('context-eval: Context Pack 不出分数、不出正文、不出绝对路径', () => {
338
+ const { pack } = RESULTS.get(CASES[0].name)
339
+ const serialized = JSON.stringify(pack)
340
+ for (const forbidden of ['score', 'raw', 'strength', 'haystack', 'matchedTerms', 'rank']) {
341
+ assert.ok(!serialized.includes(`"${forbidden}"`), `Context Pack 不该出现 ${forbidden}`)
342
+ }
343
+ assert.ok(!serialized.includes('归档归档'), '不该带正文')
344
+ assert.ok(!serialized.includes('"text"'), '不该带原文')
345
+ for (const item of [...pack.primary, ...pack.supporting, ...pack.related]) {
346
+ assert.ok(!item.rel.startsWith('/'), `rel 必须是相对路径:${item.rel}`)
347
+ assert.deepEqual(
348
+ Object.keys(item).sort(),
349
+ ['kind', 'mtimeMs', 'reason', 'rel', 'source', 'summary', 'title'],
350
+ `条目字段必须固定:${Object.keys(item).join('/')}`,
351
+ )
352
+ }
353
+ })
354
+
355
+ test('context-eval: 每条都能说出为什么在这里(理由码在封闭集合里)', () => {
356
+ const allowed = new Set([
357
+ 'direct', 'titleMatch', 'summaryMatch', 'bodyMatch',
358
+ 'linkTarget', 'linkSource', 'related',
359
+ ])
360
+ for (const testCase of CASES) {
361
+ const { pack } = RESULTS.get(testCase.name)
362
+ for (const item of [...pack.primary, ...pack.supporting, ...pack.related]) {
363
+ assert.ok(allowed.has(item.reason.code), `未知理由码 ${item.reason.code}(${item.rel})`)
364
+ assert.ok(Array.isArray(item.reason.terms), 'terms 必须是数组')
365
+ assert.ok(Number.isInteger(item.reason.fields), 'fields 必须是整数')
366
+ }
367
+ }
368
+ })
369
+
370
+ test('context-eval: 不给 task 时为空串,给了就是**原样引用**(不做任务理解)', async () => {
371
+ const { buildContext } = await import('../src/host/context.js')
372
+ // 评测用例不喂 task ⇒ 空串。它**不是**「Knit 猜出来的任务」。
373
+ for (const testCase of CASES) {
374
+ assert.equal(RESULTS.get(testCase.name).pack.task, '', '不许编一个无法验证的「任务」')
375
+ }
376
+ // 喂了就逐字带出 —— 折叠或改写都算推断,推断在这个模块里是禁止的。
377
+ const cited = '把 Primary 的落脚点规则讲清楚'
378
+ assert.equal(buildContext({ ranked: [], task: cited }).task, cited)
379
+ })
380
+
381
+ test('context-eval: 上限是硬约束(Primary ≤ 1,Supporting ≤ 3,Related ≤ 5)', () => {
382
+ for (const testCase of CASES) {
383
+ const { pack } = RESULTS.get(testCase.name)
384
+ assert.ok(pack.primary.length <= 1, `Primary 超上限:${pack.primary.length}`)
385
+ assert.ok(pack.supporting.length <= 3, `Supporting 超上限:${pack.supporting.length}`)
386
+ assert.ok(pack.related.length <= 5, `Related 超上限:${pack.related.length}`)
387
+ }
388
+ // 上限是与规格的契约(PRD §5),不是随手定的数 —— 改了必须同步改这里和文档。
389
+ assert.equal(MAX_PRIMARY, 1)
390
+ assert.equal(MAX_SUPPORTING, 3)
391
+ assert.equal(MAX_RELATED, 5)
392
+ assert.deepEqual(pack0().totals, {
393
+ primary: pack0().primary.length,
394
+ supporting: pack0().supporting.length,
395
+ related: pack0().related.length,
396
+ matched: pack0().totals.matched,
397
+ total: pack0().totals.total,
398
+ })
399
+ })
400
+
401
+ /** 第一条用例的包(给上限测试的 totals 自洽断言用)。 */
402
+ function pack0() {
403
+ return RESULTS.get(CASES[0].name).pack
404
+ }
405
+
406
+ /* ── 9 · 纯函数边界 ─────────────────────────────────── */
407
+
408
+ test('buildContext: 没有图时退化成「只看命中」,不抛错', () => {
409
+ const keywords = extractKeywords(CASES[0].messages, 30)
410
+ const ranked = rankByRelevance(CORPUS, keywords, NOW)
411
+ const pack = buildContext({ ranked: ranked.docs, topic: 'x', total: CORPUS.length })
412
+ assert.ok(pack.primary.length > 0, '没有引用图也应当能分出主要上下文')
413
+ assert.ok(pack.primary.every((item) => item.reason.terms.length > 0), '没有图时进 Primary 的必须是真命中')
414
+ })
415
+
416
+ test('buildContext: 空输入 → 三层全空,totals 全 0', () => {
417
+ const pack = buildContext({ ranked: [], topic: '', total: 0 })
418
+ assert.deepEqual([pack.primary, pack.supporting, pack.related], [[], [], []])
419
+ assert.deepEqual(pack.totals, { primary: 0, supporting: 0, related: 0, matched: 0, total: 0 })
420
+ })
421
+
422
+ test('explainContext: 理由判定顺序固定(直接命中优先于引用关系)', () => {
423
+ // 一篇既命中、又被 Primary 引用的文档,理由必须是 `direct` ——
424
+ // 「真命中」比「被引用」强,不能因为它是邻居就把理由降级。
425
+ const one = explainContext(
426
+ { rel: 'docs/a.md', matchedTerms: [{ term: 'x', fields: { title: true, summary: false, body: true } }] },
427
+ { linkTarget: true, linkSource: true },
428
+ )
429
+ assert.equal(one.code, 'titleMatch', '标题命中优先于引用关系')
430
+ assert.equal(one.fields, 2, '标题 + 正文 = 跨 2 个字段')
431
+
432
+ // 标题命中 + 命中 ≥2 个话题词 → 升级成 `direct`(「它就是在讲这件事」)
433
+ const two = explainContext({
434
+ rel: 'docs/a.md',
435
+ matchedTerms: [
436
+ { term: 'x', fields: { title: true, summary: false, body: false } },
437
+ { term: 'y', fields: { title: false, summary: false, body: true } },
438
+ ],
439
+ })
440
+ assert.equal(two.code, 'direct')
441
+
442
+ // 只命中摘要 → `summaryMatch`;只在正文 → `bodyMatch`(fields = 焦点词正文命中数)
443
+ assert.equal(explainContext({ rel: 'a.md', matchedTerms: [{ term: 'x', fields: { summary: true } }] }).code, 'summaryMatch')
444
+ const body = explainContext({
445
+ rel: 'a.md',
446
+ matchedTerms: [
447
+ { term: 'x', fields: { body: true, bodyTf: 3 } },
448
+ { term: 'y', fields: { body: true, bodyTf: 1 } },
449
+ ],
450
+ })
451
+ assert.equal(body.code, 'bodyMatch')
452
+ assert.equal(body.fields, 2, '两个词在正文里命中 = 2')
453
+
454
+ // 零命中 + 引用关系 → link 码;都不是 → related
455
+ assert.equal(explainContext({ rel: 'a.md', matchedTerms: [] }, { linkTarget: true }).code, 'linkTarget')
456
+ assert.equal(explainContext({ rel: 'a.md', matchedTerms: [] }, { linkSource: true }).code, 'linkSource')
457
+ assert.equal(explainContext({ rel: 'a.md', matchedTerms: [] }).code, 'related')
458
+ })
459
+
460
+ test('sourceTypeOf: 角色是路径字面规则,不是内容理解', () => {
461
+ assert.equal(sourceTypeOf('test/context/fixture.mjs'), 'test', 'test/ 目录')
462
+ assert.equal(sourceTypeOf('docs/eval-benchmark.md'), 'test', 'eval- 前缀也算评测')
463
+ assert.equal(sourceTypeOf('src/host/index.js'), 'impl', '源码路径仍能认出是实现')
464
+ assert.equal(sourceTypeOf('src/host/index.md'), 'impl')
465
+ assert.equal(sourceTypeOf('docs/sdd-context-assembly.md'), 'design')
466
+ assert.equal(sourceTypeOf('docs/context-assembly.md'), 'impl', '带模块名的说明走 impl')
467
+ assert.equal(sourceTypeOf('CHANGELOG.md'), 'doc')
468
+ // ⚠️ 踩过的坑:`docs/relevance-algorithm.md` 曾经因为文件名里有 relevance 被判成 impl。
469
+ // design 规则排在 impl 前面之后仍然正确 —— 它确实不是设计文档,就是 impl。
470
+ assert.equal(sourceTypeOf('docs/relevance-algorithm.md'), 'impl')
471
+ })
472
+
473
+ /* ── 具名指标(SDD §27)────────────────────────────────
474
+ *
475
+ * SDD §27 点了三个指标的名字,但**没有给公式** —— 公式由这里定义,并在文档里写明:
476
+ *
477
+ * Primary@1 = 「唯一那篇 Primary 命中期望」的用例数 / 「期望有 Primary」的用例数。
478
+ * 期望 Primary 为空的用例(任务 12)不进分母 —— 那是另一条守卫。
479
+ * Supporting Recall = Σ|实际 Supporting ∩ 期望 Supporting| / Σ|期望 Supporting|
480
+ * (微平均,只统计**声明过**期望 Supporting 的用例)。
481
+ * Role Precision = 「角色判定未被 fixture 否认」的条目数 / 「被 fixture 表态过的」条目数。
482
+ *
483
+ * ⚠️ Role Precision 的**局限必须说清楚**:fixture 声明的是**必需项**,不是穷举名册。
484
+ * 所以它测的是「没有出现被明确否认的角色」,不是「每个条目都分对了」。
485
+ * 一个条目的角色只有在满足下面任一条时才被计入:
486
+ * - 它在用例的 expectPrimary / expectSupporting / expectRelated 里被点名 → 必须落在那一层;
487
+ * - 它在 notPrimary 里被点名且落进了 Primary → 算错。
488
+ * 没被点名的条目(fixture 对它没表态)不计入 —— 不拿没说的话当标准。
489
+ *
490
+ * ⚠️ 三个指标目前都是 1.000(全绿),**这不代表分层有多准** —— 用例本身就是照着
491
+ * 规则写出来的。它们的作用是**回归**:任何一条分层规则漂移,至少会有一个掉下来。
492
+ * SDD §18 明令禁止写「context score 必须 > 80」这种拍出来的分数阈值,
493
+ * 所以这里断言的是**精确的集合关系**(= 1 / 分母 > 0),不是百分比门槛。
494
+ */
495
+ test('context-eval: 具名指标 —— Primary@1 / Supporting Recall / Role Precision', (t) => {
496
+ /* Primary@1 */
497
+ let primaryCases = 0
498
+ let primaryHits = 0
499
+ const primaryMisses = []
500
+ for (const testCase of CASES) {
501
+ const expected = (testCase.expectPrimary && testCase.expectPrimary.length
502
+ ? testCase.expectPrimary
503
+ : (testCase.expectPrimaryOneOf || []))
504
+ if (!expected.length) continue // 期望为空 → 不进分母
505
+ primaryCases += 1
506
+ const { pack } = RESULTS.get(testCase.name)
507
+ const top = pack.primary.length === 1 ? pack.primary[0].rel : null
508
+ if (top && expected.includes(top)) primaryHits += 1
509
+ else primaryMisses.push(`${testCase.name}: 期望 ${JSON.stringify(expected)},实际 ${JSON.stringify(rels(pack.primary))}`)
510
+ }
511
+
512
+ /* Supporting Recall(微平均) */
513
+ let supportingExpected = 0
514
+ let supportingFound = 0
515
+ const supportingMisses = []
516
+ for (const testCase of CASES) {
517
+ const expected = testCase.expectSupporting || []
518
+ if (!expected.length) continue
519
+ supportingExpected += expected.length
520
+ const actual = rels(RESULTS.get(testCase.name).pack.supporting)
521
+ for (const rel of expected) {
522
+ if (actual.includes(rel)) supportingFound += 1
523
+ else supportingMisses.push(`${testCase.name}: ${rel} 不在 Supporting 里(实际 ${JSON.stringify(actual)})`)
524
+ }
525
+ }
526
+
527
+ /* Role Precision */
528
+ let declared = 0
529
+ let correct = 0
530
+ const roleMisses = []
531
+ for (const testCase of CASES) {
532
+ const { pack } = RESULTS.get(testCase.name)
533
+ const expPrimary = (testCase.expectPrimary && testCase.expectPrimary.length
534
+ ? testCase.expectPrimary
535
+ : (testCase.expectPrimaryOneOf || []))
536
+ const expSupporting = testCase.expectSupporting || []
537
+ const expRelated = testCase.expectRelated || []
538
+ const notPrimary = testCase.notPrimary || []
539
+ // ⚠️ `expectPrimaryOneOf` 的用例(任务 11)是一条**局限的存档**:那两篇的 BM25 分完全并列
540
+ // (raw 都是 4、标题里都含「排序」),检索没有任何依据分高下,所以断言的是
541
+ // 「一对可接受的答案」。⇒ **落选的那一篇允许待在 Supporting**,不算角色错误 ——
542
+ // 否则这条指标会逼我们去加一层本来不存在的语义判断。
543
+ const oneOfMode = !(testCase.expectPrimary && testCase.expectPrimary.length)
544
+ && (testCase.expectPrimaryOneOf || []).length > 0
545
+ const inExpected = (rel) => expPrimary.includes(rel) || expSupporting.includes(rel) || expRelated.includes(rel)
546
+ const satisfied = (tier, rel) => (tier === 'primary' && expPrimary.includes(rel))
547
+ || (tier === 'supporting' && (expSupporting.includes(rel) || (oneOfMode && expPrimary.includes(rel))))
548
+ || (tier === 'related' && expRelated.includes(rel))
549
+
550
+ for (const [tier, items] of [['primary', pack.primary], ['supporting', pack.supporting], ['related', pack.related]]) {
551
+ for (const item of items) {
552
+ const isDeclared = inExpected(item.rel) || (tier === 'primary' && notPrimary.includes(item.rel))
553
+ if (!isDeclared) continue
554
+ declared += 1
555
+ if (satisfied(tier, item.rel)) correct += 1
556
+ else roleMisses.push(`${testCase.name}: ${item.rel} 落在 ${tier},但期望不是这一层`)
557
+ }
558
+ }
559
+ }
560
+
561
+ const primaryAt1 = primaryCases ? primaryHits / primaryCases : 1
562
+ const supportingRecall = supportingExpected ? supportingFound / supportingExpected : 1
563
+ const rolePrecision = declared ? correct / declared : 1
564
+
565
+ t.diagnostic(`Primary@1 = ${primaryHits}/${primaryCases} = ${primaryAt1.toFixed(3)}`)
566
+ t.diagnostic(`Supporting Recall = ${supportingFound}/${supportingExpected} = ${supportingRecall.toFixed(3)}`)
567
+ t.diagnostic(`Role Precision = ${correct}/${declared} = ${rolePrecision.toFixed(3)}`)
568
+
569
+ assert.ok(primaryCases > 0, '分母为 0 说明用例丢了期望 — 指标会假绿')
570
+ assert.equal(primaryAt1, 1, `Primary@1 掉了:\n${primaryMisses.join('\n')}`)
571
+ assert.ok(supportingExpected > 0, '分母为 0 说明用例丢了期望 — 指标会假绿')
572
+ assert.equal(supportingRecall, 1, `Supporting Recall 掉了:\n${supportingMisses.join('\n')}`)
573
+ assert.ok(declared > 0, '分母为 0 说明用例丢了期望 — 指标会假绿')
574
+ assert.equal(rolePrecision, 1, `Role Precision 掉了:\n${roleMisses.join('\n')}`)
575
+ })
576
+