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.
- package/CHANGELOG.md +166 -0
- package/README.en.md +155 -9
- package/README.md +148 -14
- package/package.json +5 -2
- package/src/client/client.js +501 -197
- package/src/host/context.js +568 -0
- package/src/host/index.js +305 -20
- package/src/host/relevance.js +44 -6
- package/src/host/tool.js +274 -58
- package/test/client.test.mjs +488 -92
- package/test/context/fixture.mjs +553 -0
- package/test/context-eval.test.mjs +576 -0
- package/test/context.test.mjs +542 -0
- package/test/harness.mjs +33 -7
- package/test/host-http.test.mjs +71 -0
- package/test/host.test.mjs +105 -0
- package/test/i18n.test.mjs +46 -3
- package/test/tool.test.mjs +328 -96
- package/tools/json-schema-subset.mjs +89 -0
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Knit · **上下文装配**(v0.14)
|
|
3
|
+
*
|
|
4
|
+
* ## 这一层是干什么的
|
|
5
|
+
*
|
|
6
|
+
* Retrieval 回答「哪几篇跟这段对话最像」,本模块回答**另一个问题**:
|
|
7
|
+
*
|
|
8
|
+
* > 这个任务,项目里哪些东西**最值得先看**,哪些是证据与实现支撑,哪些只是相关资料。
|
|
9
|
+
*
|
|
10
|
+
* 它是一层**纯投影**:输入是 `rankByRelevance()` 已经算好的名次与命中词、
|
|
11
|
+
* 以及 `links.js` 已经解出来的引用图,输出是三层 Context Pack。
|
|
12
|
+
* **不重新扫工作区、不重新打分、不引入新的相似度。**
|
|
13
|
+
*
|
|
14
|
+
* ## 三条硬约束(都是产品决定,不是实现细节)
|
|
15
|
+
*
|
|
16
|
+
* 1. **零模型、零网络。** 分层全部由下面的确定性规则算出,每一层都能说出
|
|
17
|
+
* 「它凭什么在这里」。不是 embedding,不是 LLM rerank,不是「AI 判断」。
|
|
18
|
+
* 2. **不出新分数。** 对外只给名次与理由,不给 `contextScore = 87.6` ——
|
|
19
|
+
* 相关度是相对量,名次本身就是答案(v0.5 起就守着的口径,见 AGENTS.md §6.6)。
|
|
20
|
+
* 3. **确定性。** 相同输入必然产出逐字相同的顺序。所有并列都有显式兜底键。
|
|
21
|
+
*
|
|
22
|
+
* ## 三层各自的判据
|
|
23
|
+
*
|
|
24
|
+
* | 层 | 什么时候进 | 上限 |
|
|
25
|
+
* |---|---|---|
|
|
26
|
+
* | **Primary**(主要上下文) | 命中,**且**有「落脚点」(有个话题词命中标题或摘要),**且**相关度不是背景噪音(≥ 最高分的 30%) | 3 |
|
|
27
|
+
* | **Supporting**(辅助上下文) | 对某个「焦点词」有**深入命中**(该词不止一篇在讲,而且这一篇是把它**讲得最多**的那一篇);**或**与某个 Primary 有引用关系 | 5 |
|
|
28
|
+
* | **Related**(相关上下文) | 其余有命中的条目,然后才是其余的引用邻居与零命中项 | 12 |
|
|
29
|
+
*
|
|
30
|
+
* 两个概念都是**可解释、无阈值**的,这是这一层能用一句话讲清的前提:
|
|
31
|
+
*
|
|
32
|
+
* - **落脚点**:作者把话题词写进了标题或摘要 —— 这是「这篇就是在讲这件事」的
|
|
33
|
+
* 最直接的作者信号。只在正文里提到一次不算。
|
|
34
|
+
* - **焦点词**:一个话题词在这批结果里**至少两篇**命中。只在一篇里出现的词
|
|
35
|
+
* 要么是罕见词(那一篇就是答案),要么是噪音;只有「不止一篇在讲」的词
|
|
36
|
+
* 才能把一个正文命中抬到 Supporting。用**结果集内部**的提及次数而不是语料频率,
|
|
37
|
+
* 是因为前者与「这批结果正在讨论什么」严格同源,不用挑一个 df 比例。
|
|
38
|
+
* - **深入命中(docHit)**:焦点词还不够,这一篇得是把它**讲得最多**的那一篇
|
|
39
|
+
* (正文字频等于全批最大,且至少 2 次)。这一条是实测补的,也是整个分层里
|
|
40
|
+
* 最关键的一条 —— 它把「什么话题都提一句」的归档长文彻底挡住:
|
|
41
|
+
* 长文里每个话题词各出现一次,而真正在讲这件事的文档最少也有两三次。
|
|
42
|
+
* 没有它,长文会出现在**每一条**任务的 Supporting 里,把真正的支撑材料挤掉。
|
|
43
|
+
*
|
|
44
|
+
* ⚠️ 这套规则是**实测调出来的**,不是拍脑袋。三条真实教训:
|
|
45
|
+
* 1. 只要求「命中 ≥2 个话题词」时,满篇话题词的 `CHANGELOG.md` 与
|
|
46
|
+
* 「什么话题都提一句」的长归档会霸占 Primary(实测:任务 2/4/7 全红)。
|
|
47
|
+
* ⇒ Primary 必须有落脚点。
|
|
48
|
+
* 2. 落脚点单独用也不够:摘要里正好出现话题词的文档也会被抬进 Primary
|
|
49
|
+
* (实测任务 3 / 9 / 10 全红)。⇒ 再加一条相对强度下限。
|
|
50
|
+
* 4. 只看「有没有出现」还不够:每个话题词各提一句的归档长文会进每一条任务的
|
|
51
|
+
* Supporting。⇒ 焦点词还要在正文里出现 ≥2 次(`STRONG_BODY_TF`)。
|
|
52
|
+
* 3. 强度下限**不能太高**:「取一半」会误杀同一话题下的第二篇
|
|
53
|
+
* (实测任务 5 的第二篇只有最高分的 27%)。取 30% 刚好分开两者。
|
|
54
|
+
*
|
|
55
|
+
* ## 引用关系只是上下文信号,不是「更相关」
|
|
56
|
+
*
|
|
57
|
+
* `links.js` 的文件头已经用实测写过:把引用图当排序信号**补不上**词面错配那个缺口
|
|
58
|
+
* (目标文档 BM25 第 45 名 → 融合后最好第 8 名,从未进 top-5)。
|
|
59
|
+
* 所以这里**不许**引用关系把一篇文档抬进 Primary —— 它只能把一篇文档
|
|
60
|
+
* 放进 Supporting / Related。反过来,「被 Primary 引用」是个很强的**阅读顺序**信号:
|
|
61
|
+
* 你读主文档时就会看到那条路径,它就是下一步该打开的东西。
|
|
62
|
+
*
|
|
63
|
+
* ## 已知边界(不要读成缺陷报告,是如实记录)
|
|
64
|
+
*
|
|
65
|
+
* - **只看 Markdown。** 工作区里的 `.js` / `.mjs` 是真实存在的「实现 / 测试」,
|
|
66
|
+
* 但它们不进语料(v0.14 明确不做源码索引),所以
|
|
67
|
+
* 「Supporting = 实现文件」只能由**描述该实现的 Markdown** 承担。
|
|
68
|
+
* - **不做任务理解。** `task` 字段是**引用**,不是推断:它由调用方传入
|
|
69
|
+
* (`index.js` 取「最新一条有实质内容的用户消息」原文),本模块只负责透传,
|
|
70
|
+
* **永远不生成**任务描述 —— 那需要模型,违反约束 1。
|
|
71
|
+
* 没有可引用的用户消息时它就是空串,界面与工具都照常工作。
|
|
72
|
+
* - **媒体不参与分层。** 图片/视频的 haystack 只有文件名,命中即命中,
|
|
73
|
+
* 但把它们排进「先看哪几篇」没有意义,所以不放进 Context Pack。
|
|
74
|
+
* - **不判断「够不够」**。Primary 一篇都没有也要照常交付(三层全空就是全空)——
|
|
75
|
+
* 硬凑一篇「看起来像主文档的」是编造。`MAX_PRIMARY = 1` 是上限,不是指标。
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
/* ── 上限(对外契约的一部分,测试直接断言它们)───────────────── */
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Primary 最多几项。
|
|
82
|
+
*
|
|
83
|
+
* **1** —— PRD §5「Primary = Top 1 relevant artifact」、SDD §25「primary <= 1」。
|
|
84
|
+
* 为什么是 1 而不是 3:Design §30 的完成标准是用户第一眼看到
|
|
85
|
+
* 「这个任务,现在应该先看**这一篇**」。给三篇等于把「哪篇最重要」这个判断
|
|
86
|
+
* 又推回给用户 —— 那正是 Context Pack 要替掉的东西。
|
|
87
|
+
*
|
|
88
|
+
* 实现上它是「名次最靠前、且**通过落脚点与强度闸门**的那一篇」(见下面 `classifyPrimary`
|
|
89
|
+
* 附近的循环)。SDD §6 的字面规则是 `Primary = rankedDocs[0]`;两者在
|
|
90
|
+
* 「榜首本身合格」时完全一致,只有在榜首是污染源(README / 什么都提一句的长文)
|
|
91
|
+
* 时才分叉 —— 那种情况下本实现给出后面那篇真正在讲这件事的,而不是空手。
|
|
92
|
+
*/
|
|
93
|
+
export const MAX_PRIMARY = 1
|
|
94
|
+
|
|
95
|
+
/** Supporting 最多几项 —— PRD §5「0 ~ 3」。超过 3 项就不再是支撑,而是第二份清单了。 */
|
|
96
|
+
export const MAX_SUPPORTING = 3
|
|
97
|
+
|
|
98
|
+
/** Related 最多几项 —— PRD §5「0 ~ 5」。 */
|
|
99
|
+
export const MAX_RELATED = 5
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 进 Primary 的相对强度下限:`raw / maxRaw`。
|
|
103
|
+
*
|
|
104
|
+
* 低于这条线的条目是「标题里正好出现了这个词」的背景噪音
|
|
105
|
+
* (比如一篇讲 npm 的文档,摘要里恰好有一句「图片与视频」)。
|
|
106
|
+
*
|
|
107
|
+
* 取 30% 是**实测定下来的**:
|
|
108
|
+
* - 取 50% 会误杀同一个话题下的第二篇(实测只有最高分的 27%);
|
|
109
|
+
* - 去掉这条(0%)会让任务 3、9、10 的 Primary 被误判。
|
|
110
|
+
* 30% 刚好把「这一类噪音」与「同一话题的第二篇」分开。
|
|
111
|
+
*/
|
|
112
|
+
const PRIMARY_MIN_SHARE = 0.3
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 一个话题词要算「焦点词」,至少得在这批结果里的几篇命中。
|
|
116
|
+
* = 1 篇(提问者自己提到的那篇)+ 1 篇以上(项目里真的还有别处在讲它)。
|
|
117
|
+
*/
|
|
118
|
+
const FOCUS_MIN_DOCS = 2
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 进 Supporting 的正文命中,同一个词至少要在正文里出现几次。
|
|
122
|
+
*
|
|
123
|
+
* `2` 是**实测定下来的**:取 `1` 时「什么话题都提一句」的归档长文会进每一条任务的
|
|
124
|
+
* Supporting;取 `3` 会误杀合理的支撑材料(`docs/api-contract.md` 在任务 3 里
|
|
125
|
+
* 「返回」正好 2 次)。见 `context.js` 文件头「三个真实教训」。
|
|
126
|
+
*/
|
|
127
|
+
const STRONG_BODY_TF = 2
|
|
128
|
+
|
|
129
|
+
/** 判定「话题词」时最多回看多少条结果 —— 名次更靠后的提及不构成焦点。 */
|
|
130
|
+
const FOCUS_WINDOW = 8
|
|
131
|
+
|
|
132
|
+
/* ── 代码角色识别 ───────────────────────────────────── */
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 角色规则表。**顺序即优先级** —— 一篇文章同时像测试又像文档时,
|
|
136
|
+
* 靠前的赢,保证同一篇每次拿到同一个角色。
|
|
137
|
+
*
|
|
138
|
+
* 这些不是「智能识别」:就是路径与文件名的字面规则,可以逐条解释给用户听。
|
|
139
|
+
* 放在 Markdown 语料上,命中的多是 SDD / 设计笔记这类**描述实现**的文档 ——
|
|
140
|
+
* 「对应实现文件」这句解释说的正是「它是那份实现的文字载体」。
|
|
141
|
+
*
|
|
142
|
+
* ⚠️ `design` 必须排在 `impl` **前面**,因为两条规则可能同时命中一条完整路径 ——
|
|
143
|
+
* 例如 `src/host/design.md` 既在 `src/` 下、文件名又明说「这是设计」,必须取 `design`。
|
|
144
|
+
* 顺序写反时,`design` 永远轮不到。
|
|
145
|
+
* (注意 `docs/relevance-algorithm.md` **不属于**这种冲突:它两条规则只命中 `impl` 一条 ——
|
|
146
|
+
* 「文档里描述了某个模块」就是 impl 角色的本意,见 `test/context.test.mjs` 的对照断言。)
|
|
147
|
+
*/
|
|
148
|
+
const SOURCE_RULES = [
|
|
149
|
+
// 测试 / 评测 / 夹具。分隔符允许 `/` 与 `-`:`test/` 与 `eval-benchmark.md` 都是真实写法。
|
|
150
|
+
{ type: 'test', re: /(^|[\/-])(test|tests|spec|specs|__tests__|eval|evals|fixtures?)([\/-]|$)|[.-](test|spec)\.|fixture/i },
|
|
151
|
+
// 配置 / 契约 / 清单
|
|
152
|
+
{ type: 'config', re: /(^|\/)(package\.json|package-lock\.json|pnpm-lock\.yaml|cordis\.patch\.yml|tsconfig|\.github)(\/|$|\.)|(^|\/)(config|settings|manifest)/i },
|
|
153
|
+
// 设计 / 决策 / 复盘
|
|
154
|
+
{ type: 'design', re: /(sdd|prd|rfc|adr|design|spec-|方案|设计|决策|复盘)/i },
|
|
155
|
+
// 实现 / 宿主 / 接口
|
|
156
|
+
{ type: 'impl', re: /(^|\/)(src|lib|host|client|impl|runtime)(\/|$)|(^|\/)(api|tool|links|relevance|context|index)[\w.-]*\.md$/i },
|
|
157
|
+
// 文档 / 说明 / 清单
|
|
158
|
+
{ type: 'doc', re: /(^|\/)(docs?|guide|manual|readme|changelog|notes?)[\w.-]*\.md$|readme|changelog|\.md$/i },
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 判定一篇文档在项目里是什么角色。
|
|
163
|
+
* @param {string} rel - 工作区相对路径
|
|
164
|
+
* @returns {'impl'|'test'|'config'|'design'|'doc'} 角色
|
|
165
|
+
*/
|
|
166
|
+
export function sourceTypeOf(rel) {
|
|
167
|
+
const value = String(rel || '')
|
|
168
|
+
if (!value) return 'doc'
|
|
169
|
+
for (const rule of SOURCE_RULES) {
|
|
170
|
+
if (rule.re.test(value)) return rule.type
|
|
171
|
+
}
|
|
172
|
+
return 'doc'
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/* ── 与 Primary 的引用关系 ─────────────────────────── */
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 把引用图里某一篇的邻居取出来(出边 + 入边),去重、去掉自己。
|
|
179
|
+
*
|
|
180
|
+
* 图可能不存在(`/api/recent` 那条路不建图,成本要留给真正需要的接口),
|
|
181
|
+
* 这时返回空集合 —— 分层退化成「只看命中」,而不是报错。
|
|
182
|
+
*
|
|
183
|
+
* @param {object|undefined} graph - `buildLinkGraph()` 的产物
|
|
184
|
+
* @param {string} rel - 文档 rel
|
|
185
|
+
* @returns {Set<string>} 邻居 rel 集合
|
|
186
|
+
*/
|
|
187
|
+
function neighboursOf(graph, rel) {
|
|
188
|
+
const out = new Set()
|
|
189
|
+
if (!graph || !(graph.out instanceof Map) || !(graph.in instanceof Map)) return out
|
|
190
|
+
for (const side of [graph.out.get(rel), graph.in.get(rel)]) {
|
|
191
|
+
if (!(side instanceof Set)) continue
|
|
192
|
+
for (const other of side) {
|
|
193
|
+
if (other && other !== rel) out.add(other)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return out
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/* ── 理由(为什么它在这个包里)─────────────────────── */
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 命中词分几个字段。
|
|
203
|
+
* @param {{title:boolean,summary:boolean,body:boolean}|undefined} fields - 字段位图
|
|
204
|
+
* @returns {number} 0..3
|
|
205
|
+
*/
|
|
206
|
+
function fieldCount(fields) {
|
|
207
|
+
if (!fields) return 0
|
|
208
|
+
return (fields.title ? 1 : 0) + (fields.summary ? 1 : 0) + (fields.body ? 1 : 0)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 给一篇文档算「它凭什么在这个包里」。
|
|
213
|
+
*
|
|
214
|
+
* 返回值是一个**结构化理由**:`{ code, terms, fields }`。
|
|
215
|
+
* 文案不由宿主生成 —— 宿主只给码,界面语言由客户端词典负责(AGENTS.md §4.5)。
|
|
216
|
+
*
|
|
217
|
+
* 判定顺序是**固定的**,所以同一篇文档每次拿到同一个理由:
|
|
218
|
+
*
|
|
219
|
+
* 1. `direct` —— 命中标题,且命中 ≥2 个话题词:作者把它写进标题、你还问了不止一个词
|
|
220
|
+
* 2. `titleMatch` —— 命中标题
|
|
221
|
+
* 3. `summaryMatch`—— 命中摘要(没有标题命中时)
|
|
222
|
+
* 4. `bodyMatch` —— 只在正文命中(`fields` 是**焦点词**的正文命中个数,能区分
|
|
223
|
+
* 「真的在讲」与「正文里蹭了一下」,且不暴露 BM25 分数)
|
|
224
|
+
* 5. `linkTarget` —— 被某个 Primary 引用
|
|
225
|
+
* 6. `linkSource` —— 引用了某个 Primary
|
|
226
|
+
* 7. `related` —— 兜底:名次靠后的命中项
|
|
227
|
+
*
|
|
228
|
+
* @param {object} doc - 记录(`{rel, matchedTerms}`;`matchedTerms[].fields` 是字段位图)
|
|
229
|
+
* @param {{linkTarget?:boolean, linkSource?:boolean}} [links] - 与 Primary 的关系
|
|
230
|
+
* @returns {{code:string, terms:string[], fields:number, term:string}} 理由
|
|
231
|
+
*/
|
|
232
|
+
export function explainContext(doc, links = {}) {
|
|
233
|
+
const terms = Array.isArray(doc && doc.matchedTerms) ? doc.matchedTerms : []
|
|
234
|
+
const names = terms.map((t) => t.term)
|
|
235
|
+
const merged = { title: false, summary: false, body: false }
|
|
236
|
+
let titleTerm = ''
|
|
237
|
+
let bodyTerm = ''
|
|
238
|
+
let bodyHits = 0
|
|
239
|
+
for (const entry of terms) {
|
|
240
|
+
const fields = entry.fields || {}
|
|
241
|
+
// 只记「有没有命中」,不记次数 —— 次数是 BM25 的内部量,不对外。
|
|
242
|
+
if (fields.title) {
|
|
243
|
+
merged.title = true
|
|
244
|
+
if (!titleTerm) titleTerm = entry.term
|
|
245
|
+
}
|
|
246
|
+
if (fields.summary) merged.summary = true
|
|
247
|
+
if (fields.body) {
|
|
248
|
+
merged.body = true
|
|
249
|
+
bodyHits += 1
|
|
250
|
+
if (!bodyTerm) bodyTerm = entry.term
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const total = fieldCount(merged)
|
|
254
|
+
|
|
255
|
+
if (merged.title) {
|
|
256
|
+
return {
|
|
257
|
+
code: merged.title && names.length >= 2 ? 'direct' : 'titleMatch',
|
|
258
|
+
terms: names,
|
|
259
|
+
fields: total,
|
|
260
|
+
term: titleTerm || names[0] || '',
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (merged.summary) {
|
|
264
|
+
return { code: 'summaryMatch', terms: names, fields: total, term: names[0] || '' }
|
|
265
|
+
}
|
|
266
|
+
if (names.length > 0) {
|
|
267
|
+
return { code: 'bodyMatch', terms: names, fields: bodyHits, term: bodyTerm || names[0] }
|
|
268
|
+
}
|
|
269
|
+
if (links.linkTarget) return { code: 'linkTarget', terms: [], fields: 0, term: '' }
|
|
270
|
+
if (links.linkSource) return { code: 'linkSource', terms: [], fields: 0, term: '' }
|
|
271
|
+
return { code: 'related', terms: [], fields: 0, term: '' }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* 理由的强弱:越小越靠前。仅用于**同一层内**排序时的兜底(名次相同时才看它),
|
|
276
|
+
* 不是分数,也不对外暴露。
|
|
277
|
+
*/
|
|
278
|
+
const REASON_ORDER = {
|
|
279
|
+
direct: 0,
|
|
280
|
+
titleMatch: 1,
|
|
281
|
+
summaryMatch: 2,
|
|
282
|
+
bodyMatch: 3,
|
|
283
|
+
linkTarget: 4,
|
|
284
|
+
linkSource: 5,
|
|
285
|
+
related: 6,
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/* ── 主函数 ─────────────────────────────────────────── */
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 从一次检索结果装配出 Context Pack。
|
|
292
|
+
*
|
|
293
|
+
* **纯函数**:不读盘、不看时钟、不发请求。`ranked` 必须是
|
|
294
|
+
* `rankByRelevance()` 的文档数组(已按相关度降序,且带 `matchedTerms`)。
|
|
295
|
+
*
|
|
296
|
+
* @param {object} input - 装配输入
|
|
297
|
+
* @param {Array<object>} input.ranked - 相关度降序的文档(`rankByRelevance().docs`)
|
|
298
|
+
* @param {string} [input.topic] - 当前话题标签(`topicLabel()` 的产物)
|
|
299
|
+
* @param {object} [input.graph] - `buildLinkGraph()` 的产物;不给就退化成「只看命中」
|
|
300
|
+
* @param {number} [input.maxPrimary] - 覆盖 Primary 上限(默认 `MAX_PRIMARY` = 1)
|
|
301
|
+
* @param {number} [input.maxSupporting] - 覆盖 Supporting 上限(默认 `MAX_SUPPORTING` = 3)
|
|
302
|
+
* @param {number} [input.maxRelated] - 覆盖 Related 上限(默认 `MAX_RELATED` = 5)
|
|
303
|
+
* @param {number} [input.total] - 整个工作区一共有多少篇(只进 `totals.total`)
|
|
304
|
+
* @param {string} [input.task] - 当前任务的**原文引用**(最新一条有实质内容的用户消息)。
|
|
305
|
+
* 本模块不生成它、也不改写它;不给就是空串。
|
|
306
|
+
* @returns {object} Context Pack(见文件头;`items` 里只有 `rel/title/summary/mtimeMs/kind/source/reason`)
|
|
307
|
+
*/
|
|
308
|
+
export function buildContext(input = {}) {
|
|
309
|
+
const ranked = Array.isArray(input.ranked) ? input.ranked.filter(Boolean) : []
|
|
310
|
+
const graph = input.graph
|
|
311
|
+
const topic = typeof input.topic === 'string' ? input.topic : ''
|
|
312
|
+
// `task` 原样透传 —— 它可能很长、可能为空,这里一个字都不加工(加工就是编造)。
|
|
313
|
+
const task = typeof input.task === 'string' ? input.task : ''
|
|
314
|
+
const capPrimary = Number.isInteger(input.maxPrimary) && input.maxPrimary > 0
|
|
315
|
+
? input.maxPrimary : MAX_PRIMARY
|
|
316
|
+
const capSupporting = Number.isInteger(input.maxSupporting) && input.maxSupporting > 0
|
|
317
|
+
? input.maxSupporting : MAX_SUPPORTING
|
|
318
|
+
const capRelated = Number.isInteger(input.maxRelated) && input.maxRelated > 0
|
|
319
|
+
? input.maxRelated : MAX_RELATED
|
|
320
|
+
|
|
321
|
+
const topRaw = ranked.reduce((max, doc) => Math.max(max, Number(doc.raw) || 0), 0)
|
|
322
|
+
|
|
323
|
+
// 内部记录:**只带下游真正要用的字段**,不把 haystack / matchedTerms / raw 传出去。
|
|
324
|
+
const records = ranked.map((doc, index) => {
|
|
325
|
+
const terms = Array.isArray(doc.matchedTerms) ? doc.matchedTerms : []
|
|
326
|
+
const fields = { title: false, summary: false, body: false }
|
|
327
|
+
for (const entry of terms) {
|
|
328
|
+
const f = entry.fields || {}
|
|
329
|
+
if (f.title) fields.title = true
|
|
330
|
+
if (f.summary) fields.summary = true
|
|
331
|
+
if (f.body) fields.body = true
|
|
332
|
+
}
|
|
333
|
+
const raw = Number(doc.raw) || 0
|
|
334
|
+
return {
|
|
335
|
+
rel: String(doc.rel || ''),
|
|
336
|
+
title: String(doc.title || doc.name || doc.rel || ''),
|
|
337
|
+
summary: doc.summary == null ? '' : String(doc.summary),
|
|
338
|
+
mtimeMs: Number.isFinite(doc.mtimeMs) ? doc.mtimeMs : 0,
|
|
339
|
+
kind: doc.kind || 'md',
|
|
340
|
+
source: sourceTypeOf(doc.rel),
|
|
341
|
+
terms: terms.map((t) => t.term),
|
|
342
|
+
// 逐词的字段位图,原样留着给 `explainContext()` 用(合并后的 `fields` 只服务分层判断)
|
|
343
|
+
termFields: terms.map((t) => ({ term: t.term, fields: t.fields || {} })),
|
|
344
|
+
fields,
|
|
345
|
+
raw,
|
|
346
|
+
// 相关度带宽(占本批最高 raw 的比例)。**只在函数内部用来判 Primary 的强度下限**,
|
|
347
|
+
// 不出现在任何返回值里。
|
|
348
|
+
strength: topRaw > 0 ? raw / topRaw : 0,
|
|
349
|
+
rank: index,
|
|
350
|
+
}
|
|
351
|
+
})
|
|
352
|
+
|
|
353
|
+
// 命中了话题的篇(`raw > 0`)。**只有它们才有资格进任何一层** ——
|
|
354
|
+
// 零命中的文档只能靠「与 Primary 的引用关系」被带进 Supporting / Related(见下)。
|
|
355
|
+
const hit = records.filter((r) => r.raw > 0)
|
|
356
|
+
|
|
357
|
+
/* ── 焦点词 ─────────────────────────────────────────
|
|
358
|
+
* 一个话题词在这批结果的前 `FOCUS_WINDOW` 篇里**至少两篇**命中,才算「项目里真的
|
|
359
|
+
* 还有别处在讲它」—— 只有它才能把一个**正文**命中抬到 Supporting。
|
|
360
|
+
*
|
|
361
|
+
* 为什么用「结果集内部的提及次数」而不是语料 df 比例:结果集就是「这批结果正在
|
|
362
|
+
* 讨论什么」的直接证据,两者同源;而 df 比例要挑一个(0.2?0.3?)拍出来的阈值。
|
|
363
|
+
*/
|
|
364
|
+
const mentionCount = new Map()
|
|
365
|
+
for (const record of records.slice(0, FOCUS_WINDOW)) {
|
|
366
|
+
for (const term of record.terms) mentionCount.set(term, (mentionCount.get(term) || 0) + 1)
|
|
367
|
+
}
|
|
368
|
+
const isFocusTerm = (term) => (mentionCount.get(term) || 0) >= FOCUS_MIN_DOCS
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* 落脚点:有没有话题词命中**标题或摘要**。
|
|
372
|
+
* 这是「这篇就是在讲这件事」的作者信号 —— 只在正文提一句不算。
|
|
373
|
+
*/
|
|
374
|
+
const grounded = (record) => record.fields.title || record.fields.summary
|
|
375
|
+
|
|
376
|
+
/* ── 深入命中(docHit)─────────────────────────────
|
|
377
|
+
* 一个焦点词还要满足:这一篇是**把它讲得最多**的那一篇(全批正文字频最大),
|
|
378
|
+
* 且至少 `STRONG_BODY_TF` 次。
|
|
379
|
+
*
|
|
380
|
+
* 这条是分层里最关键的一道闸门,也是**实测定下来的**:
|
|
381
|
+
* `FOCUS_MIN_DOCS` 只证明「不止一篇提到它」,证明不了「这一篇在讲它」。
|
|
382
|
+
* 「什么话题都提一句」的归档长文满足前一条(每个词都提到一次),
|
|
383
|
+
* 但每一个词都在别处被讲得更多 —— 于是它对**任何**任务都进不了 Supporting。
|
|
384
|
+
* 没有它,那篇长文会出现在每一条任务的 Supporting 里。
|
|
385
|
+
*
|
|
386
|
+
* 用的是**正文字频**(不是 BM25 分数),不进对外输出,只决定资格。
|
|
387
|
+
*/
|
|
388
|
+
const maxBodyTf = new Map()
|
|
389
|
+
for (const record of records) {
|
|
390
|
+
for (const entry of record.termFields) {
|
|
391
|
+
const f = entry.fields || {}
|
|
392
|
+
if (!f.body) continue
|
|
393
|
+
const best = maxBodyTf.get(entry.term) || 0
|
|
394
|
+
if ((f.bodyTf || 0) > best) maxBodyTf.set(entry.term, f.bodyTf || 0)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const isDocHit = (record) => record.termFields.some((entry) => {
|
|
398
|
+
const f = entry.fields || {}
|
|
399
|
+
if (!f.body) return false
|
|
400
|
+
const tf = f.bodyTf || 0
|
|
401
|
+
return tf >= STRONG_BODY_TF && tf >= (maxBodyTf.get(entry.term) || 0)
|
|
402
|
+
})
|
|
403
|
+
|
|
404
|
+
/* ── Primary ────────────────────────────────────────
|
|
405
|
+
* 三个条件**同时**成立才进 —— 见文件头表格。`capPrimary` 是硬上限。 */
|
|
406
|
+
const primary = []
|
|
407
|
+
const bodyOnly = []
|
|
408
|
+
for (const record of hit) {
|
|
409
|
+
const qualifies = grounded(record) && record.strength >= PRIMARY_MIN_SHARE
|
|
410
|
+
if (qualifies && primary.length < capPrimary) primary.push(record)
|
|
411
|
+
else bodyOnly.push(record)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// Primary 之间:先按名次(相关度本身就是主排序)。
|
|
415
|
+
// ⚠️ **不要**为了「看起来更像主文档」再按词的个数排一次 —— 那是第二套打分。
|
|
416
|
+
primary.sort((a, b) => a.rank - b.rank)
|
|
417
|
+
|
|
418
|
+
const primaryRels = new Set(primary.map((r) => r.rel))
|
|
419
|
+
|
|
420
|
+
/* ── Supporting ─────────────────────────────────────
|
|
421
|
+
* 两种来源:① 有**焦点词的正文命中**(真命中,只是没有落脚点);
|
|
422
|
+
* ② 与某个 Primary 有引用关系。② 里可能包含**零命中**的文档
|
|
423
|
+
* (比如 README 引用了主文档)—— 它们的理由会是 `linkTarget` / `linkSource`,
|
|
424
|
+
* 而不是伪装成命中。 */
|
|
425
|
+
const supporting = []
|
|
426
|
+
const seenSupporting = new Set(primaryRels)
|
|
427
|
+
for (const record of bodyOnly) {
|
|
428
|
+
if (supporting.length >= capSupporting) break
|
|
429
|
+
if (!isDocHit(record)) continue
|
|
430
|
+
if (seenSupporting.has(record.rel)) continue
|
|
431
|
+
seenSupporting.add(record.rel)
|
|
432
|
+
supporting.push({ record, linkTarget: false, linkSource: false })
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const byRel = new Map(records.map((r) => [r.rel, r]))
|
|
436
|
+
const linkedToPrimary = []
|
|
437
|
+
if (graph instanceof Object && supporting.length < capSupporting) {
|
|
438
|
+
// 邻居按「对方的 BM25 名次」排 —— 名次靠前的先看,且顺序确定。
|
|
439
|
+
const seenLink = new Set()
|
|
440
|
+
for (const anchor of primary) {
|
|
441
|
+
for (const other of neighboursOf(graph, anchor.rel)) {
|
|
442
|
+
if (seenLink.has(other) || primaryRels.has(other)) continue
|
|
443
|
+
seenLink.add(other)
|
|
444
|
+
const record = byRel.get(other)
|
|
445
|
+
// 图里有、但这一批语料里没有的(被 limit 切掉的)不硬凑。
|
|
446
|
+
if (!record) continue
|
|
447
|
+
linkedToPrimary.push({
|
|
448
|
+
record,
|
|
449
|
+
linkTarget: (graph.out.get(anchor.rel) || new Set()).has(other),
|
|
450
|
+
linkSource: (graph.in.get(anchor.rel) || new Set()).has(other),
|
|
451
|
+
})
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
for (const entry of linkedToPrimary) {
|
|
456
|
+
if (supporting.length >= capSupporting) break
|
|
457
|
+
if (seenSupporting.has(entry.record.rel)) continue
|
|
458
|
+
seenSupporting.add(entry.record.rel)
|
|
459
|
+
supporting.push(entry)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/* ── Related ────────────────────────────────────────
|
|
463
|
+
* 有命中、但没进上面两层的;再补上「引用了 Primary / 被 Primary 引用」的其余邻居。
|
|
464
|
+
*
|
|
465
|
+
* ⚠️ **只走 `hit`,不走 `noHit`**(2026-09-29 改,对齐 PRD §5 / SDD §25)。
|
|
466
|
+
* PRD §5 对 Related 的定义是「**与当前任务有关**,但没有足够证据进入 Primary / Supporting 的资料」——
|
|
467
|
+
* 一个话题词都没命中、又没有引用关系的文档**不是「有关」**,它只是「工作区里还有这一篇」。
|
|
468
|
+
* 放进来会让它带着兜底理由码 `related` 出场,而客户端把那句翻译成
|
|
469
|
+
* 「与当前工作区相关」—— 那正是需求 §九 明令禁止的「可能对你有帮助」(无法验证的推断)。
|
|
470
|
+
* ⇒ 每个进包的东西都要能说出凭什么;说不出就**不出场**(Related 允许为空)。
|
|
471
|
+
* `explainContext()` 里的 `related` 兜底码因此在本装配路径上不再产生,
|
|
472
|
+
* 但保留它:那个函数是纯函数,可以被独立调用。 */
|
|
473
|
+
const related = []
|
|
474
|
+
const seenRelated = new Set([...seenSupporting])
|
|
475
|
+
for (const record of hit) {
|
|
476
|
+
if (related.length >= capRelated) break
|
|
477
|
+
if (seenRelated.has(record.rel)) continue
|
|
478
|
+
seenRelated.add(record.rel)
|
|
479
|
+
related.push({ record, linkTarget: false, linkSource: false })
|
|
480
|
+
}
|
|
481
|
+
if (graph instanceof Object && related.length < capRelated) {
|
|
482
|
+
for (const anchor of primary) {
|
|
483
|
+
for (const other of neighboursOf(graph, anchor.rel)) {
|
|
484
|
+
if (related.length >= capRelated) break
|
|
485
|
+
if (seenRelated.has(other)) continue
|
|
486
|
+
const record = byRel.get(other)
|
|
487
|
+
if (!record) continue
|
|
488
|
+
seenRelated.add(other)
|
|
489
|
+
related.push({
|
|
490
|
+
record,
|
|
491
|
+
linkTarget: (graph.out.get(anchor.rel) || new Set()).has(other),
|
|
492
|
+
linkSource: (graph.in.get(anchor.rel) || new Set()).has(other),
|
|
493
|
+
})
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* 把内部记录投影成对外的条目:**只有 rel / title / summary / mtimeMs / kind / source / reason**。
|
|
500
|
+
* `raw` / `strength` / `terms` / `fields` 一个都不出去 —— 名次本身就是答案。
|
|
501
|
+
*/
|
|
502
|
+
const project = (entry) => {
|
|
503
|
+
const record = entry.record
|
|
504
|
+
return {
|
|
505
|
+
rel: record.rel,
|
|
506
|
+
title: record.title,
|
|
507
|
+
summary: record.summary,
|
|
508
|
+
mtimeMs: record.mtimeMs,
|
|
509
|
+
kind: record.kind,
|
|
510
|
+
source: record.source,
|
|
511
|
+
reason: explainContext(
|
|
512
|
+
{ rel: record.rel, matchedTerms: record.termFields },
|
|
513
|
+
entry,
|
|
514
|
+
),
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** 同一层内:名次优先;名次相同按理由强弱;再相同按 rel 字典序(确定性兜底)。 */
|
|
519
|
+
const orderTier = (entries) => entries
|
|
520
|
+
.map((entry) => ({ entry, item: project(entry) }))
|
|
521
|
+
.sort((a, b) => {
|
|
522
|
+
if (a.entry.record.rank !== b.entry.record.rank) return a.entry.record.rank - b.entry.record.rank
|
|
523
|
+
const ra = REASON_ORDER[a.item.reason.code] ?? 99
|
|
524
|
+
const rb = REASON_ORDER[b.item.reason.code] ?? 99
|
|
525
|
+
if (ra !== rb) return ra - rb
|
|
526
|
+
return a.item.rel < b.item.rel ? -1 : a.item.rel > b.item.rel ? 1 : 0
|
|
527
|
+
})
|
|
528
|
+
.map((wrapped) => wrapped.item)
|
|
529
|
+
|
|
530
|
+
const primaryItems = orderTier(primary.map((r) => ({ record: r, linkTarget: false, linkSource: false })))
|
|
531
|
+
const supportingItems = orderTier(supporting)
|
|
532
|
+
const relatedItems = orderTier(related)
|
|
533
|
+
|
|
534
|
+
return {
|
|
535
|
+
mode: 'relevance',
|
|
536
|
+
topic,
|
|
537
|
+
// **引用,不是推断**(SDD §12):调用方把「最新一条有实质内容的用户消息」原文递进来,
|
|
538
|
+
// 这里原样带出。填一个猜出来的「任务」比空着更糟 —— 它不可验证,
|
|
539
|
+
// 而 Context Pack 的全部价值就是「每条都能说出凭什么」。
|
|
540
|
+
// 空串是合法值:显式 query 路径(`knit_docs(query)`)就没有对话可引用。
|
|
541
|
+
task,
|
|
542
|
+
primary: primaryItems,
|
|
543
|
+
supporting: supportingItems,
|
|
544
|
+
related: relatedItems,
|
|
545
|
+
totals: {
|
|
546
|
+
primary: primaryItems.length,
|
|
547
|
+
supporting: supportingItems.length,
|
|
548
|
+
related: relatedItems.length,
|
|
549
|
+
// 本批语料里**命中了话题**的篇数。
|
|
550
|
+
matched: hit.length,
|
|
551
|
+
// 整个工作区一共有多少篇(由调用方给全量数;不给就是这一批的条数)。
|
|
552
|
+
// 与 `knit_docs` 头部的 `of N Markdown documents` 是同一个口径。
|
|
553
|
+
total: Number.isInteger(input.total) && input.total >= 0 ? input.total : records.length,
|
|
554
|
+
},
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/*
|
|
559
|
+
* ⚠️ 这里**故意没有** `renderContextText()`。
|
|
560
|
+
*
|
|
561
|
+
* v0.14 开发中曾有一个把 Context Pack 压成文本的渲染函数,但它是**第二个渲染器**:
|
|
562
|
+
* 模型真正看到的是 `tool.js` 的 `renderToolText()`(`src/host/tool.js:328`),
|
|
563
|
+
* 而 `tool.js:452` 的 `render:` 只把那段文本塞进返回信封 —— 结构化 JSON 模型看不见。
|
|
564
|
+
* 两个渲染器必然漂移(层标题、理由文案、`of N` 的口径都会各走各的),
|
|
565
|
+
* 于是这个函数从未被任何代码调用过(`src/` / `test/` / `tools/` 全查过),已被删除。
|
|
566
|
+
*
|
|
567
|
+
* ⇒ **要改模型看到的文本,改 `tool.js`;不要在这里再造一个渲染器。**
|
|
568
|
+
*/
|