dsh-knit 0.13.1 → 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/index.js CHANGED
@@ -21,6 +21,11 @@ import { extractKeywords, rankByRelevance, topicLabel } from './relevance.js'
21
21
  import { registerKnitDocsTool } from './tool.js'
22
22
  // v0.12:引用关系。`links.js` **不反过来 import 本文件**(依赖由这里注入),所以没有环。
23
23
  import { buildLinkGraph, linksOf } from './links.js'
24
+ // v0.14:上下文装配。同样由这里注入依赖(`list` / `read`),保持纯函数可单测。
25
+ // ⚠️ 这里**只 import `buildContext`**:Context Pack 的文本渲染只在 `tool.js` 的
26
+ // `renderToolText()` 里发生(模型看到的是那段文本,不是结构化 JSON)。曾经多导出一个
27
+ // `renderContextText` 却没人调用 —— 那是个会与 `tool.js` 漂移的第二渲染器,已删。
28
+ import { buildContext } from './context.js'
24
29
 
25
30
  export const name = 'dsh-knit'
26
31
 
@@ -45,6 +50,27 @@ const CONV_MAX_MESSAGES = 6
45
50
  const CONV_MAX_CHARS = 6000
46
51
  const CONV_MESSAGE_CHARS = 2000
47
52
 
53
+ /**
54
+ * `task` 字段(当前任务的**原文引用**)的长度上限。
55
+ *
56
+ * 右栏要显示它、agent 文本里也会带一行,所以太长的消息会把它变成一个正文块。
57
+ * 截断是这里唯一允许的加工 —— 它不改语义,只是裁剪,超出部分用 `…` 标出。
58
+ */
59
+ const TASK_MAX_CHARS = 80
60
+
61
+ /**
62
+ * 纯应答词表:这些不是任务,是「接着说」。
63
+ *
64
+ * `task` 要回答「现在这个任务是什么」,而「继续」「好的」回答不了这个问题 ——
65
+ * 把它们当任务显示,比空着更糟(空着至少不撒谎)。判定前先按标点切成段,
66
+ * 所以「好的,继续」也命中。
67
+ */
68
+ const TASK_ACK = new Set([
69
+ '继续', '好的', '好', '嗯', '嗯嗯', '收到', '谢谢', '可以', '行', '对',
70
+ '是的', '没问题', '辛苦了', '麻烦了',
71
+ 'ok', 'okay', 'yes', 'yep', 'y', 'thanks', 'thx', 'gotit', 'continue', 'goon', 'next', 'done',
72
+ ])
73
+
48
74
  /**
49
75
  * 允许内联渲染的图片类型白名单。
50
76
  *
@@ -208,7 +234,7 @@ export function parseMarkdown(head, fileName) {
208
234
  /**
209
235
  * 读一个 Markdown 文件的元信息,命中缓存则跳过读盘。
210
236
  * @param {string} absPath - 绝对路径
211
- * @returns {Promise<object|null>} 解析结果(含小写 haystack),读失败返回 null
237
+ * @returns {Promise<object|null>} 解析结果(含小写 haystack 与原文首部 head),读失败返回 null
212
238
  */
213
239
  async function readDoc(absPath) {
214
240
  let st
@@ -237,6 +263,9 @@ async function readDoc(absPath) {
237
263
  size: st.size,
238
264
  title,
239
265
  summary,
266
+ // ⚠️ 原文首部**留在缓存里**(v0.14):上下文装配要用它抽引用关系。
267
+ // 它已经在内存里了 —— 再读一遍盘才是浪费。`publicDoc()` 不会把它发出去。
268
+ head,
240
269
  hayTitle: title.toLowerCase(),
241
270
  haySummary: summary.toLowerCase(),
242
271
  hayBody: head.slice(0, HAYSTACK_CHARS).toLowerCase(),
@@ -371,6 +400,8 @@ export async function collectDocs(root) {
371
400
  summary: meta.summary,
372
401
  size: meta.size,
373
402
  mtimeMs: meta.mtimeMs,
403
+ // 原文首部:`buildContextFor()` 抽引用关系用(v0.14)。内部字段,不下发。
404
+ head: meta.head,
374
405
  haystack: { title: meta.hayTitle, summary: meta.haySummary, body: meta.hayBody },
375
406
  })
376
407
  }
