dsh-knit 0.9.0 → 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.
- package/README.en.md +9 -4
- package/README.md +8 -4
- package/SECURITY.md +51 -0
- package/package.json +4 -3
- package/src/client/client.js +14 -8
- package/src/host/index.js +1 -1
- package/src/host/tool.js +170 -12
- package/test/host-http.test.mjs +4 -0
- package/test/path.test.mjs +67 -0
- package/test/security.test.mjs +148 -0
- package/test/tool.test.mjs +138 -1
package/README.en.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
> Your agent writes 20 documents a day. You can't find the one you just saw.
|
|
4
4
|
> Knit puts them next to the conversation — whatever you're talking about, the relevant doc is on top.
|
|
5
|
+
>
|
|
6
|
+
> **Your agent has the same problem.** It gets the same ranking as a tool — so it reads one doc instead of five.
|
|
5
7
|
|
|
6
|
-
|
|
7
|
-
alt="Screenshot from a real machine: the Knit sidebar listing the workspace documents, with a Markdown preview expanded in place"
|
|
8
|
-
width="880">
|
|
8
|
+

|
|
9
9
|
|
|
10
10
|
*Screenshot from a real machine, not a mock-up: a workspace with 16 documents, the list plus an
|
|
11
11
|
inline preview.*
|
|
@@ -188,7 +188,8 @@ as one of its tabs. Each host is an independent optional dependency; missing one
|
|
|
188
188
|
| Click an image / video to preview **inline**: large image, playable & seekable video streamed over HTTP Range (no full download) | ✅ |
|
|
189
189
|
| The **All** view splits into **two stacked sections**: docs (max 4, with "View all →" when truncated) and images & video (**never truncated**, count only) | ✅ |
|
|
190
190
|
| Preview pane is height-draggable (20%–80%, remembered), fullscreen-able, `Esc` to exit | ✅ |
|
|
191
|
-
|
|
|
191
|
+
| **"Open locally"**: opens the previewed document in your default app (the path breadcrumb in the preview header is clickable too) | ✅ |
|
|
192
|
+
| Double-click opens in a new tab (the official document preview, with its PDF renderer and renderer switching) | ✅ |
|
|
192
193
|
| Filter box over title / summary / path | ✅ |
|
|
193
194
|
| **Click the workspace path** to open the project folder in your file manager | ✅ |
|
|
194
195
|
| **Hover the entry button to peek**: a read-only floating list of the 5 most recent docs; click to open the right sidebar (doesn't push the layout) | ✅ |
|
|
@@ -219,6 +220,10 @@ as one of its tabs. Each host is an independent optional dependency; missing one
|
|
|
219
220
|
|
|
220
221
|
The relevance figure only affects ordering — it is **never displayed and never sent anywhere**.
|
|
221
222
|
|
|
223
|
+
> Every claim above is guarded by an automated check, listed one by one in
|
|
224
|
+
> **[SECURITY.md](SECURITY.md)** — each property points at a test that actually exists.
|
|
225
|
+
> `npm test` verifies that the table itself has not rotted.
|
|
226
|
+
|
|
222
227
|
---
|
|
223
228
|
|
|
224
229
|
## Known limitations
|
package/README.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
> Agent 一天产出 20 篇文档,你找不到刚才那篇。
|
|
4
4
|
> Knit 把它们放到对话旁边 —— 你正在聊什么,相关的那篇就在最上面。
|
|
5
|
+
>
|
|
6
|
+
> **你的 agent 也一样。** 同一份排序也给它当工具用 —— 它读一篇,而不是翻五篇。
|
|
5
7
|
|
|
6
|
-
|
|
7
|
-
alt="Knit 面板真机截图:右侧栏列出工作区里的文档,下方就地展开 Markdown 预览"
|
|
8
|
-
width="880">
|
|
8
|
+

|
|
9
9
|
|
|
10
10
|
*真机截图(不是原型):一个含 16 篇文档的工作区,列表 + 就地预览。*
|
|
11
11
|
*顶行会跟着你正在聊什么变;对话内容还不足时它退回按时间排,并如实说明依据。*
|
|
@@ -142,7 +142,8 @@ dsh plugin --profile web add dsh-knit
|
|
|
142
142
|
| 点图片 / 视频在面板内**就地预览**:图片大图、视频可播放可拖动(HTTP Range 流式,不全量下载) | ✅ |
|
|
143
143
|
| 「全部」视图**分上下两区**:文档最多 4 条(超出给「查看全部 →」);图片视频**不截断**,只给计数 | ✅ |
|
|
144
144
|
| 预览面板可拖高度(20%–80%,位置记住)、可全屏,`Esc` 退出 | ✅ |
|
|
145
|
-
|
|
|
145
|
+
| **「在本地打开」**:用系统默认应用打开当前预览的这篇文档(预览头的路径面包屑同样可点) | ✅ |
|
|
146
|
+
| 双击在新标签页打开(官方文档预览,带 PDF 渲染器与渲染方式切换) | ✅ |
|
|
146
147
|
| 过滤框:按标题 / 摘要 / 路径实时过滤 | ✅ |
|
|
147
148
|
| **点工作区路径**:用系统文件管理器打开项目文件夹 | ✅ |
|
|
148
149
|
| **悬停入口按钮偷看**:弹只读浮层列最近 5 篇,点击才进右边栏(不推挤布局) | ✅ |
|
|
@@ -198,6 +199,9 @@ Knit 一装上就有整个项目的历史文档可用。
|
|
|
198
199
|
|
|
199
200
|
面板里那份「相关度」只影响排序,**不显示也不外传**。
|
|
200
201
|
|
|
202
|
+
> 上面每一条都有自动化检查守着,逐条列在 **[SECURITY.md](SECURITY.md)** 里 ——
|
|
203
|
+
> 每条属性都指向一个真实存在的测试。`npm test` 会校验那张表本身没腐烂。
|
|
204
|
+
|
|
201
205
|
---
|
|
202
206
|
|
|
203
207
|
## 已知限制
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# Security
|
|
2
|
+
|
|
3
|
+
> **Knit 的安全属性 —— 每一条都指向一个真实存在的检查。**
|
|
4
|
+
>
|
|
5
|
+
> 最后更新:2026-09-18(v0.11.0)
|
|
6
|
+
|
|
7
|
+
## 为什么有这份文件
|
|
8
|
+
|
|
9
|
+
Codex 插件生态**强制**每个插件过安全扫描([HOL `plugin-scanner`](https://github.com/hashgraph-online/hol-guard),
|
|
10
|
+
准入线 ≥80/130 分),给六维信任分,还把结果发成公开数据集。
|
|
11
|
+
DSH 的插件市场**只有一条「描述只说功能」的文案规范,没有任何安全评分**
|
|
12
|
+
(对比见 `00_调研与规划/竞品调研-Codex插件生态.md`)。
|
|
13
|
+
|
|
14
|
+
Knit 的安全属性其实一直成立 —— 但它们此前只散落在文档和代码注释里,
|
|
15
|
+
**没有任何一处能被机器核验**。在一个人人自述的市场里,「**能被核验**」本身就是差异化。
|
|
16
|
+
|
|
17
|
+
所以这份表格的规矩是:
|
|
18
|
+
|
|
19
|
+
- **✅ 只给真的有检查守着的属性**;没检查的宁可不写
|
|
20
|
+
- 每条 ✅ 的「证据」列必须指向一个**真实路径**
|
|
21
|
+
- **允许出现 ⚠️/❌** —— 没验证的事不装成验证过
|
|
22
|
+
- `test/security.test.mjs` 会**自动校验这张表**:引用的路径必须存在、
|
|
23
|
+
✅ 行必须指向具体检查、每行必须有状态列。**表格腐烂会直接让测试变红。**
|
|
24
|
+
|
|
25
|
+
## 属性对照表
|
|
26
|
+
|
|
27
|
+
| 属性 | 状态 | 证据(指向真实的检查) |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| 零运行时依赖 | ✅ | `package.json` 的 `dependencies` 为空;`test/security.test.mjs` 断言 |
|
|
30
|
+
| 无安装期脚本 | ✅ | `package.json` 只有 `test` 一个 script,无 `install`/`postinstall`/`prepare`;`test/security.test.mjs` 断言 |
|
|
31
|
+
| 读文件接口守在会话工作区内 | ✅ | `test/host.test.mjs` 的越界用例(解析后必须落在工作区内,否则一律拒绝) |
|
|
32
|
+
| `/knit/api/raw` 叠扩展名白名单 | ✅ | `test/host-http.test.mjs`(非图片/视频扩展名一律拒绝) |
|
|
33
|
+
| 只允许 GET、只允许回环地址 | ✅ | `test/host-http.test.mjs` |
|
|
34
|
+
| 响应带 `nosniff` 与 `default-src 'none'; sandbox` | ✅ | `test/host-http.test.mjs`(两个指令各自断言) |
|
|
35
|
+
| 零网络出口:客户端 `fetch` 全部同源相对路径 | ✅ | `src/client/client.js` 的三个接口常量都是 `/knit/api/*`;`test/security.test.mjs` 断言无协议头 |
|
|
36
|
+
| 宿主半边不 import `@deepseek-ai/*` | ✅ | `test/security.test.mjs` 扫三个宿主文件,注释里提到可以、真实 `import` 不行 |
|
|
37
|
+
| `knit_docs` 工具只读,不写任何文件 | ✅ | `src/host/tool.js` 只调注入进来的 `scan` 与只读的 `readDocument`;无写文件调用 |
|
|
38
|
+
| 未经第三方安全审计 | ⚠️ | **如实说明**:这张表是**自证**。没有外部审计报告,也没有自动化扫描评分 —— 它不等于「已证明安全」 |
|
|
39
|
+
|
|
40
|
+
## 不在这张表里的东西
|
|
41
|
+
|
|
42
|
+
- **DSH 主程序本身的安全性**不在 Knit 的责任范围内。
|
|
43
|
+
- **用户装的其他插件**不受 Knit 影响。
|
|
44
|
+
- 装任何插件都等于在本机跑第三方代码。**建议只装你信任的来源。**
|
|
45
|
+
|
|
46
|
+
## 如何自己复核
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
npm test # 231 项,含本节所有断言
|
|
50
|
+
npm test -- test/security.test.mjs # 只跑安全守卫
|
|
51
|
+
```
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-knit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Find the doc your agent just wrote. Lists the DSH workspace's Markdown, images and video in the sidebar, ranked by relevance to the current conversation, with inline preview. Zero model calls, zero network.",
|
|
5
|
+
"description": "Find the doc your agent just wrote. Lists the DSH workspace's Markdown, images and video in the sidebar, ranked by relevance to the current conversation, with inline preview — and hands the same ranking to the agent as a tool, so it reads one doc instead of five. Zero model calls, zero network.",
|
|
6
6
|
"main": "./src/host/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./src/host/index.js",
|
|
@@ -16,10 +16,11 @@
|
|
|
16
16
|
"test",
|
|
17
17
|
"cordis.patch.yml",
|
|
18
18
|
"README.md",
|
|
19
|
+
"SECURITY.md",
|
|
19
20
|
"LICENSE"
|
|
20
21
|
],
|
|
21
22
|
"scripts": {
|
|
22
|
-
"test": "node --test test/host.test.mjs test/host-http.test.mjs test/client.test.mjs test/tier1.test.mjs test/entry.test.mjs test/i18n.test.mjs test/icon.test.mjs test/path.test.mjs test/peek.test.mjs test/eval.test.mjs test/tool.test.mjs test/label.test.mjs"
|
|
23
|
+
"test": "node --test test/host.test.mjs test/host-http.test.mjs test/client.test.mjs test/tier1.test.mjs test/entry.test.mjs test/i18n.test.mjs test/icon.test.mjs test/path.test.mjs test/peek.test.mjs test/eval.test.mjs test/tool.test.mjs test/label.test.mjs test/security.test.mjs"
|
|
23
24
|
},
|
|
24
25
|
"dsh": {
|
|
25
26
|
"bundle": {
|
package/src/client/client.js
CHANGED
|
@@ -81,9 +81,8 @@ window.__ModuleLoader__.load({
|
|
|
81
81
|
'preview.exitFullscreen': '退出全屏',
|
|
82
82
|
'preview.fullscreenTitle': '全屏阅读',
|
|
83
83
|
'preview.exitFullscreenTitle': '退出全屏(Esc)',
|
|
84
|
-
'preview.newTab': '新标签页',
|
|
85
|
-
'preview.newTabTitle': '在新标签页打开',
|
|
86
84
|
'preview.openLocal': '{path}\n用系统默认应用打开这篇文档',
|
|
85
|
+
'preview.openLocalBtn': '在本地打开',
|
|
87
86
|
'preview.close': '收起预览',
|
|
88
87
|
'preview.resizeTitle': '拖动调整高度',
|
|
89
88
|
'preview.rawFallback': '原生 Markdown 渲染不可用,下面是纯文本。请看控制台的 [knit] 日志。',
|
|
@@ -171,9 +170,8 @@ window.__ModuleLoader__.load({
|
|
|
171
170
|
'preview.exitFullscreen': 'Exit fullscreen',
|
|
172
171
|
'preview.fullscreenTitle': 'Read fullscreen',
|
|
173
172
|
'preview.exitFullscreenTitle': 'Exit fullscreen (Esc)',
|
|
174
|
-
'preview.newTab': 'New tab',
|
|
175
|
-
'preview.newTabTitle': 'Open in a new tab',
|
|
176
173
|
'preview.openLocal': '{path}\nOpen this document in your default app',
|
|
174
|
+
'preview.openLocalBtn': 'Open locally',
|
|
177
175
|
'preview.close': 'Close preview',
|
|
178
176
|
'preview.resizeTitle': 'Drag to resize',
|
|
179
177
|
'preview.rawFallback': 'Native Markdown rendering is unavailable — showing plain text. Check the [knit] logs in the console.',
|
|
@@ -987,10 +985,10 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
987
985
|
|
|
988
986
|
/**
|
|
989
987
|
* 列表下方的预览面板。
|
|
990
|
-
* @param {{preview:object,pathImages:object|null,fullscreen:boolean,onClose:Function,
|
|
988
|
+
* @param {{preview:object,pathImages:object|null,fullscreen:boolean,onClose:Function,onOpenLocal:Function|null,onToggleFullscreen:Function,onResizeStart:Function}} props - 渲染入参
|
|
991
989
|
* @returns {import('react').ReactElement} 元素
|
|
992
990
|
*/
|
|
993
|
-
function PreviewPanel({ preview, pathImages, fullscreen, ratio, reading, onClose,
|
|
991
|
+
function PreviewPanel({ preview, pathImages, fullscreen, ratio, reading, onClose, onOpenLocal, onToggleFullscreen, onResizeStart, onScrollBody }) {
|
|
994
992
|
const isMedia = preview.kind === 'image' || preview.kind === 'video'
|
|
995
993
|
const previewPath = splitRelPath(preview.rel)
|
|
996
994
|
|
|
@@ -1048,7 +1046,16 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1048
1046
|
onClick: onToggleFullscreen,
|
|
1049
1047
|
title: fullscreen ? t('preview.exitFullscreenTitle') : t('preview.fullscreenTitle'),
|
|
1050
1048
|
}, fullscreen ? t('preview.exitFullscreen') : t('preview.fullscreen')),
|
|
1051
|
-
|
|
1049
|
+
// 「在本地打开」= 之前那个「新标签页」的位置(v0.10)。
|
|
1050
|
+
// 「新标签页」开的是官方文档预览,但面板里已经有就地预览,重复度高、用得少;
|
|
1051
|
+
// 而「用默认应用打开这篇文档」原本只藏在路径面包屑的悬停提示里 ——
|
|
1052
|
+
// 把值钱的那个放到显眼处,把鸡肋的那个让位(双击列表行仍能开新标签页)。
|
|
1053
|
+
h('button', {
|
|
1054
|
+
className: 'knit-btn',
|
|
1055
|
+
onClick: () => { if (onOpenLocal) onOpenLocal() },
|
|
1056
|
+
disabled: !onOpenLocal,
|
|
1057
|
+
title: onOpenLocal ? t('preview.openLocal', { path: preview.rel }) : preview.rel,
|
|
1058
|
+
}, t('preview.openLocalBtn')),
|
|
1052
1059
|
h('button', { className: 'knit-preview-close', onClick: onClose, title: t('preview.close') }, '✕')),
|
|
1053
1060
|
h('div', {
|
|
1054
1061
|
className: `knit-preview-body${isMedia ? ' is-media' : ''}`,
|
|
@@ -1548,7 +1555,6 @@ body[data-ds-dark-theme] .knit-icon{color:#fff}
|
|
|
1548
1555
|
// 拿不到绝对路径就不给点(而不是点了没反应)
|
|
1549
1556
|
onOpenLocal: previewAbsPath ? openPreviewLocal : null,
|
|
1550
1557
|
onClose: closePreview,
|
|
1551
|
-
onOpenTab: () => onOpenTab(null),
|
|
1552
1558
|
onToggleFullscreen: () => setFullscreen((v) => !v),
|
|
1553
1559
|
onResizeStart,
|
|
1554
1560
|
}) : null)
|
package/src/host/index.js
CHANGED
|
@@ -864,7 +864,7 @@ export function apply(ctx) {
|
|
|
864
864
|
// 两条路互不依赖:没有 tools 服务时,浏览器那半边照常工作。
|
|
865
865
|
ctx.inject(['tools'], (toolCtx) => {
|
|
866
866
|
toolCtx.effect(
|
|
867
|
-
() => registerKnitDocsTool(toolCtx, scan),
|
|
867
|
+
() => registerKnitDocsTool(toolCtx, scan, readDocument),
|
|
868
868
|
'dsh-knit: knit_docs tool',
|
|
869
869
|
)
|
|
870
870
|
console.log(`[${name}] agent tool ready: knit_docs`)
|
package/src/host/tool.js
CHANGED
|
@@ -41,6 +41,23 @@ export const MAX_LIMIT = 20
|
|
|
41
41
|
/** 结果里摘要再截一次(宿主的首段摘要本身是 60 字,这里防的是极端长首段)。 */
|
|
42
42
|
const SUMMARY_CHARS = 90
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* 命中段落的上限(v0.11)。
|
|
46
|
+
*
|
|
47
|
+
* 取值依据是实测:`knit_docs` 一次输出约 710 字符,而**一篇文档平均 12,930 字符**。
|
|
48
|
+
* 每篇多 200 字 ≈ 一篇文档的 7.7%,而它想省掉的是整整一次 `read`。
|
|
49
|
+
* 见 `Knit_SDD-v0.11-knit_docs命中段落.md` §一。
|
|
50
|
+
*/
|
|
51
|
+
const SNIPPET_CHARS = 200
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 只在原文的**前 2500 字**里找命中段落。
|
|
55
|
+
*
|
|
56
|
+
* 必须与 `index.js` 的 `HAYSTACK_CHARS` 一致 —— 评分只看这个窗口,
|
|
57
|
+
* 若在这里找窗口外的内容,会出现「排上来了、但段落里没有命中词」的自相矛盾。
|
|
58
|
+
*/
|
|
59
|
+
const SNIPPET_WINDOW = 2500
|
|
60
|
+
|
|
44
61
|
/**
|
|
45
62
|
* 模型面向的描述。**必须短** —— 它会进每一次请求的系统提示词。
|
|
46
63
|
*
|
|
@@ -109,6 +126,10 @@ const OUTPUT_SCHEMA = {
|
|
|
109
126
|
title: { type: 'string' },
|
|
110
127
|
summary: { type: 'string' },
|
|
111
128
|
mtimeMs: { type: 'integer' },
|
|
129
|
+
// v0.11:命中的那一小段**原文**(不是整篇)。**可选** ——
|
|
130
|
+
// 时间序模式没有命中词,抽不出来就不带这个字段,
|
|
131
|
+
// 而不是给个空串假装有。
|
|
132
|
+
snippet: { type: 'string' },
|
|
112
133
|
},
|
|
113
134
|
required: ['rel', 'title', 'summary', 'mtimeMs'],
|
|
114
135
|
},
|
|
@@ -157,9 +178,99 @@ export function agentScope(exec) {
|
|
|
157
178
|
* @param {unknown} text - 摘要
|
|
158
179
|
* @returns {string} 单行摘要
|
|
159
180
|
*/
|
|
160
|
-
|
|
181
|
+
/**
|
|
182
|
+
* 压成单行并截断。
|
|
183
|
+
*
|
|
184
|
+
* ⚠️ **截断上限是参数,不是常量** —— v0.11 加命中段落时踩过一次:
|
|
185
|
+
* 段落提取出来是 200 字,若复用只认 `SUMMARY_CHARS`(90) 的 `oneLine`,
|
|
186
|
+
* 会被二次截掉一半,而且**测试不会报错**(输出仍然是合法的短文本)。
|
|
187
|
+
*
|
|
188
|
+
* @param {unknown} text - 任意文本
|
|
189
|
+
* @param {number} cap - 上限字符数
|
|
190
|
+
* @returns {string} 单行文本
|
|
191
|
+
*/
|
|
192
|
+
function flatten(text, cap) {
|
|
161
193
|
const flat = String(text == null ? '' : text).replace(/\s+/g, ' ').trim()
|
|
162
|
-
return flat.length >
|
|
194
|
+
return flat.length > cap ? `${flat.slice(0, cap)}…` : flat
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function oneLine(text) {
|
|
198
|
+
return flatten(text, SUMMARY_CHARS)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 从**原文**里挑出「命中的那一段」,给模型判断「要不要读整篇」用(v0.11)。
|
|
203
|
+
*
|
|
204
|
+
* 三条设计约束,每条都有原因:
|
|
205
|
+
*
|
|
206
|
+
* 1. **在原文上切,不在 `haystack` 上切。** `haystack.body` 是 `.toLowerCase()` 过的
|
|
207
|
+
* (`index.js:240`),在它上面切会把 `BM25` 变成 `bm25` ——
|
|
208
|
+
* 与「标签是你自己打的字,大小写原样保留」这条既有承诺直接冲突。
|
|
209
|
+
* 2. **只看前 `SNIPPET_WINDOW` 字**,与评分窗口一致,避免「排上来但段落里没命中词」。
|
|
210
|
+
* 3. **块太长时以命中词为中心截**,不是从头截 —— 否则命中那句话可能正好被截掉,
|
|
211
|
+
* 段落就白给了。
|
|
212
|
+
* 4. **跳过与标题重复的块。** 拿真实工作区试跑时发现的:一篇文档的 H1 标题里含全部命中词,
|
|
213
|
+
* 于是「命中词最多的块」就是标题本身 —— 而标题**第 1 行已经给过了**。
|
|
214
|
+
* 这种段落是纯浪费,正是要避免的「负收益」情形。
|
|
215
|
+
*
|
|
216
|
+
* 纯函数:不读盘、不看时钟、无副作用。抽不出命中段落时返回空串
|
|
217
|
+
* (**不编造** —— 「没有命中」和「命中在别处」都不该被伪装成有一段)。
|
|
218
|
+
*
|
|
219
|
+
* @param {string} text - 文档**原文**
|
|
220
|
+
* @param {string[]} terms - 命中词(来自 `scan()` 的 `keywords`,即语料里真实存在的词)
|
|
221
|
+
* @param {{title?: string}} [options] - `title` 用于排除「与标题重复」的块
|
|
222
|
+
* @returns {string} 命中段落(已压成单行、截断),或空串
|
|
223
|
+
*/
|
|
224
|
+
export function pickSnippet(text, terms, options = {}) {
|
|
225
|
+
const source = String(text == null ? '' : text)
|
|
226
|
+
const words = (Array.isArray(terms) ? terms : [])
|
|
227
|
+
.map((term) => String(term == null ? '' : term).trim().toLowerCase())
|
|
228
|
+
.filter(Boolean)
|
|
229
|
+
if (!source || words.length === 0) return ''
|
|
230
|
+
|
|
231
|
+
// 归一化只用于**比较**:去掉 Markdown 标题号、强调号、表格竖线,压平空白,小写
|
|
232
|
+
const norm = (s) => String(s).replace(/[#*|`>\s]+/g, ' ').trim().toLowerCase()
|
|
233
|
+
const titleNorm = norm(options.title || '')
|
|
234
|
+
|
|
235
|
+
const window = source.slice(0, SNIPPET_WINDOW)
|
|
236
|
+
|
|
237
|
+
// 按空行切块 —— 纯字符串运算,不解析 Markdown 结构
|
|
238
|
+
const blocks = window.split(/\n\s*\n/).map((block) => block.trim()).filter(Boolean)
|
|
239
|
+
if (blocks.length === 0) return ''
|
|
240
|
+
|
|
241
|
+
// 选**命中词种数最多**的那块;并列取靠前的(不给后面的块不该有的优势)
|
|
242
|
+
const scored = blocks.map((block) => {
|
|
243
|
+
const lower = block.toLowerCase()
|
|
244
|
+
let hits = 0
|
|
245
|
+
for (const word of words) if (lower.includes(word)) hits += 1
|
|
246
|
+
return { block, hits, norm: norm(block) }
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
// 跳过「与标题重复」的块(见 JSDoc 第 4 条)
|
|
250
|
+
const usable = scored.filter((item) => !(titleNorm && item.norm && titleNorm.includes(item.norm)))
|
|
251
|
+
if (usable.length === 0) return ''
|
|
252
|
+
|
|
253
|
+
let best = null
|
|
254
|
+
for (const item of usable) {
|
|
255
|
+
if (item.hits > 0 && (best === null || item.hits > best.hits)) best = item
|
|
256
|
+
}
|
|
257
|
+
// 一块都没命中 → 返回空串,而不是退化成「随便给第一段」
|
|
258
|
+
if (best === null) return ''
|
|
259
|
+
|
|
260
|
+
const flat = best.block.replace(/\s+/g, ' ').trim()
|
|
261
|
+
if (flat.length <= SNIPPET_CHARS) return flat
|
|
262
|
+
|
|
263
|
+
const lowerFlat = flat.toLowerCase()
|
|
264
|
+
let at = -1
|
|
265
|
+
for (const word of words) {
|
|
266
|
+
const found = lowerFlat.indexOf(word)
|
|
267
|
+
if (found >= 0 && (at < 0 || found < at)) at = found
|
|
268
|
+
}
|
|
269
|
+
const maxStart = flat.length - SNIPPET_CHARS
|
|
270
|
+
const start = at < 0 ? 0 : Math.max(0, Math.min(at - Math.floor(SNIPPET_CHARS / 3), maxStart))
|
|
271
|
+
const head = start > 0 ? '…' : ''
|
|
272
|
+
const tail = start < maxStart ? '…' : ''
|
|
273
|
+
return `${head}${flat.slice(start, start + SNIPPET_CHARS).trim()}${tail}`
|
|
163
274
|
}
|
|
164
275
|
|
|
165
276
|
/**
|
|
@@ -193,7 +304,13 @@ export function renderToolText(value) {
|
|
|
193
304
|
|
|
194
305
|
const lines = docs.map((doc, index) => {
|
|
195
306
|
const summary = oneLine(doc.summary)
|
|
196
|
-
|
|
307
|
+
// 命中段落(v0.11):给模型判断「要不要读整篇」用。
|
|
308
|
+
// 用一个 `match:` 前缀把它和**首段摘要**区分开 —— 两者都是一行压平的文本,
|
|
309
|
+
// 不加标记的话模型分不清哪行是什么。
|
|
310
|
+
const snippet = doc.snippet ? flatten(doc.snippet, SNIPPET_CHARS) : ''
|
|
311
|
+
return `${index + 1}. ${doc.rel} — ${doc.title}`
|
|
312
|
+
+ `${summary ? `\n ${summary}` : ''}`
|
|
313
|
+
+ `${snippet ? `\n match: ${snippet}` : ''}`
|
|
197
314
|
})
|
|
198
315
|
|
|
199
316
|
return [head, ...lines].join('\n')
|
|
@@ -205,9 +322,35 @@ export function renderToolText(value) {
|
|
|
205
322
|
* 形状与官方 `defineTool(...)` 的产物一致:`{ name, description, parameters, output, execute }`。
|
|
206
323
|
*
|
|
207
324
|
* @param {Function} scan - 宿主的扫描函数(注入进来,避免 index.js ↔ tool.js 循环 import)
|
|
325
|
+
* @param {Function} [read] - 宿主的单篇读取函数 `readDocument(root, rel)`。
|
|
326
|
+
* **同样注入**,理由与 `scan` 一样。**可选** —— 没给就只是不带命中段落,
|
|
327
|
+
* `knit_docs` 的其余行为一字不变(老调用方不会坏)。
|
|
208
328
|
* @returns {object} 工具定义
|
|
209
329
|
*/
|
|
210
|
-
export function knitDocsDefinition(scan) {
|
|
330
|
+
export function knitDocsDefinition(scan, read) {
|
|
331
|
+
/**
|
|
332
|
+
* 给一篇文档抽命中段落。
|
|
333
|
+
*
|
|
334
|
+
* **任何失败都咽掉并返回空串** —— 抽不出段落只是少一条信息,
|
|
335
|
+
* 不该让整次工具调用失败(工具已经拿到了排序结果,那才是主要产出)。
|
|
336
|
+
*
|
|
337
|
+
* @param {string} root - 工作区根
|
|
338
|
+
* @param {string} rel - 相对路径
|
|
339
|
+
* @param {string[]} terms - 命中词
|
|
340
|
+
* @param {string} title - 这一篇的标题(用于排除「与标题重复」的块)
|
|
341
|
+
* @returns {Promise<string>} 命中段落或空串
|
|
342
|
+
*/
|
|
343
|
+
async function snippetFor(root, rel, terms, title) {
|
|
344
|
+
if (typeof read !== 'function' || !rel || terms.length === 0) return ''
|
|
345
|
+
try {
|
|
346
|
+
const doc = await read(root, rel)
|
|
347
|
+
if (!doc || doc.ok !== true) return ''
|
|
348
|
+
return pickSnippet(doc.text, terms, { title })
|
|
349
|
+
} catch {
|
|
350
|
+
return ''
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
211
354
|
return {
|
|
212
355
|
name: TOOL_NAME,
|
|
213
356
|
description: DESCRIPTION,
|
|
@@ -235,18 +378,32 @@ export function knitDocsDefinition(scan) {
|
|
|
235
378
|
query,
|
|
236
379
|
})
|
|
237
380
|
|
|
381
|
+
// 命中词用 `scan()` 的 `keywords` —— 它是**语料里真实存在**的那批词
|
|
382
|
+
// (不是原始候选),所以拿它去原文里找段落,必然找得到。
|
|
383
|
+
// 时间序模式下它是空数组 ⇒ terms 为空 ⇒ 不抽段落,正合语义。
|
|
384
|
+
const terms = Array.isArray(payload.keywords) ? payload.keywords : []
|
|
385
|
+
|
|
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,
|
|
392
|
+
}
|
|
393
|
+
const snippet = await snippetFor(root, row.rel, terms, row.title)
|
|
394
|
+
// 抽不到就**不带这个字段**,不写空串 —— 让「没有命中」和「命中但没抽出来」
|
|
395
|
+
// 在输出里都是「没有 match 行」,而不是一行空的 `match: `
|
|
396
|
+
if (snippet) row.snippet = snippet
|
|
397
|
+
return row
|
|
398
|
+
}))
|
|
399
|
+
|
|
238
400
|
return {
|
|
239
401
|
mode: payload.mode === 'relevance' ? 'relevance' : 'time',
|
|
240
402
|
topic: typeof payload.topic === 'string' ? payload.topic : '',
|
|
241
403
|
// `scan()` 的 total 是**全量池子**的条数(在 limit 切片之前),
|
|
242
404
|
// 正好是这里要的「工作区一共有多少篇」。
|
|
243
405
|
total: Number.isInteger(payload.total) ? payload.total : 0,
|
|
244
|
-
docs
|
|
245
|
-
rel: String(doc.rel || ''),
|
|
246
|
-
title: String(doc.title || ''),
|
|
247
|
-
summary: doc.summary == null ? '' : String(doc.summary),
|
|
248
|
-
mtimeMs: Number.isFinite(doc.mtimeMs) ? Math.trunc(doc.mtimeMs) : 0,
|
|
249
|
-
})),
|
|
406
|
+
docs,
|
|
250
407
|
}
|
|
251
408
|
},
|
|
252
409
|
}
|
|
@@ -259,8 +416,9 @@ export function knitDocsDefinition(scan) {
|
|
|
259
416
|
*
|
|
260
417
|
* @param {object} ctx - cordis 上下文(带 `tools` 服务)
|
|
261
418
|
* @param {Function} scan - 宿主的扫描函数
|
|
419
|
+
* @param {Function} [read] - 宿主的单篇读取函数(抽命中段落用;可选)
|
|
262
420
|
* @returns {() => void} 注销函数
|
|
263
421
|
*/
|
|
264
|
-
export function registerKnitDocsTool(ctx, scan) {
|
|
265
|
-
return ctx.tools.register(knitDocsDefinition(scan))
|
|
422
|
+
export function registerKnitDocsTool(ctx, scan, read) {
|
|
423
|
+
return ctx.tools.register(knitDocsDefinition(scan, read))
|
|
266
424
|
}
|
package/test/host-http.test.mjs
CHANGED
|
@@ -86,7 +86,11 @@ test('HTTP 端到端:媒体列表、/raw 整文件、Range 206、安全拒绝'
|
|
|
86
86
|
assert.match(r.headers.get('content-type'), /image\/png/)
|
|
87
87
|
assert.equal(r.headers.get('accept-ranges'), 'bytes')
|
|
88
88
|
assert.equal(r.headers.get('x-content-type-options'), 'nosniff')
|
|
89
|
+
// v0.11 ③:`sandbox` 这一半原来只写在源码里、没有断言 —— 而它是 SVG 脚本失效的
|
|
90
|
+
// 关键(`default-src 'none'` 管外链,`sandbox` 管内联脚本上下文)。
|
|
91
|
+
// 「安全说明里声称的都指向真实检查」这条要求把它抓出来了。
|
|
89
92
|
assert.match(r.headers.get('content-security-policy') || '', /default-src 'none'/)
|
|
93
|
+
assert.match(r.headers.get('content-security-policy') || '', /sandbox/)
|
|
90
94
|
assert.equal(Number(r.headers.get('content-length')), realSize)
|
|
91
95
|
assert.equal((await r.arrayBuffer()).byteLength, realSize)
|
|
92
96
|
|
package/test/path.test.mjs
CHANGED
|
@@ -288,3 +288,70 @@ test('路径:拼不出绝对路径时按钮 disabled,点了也不发请求',
|
|
|
288
288
|
await harness.flush()
|
|
289
289
|
assert.equal(calls.length, 0)
|
|
290
290
|
})
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* v0.10:预览头右上角那个位置从「新标签页」换成了「在本地打开」。
|
|
294
|
+
*
|
|
295
|
+
* 动机:「新标签页」开的是官方文档预览,但面板里已经有就地预览(重复度高、
|
|
296
|
+
* 用得少);而「用默认应用打开这篇文档」原本只藏在路径面包屑的悬停提示里。
|
|
297
|
+
* 把值钱的那个放到显眼处。双击列表行仍能开新标签页 —— 所以这条要同时断言
|
|
298
|
+
* **头部不再有「新标签页」**。
|
|
299
|
+
*/
|
|
300
|
+
test('预览头:右上角是「在本地打开」,点击打开这篇文档', async () => {
|
|
301
|
+
const calls = []
|
|
302
|
+
globalThis.fetch = async (url) => ({
|
|
303
|
+
json: async () => (String(url).includes('/api/doc')
|
|
304
|
+
? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
|
|
305
|
+
: listPayload()),
|
|
306
|
+
})
|
|
307
|
+
const { KnitBody } = boot({
|
|
308
|
+
openWorkspacePath: async (request) => { calls.push(request); return { ok: true, value: { opened: true } } },
|
|
309
|
+
}).exports.__test
|
|
310
|
+
|
|
311
|
+
harness.reset()
|
|
312
|
+
let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
313
|
+
await harness.flush()
|
|
314
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
315
|
+
byClass(nodes, 'knit-doc')[0].props.onClick()
|
|
316
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
317
|
+
|
|
318
|
+
const headBtns = byClass(nodes, 'knit-btn')
|
|
319
|
+
const labels = headBtns.map(textOf)
|
|
320
|
+
assert.ok(labels.includes('在本地打开'), '头部有「在本地打开」按钮,实际:' + labels.join(' / '))
|
|
321
|
+
assert.ok(!labels.includes('新标签页'), '「新标签页」已从头部移除,实际:' + labels.join(' / '))
|
|
322
|
+
|
|
323
|
+
const localBtn = headBtns.find((n) => textOf(n) === '在本地打开')
|
|
324
|
+
assert.notEqual(localBtn.props.disabled, true, '有服务时不禁用')
|
|
325
|
+
// tooltip 里带完整相对路径 —— 与路径面包屑同一套提示
|
|
326
|
+
assert.match(String(localBtn.props.title), /a\.md/, 'tooltip 里带相对路径')
|
|
327
|
+
localBtn.props.onClick()
|
|
328
|
+
await harness.flush()
|
|
329
|
+
assert.deepEqual(calls[0], { path: '/Users/me/proj/a.md' }, '打开的是这篇文档的绝对路径')
|
|
330
|
+
})
|
|
331
|
+
|
|
332
|
+
test('预览头:没有 remote.session 时「在本地打开」给出提示,不是白点一下', async () => {
|
|
333
|
+
globalThis.fetch = async (url) => ({
|
|
334
|
+
json: async () => (String(url).includes('/api/doc')
|
|
335
|
+
? { ok: true, rel: 'a.md', title: 'A', text: '正文', truncated: false }
|
|
336
|
+
: listPayload()),
|
|
337
|
+
})
|
|
338
|
+
const { KnitBody } = boot({}).exports.__test // 不给 openWorkspacePath
|
|
339
|
+
|
|
340
|
+
harness.reset()
|
|
341
|
+
let nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
342
|
+
await harness.flush()
|
|
343
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
344
|
+
byClass(nodes, 'knit-doc')[0].props.onClick()
|
|
345
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
346
|
+
|
|
347
|
+
const localBtn = byClass(nodes, 'knit-btn').find((n) => textOf(n) === '在本地打开')
|
|
348
|
+
assert.ok(localBtn, '按钮仍然渲染(位置稳定)')
|
|
349
|
+
// 「禁用」只在**拿不到绝对路径**时用;拿得到路径但没有服务,走「点了给可见提示」——
|
|
350
|
+
// 与路径面包屑同一条规矩(见「路径:没有 remote.session 服务时给出提示」)
|
|
351
|
+
assert.notEqual(localBtn.props.disabled, true, '路径拿得到 → 不禁用')
|
|
352
|
+
|
|
353
|
+
localBtn.props.onClick()
|
|
354
|
+
await harness.flush()
|
|
355
|
+
nodes = harness.render(h(KnitBody, { sessionId: 's1' }))
|
|
356
|
+
assert.ok(byClass(nodes, 'knit-notice').length >= 1, '应给出可见提示而不是白点一下')
|
|
357
|
+
})
|
|
@@ -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
|
+
})
|
package/test/tool.test.mjs
CHANGED
|
@@ -16,10 +16,11 @@ import {
|
|
|
16
16
|
clampLimit,
|
|
17
17
|
agentScope,
|
|
18
18
|
renderToolText,
|
|
19
|
+
pickSnippet,
|
|
19
20
|
knitDocsDefinition,
|
|
20
21
|
registerKnitDocsTool,
|
|
21
22
|
} from '../src/host/tool.js'
|
|
22
|
-
import { scan, apply } from '../src/host/index.js'
|
|
23
|
+
import { scan, apply, readDocument } from '../src/host/index.js'
|
|
23
24
|
|
|
24
25
|
const PROJECT_ROOT = makeWorkspace()
|
|
25
26
|
|
|
@@ -333,3 +334,139 @@ test('renderToolText: 没有话题时不写空引号', () => {
|
|
|
333
334
|
assert.match(text, /to the current conversation/)
|
|
334
335
|
assert.ok(!text.includes('「」'))
|
|
335
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
|
+
})
|