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/src/host/tool.js CHANGED
@@ -58,6 +58,15 @@ const SNIPPET_CHARS = 200
58
58
  */
59
59
  const SNIPPET_WINDOW = 2500
60
60
 
61
+ /**
62
+ * 「工作区里有文档,但当前话题一个词都没命中」时补的那句真话。
63
+ *
64
+ * 拼自 `SNIPPET_WINDOW` 而不是再抄一遍 2500 —— 这个窗口在本仓库已经有两份
65
+ * (`index.js` 的 `HAYSTACK_CHARS` 和这里的 `SNIPPET_WINDOW`),不要有第三份。
66
+ */
67
+ const HAYSTACK_NOTE =
68
+ `Matches come from the first ${SNIPPET_WINDOW} characters of each file; use grep for anything deeper.`
69
+
61
70
  /**
62
71
  * 模型面向的描述。**必须短** —— 它会进每一次请求的系统提示词。
63
72
  *
@@ -76,11 +85,11 @@ const SNIPPET_WINDOW = 2500
76
85
  * 所以描述要点名两件它自己做不到的事:**稀有词权重**(不是数次数)
77
86
  * 与**不依赖文件名**。最后一句是行为引导 —— 直说「别自己来」。
78
87
  */
79
- const DESCRIPTION = 'List Markdown documents that already exist in this project, '
80
- + 'ranked by relevance to the current conversation (or to an explicit query). '
81
- + 'The ranking weighs rare terms above common ones and normalizes document length, '
82
- + 'so it beats matching filenames or counting keyword hits — prefer it to doing that yourself. '
83
- + 'Reads the workspace only; stores nothing and calls no model.'
88
+ const DESCRIPTION = 'Project context for the current task, from the workspace Markdown: '
89
+ + 'primary (read first) / supporting (evidence, implementation) / related. '
90
+ + 'Ranked by IDF-weighted relevance to the conversation (or an explicit query), then split '
91
+ + 'by deterministic local rules — prefer it to globbing filenames or counting keyword hits. '
92
+ + 'Reads the workspace only; stores nothing, calls no model.'
84
93
 
85
94
  /**
86
95
  * 参数 schema。与 `defineTool` 的编译产物逐字一致
@@ -95,7 +104,8 @@ const PARAMETERS = {
95
104
  },
96
105
  limit: {
97
106
  type: 'integer',
98
- description: `How many documents to return (1-${MAX_LIMIT}, default ${DEFAULT_LIMIT}).`,
107
+ description: `How many documents to consider (1-${MAX_LIMIT}, default ${DEFAULT_LIMIT}). `
108
+ + 'They are grouped into the context tiers, not returned as one flat list.',
99
109
  },
100
110
  },
101
111
  }
@@ -105,17 +115,89 @@ const PARAMETERS = {
105
115
  * 相关度是**相对**分数(永远有一篇 100%,且每次刷新可能换人当),
106
116
  * 面板里就不显示它,给模型看只会更糟 —— 它会把 86 当成绝对置信度去推理。
107
117
  * **顺序即相关度。**
118
+ *
119
+ * v0.14:从「一列文档」变成**三层 Context Pack**。结构变了,纪律没变 ——
120
+ * 仍然不返回分数、不返回正文、不返回绝对路径、不返回 haystack、不返回 embedding。
121
+ * 新增的 `reason` 是**结构化理由**(码 + 命中的词),不是自然语言推断:
122
+ * 宿主只给码,模型自己就能看懂 `direct` / `linkTarget` / `testSupport` 是什么意思。
108
123
  */