@@ -403,26 +434,81 @@ function messageText(message) {
403
434
  }
404
435
 
405
436
  /**
406
- * 取会话里最近的若干条人机对话文本(**最新在前**)。
437
+ * 把一段文本压成可显示的单行。
438
+ * @param {string} text - 原始文本
439
+ * @returns {string} 折叠空白后的文本
440
+ */
441
+ function tidyText(text) {
442
+ return String(text || '').replace(/\s+/g, ' ').trim()
443
+ }
444
+
445
+ /**
446
+ * 整条消息是否**只由应答词组成**(切成段后逐段查 `TASK_ACK`)。
447
+ * @param {string} tidy - 已折叠空白的文本
448
+ * @returns {boolean} 是否只是应答
449
+ */
450
+ function isAcknowledgementOnly(tidy) {
451
+ const parts = tidy.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
452
+ if (parts.length === 0) return false
453
+ return parts.every((part) => TASK_ACK.has(part.toLowerCase()))
454
+ }
455
+
456
+ /**
457
+ * 判断一条用户消息能不能当「任务」引用。
458
+ *
459
+ * 全部是确定性判定,没有任何主观打分:
460
+ * - 折叠空白后至少 2 个字符;
461
+ * - 至少含一个字母或汉字(纯数字 / emoji / 符号不算);
462
+ * - 不能只是应答词(「继续」「好的」不是任务)。
463
+ *
464
+ * @param {string} text - 用户消息文本
465
+ * @returns {boolean} 是否可作为 `task` 引用
466
+ */
467
+ function isSubstantiveTask(text) {
468
+ const tidy = tidyText(text)
469
+ if (tidy.length < 2) return false
470
+ if (!/\p{L}/u.test(tidy)) return false
471
+ return !isAcknowledgementOnly(tidy)
472
+ }
473
+
474
+ /**
475
+ * 把用户消息原文截成 `task` 字段的值。
476
+ * @param {string} text - 用户消息文本
477
+ * @returns {string} 截断后的单行文本
478
+ */
479
+ function taskText(text) {
480
+ const tidy = tidyText(text)
481
+ if (tidy.length <= TASK_MAX_CHARS) return tidy
482
+ return `${tidy.slice(0, TASK_MAX_CHARS - 1)}…`
483
+ }
484
+
485
+ /**
486
+ * 取会话里最近的若干条人机对话文本(**最新在前**),外加当前任务的原文引用。
407
487
  *
408
488
  * 只收 `source.kind === 'user'` 的 user/message —— `agent.inject()` 塞进来的
409
489
  * 合成上下文(AGENTS.md、skill 内容、文件变更通知)不是用户意图,会把话题带偏。
410
490
  *
491
+ * `task` 与用于检索的窗口**同源**:都只看最近 `CONV_MAX_MESSAGES` 条。这不是偷懒 ——
492
+ * 让「右栏显示的任务」和「实际排序依据的对话」来自两个不同窗口,用户会对不上账。
493
+ *
411
494
  * @param {object} session - 宿主会话对象
412
- * @returns {{texts: string[], seq: number}} 对话文本与最新事件的 seq
495
+ * @returns {{texts: string[], seq: number, task: string}} 对话文本、最新事件 seq、任务原文
413
496
  */
