dsh-wiki-notes 1.4.2 → 1.5.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.
Files changed (27) hide show
  1. package/README.md +43 -0
  2. package/docs/README.md +1 -1
  3. package/docs/superpowers/plans/2026-11-05-wiki-call-audit.md +553 -0
  4. package/docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md +164 -0
  5. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.657.md +657 -0
  6. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.661.md +661 -0
  7. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.final.md +661 -0
  8. package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.md +661 -0
  9. package/docs//345/245/221/347/272/246-stage0/samples/_verify_probe.json +1 -1
  10. package/docs//345/245/221/347/272/246-stage0/samples/{context.cq-shenlun.json → context.sample-cache.json} +80 -80
  11. package/docs//345/245/221/347/272/246-stage0/samples/verify.fabricated-quote.json +3 -3
  12. package/docs//345/245/221/347/272/246-stage0/samples/verify.scope-mismatch.json +3 -3
  13. package/docs//345/245/221/347/272/246-stage0/samples/verify.wrong-five.json +9 -9
  14. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2650-/345/256/241/350/256/241/344/270/216/345/245/221/347/272/246.md +10 -10
  15. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2651-/346/225/260/345/200/274/345/210/244/346/215/256/344/270/216/345/274/225/346/223/216/347/212/266/346/200/201.md +9 -9
  16. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2652-/345/277/253/347/205/247/344/270/216TTL.md +3 -3
  17. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2653-/346/224/257/346/214/201/345/216/237/345/233/240.md +3 -3
  18. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2654-/346/217/222/344/273/266/346/216/245/345/205/245.md +1 -1
  19. package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2655-/350/247/202/345/257/237/351/227/255/347/216/257/344/270/216/345/256/236/346/210/230/351/252/214/346/224/266.md +10 -10
  20. package/lib/bridge.js +10 -0
  21. package/lib/calls.js +167 -0
  22. package/lib/client.js +463 -11
  23. package/lib/config.js +33 -0
  24. package/lib/governance.js +849 -0
  25. package/lib/index.js +298 -14
  26. package/lib/jsonl-store.js +137 -0
  27. package/package.json +7 -5