124
+ const ITEM_SCHEMA = {
125
+ type: 'object',
126
+ additionalProperties: false,
127
+ properties: {
128
+ rel: { type: 'string' },
129
+ title: { type: 'string' },
130
+ summary: { type: 'string' },
131
+ mtimeMs: { type: 'integer' },
132
+ // 项目里的角色:impl / test / config / design / doc。纯路径规则,不是内容理解。
133
+ source: { type: 'string', enum: ['impl', 'test', 'config', 'design', 'doc'] },
134
+ // 条目是什么:md / image / video。
135
+ // ⚠️ **故意不给它 enum**。取值集合归 `index.js` 的 `kindOfName()` 所有;
136
+ // 在这里钉一份名单,等于以后每加一种文件类型就让工具在**校验层**静默失败一次。
137
+ // v0.14 正是这么坏掉的:`kind` 当时压根没被声明,而 schema 是 `additionalProperties: false`。
138
+ kind: { type: 'string' },
139
+ reason: {
140
+ type: 'object',
141
+ additionalProperties: false,
142
+ properties: {
143
+ // 为什么它在这个包里。全部来自确定性事实(命中字段 / 引用关系 / 文件角色)。
144
+ code: {
145
+ type: 'string',
146
+ enum: [
147
+ 'direct', 'titleMatch', 'summaryMatch', 'bodyMatch',
148
+ 'linkTarget', 'linkSource', 'related',
149
+ ],
150
+ },
151
+ // 命中的话题词(没有命中就是空数组 —— 不编造)。
152
+ terms: { type: 'array', items: { type: 'string' } },
153
+ // 命中跨了几个字段(0–3)。
154
+ fields: { type: 'integer' },
155
+ // 那句话的代表词:标题命中时取标题里那个词,正文命中时取正文里那个词。
156
+ // 与 `terms` 的区别是它是**单个**。
157
+ term: { type: 'string' },
158
+ },
159
+ // `term` 在 `explainContext()` 的每条分支上都有值(取不到时是空串),
160
+ // 所以它是 required,不是 optional —— schema 要如实描述。
161
+ required: ['code', 'terms', 'fields', 'term'],
162
+ },
163
+ // v0.11:命中的那一小段**原文**(不是整篇)。**可选** ——
164
+ // 时间序模式没有命中词,抽不出来就不带这个字段,
165
+ // 而不是给个空串假装有。
166
+ snippet: { type: 'string' },
167
+ },
168
+ // `kind` 也是 required:`buildContext()` 每条都给了(取不到时回落 `'md'`)。
169
+ // 声明成可选就等于允许「有的条目有 kind、有的没有」这种形状漂移。
170
+ required: ['rel', 'title', 'summary', 'mtimeMs', 'kind', 'source', 'reason'],
171
+ }
172
+
109
173
  const OUTPUT_SCHEMA = {
110
174
  type: 'object',
111
175
  additionalProperties: false,
112
176
  properties: {
113
177
  mode: { type: 'string', enum: ['relevance', 'time'] },
114
178
  topic: { type: 'string' },
115
- // 工作区里**一共有多少篇**(不是返回了几条)。
116
- // 给这个数是为了让模型知道结果不是「随便挑的几条」,不必再自己 glob 一遍
117
- // 做交叉验证 —— v0.8,依据是真机验收里观察到的行为。
179
+ // 本批语料里**一共有多少篇** Markdown —— 让模型知道这不是「随便挑的几条」,
180
+ // 不必再自己 glob 一遍做交叉验证(v0.8,依据是真机验收里观察到的行为)。
118
181
  total: { type: 'integer' },
182
+ // v0.14:三层。`primary` 是「先读这几篇」,`supporting` 是「证据 / 实现 / 下一步」,
183
+ // `related` 是「背景,不要从这里开始」。名字与面板逐字一致。
184
+ primary: { type: 'array', items: ITEM_SCHEMA },
185
+ supporting: { type: 'array', items: ITEM_SCHEMA },
186
+ related: { type: 'array', items: ITEM_SCHEMA },
187
+ // 渲染头部那条「N matching documents」用的计数。**它不是分数** ——
188
+ // 只是「本批语料里命中了几篇 / 一共有几篇」,给模型一个「有没有漏」的锚。
189
+ // 只有 relevance 模式有,所以不在 `required` 里。
190
+ totals: {
191
+ type: 'object',
192
+ additionalProperties: false,
193
+ properties: {
194
+ matched: { type: 'integer' },
195
+ total: { type: 'integer' },
196
+ },
197
+ required: ['matched', 'total'],
198
+ },
199
+ // 时间序(对话内容还不足,退回一列「最近改动的」)走这条。**形状比三层窄** ——
200
+ // 没有命中词,就没有 `source` / `reason` 可给,不编造。只有 time 模式有。
119
201
  docs: {
120
202
  type: 'array',
121
203
  items: {
@@ -126,16 +208,13 @@ const OUTPUT_SCHEMA = {
126
208
  title: { type: 'string' },
127
209
  summary: { type: 'string' },
128
210
  mtimeMs: { type: 'integer' },
129
- // v0.11:命中的那一小段**原文**(不是整篇)。**可选** ——
130
- // 时间序模式没有命中词,抽不出来就不带这个字段,
131
- // 而不是给个空串假装有。
132
211
  snippet: { type: 'string' },
133
212
  },
134
213
  required: ['rel', 'title', 'summary', 'mtimeMs'],
135
214
  },
136
215
  },
137
216
  },
138
- required: ['mode', 'topic', 'total', 'docs'],
217
+ required: ['mode', 'topic', 'total', 'primary', 'supporting', 'related'],
139
218
  }
