dsh-knit 0.5.1 → 0.11.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,148 @@
1
+ /**
2
+ * v0.11 ③:安全属性**可核验**的守卫。
3
+ *
4
+ * 动机来自 `竞品调研-Codex插件生态.md`:Codex 生态**强制**所有插件过安全扫描
5
+ * 并给六维信任分,而 DSH 市场只有一条「no superlatives」的文案规范,没有任何安全评分。
6
+ * Knit 的安全属性其实已经成立,但**散落在文档和注释里,没有任何一处能被机器核验**。
7
+ *
8
+ * 这个文件的职责不是「再测一遍安全」,而是保证三件事:
9
+ *
10
+ * 1. `SECURITY.md` 里**声称成立**的每条属性,都真的有一个检查在守着
11
+ * 2. `SECURITY.md` 里引用的每个文件路径**都真实存在**(表格不能腐烂)
12
+ * 3. `SECURITY.md` 本身**进得了 npm 包**(否则「随版本一起发」是空话)
13
+ *
14
+ * ⚠️ **允许出现 ❌**:没验证的属性必须标出来,不能靠这个测试「洗成 ✅」。
15
+ * 见 `Knit_PRD-v0.11-agent价值与信任.md` §7.3。
16
+ */
17
+ import test from 'node:test'
18
+ import assert from 'node:assert/strict'
19
+ import { readFile, access } from 'node:fs/promises'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { resolve, dirname, sep } from 'node:path'
22
+
23
+ /** 包根:本文件在 `test/` 下,上一层就是包根。 */
24
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
25
+
26
+ /**
27
+ * 读包内的一个文本文件。
28
+ * @param {string} rel - 相对包根的路径
29
+ * @returns {Promise<string>} 内容
30
+ */
31
+ function readPkgFile(rel) {
32
+ return readFile(resolve(PKG_ROOT, rel), 'utf8')
33
+ }
34
+
35
+ /**
36
+ * 判断包内某个路径是否存在(文件或目录都算)。
37
+ * @param {string} rel - 相对包根的路径
38
+ * @returns {Promise<boolean>} 存在与否
39
+ */
40
+ async function exists(rel) {
41
+ try {
42
+ await access(resolve(PKG_ROOT, rel))
43
+ return true
44
+ } catch {
45
+ return false
46
+ }
47
+ }
48
+
49
+ /* ── 属性本身:这几条必须永远成立 ─────────────────────── */
50
+
51
+ test('安全:零运行时依赖', async () => {
52
+ const pkg = JSON.parse(await readPkgFile('package.json'))
53
+ assert.deepEqual(pkg.dependencies || {}, {}, '运行时依赖必须为空')
54
+ })
55
+
56
+ test('安全:没有安装期脚本(用户装的时候不会执行任何东西)', async () => {
57
+ const pkg = JSON.parse(await readPkgFile('package.json'))
58
+ const scripts = Object.keys(pkg.scripts || {})
59
+ const installing = scripts.filter((name) => /^(pre|post)?install$|^prepare$/.test(name))
60
+ assert.deepEqual(installing, [], '不得有安装期脚本,实际:' + installing.join(', '))
61
+ })
62
+
63
+ test('安全:宿主半边不 import `@deepseek-ai/*`(只允许在注释里提到)', async () => {
64
+ // 理由见 AGENTS.md §4.7:Knit 被 link: 挂进 profile,裸 Node 解析不到这些包
65
+ for (const rel of ['src/host/index.js', 'src/host/relevance.js', 'src/host/tool.js']) {
66
+ const source = await readPkgFile(rel)
67
+ const realImports = source
68
+ .split('\n')
69
+ .filter((line) => /^\s*(import|export)\b.*from\s+['"]@deepseek-ai\//.test(line)
70
+ || /^\s*import\s+['"]@deepseek-ai\//.test(line))
71
+ assert.deepEqual(realImports, [], `${rel} 里出现了真实的 @deepseek-ai import`)
72
+ }
73
+ })
74
+
75
+ test('安全:客户端的 fetch 全部指向同源相对路径(零网络出口)', async () => {
76
+ const source = await readPkgFile('src/client/client.js')
77
+ // 三个接口常量必须是同源相对路径 —— 带协议或 // 就是出网了
78
+ const apis = [...source.matchAll(/const\s+\w*API\s*=\s*'([^']+)'/g)].map((m) => m[1])
79
+ assert.ok(apis.length >= 3, '应当至少有 3 个接口常量,实际:' + apis.join(', '))
80
+ for (const api of apis) {
81
+ assert.match(api, /^\/knit\/api\//, `接口必须是 /knit/api/ 开头的同源路径,实际 ${api}`)
82
+ assert.ok(!/^[a-z]+:|^\/\//i.test(api), `接口不得带协议或协议相对写法,实际 ${api}`)
83
+ }
84
+ // 所有 fetch 的第一个参数都应当是这些常量拼出来的,而不是字面量 URL
85
+ const fetches = [...source.matchAll(/fetch\(\s*([^,)]+)/g)].map((m) => m[1].trim())
86
+ assert.ok(fetches.length >= 3, '应当至少有 3 处 fetch')
87
+ for (const target of fetches) {
88
+ assert.ok(
89
+ !/^['"]https?:/.test(target),
90
+ `fetch 不得直接写 http(s) URL,实际 ${target}`,
91
+ )
92
+ }
93
+ })
94
+
95
+ test('安全:`knit_docs` 工具只读 —— 不写任何文件', async () => {
96
+ const source = await readPkgFile('src/host/tool.js')
97
+ // 按调用形态匹配,避免把注释里提到的名字当成调用
98
+ const writes = ['writeFile', 'writeFileSync', 'appendFile', 'appendFileSync',
99
+ 'createWriteStream', 'mkdir', 'mkdirSync', 'unlink', 'unlinkSync', 'rm', 'rmSync', 'rename']
100
+ .filter((name) => new RegExp(`\\b${name}\\s*\\(`).test(source))
101
+ assert.deepEqual(writes, [], 'tool.js 里出现了写操作:' + writes.join(', '))
102
+ })
103
+
104
+ /* ── SECURITY.md 自身的完整性 ────────────────────────── */
105
+
106
+ test('SECURITY.md:存在,且被声明进 npm 包(否则「随版本一起发」不成立)', async () => {
107
+ assert.ok(await exists('SECURITY.md'), 'SECURITY.md 必须存在')
108
+ const pkg = JSON.parse(await readPkgFile('package.json'))
109
+ assert.ok(
110
+ (pkg.files || []).includes('SECURITY.md'),
111
+ 'SECURITY.md 必须出现在 package.json 的 files 里,否则不会被发布',
112
+ )
113
+ })
114
+
115
+ test('SECURITY.md:引用的每个包内路径都真实存在(表格不许腐烂)', async () => {
116
+ const md = await readPkgFile('SECURITY.md')
117
+ // 抓反引号里的包内路径:test/xxx.mjs、src/xxx.js、package.json 之类
118
+ const refs = [...md.matchAll(/`((?:test|src|tools)\/[\w./-]+|package\.json)`/g)].map((m) => m[1])
119
+ assert.ok(refs.length >= 3, '表格里应当引用若干真实检查文件,实际引用数:' + refs.length)
120
+ const missing = []
121
+ for (const rel of new Set(refs)) {
122
+ if (!(await exists(rel.split(sep).join('/')))) missing.push(rel)
123
+ }
124
+ assert.deepEqual(missing, [], 'SECURITY.md 引用了不存在的路径:' + missing.join(', '))
125
+ })
126
+
127
+ test('SECURITY.md:每条属性都有状态与证据两列(不许只写「我们声称」)', async () => {
128
+ const md = await readPkgFile('SECURITY.md')
129
+ // 表格行形如:| 属性 | ✅/❌ | 证据 |
130
+ const rows = md
131
+ .split('\n')
132
+ .filter((line) => /^\|\s*[^|\s]/.test(line) && !/^\|\s*-+/.test(line))
133
+ .filter((line) => !/^\|\s*(属性|Property)\s*\|/.test(line))
134
+ assert.ok(rows.length >= 6, '属性行数太少,实际 ' + rows.length)
135
+ for (const row of rows) {
136
+ const cells = row.split('|').map((c) => c.trim()).filter(Boolean)
137
+ assert.ok(cells.length >= 3, `这一行缺少「状态/证据」列:${row.trim()}`)
138
+ assert.match(cells[1], /^(✅|❌|⚠️)/, `状态列必须是 ✅/❌/⚠️,实际「${cells[1]}」`)
139
+ // 只有 ✅ 行的证据必须指向具体检查;❌/⚠️ 行的「证据」本来就是说明,不能强求
140
+ if (cells[1] === '✅') {
141
+ assert.match(
142
+ cells[2],
143
+ /`|测试|test/,
144
+ `✅ 行的证据必须指向一个真实检查(不能是「我们声称」):${row.trim()}`,
145
+ )
146
+ }
147
+ }
148
+ })
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Knit v0.7 · agent 文档工具 `knit_docs` 的测试。
3
+ *
4
+ * 不起真 DSH:用一个假 `ctx`(`inject` + `effect`)和一个假 `exec`
5
+ * (`agent.session.header`),工作区用 `fixture.mjs` 在 tmpdir 里现造 ——
6
+ * 这样测试在任何目录布局下都能跑(AGENTS.md §6.8 的教训)。
7
+ */
8
+ import test from 'node:test'
9
+ import assert from 'node:assert/strict'
10
+
11
+ import { makeWorkspace } from './fixture.mjs'
12
+ import {
13
+ TOOL_NAME,
14
+ DEFAULT_LIMIT,
15
+ MAX_LIMIT,
16
+ clampLimit,
17
+ agentScope,
18
+ renderToolText,
19
+ pickSnippet,
20
+ knitDocsDefinition,
21
+ registerKnitDocsTool,
22
+ } from '../src/host/tool.js'
23
+ import { scan, apply, readDocument } from '../src/host/index.js'
24
+
25
+ const PROJECT_ROOT = makeWorkspace()
26
+
27
+ /**
28
+ * 造一个假会话:只需要 `header`(cwd + id)与 `snapshotEvents()`。
29
+ * @param {object[]} events - 会话事件
30
+ * @param {object} [header] - 覆盖 header
31
+ * @returns {object} 假会话
32
+ */
33
+ function fakeSession(events, header = {}) {
34
+ return {
35
+ header: { cwd: PROJECT_ROOT, id: 'sess-tool-test', ...header },
36
+ snapshotEvents: () => events,
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 造一条用户消息事件。
42
+ * @param {number} seq - 序号
43
+ * @param {string} text - 文本
44
+ * @returns {object} 事件
45
+ */
46
+ function userMessage(seq, text) {
47
+ return {
48
+ type: 'user/message',
49
+ seq,
50
+ time: Date.now(),
51
+ data: { role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } },
52
+ }
53
+ }
54
+
55
+ /**
56
+ * 造一个假 exec。
57
+ * @param {object|undefined} session - 会话;不传表示非 agent 调用方
58
+ * @returns {object} exec
59
+ */
60
+ function fakeExec(session) {
61
+ return session === undefined ? {} : { agent: { session } }
62
+ }
63
+
64
+ /**
65
+ * 调一次工具并返回规范化结果。
66
+ * @param {object} exec - 执行上下文
67
+ * @param {object} args - 参数
68
+ * @returns {Promise<object>} 工具结果
69
+ */
70
+ async function runTool(exec, args = {}) {
71
+ return knitDocsDefinition(scan).execute(args, exec)
72
+ }
73
+
74
+ /* ── 注册 ───────────────────────────────────────────── */
75
+
76
+ /** 造一个只带 `tools` + `effect` 的假 ctx。 */
77
+ function fakeToolCtx() {
78
+ const state = { definitions: [], effects: [], disposed: 0 }
79
+ return {
80
+ state,
81
+ ctx: {
82
+ tools: {
83
+ register: (definition) => {
84
+ state.definitions.push(definition)
85
+ return () => { state.disposed += 1 }
86
+ },
87
+ },
88
+ effect: (fn, label) => {
89
+ const dispose = fn()
90
+ state.effects.push({ label, dispose })
91
+ return dispose
92
+ },
93
+ },
94
+ }
95
+ }
96
+
97
+ test('registerKnitDocsTool: 注册一个叫 knit_docs 的工具', () => {
98
+ const { state, ctx } = fakeToolCtx()
99
+ registerKnitDocsTool(ctx, scan)
100
+ assert.equal(state.definitions.length, 1)
101
+ assert.equal(state.definitions[0].name, TOOL_NAME)
102
+ assert.equal(TOOL_NAME, 'knit_docs')
103
+ })
104
+
105
+ test('registerKnitDocsTool: 返回的注销函数能被调用', () => {
106
+ const { state, ctx } = fakeToolCtx()
107
+ const dispose = registerKnitDocsTool(ctx, scan)
108
+ assert.equal(typeof dispose, 'function')
109
+ dispose()
110
+ assert.equal(state.disposed, 1, '注销应当透传到 tools.register 的返回值')
111
+ })
112
+
113
+ test('apply: 只给 tools(webServer 缺席)时仍然注册工具', () => {
114
+ // 这条钉死「两条路互相独立」:面板要 webServer,工具要 tools,
115
+ // 谁先到都该各自起来。如果哪天有人把 'tools' 并进上面那个 inject 数组,
116
+ // 这条会红 —— 那时 webServer 一缺席,工具也一起没了。
117
+ const registered = []
118
+ const rootCtx = {
119
+ inject: (deps, cb) => {
120
+ if (deps.includes('tools')) {
121
+ cb({
122
+ tools: { register: (definition) => { registered.push(definition); return () => {} } },
123
+ effect: (fn) => fn(),
124
+ })
125
+ }
126
+ // webServer 那条故意不回调 —— 模拟「服务还没到」
127
+ },
128
+ }
129
+ apply(rootCtx)
130
+ assert.equal(registered.length, 1, 'webServer 缺席不该拖住工具的注册')
131
+ assert.equal(registered[0].name, TOOL_NAME)
132
+ })
133
+
134
+ test('apply: webServer 与 tools 都缺席时不抛错', () => {
135
+ assert.doesNotThrow(() => apply({ inject: () => {} }))
136
+ })
137
+
138
+ /* ── 定义形状(与官方 defineTool 的产物对齐)─────────── */
139
+
140
+ test('定义形状: 参数与输出 schema 与 defineTool 的编译产物一致', () => {
141
+ const definition = knitDocsDefinition(scan)
142
+ // 两个参数都可选 → 没有 required,根对象也没有 additionalProperties
143
+ assert.deepEqual(Object.keys(definition.parameters.properties), ['query', 'limit'])
144
+ assert.equal(definition.parameters.type, 'object')
145
+ assert.equal(definition.parameters.required, undefined)
146
+ // 输出是严格的:根与 items 都 additionalProperties: false,且字段必填
147
+ assert.equal(definition.output.schema.additionalProperties, false)
148
+ assert.deepEqual(definition.output.schema.required, ['mode', 'topic', 'total', 'docs'])
149
+ assert.deepEqual(definition.output.schema.properties.mode.enum, ['relevance', 'time'])
150
+ assert.equal(definition.output.schema.properties.total.type, 'integer')
151
+ assert.equal(definition.output.schema.properties.docs.items.additionalProperties, false)
152
+ assert.deepEqual(
153
+ definition.output.schema.properties.docs.items.required,
154
+ ['rel', 'title', 'summary', 'mtimeMs'],
155
+ )
156
+ // 定义里不许出现 score —— 相对分数会被模型当成绝对置信度
157
+ assert.ok(
158
+ !Object.keys(definition.output.schema.properties.docs.items.properties).includes('score'),
159
+ '输出里不该有 score',
160
+ )
161
+ })
162
+
163
+ test('定义形状: 描述够短(它进每一次请求的系统提示词)', () => {
164
+ const words = knitDocsDefinition(scan).description.split(/\s+/).length
165
+ assert.ok(words <= 60, `工具描述 ${words} 个词,太长了`)
166
+ })
167
+
168
+ /* ── 排序 ───────────────────────────────────────────── */
169
+
170
+ test('不传 query: 用当前对话排序', async () => {
171
+ const session = fakeSession([userMessage(1, 'sidebar 是什么?相关性排序呢')])
172
+ const result = await runTool(fakeExec(session))
173
+ assert.equal(result.mode, 'relevance')
174
+ assert.ok(result.docs.length > 0, '应当有结果')
175
+ assert.equal(result.docs[0].rel, 'README.md', '样本里只有 README 含 sidebar')
176
+ assert.ok(result.topic.length > 0, '应当给出话题')
177
+ })
178
+
179
+ test('传 query: 用 query 排序,而不是用对话', async () => {
180
+ const session = fakeSession([userMessage(1, 'sidebar 是什么?')])
181
+ const byConversation = await runTool(fakeExec(session))
182
+ const byQuery = await runTool(fakeExec(session), { query: '笔记' })
183
+ assert.equal(byConversation.docs[0].rel, 'README.md')
184
+ assert.equal(byQuery.docs[0].rel, 'docs/notes.md', 'query 应当压过对话')
185
+ })
186
+
187
+ test('传 query 时不需要会话也能排序(query 不查会话缓存)', async () => {
188
+ const result = await runTool(fakeExec(fakeSession([])), { query: 'sidebar' })
189
+ assert.equal(result.mode, 'relevance')
190
+ assert.equal(result.docs[0].rel, 'README.md')
191
+ })
192
+
193
+ test('对话为空且没传 query: 退回时间序并如实说明', async () => {
194
+ const result = await runTool(fakeExec(fakeSession([])))
195
+ assert.equal(result.mode, 'time')
196
+ const text = renderToolText(result)
197
+ assert.ok(/Not enough conversation/.test(text), `渲染文本要说实话:${text}`)
198
+ })
199
+
200
+ /* ── 边界与错误 ─────────────────────────────────────── */
201
+
202
+ test('exec.agent 缺失: 抛错而不是返回空结果', async () => {
203
+ await assert.rejects(() => runTool(fakeExec(undefined)), /requires an owning agent session/)
204
+ })
205
+
206
+ test('cwd 缺失: 抛错,且不兜底到 process.cwd()', async () => {
207
+ // 兜底到进程 cwd 会扫到一个不相干的项目并返回它的文档 —— 宁可报错
208
+ const session = fakeSession([], { cwd: undefined })
209
+ await assert.rejects(() => runTool(fakeExec(session)), /workspace root/)
210
+ })
211
+
212
+ test('clampLimit: 越界与非整数都回落到合法值', () => {
213
+ assert.equal(clampLimit(undefined), DEFAULT_LIMIT)
214
+ assert.equal(clampLimit('3'), DEFAULT_LIMIT, '字符串不是数字')
215
+ assert.equal(clampLimit(1.9), 1)
216
+ assert.equal(clampLimit(0), 1)
217
+ assert.equal(clampLimit(-5), 1)
218
+ assert.equal(clampLimit(999), MAX_LIMIT)
219
+ assert.equal(clampLimit(Number.NaN), DEFAULT_LIMIT)
220
+ assert.equal(clampLimit(Number.POSITIVE_INFINITY), DEFAULT_LIMIT)
221
+ })
222
+
223
+ test('limit: 真的限制了返回条数', async () => {
224
+ const session = fakeSession([])
225
+ const result = await runTool(fakeExec(session), { limit: 1 })
226
+ assert.equal(result.docs.length, 1)
227
+ })
228
+
229
+ test('agentScope: 从 exec 里取出的三个字段都可用', () => {
230
+ const session = fakeSession([])
231
+ const scope = agentScope(fakeExec(session))
232
+ assert.equal(scope.root, PROJECT_ROOT)
233
+ assert.equal(scope.sessionId, 'sess-tool-test')
234
+ assert.equal(scope.session, session)
235
+ })
236
+
237
+ /* ── 结果净化 ───────────────────────────────────────── */
238
+
239
+ test('结果不泄漏内部字段,也不给绝对路径', async () => {
240
+ const session = fakeSession([userMessage(1, 'sidebar 相关性排序')])
241
+ const result = await runTool(fakeExec(session))
242
+ const serialized = JSON.stringify(result)
243
+ assert.ok(!serialized.includes('haystack'), '不该出现 haystack')
244
+ assert.ok(!serialized.includes('"raw"'), '不该出现 raw')
245
+ assert.ok(!serialized.includes('"score"'), '不该出现 score')
246
+ assert.ok(!serialized.includes(PROJECT_ROOT), `不该出现绝对路径:${serialized}`)
247
+ for (const doc of result.docs) {
248
+ assert.equal(typeof doc.rel, 'string')
249
+ assert.ok(!doc.rel.startsWith('/'), 'rel 必须是工作区相对路径')
250
+ assert.ok(Number.isInteger(doc.mtimeMs), 'mtimeMs 必须是整数')
251
+ assert.equal(typeof doc.summary, 'string')
252
+ }
253
+ })
254
+
255
+ test('空工作区: 返回空数组并渲染出「没找到」', async () => {
256
+ const { mkdtempSync } = await import('node:fs')
257
+ const { tmpdir } = await import('node:os')
258
+ const { join } = await import('node:path')
259
+ const bare = mkdtempSync(join(tmpdir(), 'knit-bare-'))
260
+ const result = await runTool(fakeExec(fakeSession([], { cwd: bare })))
261
+ assert.deepEqual(result.docs, [])
262
+ assert.match(renderToolText(result), /No Markdown documents found/)
263
+ })
264
+
265
+ /* ── 渲染 ───────────────────────────────────────────── */
266
+
267
+ test('renderToolText: 有序号、rel、标题与单行摘要', () => {
268
+ const text = renderToolText({
269
+ mode: 'relevance',
270
+ topic: '排序、sidebar',
271
+ total: 9,
272
+ docs: [
273
+ { rel: 'docs/a.md', title: '甲', summary: '第一行\n第二行', mtimeMs: 1 },
274
+ { rel: 'docs/b.md', title: '乙', summary: '', mtimeMs: 2 },
275
+ ],
276
+ })
277
+ assert.match(text, /Top 2 of 9 Markdown documents in this workspace/)
278
+ assert.match(text, /ranked by IDF-weighted relevance to 「排序、sidebar」/)
279
+ assert.match(text, /1\. docs\/a\.md — 甲/)
280
+ assert.match(text, /第一行 第二行/, '摘要要压成一行')
281
+ assert.match(text, /2\. docs\/b\.md — 乙/)
282
+ })
283
+
284
+ test('renderToolText: 头部同时回答「漏没错」与「凭什么信这个排名」', () => {
285
+ // v0.8 只答了前者(`of N`),真机验证显示 agent 照样自己 grep 一遍 ——
286
+ // 因为它不认这个排名。v0.9 补上后者。
287
+ const relevance = renderToolText({
288
+ mode: 'relevance', topic: 'x', total: 21,
289
+ docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1 }],
290
+ })
291
+ assert.match(relevance, /of 21 Markdown documents in this workspace/, '要回答「一共多少篇」')
292
+ assert.match(relevance, /not a keyword count or filename match/, '要回答「凭什么信这个排名」')
293
+ assert.match(relevance, /rare terms weighted/, '要说清权重口径')
294
+
295
+ const time = renderToolText({
296
+ mode: 'time', topic: '', total: 21,
297
+ docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1 }],
298
+ })
299
+ assert.match(time, /most recently modified of 21 Markdown documents/)
300
+
301
+ // 没有 total 时回落成返回条数,不写 undefined
302
+ const fallback = renderToolText({
303
+ mode: 'relevance', topic: '', docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1 }],
304
+ })
305
+ assert.match(fallback, /of 1 Markdown document/)
306
+ assert.ok(!fallback.includes('undefined'))
307
+ })
308
+
309
+ test('renderToolText: 只有一篇时用单数', () => {
310
+ const text = renderToolText({
311
+ mode: 'relevance', topic: '', total: 1,
312
+ docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1 }],
313
+ })
314
+ assert.match(text, /of 1 Markdown document in this workspace/)
315
+ assert.ok(!text.includes('documents'))
316
+ })
317
+
318
+ test('renderToolText: 超长摘要被截断', () => {
319
+ const text = renderToolText({
320
+ mode: 'relevance',
321
+ topic: '',
322
+ docs: [{ rel: 'a.md', title: '甲', summary: 'x'.repeat(500), mtimeMs: 1 }],
323
+ })
324
+ assert.ok(!text.includes('x'.repeat(200)), '摘要必须截断')
325
+ assert.match(text, /…/)
326
+ })
327
+
328
+ test('renderToolText: 没有话题时不写空引号', () => {
329
+ const text = renderToolText({
330
+ mode: 'relevance',
331
+ topic: '',
332
+ docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1 }],
333
+ })
334
+ assert.match(text, /to the current conversation/)
335
+ assert.ok(!text.includes('「」'))
336
+ })
337
+
338
+ /* ── v0.11 ②:命中段落 ───────────────────────────────── */
339
+
340
+ test('pickSnippet: 空输入 / 空命中词 → 空串', () => {
341
+ assert.equal(pickSnippet('', ['a']), '')
342
+ assert.equal(pickSnippet('正文。', []), '')
343
+ assert.equal(pickSnippet(null, ['a']), '')
344
+ assert.equal(pickSnippet('正文。', ['', ' ']), '', '空词被过滤后也应当是空串')
345
+ })
346
+
347
+ test('pickSnippet: 一块都没命中 → 空串(**不编造**)', () => {
348
+ // 关键:不能退化成「随便给第一段」—— 那会让模型以为这里有相关内容
349
+ assert.equal(pickSnippet('第一段。\n\n第二段。\n\n第三段。', ['不存在的词']), '')
350
+ })
351
+
352
+ test('pickSnippet: 选**含命中词的那一段**,不是第一段', () => {
353
+ const text = '开头这段无关。\n\n中段才讲 BM25 的加权方式。\n\n结尾也无关。'
354
+ const snippet = pickSnippet(text, ['bm25'])
355
+ assert.match(snippet, /BM25/, '要含命中词')
356
+ assert.ok(!snippet.includes('开头这段无关'), '不能给第一段')
357
+ assert.ok(!snippet.includes('结尾也无关'), '不能给最后一段')
358
+ })
359
+
360
+ test('pickSnippet: 保留**原文大小写**(不是 haystack 的小写)', () => {
361
+ // 这是设计的硬约束:README 承诺「打 BM25 就显示 BM25」
362
+ const snippet = pickSnippet('前段。\n\n这里讲 BM25 与 IDF。\n\n后段。', ['bm25', 'idf'])
363
+ assert.match(snippet, /BM25/)
364
+ assert.match(snippet, /IDF/)
365
+ assert.ok(!snippet.includes('bm25'), '不能是小写')
366
+ })
367
+
368
+ test('pickSnippet: 跳过与标题重复的块', () => {
369
+ // 真机试跑时发现:H1 里含全部命中词 ⇒「命中最多」的块就是标题本身,
370
+ // 而标题第 1 行已经给过了,再给一次是纯浪费。
371
+ const text = '# BM25 入门\n\n这一节才展开讲 BM25 的饱和函数。\n'
372
+ const withTitle = pickSnippet(text, ['bm25'], { title: 'BM25 入门' })
373
+ assert.match(withTitle, /饱和函数/, '应当跳到正文那一块')
374
+ assert.ok(!withTitle.includes('入门'), '不能是标题本身')
375
+
376
+ // 不传 title 时没有这个排除(纯函数不猜)
377
+ assert.match(pickSnippet(text, ['bm25']), /入门/)
378
+ })
379
+
380
+ test('pickSnippet: 超长块**以命中词为中心**截,不是从头截', () => {
381
+ const head = '甲'.repeat(400)
382
+ const text = `${head}这里有 BM25。${'乙'.repeat(400)}`
383
+ const snippet = pickSnippet(text, ['bm25'])
384
+ assert.ok(snippet.length <= 205, `应当截断,实际 ${snippet.length}`)
385
+ assert.match(snippet, /BM25/, '命中词必须还在截断结果里')
386
+ assert.match(snippet, /^…/, '左边被截掉要有省略号')
387
+ assert.match(snippet, /…$/, '右边被截掉要有省略号')
388
+ })
389
+
390
+ test('pickSnippet: 只看评分窗口内的正文(2500 字之后不算)', () => {
391
+ // 与 index.js 的 HAYSTACK_CHARS 对齐;否则会出现「排上来但段落里没有命中词」
392
+ const text = `${'甲'.repeat(3000)}\n\nBM25 在很后面。`
393
+ assert.equal(pickSnippet(text, ['bm25']), '')
394
+ })
395
+
396
+ test('execute: 传了 read 时结果带 snippet;没命中词的篇**不带这个字段**', async () => {
397
+ const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
398
+ const withRead = await knitDocsDefinition(scan, readDocument).execute({ query: 'sidebar', limit: 3 }, exec)
399
+ const readme = withRead.docs.find((d) => d.rel === 'README.md')
400
+ assert.ok(readme, '样本里应当有 README.md')
401
+ assert.match(String(readme.snippet), /sidebar/, '命中的那篇要带段落')
402
+
403
+ // 一块都没命中的篇:**字段缺省**,而不是空串 —— 让「没有命中」在输出里表现为
404
+ // 「没有 match 行」,而不是一行空的 `match: `
405
+ const others = withRead.docs.filter((d) => d.rel !== 'README.md')
406
+ assert.ok(others.length > 0, '样本里有其他文档')
407
+ for (const doc of others) {
408
+ assert.equal('snippet' in doc, false, `${doc.rel} 不该有 snippet 字段`)
409
+ }
410
+ })
411
+
412
+ test('execute: 不传 read → 行为与 v0.10 一致(向后兼容)', async () => {
413
+ const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
414
+ const out = await knitDocsDefinition(scan).execute({ query: 'sidebar', limit: 3 }, exec)
415
+ for (const doc of out.docs) {
416
+ assert.equal('snippet' in doc, false, '没给 read 就不该带段落')
417
+ }
418
+ })
419
+
420
+ test('execute: read 抛错时**不影响**整次调用(只是少一段)', async () => {
421
+ const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
422
+ const boom = async () => { throw new Error('读盘炸了') }
423
+ const out = await knitDocsDefinition(scan, boom).execute({ query: 'sidebar', limit: 3 }, exec)
424
+ assert.ok(out.docs.length > 0, '排序结果照常返回')
425
+ for (const doc of out.docs) assert.equal('snippet' in doc, false)
426
+ })
427
+
428
+ test('execute: read 返回失败信封时也只是少一段,不抛', async () => {
429
+ const exec = fakeExec(fakeSession([userMessage(1, 'sidebar')]))
430
+ const denied = async () => ({ ok: false, code: 'knit/outside-workspace' })
431
+ const out = await knitDocsDefinition(scan, denied).execute({ query: 'sidebar', limit: 3 }, exec)
432
+ assert.ok(out.docs.length > 0)
433
+ for (const doc of out.docs) assert.equal('snippet' in doc, false)
434
+ })
435
+
436
+ test('execute: 时间序(无命中词)时不抽段落', async () => {
437
+ const exec = fakeExec(fakeSession([])) // 没有对话 ⇒ mode=time
438
+ const out = await knitDocsDefinition(scan, readDocument).execute({ limit: 3 }, exec)
439
+ assert.equal(out.mode, 'time')
440
+ for (const doc of out.docs) assert.equal('snippet' in doc, false, '时间序没有命中词可抽')
441
+ })
442
+
443
+ test('renderToolText: 有段落时多一行 `match:`,且不破坏既有的行格式', () => {
444
+ const text = renderToolText({
445
+ mode: 'relevance',
446
+ topic: '排序',
447
+ docs: [
448
+ { rel: 'a.md', title: '甲', summary: '摘要甲', mtimeMs: 1, snippet: '命中段落甲' },
449
+ { rel: 'b.md', title: '乙', summary: '摘要乙', mtimeMs: 2 },
450
+ ],
451
+ })
452
+ const lines = text.split('\n')
453
+ assert.match(lines[1], /^1\. a\.md — 甲$/, '第一行格式不变')
454
+ assert.equal(lines[2], ' 摘要甲', '摘要行格式不变')
455
+ assert.equal(lines[3], ' match: 命中段落甲', '段落行带 match: 前缀')
456
+ assert.equal(lines[4], '2. b.md — 乙', '第二篇序号正确')
457
+ assert.ok(!text.includes('match: \n'), '没有段落时不该出现空的 match 行')
458
+ })
459
+
460
+ test('renderToolText: 段落用 SNIPPET_CHARS 截,**不是**摘要那个 90', () => {
461
+ // 踩过的坑:段落提取是 200 字,若复用只认 90 的 oneLine 会被二次截断,
462
+ // 而且测试不会报错(输出仍是合法的短文本)。
463
+ const long = '丙'.repeat(200)
464
+ const text = renderToolText({
465
+ mode: 'relevance',
466
+ topic: '',
467
+ docs: [{ rel: 'a.md', title: '甲', summary: '', mtimeMs: 1, snippet: long }],
468
+ })
469
+ const matchLine = text.split('\n').find((l) => l.startsWith(' match: '))
470
+ assert.ok(matchLine, '应当有 match 行')
471
+ assert.ok(matchLine.length > 120, `段落不该被截到 90,实际 ${matchLine.length - 10}`)
472
+ })