package/README.md CHANGED
@@ -19,6 +19,7 @@
19
19
  | 我自己的笔记该怎么写 | [库该长什么样](#库该长什么样) |
20
20
  | 检索为什么这么打分 | [检索质量](#检索质量) |
21
21
  | 它有没有偷看我的东西 | [只读,且不往外发](#只读且不往外发) |
22
+ | 旧版本有没有遗留 | [发布物与残余风险](#发布物与残余风险) |
22
23
  | 已知毛病 | [已知局限](#已知局限) |
23
24
  | 要改代码 | [目录 / 开发](#目录--开发) |
24
25
 
@@ -35,6 +36,8 @@
35
36
  | **`wiki_verify`** | 拿已有的 context 核验一段回答,**不重新检索** | 答案写完了自查,特别是有数字的时候 |
36
37
  | **`wiki_observe`** | 查观察日志统计(调用次数、支持状态分布、违规类型) | 诊断,不参与回答 |
37
38
 
39
+ 设置页里只有一个「知识库」入口,进去分两个页签:**概览**(路径、体检、提示词)和**调用记录**(谁在什么时候查了什么、查到没有)。后者不是工具,是那本账的界面。
40
+
38
41
  ### `wiki_recall` —— 检索
39
42
 
40
43
  一个工具,七种 mode:
@@ -86,6 +89,29 @@
86
89
 
87
90
  报观察窗口内的调用次数、支持状态分布、检索状态分布、违规类型分布,还有**修正情况**(核验过的 context 里已改正 / 仍未改正的比例)—— 这一项比违规总数更能反映核验到底有没有用。只读诊断,不参与回答,也不改检索行为。
88
91
 
92
+ > ⚠️ 它只看**网关**那三次调用(`wiki_context` / `wiki_verify`)。`wiki_recall` 不走 Python,也就不写观察日志 —— 要看全部调用,去「知识库」页的「调用记录」页签。
93
+
94
+ ### 调用审计 —— 「知识库」页的「调用记录」页签
95
+
96
+ 在设置页的「知识库」里切到第二个页签。模型和面板**每一次**查库都会记一行,回答的是「我这句问话,它到底查了没有、查到没有」。
97
+
98
+ 三格数字(今日调用 / 命中率 / 零命中)+ 一张表(时间 · 来源 · 工具 · 问题 · 命中 · 耗时)+ 筛选(全部 / 模型 / 面板、只看零命中)。页面每 2 秒自己刷新。
99
+
100
+ 账本落在插件目录旁的 `calls.jsonl`(已在 `.gitignore` 里),只记 8 个字段:
101
+
102
+ ```
103
+ ts · source · tool · mode · query · hits · ms · ok
104
+ ```
105
+
106
+ **页面路径、正文、答案一律不进账本。** `query` 截到 120 字。
107
+
108
+ 几条口径值得写清楚:
109
+
110
+ - **命中率的分母不含 `wiki_verify` / `wiki_observe`**,也不算 `page` / `list` 这类非检索模式 —— 它们没有「命中几页」这回事,记成 0 会把命中率系统性压低,所以记 `null`,不进统计。
111
+ - **它只能看见「发生了的调用」**。模型压根没想起来查库,这里也不会有记录 —— 那是一种缺席,账本记不了缺席。要统计「哪类问题从来不查库」,得去读会话转录(本插件不读)。
112
+ - 记满 5000 行轮转一次,只留最近 2500 行;读取只扫文件尾部 256 KB。
113
+ - 记账是**旁路**:写不进去只打一行警告,工具的返回值一个字都不改。`calls.enabled` 可以整个关掉。
114
+
89
115
  ---
90
116
 
91
117
  ## 设计从哪来
@@ -207,6 +233,23 @@ plugin_manager { action: "install_bundle", target: "<绝对路径>" }
207
233
  - 检索在本地进程内跑,没有任何出站请求。
208
234
  - `wiki_context` / `wiki_verify` 调的是**你自己机器上的** Python 管线(`bridge.toolsRoot`),同样不出网。
209
235
  - 仓库里不含任何本机绝对路径或用户名;测试用环境变量拿真实路径(`WIKI_ROOT` / `WIKI_TOOLS`),不给就跑样例库。
236
+ - 公开仓库里的样例、契约文档与测试查询词一律用虚构语料,不写任何人的笔记主题。旧发布物仍有遗留,见下一节。
237
+
238
+ ---
239
+
240
+ ## 发布物与残余风险
241
+
242
+ **1.4.3 起是干净版本。** 仓库内 `docs/`(整目录进 `files`)、`examples/`、`tests/` 里的演示样例已全部换成虚构的「星港缓存」技术语料:没有真实引文、真实页面路径、外链、本机用户名、私有路径或凭据。发版前会解包 `npm pack` 的产物逐文件扫一遍,命中即视为发布失败。`wiki-notes.config.json` 是本机文件,`.gitignore` 覆盖,从未提交。
243
+
244
+ **1.4.2 及更早的公开传播源已经发出去了,收不回来:**
245
+
246
+ | 来源 | 情况 | 处置 |
247
+ | --- | --- | --- |
248
+ | npm `1.4.0` / `1.4.1` / `1.4.2` | 包内 `docs/契约-stage0/samples/` 与几份阶段文档含少量早期演示用的笔记引文、页面标题和一个外部链接;**不含**凭据、用户名、本机路径,也不是运行时采集的数据 | npm 不允许覆盖已发布版本 ⇒ 只把这三个版本标记 `deprecated`,提示升级到 `>=1.4.3`(更早的干净版本不误伤) |
249
+ | GitHub Release `v1.4.0` / `v1.4.1` / `v1.4.2` 的 tarball | 与对应 npm 包同源 | 不删 Release 记录,只删带内容的 tarball 资产;取包用 `v1.4.3` 或 `releases/latest/download/dsh-wiki-notes.tgz` |
250
+ | Git 历史 `36cfe85` 与标签 `v1.4.0`–`v1.4.2` 自动生成的源码归档 | `36cfe85` 曾写进本机绝对路径与用户名,`f82b125` 已在首个 1.4.0 npm 包发布**之前**清掉;但历史对象与标签归档仍在 | 不重写历史:改 tag SHA 会断掉已发 npm 包与 Release 的提交关联。在意的话请自行 fork 后清理 |
251
+
252
+ 一句话结论:**升级到 `1.4.3+` 即可**;旧版本里那部分内容不会自行消失,别把旧包当「干净语料」再分发。这里只做事实登记,不假装把它们删干净了。
210
253
 
211
254
  ---
212
255
 
package/docs/README.md CHANGED
@@ -48,7 +48,7 @@
48
48
  ### 配套产物
49
49
 
50
50
  - **[knowledge-gateway.v1.schema.json](契约-stage0/knowledge-gateway.v1.schema.json)** —— 契约的机器可读定义(28 KB),`context` / `verify` / `observe_stats` 三种输出的完整字段。
51
- - **[samples/](契约-stage0/samples/)** —— 8 份真实样例:`context.cq-shenlun.json`(一份完整的 context)、6 份 verify 场景(答对但有缺口 / 编引文 / 范围错 / 数字错 / 快照过期 / 快照损坏)、`_verify_probe.json`。
51
+ - **[samples/](契约-stage0/samples/)** —— 8 份虚构样例:`context.sample-cache.json`(一份完整的 context)、6 份 verify 场景(答对但有缺口 / 编引文 / 范围错 / 数字错 / 快照过期 / 快照损坏)、`_verify_probe.json`。
52
52
  改判据前,先拿样例跑一遍 `wiki_verify` 看行为有没有变。
53
53
 
54
54
  ---
@@ -0,0 +1,553 @@
1
+ # 调用审计页 Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use subagent-driven-development (recommended) or executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** 让知识库插件把每次工具调用(含面板手查)按最小字段记下来,并在设置页新增一个标签页把调用流水显示出来。
6
+
7
+ **Architecture:** 新增 `lib/calls.js` 一个纯 Node 模块负责环形缓冲 + `calls.jsonl` 追加写 + 尾部读取;`lib/index.js` 用 `traced()` 包住四个工具的 `execute`,并在 `/search` 路由里给面板手查补记一条;新增 `GET /calls`、`POST /calls/clear`、`POST /calls/config` 三个路由;`lib/client.js` 注册第二个 `settings.section` 承载流水页。
8
+
9
+ **Tech Stack:** Node ESM(`node:fs` 同步 API,零依赖);客户端手写 bundle,`React.createElement`;测试是 `node tests/*.mjs` 裸脚本 + `node:assert/strict`,无测试框架。
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - `engines.node` 是 `>=20.13.0`。**不许用 `zlib.zstdDecompressSync`**(Node 22.15+ 才有)、不许用 `node --run`(Node 22+ 才有)。
16
+ - 插件**零运行时依赖**:不加 `dependencies`,不 import 任何非 `node:` 前缀模块。
17
+ - 记录字段白名单**只有 8 个**:`ts`、`source`、`tool`、`mode`、`query`、`hits`、`ms`、`ok`。**绝不写页面路径、文件名、正文片段、答案原文、错误堆栈。**
18
+ - 采集是旁路:记录失败一律 `console.warn` 后继续,**不得改变任何工具的返回值、schema 或描述**。
19
+ - 客户端只能 `React.createElement`(文件内别名 `h`),不能用 JSX。
20
+ - 客户端改动要**重启 DSH** 才生效。
21
+ - 写盘只写插件根目录下的文件;**知识库本体一个字节都不写**。
22
+ - 中文注释,和现有代码同风格:注释解释「为什么」,不复述「做了什么」。
23
+
24
+ ## Review Focus
25
+
26
+ - **半行 JSON**:进程在 `appendFileSync` 中途被杀,`calls.jsonl` 末尾会留半行。读取必须跳过坏行,不能让整页白掉。
27
+ - **文件被外部删掉**:用户在资源管理器里删了 `calls.jsonl`,下一次 `record()` 必须自动重建,而不是永久静默失败。
28
+ - **目录不可写**:插件目录只读时,工具必须照常返回结果(记录只进内存),不能因为记不了账就让检索失败。
29
+ - **跨天**:`totals` 的「今日」按本地日期字符串比较;23:59 与 00:01 的两条不能被算进同一天。
30
+ - **query 含换行/超长**:`\n` 经 `JSON.stringify` 转义后不会撑破 jsonl;但长度必须截到 120 字,否则一条记录能到几十 KB。
31
+
32
+ ---
33
+
34
+ ### Task 1: 记录模块 `lib/calls.js`
35
+
36
+ **Files:**
37
+ - Create: `lib/calls.js`
38
+ - Test: `tests/calls.mjs`
39
+
40
+ **Interfaces:**
41
+ - Consumes: 无(纯 Node 模块)
42
+ - Produces:
43
+ - `CALL_FIELDS: string[]` —— `['ts','source','tool','mode','query','hits','ms','ok']`
44
+ - `normalizeEntry(raw: object) => object | null` —— 只留白名单字段;`query` 截到 120 字;非法输入返回 `null`
45
+ - `createCallLog({ file: string, enabled?: boolean }) => CallLog`
46
+ - `CallLog.record(entry: object): void`
47
+ - `CallLog.read({ limit?: number, source?: 'all'|'model'|'panel', only?: 'all'|'miss' }) => { rows, totals, enabled, window }`
48
+ - `CallLog.clear(): void`
49
+ - `CallLog.setEnabled(next: boolean): void`
50
+ - `CallLog.enabled(): boolean`
51
+ - `CallLog.buffer(): object[]` —— 只给测试看
52
+
53
+ - [ ] **Step 1: 写失败测试**
54
+
55
+ `tests/calls.mjs`:
56
+
57
+ ```js
58
+ import assert from 'node:assert/strict'
59
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
60
+ import path from 'node:path'
61
+ import os from 'node:os'
62
+
63
+ import { CALL_FIELDS, normalizeEntry, createCallLog } from '../lib/calls.js'
64
+
65
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'wiki-calls-'))
66
+ const file = path.join(tmp, 'calls.jsonl')
67
+
68
+ // 1. 字段白名单:多给的字段一律丢掉,缺的补 null
69
+ {
70
+ const entry = normalizeEntry({
71
+ ts: '2026-11-05T21:00:00', source: 'model', tool: 'wiki_recall', mode: 'search',
72
+ query: '别了 旧索引', hits: 0, ms: 1, ok: true,
73
+ file: '/wiki/某页.md', text: '正文片段',
74
+ })
75
+ assert.deepEqual(Object.keys(entry).sort(), [...CALL_FIELDS].sort())
76
+ assert.equal(entry.file, undefined)
77
+ assert.equal(entry.text, undefined)
78
+ }
79
+
80
+ // 2. query 截到 120 字
81
+ {
82
+ const entry = normalizeEntry({ query: 'x'.repeat(500) })
83
+ assert.equal(entry.query.length, 121) // 120 + 省略号
84
+ }
85
+
86
+ // 3. 非法输入不算记录
87
+ {
88
+ assert.equal(normalizeEntry(null), null)
89
+ assert.equal(normalizeEntry('字符串'), null)
90
+ }
91
+
92
+ // 4. 写进去能读出来
93
+ {
94
+ const log = createCallLog({ file })
95
+ log.record({ source: 'model', tool: 'wiki_recall', mode: 'search', query: '甲', hits: 2, ms: 3, ok: true })
96
+ const { rows } = log.read({})
97
+ assert.equal(rows.length, 1)
98
+ assert.equal(rows[0].query, '甲')
99
+ assert.equal(JSON.parse(readFileSync(file, 'utf8').trim()).tool, 'wiki_recall')
100
+ }
101
+ ```
102
+
103
+ - [ ] **Step 2: 跑测试确认失败**
104
+
105
+ Run: `node tests/calls.mjs`
106
+ Expected: `Cannot find module .../lib/calls.js`
107
+
108
+ - [ ] **Step 3: 实现 `lib/calls.js`**
109
+
110
+ 要点(签名与上面 Interfaces 一致):
111
+ - `record()`:`normalizeEntry` → 推入内存环形缓冲(上限 500)→ 若 `enabled` 则 `appendFileSync(file, JSON.stringify(entry) + '\n')`,`try/catch` 包住,失败只 `console.warn` 且记一个 `writeBroken` 标志(下次不再重试直到文件可写)。
112
+ - 轮转:模块内维护 `lineCount`,首次为 `null`,第一次写时用 `readFileSync` 数行数(文件不存在记为 0);`lineCount > 5000` 时读全部行、取最后 2500 行重写、更新 `lineCount`。
113
+ - `read()`:读文件**尾部** `TAIL_BYTES = 262144` 字节;按 `\n` 切、逐行 `JSON.parse`,坏行 `continue`;然后按 `ts|tool|query` 键去重并入内存缓冲里文件没有的行;再按 `source` / `only === 'miss'`(`hits === 0`)过滤;`rows` 取 `limit`(默认 200,夹到 1–500),`totals` 用**过滤前**的全部行算。
114
+ - `totals`:`{ today, calls, hits, misses, hitRate }`。`today` 是本地日期 `YYYY-MM-DD`;只统计 `ts.slice(0,10) === today` 的行;`hitRate` 的分母是**`hits !== null` 的行**(即排除 `verify` / `observe`),分子是 `hits > 0` 的行;分母为 0 时 `hitRate = null`。
115
+ - `window` = 参与 `totals` 计算的行数。
116
+ - `clear()`:`writeFileSync(file, '')`,`lineCount = 0`,清空缓冲,`try/catch`。
117
+ - `setEnabled()` / `enabled()`:读写闭包里的 `enabled`。
118
+ - 文件不存在或读失败时,`read()` 返回内存缓冲里的行,`totals` 照算。
119
+
120
+ - [ ] **Step 4: 跑测试确认通过**
121
+
122
+ Run: `node tests/calls.mjs`
123
+ Expected: 无输出、退出码 0
124
+
125
+ - [ ] **Step 5: 补两组边界测试并跑**
126
+
127
+ 追加到 `tests/calls.mjs`:
128
+
129
+ ```js
130
+ // 5. 坏行跳过
131
+ {
132
+ const f2 = path.join(tmp, 'broken.jsonl')
133
+ writeFileSync(f2, '{"ts":"2026-11-05T21:00:00","tool":"wiki_recall","hits":1}\n{"半个\n')
134
+ const log = createCallLog({ file: f2 })
135
+ assert.equal(log.read({}).rows.length, 1)
136
+ }
137
+
138
+ // 6. enabled=false 时不写文件
139
+ {
140
+ const f3 = path.join(tmp, 'off.jsonl')
141
+ const log = createCallLog({ file: f3, enabled: false })
142
+ log.record({ tool: 'wiki_recall', hits: 1 })
143
+ assert.equal(log.read({}).rows.length, 1) // 内存里有
144
+ assert.equal(existsSync(f3), false) // 文件没有
145
+ }
146
+
147
+ // 7. 命中率排除 verify / observe
148
+ {
149
+ const log = createCallLog({ file: path.join(tmp, 'rate.jsonl') })
150
+ const today = new Date().toISOString().slice(0, 10)
151
+ log.record({ ts: `${today}T10:00:00`, tool: 'wiki_recall', hits: 3, ok: true })
152
+ log.record({ ts: `${today}T10:01:00`, tool: 'wiki_recall', hits: 0, ok: true })
153
+ log.record({ ts: `${today}T10:02:00`, tool: 'wiki_verify', hits: null, ok: true })
154
+ const { totals } = log.read({})
155
+ assert.equal(totals.calls, 3)
156
+ assert.equal(totals.hitRate, 0.5) // 1 / 2,verify 不进分母
157
+ }
158
+
159
+ // 8. 目录不可写不抛错
160
+ {
161
+ const log = createCallLog({ file: path.join(tmp, 'no-such-dir', 'x.jsonl') })
162
+ assert.doesNotThrow(() => log.record({ tool: 'wiki_recall', hits: 1 }))
163
+ assert.equal(log.read({}).rows.length, 1)
164
+ }
165
+
166
+ // 9. 文件被外部删掉后,下一次 record 自动重建
167
+ {
168
+ const f4 = path.join(tmp, 'gone.jsonl')
169
+ const log = createCallLog({ file: f4 })
170
+ log.record({ tool: 'wiki_recall', hits: 1 })
171
+ rmSync(f4)
172
+ log.record({ tool: 'wiki_recall', hits: 2 })
173
+ assert.equal(existsSync(f4), true)
174
+ assert.equal(log.read({}).rows.length, 2) // 被删前那条还在内存里
175
+ }
176
+
177
+ // 10. 跨天不混算:昨天那两条不进今日统计
178
+ {
179
+ const f5 = path.join(tmp, 'crossday.jsonl')
180
+ const log = createCallLog({ file: f5 })
181
+ log.record({ ts: '2026-11-04T23:59:00', tool: 'wiki_recall', hits: 5, ok: true })
182
+ log.record({ ts: '2026-11-04T00:01:00', tool: 'wiki_recall', hits: 5, ok: true })
183
+ log.record({ ts: `${new Date().toISOString().slice(0, 10)}T00:01:00`, tool: 'wiki_recall', hits: 0, ok: true })
184
+ assert.equal(log.read({}).totals.calls, 1)
185
+ assert.equal(log.read({}).totals.misses, 1)
186
+ }
187
+
188
+ // 11. query 里的换行不会撑破 jsonl
189
+ {
190
+ const f6 = path.join(tmp, 'newline.jsonl')
191
+ const log = createCallLog({ file: f6 })
192
+ log.record({ query: '第一行\n第二行', tool: 'wiki_recall', hits: 0 })
193
+ const lines = readFileSync(f6, 'utf8').split('\n').filter(Boolean)
194
+ assert.equal(lines.length, 1)
195
+ assert.equal(JSON.parse(lines[0]).query, '第一行\n第二行')
196
+ }
197
+ ```
198
+
199
+ 跑之前补 `existsSync` 到 import 列表。
200
+
201
+ Run: `node tests/calls.mjs`
202
+ Expected: 退出码 0
203
+
204
+ - [ ] **Step 6: 提交**
205
+
206
+ ```bash
207
+ git add lib/calls.js tests/calls.mjs
208
+ git commit -m "feat(calls): 调用记录模块——8 字段白名单、环形缓冲、尾部读取"
209
+ ```
210
+
211
+ ---
212
+
213
+ ### Task 2: 配置项 `calls`
214
+
215
+ **Files:**
216
+ - Modify: `lib/config.js`(在 `writeTopicConfig` 之后、提示词那节之前插入)
217
+ - Modify: `tests/config.mjs`
218
+
219
+ **Interfaces:**
220
+ - Consumes: `readRecord(pluginRoot)` / `writeRecord(pluginRoot, record)`(`lib/config.js` 内部已有,不导出)
221
+ - Produces:
222
+ - `DEFAULT_CALLS_CONFIG = { enabled: true, log: '' }`
223
+ - `normalizeCallsConfig(raw) => { enabled: boolean, log: string } | null`
224
+ - `readCallsConfig(pluginRoot) => { enabled, log }`
225
+ - `writeCallsConfig(pluginRoot, next) => { file, config }`
226
+
227
+ - [ ] **Step 1: 写失败测试**
228
+
229
+ `tests/config.mjs` 追加:
230
+
231
+ ```js
232
+ import { DEFAULT_CALLS_CONFIG, normalizeCallsConfig, readCallsConfig, writeCallsConfig } from '../lib/config.js'
233
+
234
+ // calls 配置:缺字段按默认补齐,log 只认字符串
235
+ assert.deepEqual(normalizeCallsConfig({}), { enabled: true, log: '' })
236
+ assert.deepEqual(normalizeCallsConfig({ enabled: false }), { enabled: false, log: '' })
237
+ assert.deepEqual(normalizeCallsConfig({ log: '/tmp/x.jsonl' }), { enabled: true, log: '/tmp/x.jsonl' })
238
+ assert.equal(normalizeCallsConfig(null), null)
239
+ assert.deepEqual(readCallsConfig('/不存在的目录'), { ...DEFAULT_CALLS_CONFIG })
240
+ ```
241
+
242
+ - [ ] **Step 2: 跑测试确认失败**
243
+
244
+ Run: `node tests/config.mjs`
245
+ Expected: `does not provide an export named 'normalizeCallsConfig'`
246
+
247
+ - [ ] **Step 3: 实现**
248
+
249
+ 照 `DEFAULT_TOPIC_CONFIG` / `normalizeTopicConfig` / `readTopicConfig` / `writeTopicConfig` 那组的写法:
250
+ `normalizeCallsConfig` 不是对象返回 `null`;`enabled` 只认 `=== false` 为关闭;`log` 用 `typeof === 'string' ? trim() : ''`。
251
+ `readCallsConfig` = `normalizeCallsConfig(readRecord(pluginRoot).calls) ?? {...DEFAULT_CALLS_CONFIG}`。
252
+ `writeCallsConfig` 整块替换 `calls` 字段,其余字段原样保留。
253
+
254
+ - [ ] **Step 4: 跑测试确认通过**
255
+
256
+ Run: `node tests/config.mjs`
257
+ Expected: 全绿
258
+
259
+ - [ ] **Step 5: 提交**
260
+
261
+ ```bash
262
+ git add lib/config.js tests/config.mjs
263
+ git commit -m "feat(config): 加 calls 配置块(enabled / log)"
264
+ ```
265
+
266
+ ---
267
+
268
+ ### Task 3: 接入四个工具 + 三个 HTTP 路由
269
+
270
+ **Files:**
271
+ - Modify: `lib/index.js`
272
+ - Modify: `lib/config.js` 的 import 行(`readCallsConfig`)
273
+ - Test: `tests/api.mjs`
274
+
275
+ **Interfaces:**
276
+ - Consumes: Task 1 的 `createCallLog` / Task 2 的 `readCallsConfig`、`writeCallsConfig`
277
+ - Produces(HTTP):
278
+ - `GET /api/wiki-notes/calls?limit=200&source=all|model|panel&only=all|miss` → `{ rows, totals, enabled, window }`
279
+ - `POST /api/wiki-notes/calls/clear` → `{ ok: true, cleared: number }`(过 `blockedOrigin` 写闸)
280
+ - `POST /api/wiki-notes/calls/config` body `{ enabled: boolean }` → `{ ok: true, config }`(过写闸)
281
+
282
+ - [ ] **Step 1: 写失败测试**
283
+
284
+ `tests/api.mjs` 追加:
285
+
286
+ ```js
287
+ // 调用记录:记一条,/calls 能读回来;/calls/clear 清空
288
+ await call('POST', '/save', JSON.stringify({ root: wiki }))
289
+ const callsFile = path.join(path.dirname(configFile), 'calls.jsonl')
290
+ process.env.DSH_WIKI_CALLS_LOG = callsFile // 见 Step 3:允许环境变量指定
291
+ ```
292
+
293
+ **注意**:为了让测试不污染真实文件,`apply()` 读配置时 `log` 为空就用 `path.join(pluginRoot, 'calls.jsonl')`,而测试里走 env `DSH_WIKI_CALLS_LOG` 覆盖(和 `DSH_WIKI_CONFIG` 同样的手法)。所以断言写成:
294
+
295
+ ```js
296
+ const { status, body } = await call('GET', '/calls')
297
+ check('/calls 返回 rows 数组', Array.isArray(body.rows))
298
+ check('/calls 返回 totals', typeof body.totals?.calls === 'number')
299
+ check('/calls 返回 enabled 布尔', body.enabled === true)
300
+
301
+ const cleared = await call('POST', '/calls/clear')
302
+ check('/calls/clear 返回 200', cleared.status === 200)
303
+
304
+ const off = await call('POST', '/calls/config', JSON.stringify({ enabled: false }))
305
+ check('/calls/config 关掉后 enabled=false', off.body?.enabled === false)
306
+ const after = await call('GET', '/calls')
307
+ check('关掉后 /calls 的 enabled 是 false', after.body.enabled === false)
308
+
309
+ // 跨源写闸:带外来源的 POST 必须被拒
310
+ const blocked = await call('POST', '/calls/clear', '', { origin: 'https://evil.example' })
311
+ check('/calls/clear 拒绝跨源', blocked.status === 403)
312
+ ```
313
+
314
+ - [ ] **Step 2: 跑测试确认失败**
315
+
316
+ Run: `node tests/api.mjs`
317
+ Expected: `/calls 返回 rows 数组` 等几条 `✗`
318
+
319
+ - [ ] **Step 3: 实现**
320
+
321
+ 在 `apply()` 内、`invalidate` 那组状态之后:
322
+
323
+ ```js
324
+ const callsCfg = readCallsConfig(pluginRoot)
325
+ const callFile = process.env.DSH_WIKI_CALLS_LOG || callsCfg.log || path.join(pluginRoot, 'calls.jsonl')
326
+ const callLog = createCallLog({ file: callFile, enabled: callsCfg.enabled })
327
+ ```
328
+
329
+ `traced()` 包装器(同作用域):
330
+
331
+ ```js
332
+ /** 记账,但不改变被包的东西:返回值、异常、耗时语义一律原样透传。 */
333
+ function traced(name, execute) {
334
+ return async function (args) {
335
+ const started = Date.now()
336
+ let ok = true
337
+ let hits = null
338
+ try {
339
+ const value = await execute(args)
340
+ if (value && value.mode === 'error') ok = false
341
+ hits = countHits(name, value)
342
+ return value
343
+ } catch (error) {
344
+ ok = false
345
+ throw error
346
+ } finally {
347
+ callLog.record({
348
+ source: 'model', tool: name, mode: modeOf(args),
349
+ query: queryOf(args), hits, ms: Date.now() - started, ok,
350
+ })
351
+ }
352
+ }
353
+ }
354
+ ```
355
+
356
+ `countHits`:`wiki_recall` → `Array.isArray(value?.hits) ? value.hits.length : null`;
357
+ `wiki_context` → `Array.isArray(value?.evidence) ? value.evidence.length : null`;
358
+ `wiki_verify` / `wiki_observe` → `null`。
359
+
360
+ `queryOf`:`wiki_recall` / `wiki_context` → `typeof args?.query === 'string' ? args.query : ''`;
361
+ `wiki_verify` → `typeof args?.context_id === 'string' ? args.context_id : ''`;
362
+ `wiki_observe` → `''`。
363
+
364
+ `modeOf`:`typeof args?.mode === 'string' ? args.mode : ''`。
365
+
366
+ 接法:把四处 `ctx.tools.register({ ..., execute(args) {...} })` 里的 `execute` 改成
367
+ `execute: traced('wiki_recall', async (args) => { ...原函数体... })`,**函数体一个字都不动**。
368
+
369
+ `/search` 路由里,在 `sendJson` 之前补:
370
+
371
+ ```js
372
+ callLog.record({
373
+ source: 'panel', tool: 'wiki_search', mode: 'search', query,
374
+ hits: result.hits.length, ms: Date.now() - started, ok: true,
375
+ })
376
+ ```
377
+
378
+ 三个新路由,插在 `/search` 之后:
379
+
380
+ ```js
381
+ if (route === '/calls' && req.method === 'GET') {
382
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
383
+ const limit = Number(parsed.searchParams.get('limit') ?? 200)
384
+ const source = parsed.searchParams.get('source') ?? 'all'
385
+ const only = parsed.searchParams.get('only') ?? 'all'
386
+ return sendJson(res, 200, callLog.read({
387
+ limit: Number.isFinite(limit) ? limit : 200, source, only,
388
+ }))
389
+ }
390
+ if (route === '/calls/clear' && req.method === 'POST') {
391
+ if (blockedOrigin(req)) return sendJson(res, 403, { error: '拒绝跨源写入' })
392
+ return sendJson(res, 200, { ok: true, cleared: callLog.read({ limit: 1 }).totals.calls })
393
+ }
394
+ if (route === '/calls/config' && req.method === 'POST') {
395
+ if (blockedOrigin(req)) return sendJson(res, 403, { error: '拒绝跨源写入' })
396
+ const body = await readBody(req)
397
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
398
+ const next = writeCallsConfig(pluginRoot, body)
399
+ callLog.setEnabled(next.config.enabled)
400
+ return sendJson(res, 200, { ok: true, enabled: next.config.enabled })
401
+ }
402
+ ```
403
+
404
+ `/calls/clear` 里 `callLog.clear()` 要在取完 `cleared` 之后调。
405
+
406
+ - [ ] **Step 4: 跑测试确认通过**
407
+
408
+ Run: `node tests/api.mjs`
409
+ Expected: 全绿
410
+
411
+ - [ ] **Step 5: 确认记录真的落盘了**
412
+
413
+ Run: `DSH_WIKI_CALLS_LOG=/tmp/probe-calls.jsonl node tests/gateway.mjs`
414
+ Expected: 11/11 通过,且 `/tmp/probe-calls.jsonl` 存在、每行恰好 8 个键(`node -e` 数一下键名)。
415
+
416
+ - [ ] **Step 6: 提交**
417
+
418
+ ```bash
419
+ git add lib/index.js lib/config.js tests/api.mjs
420
+ git commit -m "feat(calls): 四个工具接入调用记录,加 /calls 三条路由"
421
+ ```
422
+
423
+ ---
424
+
425
+ ### Task 4: 设置页新标签页
426
+
427
+ **Files:**
428
+ - Modify: `lib/client.js`
429
+ - Test: `tests/client.mjs`
430
+
431
+ **Interfaces:**
432
+ - Consumes: Task 3 的 `GET /calls`、`POST /calls/clear`、`POST /calls/config`
433
+ - Produces: `WikiCallsSection(props)` 组件 + 第二个 `settings.section` 注册(`id: 'wiki-notes-calls'`,`order: 48`,`label: () => '知识库 · 调用'`)
434
+
435
+ - [ ] **Step 1: 写失败测试**
436
+
437
+ `tests/client.mjs` 追加:
438
+
439
+ ```js
440
+ check('调用审计页:section id 存在', source.includes("id: 'wiki-notes-calls'"))
441
+ check('调用审计页:label 是「知识库 · 调用」', source.includes("'知识库 · 调用'"))
442
+ check('调用审计页:组件是函数', typeof mod.WikiCallsSection === 'function' || source.includes('function WikiCallsSection'))
443
+ check('调用审计页:调 /calls 接口', source.includes("'/calls'"))
444
+ check('调用审计页:清空要过写闸', source.includes("'/calls/clear'"))
445
+ ```
446
+
447
+ - [ ] **Step 2: 跑测试确认失败**
448
+
449
+ Run: `node tests/client.mjs`
450
+ Expected: 前两条 `✗`
451
+
452
+ - [ ] **Step 3: 实现 `WikiCallsSection`**
453
+
454
+ 放在 `WikiNotesSection`(`lib/client.js:170`)之后。结构:
455
+
456
+ ```js
457
+ function WikiCallsSection(props) {
458
+ var state = React.useState({ rows: [], totals: null, enabled: true, error: '' })
459
+ // fetchCalls(limit, source, only) -> fetch(API + '/calls?...')
460
+ // React.useEffect:立即拉一次,然后 setInterval 2000;document.visibilityState 不可见时跳过
461
+ // clear:window.confirm 一行确认 -> POST /calls/clear -> 重拉
462
+ // toggle:POST /calls/config {enabled} -> 重拉
463
+ return h('div', { className: 'wn-root' }, 三格数字, 筛选行, 表格, 空态)
464
+ }
465
+ ```
466
+
467
+ 细节:
468
+ - 顶部三格:`今日调用 {totals.calls}`、`命中率 {totals.hitRate === null ? '—' : Math.round(totals.hitRate * 100) + '%'}`、`零命中 {totals.misses}`;下方小字 `统计基于最近 {window} 条记录;命中率分母不含 verify / observe`。
469
+ - 筛选:`全部 / 模型 / 面板` 三按钮 + `只看零命中` 开关 + `清空` 按钮 + `记录开关` 勾选框。
470
+ - 表格行:`时间`(`ts.slice(11,16)`)· `来源`(`model` → `模型`,`panel` → `面板`)· `工具` · `问题`(`title={row.query}`,CSS `text-overflow:ellipsis`)· `命中`(`hits === null ? '—' : hits`)· `耗时`(`${ms}ms`,`> 1000` 加 `wn-slow` 类)。
471
+ - 空态:`还没有调用记录。让模型查一次库,或在这儿手查一次。`
472
+ - 新增 CSS 全部用 `wn-calls-` 前缀,追加到现有 `CSS` 数组末尾。
473
+
474
+ 在 `apply(ctx)` 里、现有 `settings.section` 注册之后,再注册一个:
475
+
476
+ ```js
477
+ ctx.slots.inject('settings.section', function () {
478
+ return ctx.slots.register(
479
+ { name: 'settings.section', id: 'wiki-notes-calls', order: 48,
480
+ label: function () { return '知识库 · 调用' } },
481
+ function (props) { return h(WikiCallsSection, props || {}) },
482
+ )
483
+ })
484
+ ```
485
+
486
+ - [ ] **Step 4: 跑测试确认通过**
487
+
488
+ Run: `node tests/client.mjs`
489
+ Expected: 全绿
490
+
491
+ - [ ] **Step 5: 重启 DSH 后人工验一遍**
492
+
493
+ 重启 DSH → 设置 → 左边应出现第二个入口「知识库 · 调用」→ 让模型查一次库 → 页面上 2 秒内出现那一行。
494
+
495
+ - [ ] **Step 6: 提交**
496
+
497
+ ```bash
498
+ git add lib/client.js tests/client.mjs
499
+ git commit -m "feat(calls): 设置页加「知识库 · 调用」标签页"
500
+ ```
501
+
502
+ ---
503
+
504
+ ### Task 5: 挂进测试流水线 + 文档 + 发版号
505
+
506
+ **Files:**
507
+ - Modify: `package.json`(`scripts.test` 末尾加 `&& node tests/calls.mjs`;`version` → `1.4.3`)
508
+ - Modify: `README.md`
509
+ - Modify: `docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md`
510
+
511
+ - [ ] **Step 1: 接测试**
512
+
513
+ `package.json` 的 `scripts.test` 在 `client` 那一段之前插入 `node tests/calls.mjs &&`。
514
+
515
+ Run: `npm test`
516
+ Expected: 18 个文件全绿
517
+
518
+ - [ ] **Step 2: 写 README**
519
+
520
+ 在 `wiki_observe` 那段之后加一小节:
521
+
522
+ ```markdown
523
+ ### 调用审计(设置页「知识库 · 调用」)
524
+
525
+ `wiki_observe` 只统计走 Python 网关的 `wiki_context` / `wiki_verify`。
526
+ `wiki_recall` 是纯 JS 路径,从来不进观察日志——所以「模型到底查没查库」这个问题,
527
+ 观察日志答不了。
528
+
529
+ 设置页新增的「知识库 · 调用」页补上这一块:每次工具调用与面板手查都记一行,
530
+ 只存 `ts / source / tool / mode / query / hits / ms / ok` 八个字段,
531
+ **不存页面路径、正文与答案**。记录写到插件目录下的 `calls.jsonl`(已被 `.gitignore` 忽略),
532
+ 超过 5000 行自动裁到 2500 行。可以在页面上关掉记录,也可以一键清空。
533
+ ```
534
+
535
+ - [ ] **Step 3: 更新设计稿状态**
536
+
537
+ `docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md` 的「待确认」三条改写为已定结论:
538
+ 标题「知识库 · 调用」;命中率分母排除 `verify` / `observe`;清空要一行确认。
539
+
540
+ - [ ] **Step 4: 提交并打 tag**
541
+
542
+ ```bash
543
+ git add package.json README.md docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md
544
+ git commit -m "docs+chore: 调用审计页文档与 1.4.3"
545
+ ```
546
+
547
+ - [ ] **Step 5: 全量回归**
548
+
549
+ Run: `npm test`
550
+ Expected: 18 个文件全绿
551
+
552
+ Run: `node tests/gateway.mjs`
553
+ Expected: 11/11(未配管线时)