140
219
 
141
220
  /**
@@ -274,7 +353,7 @@ export function pickSnippet(text, terms, options = {}) {
274
353
  }
275
354
 
276
355
  /**
277
- * 把工具结果渲染成模型看的文本。
356
+ * 把 Context Pack 渲染成模型看的文本。
278
357
  *
279
358
  * **英文**:模型面向文本要的是词表稳定,不跟随界面语言 —— 官方工具
280
359
  * (`todo_write`、`present`)也都是英文硬编码。这不是 i18n 违约:
@@ -283,37 +362,104 @@ export function pickSnippet(text, terms, options = {}) {
283
362
  * **头部要说清「一共多少篇」**(v0.8):真机验收里 agent 每次拿到结果都还要
284
363
  * 自己 `find` 一遍来确认没漏 —— 把总数写在第一行,是为了消掉这次多余的调用。
285
364
  *
286
- * @param {{mode: string, topic: string, total?: number, docs: Array<object>}} value - 工具结果
365
+ * **v0.14 改的是什么**:以前是一条按相关度排的平铺列表(`Top 5 of 23 …`),
366
+ * 现在是一条**带层级的任务上下文**(Primary / Supporting / Related),
367
+ * 每一项都带 `Why:`。真机上 agent 拿到平铺列表后仍然要自己判断
368
+ * 「哪篇是主文档、哪篇只是背景」—— 那正是这一版要替它省掉的判断。
369
+ *
370
+ * @param {{mode: string, topic: string, total?: number, primary?: Array<object>,
371
+ * supporting?: Array<object>, related?: Array<object>,
372
+ * docs?: Array<object>}} value - 工具结果(兼容 v0.13 的 `docs` 形状,供时间序使用)
373
+ * @param {Function} [readSnippet] - 可选:从一条结果里取它的命中段落(`doc.snippet`)。
374
+ * **注入成函数而不是直接读字段**,是为了让「段落从哪来」这件事留在 `execute` 里,
375
+ * 渲染函数保持无副作用、可单测。
287
376
  * @returns {string} 文本
288
377
  */