414
497
  function recentConversation(session) {
415
498
  let events
416
499
  try {
417
500
  events = session && typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : null
418
501
  } catch {
419
- return { texts: [], seq: -1 }
502
+ return { texts: [], seq: -1, task: '' }
420
503
  }
421
- if (!Array.isArray(events) || events.length === 0) return { texts: [], seq: -1 }
504
+ if (!Array.isArray(events) || events.length === 0) return { texts: [], seq: -1, task: '' }
422
505
 
423
506
  const texts = []
424
507
  let seq = -1
425
508
  let chars = 0
509
+ // 从新往旧扫,第一条通过 `isSubstantiveTask()` 的用户消息就是当前任务。
510
+ // 用**第一条**而不是最长的:任务会变,「现在在做什么」由最近那句说了算。
511
+ let task = ''
426
512
 
427
513
  for (let i = events.length - 1; i >= 0 && texts.length < CONV_MAX_MESSAGES; i -= 1) {
428
514
  const event = events[i]
@@ -433,6 +519,7 @@ function recentConversation(session) {
433
519
  const source = event.data && event.data.source
434
520
  if (source && source.kind && source.kind !== 'user') continue
435
521
  text = messageText(event.data)
522
+ if (!task && isSubstantiveTask(text)) task = taskText(text)
436
523
  } else if (event.type === 'assistant/message') {
437
524
  text = messageText(event.data && event.data.message)
438
525
  } else {
@@ -448,29 +535,38 @@ function recentConversation(session) {
448
535
  if (chars >= CONV_MAX_CHARS) break
449
536
  }
450
537
 
451
- return { texts, seq }
538
+ return { texts, seq, task }
452
539
  }
453
540
 
454
541
  /**
455
- * 取一个会话当前的话题关键词,按最新事件 seq 缓存。
542
+ * 取一个会话当前的检索关键词与任务引用,按最新事件 seq 缓存。
543
+ *
544
+ * 两者一起缓存是因为它们**必须来自同一次读数** —— 分开缓存会在「用户刚说完一句话」
545
+ * 的那个 5 秒轮询里出现「词已经更新、任务还是上一句」的错位。
546
+ *
456
547
  * @param {object} session - 宿主会话对象
457
548
  * @param {string} sessionId - 会话 id(缓存键)
458
- * @returns {Array<{term:string,weight:number}>} 关键词表
549
+ * @returns {{keywords: Array<{term:string,weight:number}>, task: string}} 关键词表与任务原文
459
550
  */
460
- function keywordsFor(session, sessionId) {
461
- const { texts, seq } = recentConversation(session)
551
+ function conversationFor(session, sessionId) {
552
+ const { texts, seq, task } = recentConversation(session)
462
553
  const hit = convCache.get(sessionId)
463
- if (hit && hit.seq === seq) return hit.keywords
554
+ if (hit && hit.seq === seq) return hit
464
555
 
465
556
  const keywords = extractKeywords(texts, 30)
466
- convCache.set(sessionId, { seq, keywords })
467
- return keywords
557
+ const entry = { seq, keywords, task }
558
+ convCache.set(sessionId, entry)
559
+ return entry
468
560
  }
469
561
 
470
562
  /* ── 对外载荷 ───────────────────────────────────────── */
471
563
 
472
564
  /**
473
565
  * 剥掉内部字段,得到发给浏览器的文档记录。
566
+ *
567
+ * ⚠️ `raw` 与 `matchedTerms` **必须**留在这里被剥掉(v0.14):它们是上下文装配的
568
+ * 内部输入,泄漏出去就等于对外给了一套第二分数(`test/host.test.mjs` 有守卫)。
569
+ *
474
570
  * @param {object} doc - 内部文档记录
475
571
  * @returns {object} 公开记录
476
572
  */
@@ -497,7 +593,10 @@ function publicDoc(doc) {
497
593
  * 排序上下文;`kind` 为 `doc`(默认,仅 Markdown)、`media`(仅图片/视频)或 `all`;
498
594
  * `query` 非空时**用它排序,而不是用当前对话**(v0.7 的 agent 工具走这条路);
499
595
  * HTTP 路由不传 `query`,所以 `/knit/api/recent` 的行为逐字不变
500
- * @returns {Promise<object>} 给浏览器的载荷
596
+ * @returns {Promise<object>} 给浏览器的载荷。
597
+ * ⚠️ **不要把这个对象直接 `sendJson`** —— 它现在带一个 `ranked` 键(全量名次,
598
+ * 含 `raw` 与 `matchedTerms`),是给 `buildContextFor()` 用的**内部输入**。
599
+ * HTTP 路由必须走 `publicScanPayload()`(`test/host.test.mjs` 有守卫)。
501
600
  */
502
601
  export async function scan(root, limit, options = {}) {
503
602
  const collected = await collectDocs(root)
@@ -522,15 +621,22 @@ export async function scan(root, limit, options = {}) {
522
621
  let keywords = NO_KEYWORDS
523
622
  let mode = 'time'
524
623
  let matched = []
624
+ // 当前任务的**原文引用**(SDD §12)。只在「对话驱动」这条路上有值:
625
+ // 显式 query 路径下模型自己知道在问什么,把 query 当「任务」是编的。
626
+ let task = ''
525
627
 
526
628
  if (wantRelevance) {
527
629
  // 调用方给了明确的 query(v0.7 的 agent 工具走这条路):把它当成**一条最新的消息**,
528
630
  // 于是走的是完全相同的抽取与门槛规则,不引入第二条抽取路径。
529
631
  // 不进 convCache —— 那个缓存按 session seq 键控,塞 query 进去会互相污染。
530
632
  const explicitQuery = typeof options.query === 'string' ? options.query.trim() : ''
531
- keywords = explicitQuery
532
- ? extractKeywords([explicitQuery], 30)
533
- : keywordsFor(options.session, sessionId)
633
+ if (explicitQuery) {
634
+ keywords = extractKeywords([explicitQuery], 30)
635
+ } else {
636
+ const conv = conversationFor(options.session, sessionId)
637
+ keywords = conv.keywords
638
+ task = conv.task
639
+ }
534
640
  // 没有对话可依据时老实退回时间序,而不是假装排了个序
535
641
  mode = keywords.length > 0 ? 'relevance' : 'time'
536
642
  }
@@ -560,10 +666,159 @@ export async function scan(root, limit, options = {}) {
560
666
  mode,
561
667
  topic,
562
668
  keywords: mode === 'relevance' ? matched.slice(0, 8) : [],
669
+ // 全量名次(未按 limit 切片)。**只给上下文装配用**,由 `publicScanPayload()` 剥掉。
670
+ // 放在这里而不是让调用方再扫一遍,是 §二十「不要为了 Context Pack 再扫描一次
671
+ // 整个 Workspace」那条要求的实现:这里复用同一次 `rankByRelevance` 的结果。
672
+ ranked: mode === 'relevance' ? ordered : [],
673
+ // 任务原文。**也不下发**(由 `publicScanPayload()` 一并剥掉)—— 它只喂装配层与右栏。
674
+ // 剥掉不是为了保密(这是用户自己刚说过的话),而是为了不动 v0.13 的响应形状:
675
+ // `context.task` 已经把这个值带出去了,顶层再来一份是重复。
676
+ task: mode === 'relevance' ? task : '',
563
677
  docs: ordered.slice(0, limit).map(publicDoc),
564
678
  }
565
679
  }
566
680
 
681
+ /**
682
+ * 把 `scan()` 的载荷压成**可以发给浏览器/模型**的那一份。
683
+ *
684
+ * 存在的唯一理由是 `ranked`(全量名次、含 `raw` 与 `matchedTerms`)必须被剥掉 ——
685
+ * 它是装配层的内部输入,发出去就等于对外给了一套第二分数,而且响应体会大好几倍。
686
+ * `task` 同理:装配层已经把它放进 `context.task` 了。
687
+ * HTTP 路由与 agent 工具都只许返回这个函数的产物。
688
+ *
689
+ * @param {object} payload - `scan()` 的产物
690
+ * @returns {object} 公开载荷(与 v0.13 逐字一致,外加 v0.14 的 `context`)
691
+ */
692
+ export function publicScanPayload(payload) {
693
+ if (!payload || typeof payload !== 'object') return payload
694
+ const { ranked, task, ...rest } = payload
695
+ void ranked
696
+ void task
697
+ return rest
698
+ }
699
+
700
+ /**
701
+ * 按需建引用图。
702
+ *
703
+ * `withLinks` 为假时**连图都不建** —— 媒体档 / 时间序 / 悬停浮层的条数不需要分层,
704
+ * 不该为它们读全库(这是 §二十「不要为了 Context Pack 再扫描一次整个 Workspace」
705
+ * 那条要求的一半;另一半是复用 `rankByRelevance` 已经算好的名次与命中词)。
706
+ *
707
+ * `read` 用文档记录上现成的 `head`(`collectDocs` 解析 title / summary 时已经读过
708
+ * 同样的 16KB)—— **零额外 I/O**。代价是只看头部 16KB,长文档尾部的引用会漏,
709
+ * 但那只影响「哪些邻居进 Supporting」,不影响任何一篇的名次。
710
+ *
711
+ * @param {string} root - 工作区根
712
+ * @param {boolean} withLinks - 是否要引用关系
713
+ * @param {Map<string, object>} byRel - 本次扫描到的文档(按 rel)
714
+ * @returns {Promise<object|null>} 图或 null
715
+ */
716
+ async function linkGraphFor(root, withLinks, byRel) {
717
+ if (!withLinks) return null
718
+ try {
719
+ return await buildLinkGraph(root, {
720
+ list: async () => ({ docs: [...byRel.values()], truncated: false }),
721
+ read: async (_root, rel) => {
722
+ const entry = byRel.get(rel)
723
+ if (!entry || typeof entry.head !== 'string') return { ok: false }
724
+ return { ok: true, text: entry.head }
725
+ },
726
+ })
727
+ } catch {
728
+ // 图建不起来只是少一个上下文信号 —— 分层退化成「只看命中」,不报错。
729
+ return null
730
+ }
731
+ }
732
+
733
+ /**
734
+ * 装配一个工作区的 Context Pack(v0.14)。
735
+ *
736
+ * 顺序固定:`collect → relevance → links → context assembly`,四步复用同一批结果。
737
+ * `ranked` 为空时**不读盘**(媒体档 / 时间序走的就是这条),直接返回空包。
738
+ *
739
+ * @param {string} root - 工作区根
740
+ * @param {{ranked?: Array<object>, topic?: string, task?: string, total?: number, withLinks?: boolean}} [options] -
741
+ * `ranked` 是 `scan()` 里的全量名次(含 `raw` 与 `matchedTerms`);
742
+ * `task` 是当前任务的**原文引用**,原样透传给 `buildContext()`,这里不生成也不改写
743
+ * @returns {Promise<object>} Context Pack
744
+ */
745
+ export async function buildContextFor(root, options = {}) {
746
+ const ranked = Array.isArray(options.ranked) ? options.ranked : []
747
+ const total = Number.isInteger(options.total) ? options.total : ranked.length
748
+ const task = typeof options.task === 'string' ? options.task : ''
749
+ const empty = () => buildContext({ ranked: [], topic: options.topic || '', task, total })
750
+ if (ranked.length === 0) return empty()
751
+
752
+ const byRel = new Map()
753
+ for (const doc of ranked) {
754
+ if (doc && doc.rel) byRel.set(String(doc.rel), doc)
755
+ }
756
+
757
+ const graph = await linkGraphFor(root, options.withLinks !== false, byRel)
758
+ return buildContext({ ranked, topic: options.topic || '', task, total, graph })
759
+ }
760
+
761
+ /**
762
+ * 给 Context Pack 补一份**计数摘要**(不是分数)。
763
+ *
764
+ * 客户端需要它来做两件事:① 在没有可见条目时区分「这个工作区是空的」与
765
+ * 「有文档但当前话题一篇都没命中」;② 显示「相关上下文还有 N 篇」。
766
+ * 数字全部是**集合大小**,没有任何相似度含义。
767
+ *
768
+ * @param {object} pack - `buildContext()` 的产物
769
+ * @returns {object} 带 `summary` 的包
770
+ */
771
+ function withStats(pack) {
772
+ const primary = Array.isArray(pack.primary) ? pack.primary : []
773
+ const supporting = Array.isArray(pack.supporting) ? pack.supporting : []
774
+ const related = Array.isArray(pack.related) ? pack.related : []
775
+ return {
776
+ ...pack,
777
+ summary: {
778
+ primary: primary.length,
779
+ supporting: supporting.length,
780
+ related: related.length,
781
+ // 三层加起来的**可见条目数**(客户端「全部」档要用它做上限判断)
782
+ shown: primary.length + supporting.length + related.length,
783
+ // 本批语料里命中了话题的篇数 —— 「有文档但一篇都没命中」靠它判
784
+ matched: pack.totals ? pack.totals.matched : 0,
785
+ total: pack.totals ? pack.totals.total : 0,
786
+ },
787
+ }
788
+ }
789
+
790
+ /**
791
+ * 一次请求里的上下文载荷:不适用(时间序 / 媒体档 / 没有命中)时返回 `null`。
792
+ *
793
+ * **只在文档档 + 相关序 + 有命中词时装配** —— 其余情形返回 null,
794
+ * 客户端于是退回它一直在用的平铺列表,行为与 v0.13 逐字一致。
795
+ *
796
+ * @param {string} root - 工作区根
797
+ * @param {object} payload - `scan()` 的产物
798
+ * @param {string} sort - 当前排序模式
799
+ * @param {string} kind - 当前条目类型
800
+ * @returns {Promise<object|null>} Context Pack(带 `summary`)或 null
801
+ */
802
+ async function contextPayload(root, payload, sort, kind) {
803
+ if (!payload || payload.mode !== 'relevance' || sort !== 'relevance' || kind !== 'doc') return null
804
+ const ranked = Array.isArray(payload.ranked) ? payload.ranked : []
805
+ if (ranked.length === 0) return null
806
+ try {
807
+ const pack = await buildContextFor(root, {
808
+ ranked,
809
+ topic: payload.topic,
810
+ task: payload.task,
811
+ total: payload.total,
812
+ // 引用图只在**真有命中**时才值得建(零命中时 Primary 为空,邻居逻辑没有锚点)
813
+ withLinks: ranked.some((doc) => Number(doc.raw) > 0),
814
+ })
815
+ return withStats(pack)
816
+ } catch {
817
+ // 装配失败不该让整个列表接口失败 —— 退回 null,面板照常出平铺列表。
818
+ return null
819
+ }
820
+ }
821
+
567
822
  /**
568
823
  * 读一篇文档的完整正文,供面板内联预览。
569
824
  *
@@ -816,7 +1071,37 @@ export function apply(ctx) {
816
1071
  const payload = await scan(root, limit, {
817
1072
  session: sessionOf(webCtx, sessionId), sessionId, sort, kind,
818
1073
  })
819
- sendJson(res, 200, payload)
1074
+ const body = publicScanPayload(payload)
1075
+ // v0.14:相关模式下顺带给出任务上下文分层。
1076
+ // ⚠️ 带上 `context` 是**可选**的(老客户端忽略它),而 `docs` 一字未动。
1077
+ body.context = await contextPayload(root, payload, sort, kind)
1078
+ sendJson(res, 200, body)
1079
+ return
1080
+ }
1081
+
1082
+ if (url.pathname === `${ROUTE_PREFIX}/api/context`) {
1083
+ // v0.14:独立的上下文接口。与 `/api/recent` 分开是为了**不让只想拿列表的
1084
+ // 调用方被迫付引用图的钱** —— 面板走 recent 里的 `context` 字段,
1085
+ // 这个路由留给「只要上下文、不要列表」的调用方。
1086
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || MAX_DOCS, 1), MAX_DOCS)
1087
+ const sort = url.searchParams.get('sort') === 'time' ? 'time' : 'relevance'
1088
+ const kindParam = url.searchParams.get('kind')
1089
+ const kind = kindParam === 'all' || kindParam === 'media' ? kindParam : 'doc'
1090
+ const payload = await scan(root, limit, {
1091
+ session: sessionOf(webCtx, sessionId), sessionId, sort, kind,
1092
+ })
1093
+ // ⚠️ 与 `/api/recent` 的 `context` 字段**语义不同**:这里永远返回一个
1094
+ // 结构齐全的包(没有命中就是三层全空),不用 null。
1095
+ // null 是「请退回平铺列表」,那是 recent 的语义;独立的上下文接口
1096
+ // 没有平铺列表可退,返回 null 只会让调用方多一次判空。
1097
+ const context = withStats(await buildContextFor(root, {
1098
+ ranked: Array.isArray(payload.ranked) ? payload.ranked : [],
1099
+ topic: payload.topic,
1100
+ task: payload.task,
1101
+ total: payload.total,
1102
+ withLinks: payload.mode === 'relevance' && kind === 'doc',
1103
+ }))
1104
+ sendJson(res, 200, { ok: true, root, mode: payload.mode, topic: payload.topic, context })
820
1105
  return
821
1106
  }
822
1107
 
@@ -869,7 +1154,7 @@ export function apply(ctx) {
869
1154
 
870
1155
  webCtx.effect(() => {
871
1156
  const unregister = webCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler })
872
- console.log(`[${name}] route ready: ${ROUTE_PREFIX}/api/recent, ${ROUTE_PREFIX}/api/doc, ${ROUTE_PREFIX}/api/raw, ${ROUTE_PREFIX}/api/links`)
1157
+ console.log(`[${name}] route ready: ${ROUTE_PREFIX}/api/recent, ${ROUTE_PREFIX}/api/doc, ${ROUTE_PREFIX}/api/raw, ${ROUTE_PREFIX}/api/links, ${ROUTE_PREFIX}/api/context`)
873
1158
  return () => unregister()
874
1159
  }, 'dsh-knit: host route')
875
1160
  })
@@ -881,7 +1166,7 @@ export function apply(ctx) {
881
1166
  // 两条路互不依赖:没有 tools 服务时,浏览器那半边照常工作。
882
1167
  ctx.inject(['tools'], (toolCtx) => {
883
1168
  toolCtx.effect(
884
- () => registerKnitDocsTool(toolCtx, scan, readDocument),
1169
+ () => registerKnitDocsTool(toolCtx, scan, readDocument, buildContextFor),
885
1170
  'dsh-knit: knit_docs tool',
886
1171
  )
887
1172
  console.log(`[${name}] agent tool ready: knit_docs`)
@@ -508,11 +508,16 @@ export function rankByRelevance(docs, keywords, now) {
508
508
  const lens = { title: 0, summary: 0, body: 0 }
509
509
  const tfList = []
510
510
 
511
+ /** 每篇文档「哪些词命中了、命中在哪些字段」—— 供 Context Assembly 定性用,不参与 BM25。 */
512
+ const termHits = []
513
+
511
514
  for (const doc of docs) {
512
515
  const hay = doc.haystack || { title: '', summary: '', body: '' }
513
516
  const tf = { title: new Map(), summary: new Map(), body: new Map() }
514
517
  const len = { title: 0, summary: 0, body: 0 }
515
518
  const seen = new Set()
519
+ /** @type {Map<string, {title:boolean, summary:boolean, body:boolean, bodyTf:number}>} */
520
+ const fields = new Map()
516
521
 
517
522
  for (const field of FIELDS) {
518
523
  const text = hay[field] || ''
@@ -524,6 +529,17 @@ export function rankByRelevance(docs, keywords, now) {
524
529
  if (hits === 0) continue
525
530
  tf[field].set(term, hits)
526
531
  seen.add(term)
532
+ // 字段命中位图 + 正文字频。位图是**定性**的(命中在标题还是正文),
533
+ // bodyTf 用来区分「正文里真的在展开讲」与「正文里只提了一句」——
534
+ // v0.14 的 Context Assembly 靠它把「什么话题都提一句」的归档长文挡在
535
+ // Supporting 之外(见 `context.js` 的 `isDocHit` 说明)。
536
+ let row = fields.get(term)
537
+ if (row === undefined) {
538
+ row = { title: false, summary: false, body: false, bodyTf: 0 }
539
+ fields.set(term, row)
540
+ }
541
+ row[field] = true
542
+ if (field === 'body') row.bodyTf = hits
527
543
  }
528
544
  }
529
545
 
@@ -531,6 +547,7 @@ export function rankByRelevance(docs, keywords, now) {
531
547
  // 同一篇里两个字段都命中不能算两次。
532
548
  for (const term of seen) df.set(term, (df.get(term) || 0) + 1)
533
549
  tfList.push({ tf, len })
550
+ termHits.push(fields)
534
551
  }
535
552
 
536
553
  const avgdl = {}
@@ -582,13 +599,34 @@ export function rankByRelevance(docs, keywords, now) {
582
599
 
583
600
  const maxRaw = Math.max(...raws, 0)
584
601
 
585
- const scored = docs.map((doc, index) => ({
586
- ...doc,
587
- raw: raws[index],
588
- score: maxRaw > 0 ? Math.round((raws[index] / maxRaw) * 100) : 0,
589
- }))
602
+ const scored = docs.map((doc, index) => {
603
+ const fields = termHits[index]
604
+ // 命中词按查询权重降序 —— 与 `matched` 同一口径(权重降序,其次按词的字典序稳定)。
605
+ const matchedTerms = keywords
606
+ .filter((k) => fields.has(k.term))
607
+ .sort((a, b) => b.weight - a.weight || a.term.localeCompare(b.term))
608
+ .map((k) => ({
609
+ term: k.term,
610
+ weight: k.weight,
611
+ fields: fields.get(k.term),
612
+ }))
613
+ return {
614
+ ...doc,
615
+ raw: raws[index],
616
+ score: maxRaw > 0 ? Math.round((raws[index] / maxRaw) * 100) : 0,
617
+ // v0.14:上下文装配的输入。**不是新的打分** —— 只是把第 1 趟已经算过的
618
+ // 「谁命中了、命中在哪个字段」留下来,避免 context.js 再扫一遍语料。
619
+ // `publicDoc()` 会把它剥掉,不下发给浏览器。
620
+ matchedTerms,
621
+ }
622
+ })
590
623
 
591
- scored.sort((a, b) => b.raw - a.raw || b.mtimeMs - a.mtimeMs)
624
+ // ⚠️ 最后一个兜底键必须是 **doc 自己的**(`rel`),不能是「它在输入里的下标」——
625
+ // 后者只在同一份输入的排列下稳定,换个扫描顺序(`collectDocs` 按 mtime 倒序给出)
626
+ // 就会换序。v0.14 的 Context Pack 承诺「相同输入产出完全相同顺序」,
627
+ // 那要求排序与输入排列无关。
628
+ scored.sort((a, b) => b.raw - a.raw || b.mtimeMs - a.mtimeMs
629
+ || (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))
592
630
 
593
631
  // 语料里真实存在的词,按查询权重降序。
594
632
  const present = keywords