289
- export function renderToolText(value) {
290
- const docs = value && Array.isArray(value.docs) ? value.docs : []
291
- const total = Number.isInteger(value && value.total) ? value.total : docs.length
292
- if (docs.length === 0) return 'No Markdown documents found in the workspace.'
378
+ export function renderToolText(value, readSnippet) {
379
+ const mode = value && value.mode === 'relevance' ? 'relevance' : 'time'
380
+ const topic = value && typeof value.topic === 'string' ? value.topic : ''
381
+ const total = Number.isInteger(value && value.total) ? value.total : 0
382
+
383
+ // 退化(时间序)与「没有对话」是同一件事的两面:都没有命中词。
384
+ if (mode !== 'relevance') {
385
+ const docs = (value && Array.isArray(value.docs)) ? value.docs : []
386
+ if (docs.length === 0) return 'No Markdown documents found in the workspace.'
387
+ const scope = ` of ${total} Markdown document${total === 1 ? '' : 's'}`
388
+ return [`Not enough conversation to rank by relevance — showing the ${docs.length} most recently modified${scope}:`,
389
+ ...docs.map((doc, index) => `${index + 1}. ${doc.rel} — ${doc.title}`)].join('\n')
390
+ }
293
391
 
294
- // 「共 total 篇」回答「是不是漏了」;「IDF-weighted … not a keyword count or filename match」
295
- // 回答「凭什么信这个排名」—— 后者才是 agent 自己再 grep 一遍的真正原因(v0.9)。
296
- const scope = ` of ${total} Markdown document${total === 1 ? '' : 's'}`
392
+ const primary = (value && Array.isArray(value.primary)) ? value.primary : []
393
+ const supporting = (value && Array.isArray(value.supporting)) ? value.supporting : []
394
+ const related = (value && Array.isArray(value.related)) ? value.related : []
395
+
396
+ // 三层都空 = 真的没有可看的上下文。**不能只判 total** —— 工作区有文档、
397
+ // 但当前话题一篇都没命中、且一条引用邻居都没有时,`total` 是正数而三层全空。
398
+ if (primary.length + supporting.length + related.length === 0) {
399
+ if (total === 0) return 'No Markdown documents found in the workspace.'
400
+ // 文档在、但一个词都没命中 —— **不许说成「工作区里没有 Markdown」**:
401
+ // 那是一句假话,而且会把 agent 推向一个错的结论(「这个项目里没有相关材料」)。
402
+ // 真机实测:问「路径越界怎么防」时 49 篇一篇都没命中,因为文档侧只看每篇
403
+ // **前 2500 字**(`index.js` 的 HAYSTACK_CHARS),而这个词在 5 篇 .md 里
404
+ // 全部出现在 2500 字之后。说实话 + 给下一步,比一句错的空结果有用。
405
+ return [
406
+ `No document matched the current topic — 0 of ${total} Markdown document${total === 1 ? '' : 's'} contain the query terms.`,
407
+ HAYSTACK_NOTE,
408
+ ].join('\n')
409
+ }
297
410
 
298
- // 退化情形要**如实说明**,与面板那行「对话内容还不足,暂按最新排序」同一个口径
299
- const head = value.mode === 'time'
300
- ? `Not enough conversation to rank by relevance — showing the ${docs.length} most recently modified${scope}:`
301
- : `Top ${docs.length}${scope} in this workspace, ranked by IDF-weighted relevance to `
302
- + `${value.topic ? `「${value.topic}」` : 'the current conversation'} `
303
- + '(rare terms weighted, length-normalised — not a keyword count or filename match):'
304
-
305
- const lines = docs.map((doc, index) => {
306
- const summary = oneLine(doc.summary)
307
- // 命中段落(v0.11):给模型判断「要不要读整篇」用。
308
- // 用一个 `match:` 前缀把它和**首段摘要**区分开 —— 两者都是一行压平的文本,
309
- // 不加标记的话模型分不清哪行是什么。
310
- const snippet = doc.snippet ? flatten(doc.snippet, SNIPPET_CHARS) : ''
311
- return `${index + 1}. ${doc.rel} — ${doc.title}`
411
+ /** 层内每一项:一行路径 + 标题、一行摘要、一行 `Why:`、可选的 `match:` 段落。 */
412
+ const lines = (items) => items.map((item, index) => {
413
+ const summary = oneLine(item.summary)
414
+ const why = whyText(item.reason)
415
+ const raw = typeof readSnippet === 'function' ? readSnippet(item) : ''
416
+ const snippet = raw ? flatten(raw, SNIPPET_CHARS) : ''
417
+ return `${index + 1}. ${item.rel} — ${item.title}`
312
418
  + `${summary ? `\n ${summary}` : ''}`
419
+ + `${why ? `\n Why: ${why}` : ''}`
313
420
  + `${snippet ? `\n match: ${snippet}` : ''}`
314
421
  })
315
422
 
316
- return [head, ...lines].join('\n')
423
+ const out = []
424
+ const matched = (value && value.totals && Number.isInteger(value.totals.matched))
425
+ ? value.totals.matched : 0
426
+ const scope = ` of ${total} Markdown document${total === 1 ? '' : 's'}`
427
+ out.push(`Context for ${topic ? `「${topic}」` : 'the current conversation'}: `
428
+ + `${matched} matching document${matched === 1 ? '' : 's'}${scope}, split into `
429
+ + 'primary / supporting / related by deterministic local rules (first-read order — '
430
+ + 'not a flat relevance list; each tier is still ranked by IDF-weighted relevance):')
431
+
432
+ if (primary.length > 0) {
433
+ out.push('', 'Primary (read these first):', ...lines(primary))
434
+ }
435
+ if (supporting.length > 0) {
436
+ out.push('', 'Supporting (evidence, implementation, next step):', ...lines(supporting))
437
+ }
438
+ if (related.length > 0) {
439
+ out.push('', 'Related (background — do not start here):', ...lines(related))
440
+ }
441
+ return out.join('\n')
442
+ }
443
+
444
+ /**
445
+ * 把结构化理由翻成一句英文。**码 → 文案**,不是自然语言推断 ——
446
+ * 每个码背后都是一条可核验的确定性事实。
447
+ *
448
+ * @param {{code?: string, terms?: string[], fields?: number}} [reason] - `explainContext()` 的产物
449
+ * @returns {string} 文本
450
+ */
451
+ function whyText(reason) {
452
+ const code = reason && reason.code ? String(reason.code) : ''
453
+ const terms = reason && Array.isArray(reason.terms) ? reason.terms.join(', ') : ''
454
+ switch (code) {
455
+ case 'direct': return terms ? `direct topic match in the title (${terms})` : 'direct topic match in the title'
456
+ case 'titleMatch': return terms ? `matched in the title (${terms})` : 'matched in the title'
457
+ case 'summaryMatch': return terms ? `matched in the summary (${terms})` : 'matched in the summary'
458
+ case 'bodyMatch': return terms ? `matched in the body (${terms})` : 'matched in the body'
459
+ case 'linkTarget': return 'referenced by a primary document'
460
+ case 'linkSource': return 'references a primary document'
461
+ default: return 'related in the current workspace'
462
+ }
317
463
  }
318
464
 
319
465
  /**
@@ -325,9 +471,13 @@ export function renderToolText(value) {
325
471
  * @param {Function} [read] - 宿主的单篇读取函数 `readDocument(root, rel)`。
326
472
  * **同样注入**,理由与 `scan` 一样。**可选** —— 没给就只是不带命中段落,
327
473
  * `knit_docs` 的其余行为一字不变(老调用方不会坏)。
474
+ * @param {Function} [contextFor] - 宿主的上下文装配函数
475
+ * `contextFor(root, {ranked, topic, task, total})` → Context Pack。
476
+ * **同样注入**(v0.14):装配规则长在 `context.js` 里,工具只负责投影。
477
+ * 不给就退化成 v0.13 的平铺列表 —— 但那只是兜底,正常路径 always 会传。
328
478
  * @returns {object} 工具定义
329
479
  */
330
- export function knitDocsDefinition(scan, read) {
480
+ export function knitDocsDefinition(scan, read, contextFor) {
331
481
  /**
332
482
  * 给一篇文档抽命中段落。
333
483
  *
@@ -357,7 +507,11 @@ export function knitDocsDefinition(scan, read) {
357
507
  parameters: PARAMETERS,
358
508
  output: {
359
509
  schema: OUTPUT_SCHEMA,
360
- render: (_args, value) => [{ type: 'text', text: renderToolText(value) }],
510
+ // 命中段落从条目自己的 `snippet` 字段取 —— `execute` 已经把它填好了。
511
+ render: (_args, value) => [{
512
+ type: 'text',
513
+ text: renderToolText(value, (item) => (item && item.snippet) || ''),
514
+ }],
361
515
  },
362
516
  async execute(args, exec) {
363
517
  const { root, sessionId, session } = agentScope(exec)
@@ -383,27 +537,88 @@ export function knitDocsDefinition(scan, read) {
383
537
  // 时间序模式下它是空数组 ⇒ terms 为空 ⇒ 不抽段落,正合语义。
384
538
  const terms = Array.isArray(payload.keywords) ? payload.keywords : []
385
539
 
386
- const docs = await Promise.all((payload.docs || []).map(async (doc) => {
387
- const row = {
388
- rel: String(doc.rel || ''),
389
- title: String(doc.title || ''),
390
- summary: doc.summary == null ? '' : String(doc.summary),
391
- mtimeMs: Number.isFinite(doc.mtimeMs) ? Math.trunc(doc.mtimeMs) : 0,
540
+ /** 给一篇抽段落:**只用这一篇自己命中的词** —— 拿别篇的词去原文里找,抽出来的段落跟这篇无关。 */
541
+ const snippetOf = async (item) => {
542
+ const own = (item.reason && Array.isArray(item.reason.terms)) ? item.reason.terms : []
543
+ return snippetFor(root, item.rel, own, item.title)
544
+ }
545
+
546
+ // 时间序(没有对话可依据):退回一列「最近改动的」,**不硬凑三层**。
547
+ if (payload.mode !== 'relevance') {
548
+ const recent = await Promise.all((payload.docs || []).map(async (doc) => {
549
+ const row = {
550
+ rel: String(doc.rel || ''),
551
+ title: String(doc.title || ''),
552
+ summary: doc.summary == null ? '' : String(doc.summary),
553
+ mtimeMs: Number.isFinite(doc.mtimeMs) ? Math.trunc(doc.mtimeMs) : 0,
554
+ }
555
+ const snippet = await snippetFor(root, row.rel, terms, row.title)
556
+ if (snippet) row.snippet = snippet
557
+ return row
558
+ }))
559
+ return {
560
+ mode: 'time',
561
+ topic: '',
562
+ total: Number.isInteger(payload.total) ? payload.total : 0,
563
+ primary: [],
564
+ supporting: [],
565
+ related: [],
566
+ docs: recent,
392
567
  }
393
- const snippet = await snippetFor(root, row.rel, terms, row.title)
394
- // 抽不到就**不带这个字段**,不写空串 —— 让「没有命中」和「命中但没抽出来」
395
- // 在输出里都是「没有 match 行」,而不是一行空的 `match: `
396
- if (snippet) row.snippet = snippet
397
- return row
568
+ }
569
+
570
+ const pack = typeof contextFor === 'function'
571
+ ? await contextFor(root, {
572
+ // ⚠️ 用 `payload.ranked`(全量、未切片)而不是 `payload.docs`(已切到 limit)——
573
+ // 分层要在完整名次上做,否则「Primary 3 篇 + Supporting 5 篇」会把
574
+ // 本该是 Supporting 的文档因为切片而挤掉(它会掉进 Related,或整个消失)。
575
+ ranked: Array.isArray(payload.ranked) ? payload.ranked : [],
576
+ topic: payload.topic,
577
+ // 任务原文(可能为空:显式 `query` 路径没有对话可引用)。
578
+ // 它进 `pack.task`,但**不出现在工具返回值里** —— 模型看到的是 `output.render`
579
+ // 渲染的那段文本,结构化 JSON 它根本看不见;而 `OUTPUT_SCHEMA` 是封闭的
580
+ // (`additionalProperties: false`),加一个模型用不到的字段只会把 schema 撑开。
581
+ // 头部已经用 topic 标签说了「这次是按什么排的」,那比原文更省 token。
582
+ // Human 面板走 HTTP,`context.task` 在那里有值。
583
+ task: payload.task,
584
+ total: Number.isInteger(payload.total) ? payload.total : 0,
585
+ })
586
+ : { mode: 'relevance', topic: payload.topic || '', total: 0, primary: [], supporting: [], related: [] }
587
+
588
+ /**
589
+ * 把装配层的条目投影成 `ITEM_SCHEMA` 的形状。
590
+ *
591
+ * ⚠️ `mtimeMs` **必须在这里取整**。`fs.Stats.mtimeMs` 是浮点,而 schema 写的是
592
+ * `integer` —— v0.14 把三层条目**原样透传**过一次,于是 `knit_docs` 每次调用
593
+ * 都在校验层失败(`"value.primary[0].mtimeMs" must be an integer`),
594
+ * agent 一个 Context Pack 都拿不到。时间序那条分支一直是取整的,两边不一致。
595
+ */
596
+ const project = (item) => ({
597
+ ...item,
598
+ mtimeMs: Number.isFinite(item.mtimeMs) ? Math.trunc(item.mtimeMs) : 0,
599
+ })
600
+
601
+ // 逐个抽命中段落 —— **只对真正要返回的条目做 I/O**,不在全量名次上读盘。
602
+ const withSnippets = async (items) => Promise.all(items.map(async (raw) => {
603
+ const item = project(raw)
604
+ const snippet = await snippetOf(item)
605
+ return snippet ? { ...item, snippet } : item
398
606
  }))
399
607
 
400
608
  return {
401
- mode: payload.mode === 'relevance' ? 'relevance' : 'time',
402
- topic: typeof payload.topic === 'string' ? payload.topic : '',
403
- // `scan()` 的 total 是**全量池子**的条数(在 limit 切片之前),
404
- // 正好是这里要的「工作区一共有多少篇」。
405
- total: Number.isInteger(payload.total) ? payload.total : 0,
406
- docs,
609
+ mode: 'relevance',
610
+ topic: typeof pack.topic === 'string' ? pack.topic : '',
611
+ total: Number.isInteger(pack.totals && pack.totals.total) ? pack.totals.total : 0,
612
+ // `matched` 走 `totals` —— 头部的「N matching documents」靠它。
613
+ // 漏掉这一个字段会让头部永远写「0 matching documents」,而下面明明列着结果
614
+ // (实测踩过一次,是渲染层的一个真实缺陷,不是美观问题)。
615
+ totals: {
616
+ matched: Number.isInteger(pack.totals && pack.totals.matched) ? pack.totals.matched : 0,
617
+ total: Number.isInteger(pack.totals && pack.totals.total) ? pack.totals.total : 0,
618
+ },
619
+ primary: await withSnippets(pack.primary || []),
620
+ supporting: await withSnippets(pack.supporting || []),
621
+ related: await withSnippets(pack.related || []),
407
622
  }
408
623
  },
409
624
  }
@@ -417,8 +632,9 @@ export function knitDocsDefinition(scan, read) {
417
632
  * @param {object} ctx - cordis 上下文(带 `tools` 服务)
418
633
  * @param {Function} scan - 宿主的扫描函数
419
634
  * @param {Function} [read] - 宿主的单篇读取函数(抽命中段落用;可选)
635
+ * @param {Function} [contextFor] - 宿主的上下文装配函数(v0.14;可选)
420
636
  * @returns {() => void} 注销函数
421
637
  */
422
- export function registerKnitDocsTool(ctx, scan, read) {
423
- return ctx.tools.register(knitDocsDefinition(scan, read))
638
+ export function registerKnitDocsTool(ctx, scan, read, contextFor) {
639
+ return ctx.tools.register(knitDocsDefinition(scan, read, contextFor))
424
640
  }