dsh-wiki-notes 1.1.1 → 1.1.3

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.md CHANGED
@@ -66,16 +66,17 @@ plugin_manager { action: "install_bundle", target: "<绝对路径>" }
66
66
  | `page` | 按页名/别名取整页 | `name`、`pageChars`(6000) |
67
67
  | `list` | 按类型/标签/状态列目录 | `type`、`tags`、`status`、`limit`(40,≤200) |
68
68
  | `overview` | 总览 + 规模行 + 最近日志 + 健康计数 | `pageChars`(4000)、`logLimit`(5,≤20) |
69
- | `lint` | 库健康检查:孤儿页、断链名字、缺字段、别名冲突、久未更新、无出链、草稿、index 与磁盘不一致 | `limit`(8,≤40)、`staleDays`(120) |
69
+ | `lint` | 库健康检查:孤儿页、断链名字、缺字段、别名冲突、久未更新、无出链、草稿、index 与磁盘不一致;**并和上次体检对比,报出新增与已修** | `limit`(8,≤40)、`staleDays`(120) |
70
70
  | `draft` | 把好答案回写成新页的落盘骨架(目录、frontmatter、index 行、log 条),不写文件 | `title`、`type`、`tags`、`summary`、`sources` |
71
+ | `help` | 用法与状态说明:七个 mode 各返回什么、`status` 各取值怎么读、参数默认值 | 无 |
71
72
 
72
73
  ```jsonc
73
74
  { "mode": "search", "query": "上下文 预算", "limit": 5 }
74
75
  ```
75
76
 
76
- 每条命中带 `kind`(note / raw-summary / source)、`sources`(来源数,**证据强度的唯一可靠代理**)、`status`、`gist`、`section`(命中小节正文,不是 90 字片段)、`citation`(`← [[页名]] §小节 → 路径`)、`brokenLinks`(指向不存在页的双链 = 「库里没依据」的硬信号)。`overview` 额外给三项健康信号:index 有磁盘无、磁盘有 index 无、跨目录重名。
77
+ 每条命中带 `kind`(note / raw-summary / source)、`sources`(来源数,**证据强度的唯一可靠代理**)、`status`、`gist`、`section`(命中小节正文,不是 90 字片段)、`citation`(`← [[页名]] §小节 → 路径`)、`brokenLinks`(指向不存在页的双链 = 「库里没依据」的硬信号),以及 `updated` 后面的**距今天数**(超过 180 天标「可能已过时」——三年前的结论和上周的长得一样,模型需要这个信号)。`overview` 额外给三项健康信号:index 有磁盘无、磁盘有 index 无、跨目录重名。
77
78
 
78
- 模型怎么知道该查库:插件会从你库里现有的 `标签` 算出主题词,注入一行(约 50 token,例如「本地知识库 73 页,主题:上下文工程、ai、agent…」)。换库自动变,所以问题沾这些主题时它自己会去查,不用你提醒。设置页里可以关掉(不占上下文)、换成自己的整段、或在末尾追加一句,改完下一回合生效。
79
+ 模型怎么知道该查库:插件会从你库里现有的 `标签` 算出主题词,注入一行(约 50 token,例如「本地知识库主题:上下文工程、ai、agent…」)。不带页数 —— 页数一变就会打掉提示词的前缀缓存,而它对「该不该查」没有帮助。换库自动变,所以问题沾这些主题时它自己会去查,不用你提醒。设置页里可以关掉(不占上下文)、换成自己的整段、或在末尾追加一句,改完下一回合生效。
79
80
 
80
81
  主题词怎么挑:跳过 `总览`/`index` 这类结构页,跳过 `数据`/`工具`/`meta` 这类空泛标签,默认只留出现 ≥2 次的标签(设置页可改回 ≥1)。全被滤掉时退回不过滤的前五 —— 小库不至于一条提示都没有。
81
82
 
@@ -125,20 +126,22 @@ plugin_manager { action: "install_bundle", target: "<绝对路径>" }
125
126
 
126
127
  ```
127
128
  lib/corpus.js 扫描 + frontmatter / 小节 / 双链解析
128
- lib/engine.js 评分、选节、六种模式(纯函数)
129
+ lib/engine.js 评分、选节、七种模式(纯函数)
129
130
  lib/config.js 库路径解析与配置读写
130
131
  lib/index.js 插件入口:工具、渲染、设置页 API、目录监听
131
132
  lib/client.js 设置页(手写 bundle,无构建)
132
133
  bin/cli.mjs 命令行,不装插件也能跑
134
+ tools/probe.mjs 检索质量探针:hit@1 / hit@3 / Recall@5,追加趋势 CSV
133
135
  docs/库结构.md 库结构约定(这份才是一手文档)
134
136
  examples/ 可跑的最小样例库
135
- tests/ smoke / watch / client bundle
137
+ tests/ smoke / status / lint / api / help / contract / watch / client bundle
136
138
  ```
137
139
 
138
140
  ```bash
139
141
  node --run test # 跑样例库,不需要本地知识库
140
142
  node bin/cli.mjs search 上下文 --root=examples/sample-wiki
141
143
  WIKI_ROOT="/path/your/wiki" node tests/smoke.mjs # 拿自己的库跑通就行(不校验答案)
144
+ node --run probe -- --root "/path/your/wiki" # 攒一行检索质量趋势
142
145
  ```
143
146
 
144
147
  ## License
package/bin/cli.mjs CHANGED
@@ -22,12 +22,26 @@ const rest = argv.slice(1)
22
22
 
23
23
  const flags = {}
24
24
  const positional = []
25
- for (const item of rest) {
26
- if (item.startsWith('--')) {
27
- const [key, value] = item.slice(2).split('=')
28
- flags[key] = value ?? true
29
- } else {
25
+ // 两种写法都收:`--limit=3` 和 `--limit 3`。
26
+ // 只认等号那版曾让 `--limit 3` 变成 flags.limit === true,Number(true) === 1,
27
+ // 于是「要 3 条」安静地只返回 1 条;`--root 路径` 同样被整个忽略,实际读的还是默认库。
28
+ for (let i = 0; i < rest.length; i += 1) {
29
+ const item = rest[i]
30
+ if (!item.startsWith('--')) {
30
31
  positional.push(item)
32
+ continue
33
+ }
34
+ const eq = item.indexOf('=')
35
+ if (eq !== -1) {
36
+ flags[item.slice(2, eq)] = item.slice(eq + 1)
37
+ continue
38
+ }
39
+ const next = rest[i + 1]
40
+ if (next !== undefined && !next.startsWith('--')) {
41
+ flags[item.slice(2)] = next
42
+ i += 1
43
+ } else {
44
+ flags[item.slice(2)] = true
31
45
  }
32
46
  }
33
47
 
package/docs/metrics.md CHANGED
@@ -59,7 +59,9 @@ $$
59
59
  1. **基线指纹**:`tests/local/ab_baseline.meta.json` 里的 `library.fingerprint`。
60
60
  计算方式与导出时一致:对 `name|body.length` 排序后取 sha256 前 16 位。
61
61
  2. **引擎版本**:报告里打印当次 `lib/engine.js` 的 git commit。
62
- 3. **基线版本**:v2,14 查询 / 68 槽位。不与其他历史快照混合统计。
62
+ 3. **基线版本**:v3,14 查询 / 68 槽位。不与其他历史快照混合统计。
63
+ v3 于 2026-11-04 重导(库 90 → 91 页,两条期望页名随库内容变化),v2 快照留在
64
+ `tests/local/history/` 作对照:拿 v2 跑今天这个库只能到 66/68,差的 2 项是库漂移,不是检索退化。
63
65
 
64
66
  ## 判定顺序(严格按序,先中先停)
65
67
 
package/lib/config.js CHANGED
@@ -131,6 +131,23 @@ export function normalizeTopicConfig(raw) {
131
131
  return { minCount, stopwords: raw.stopwords !== false }
132
132
  }
133
133
 
134
+ /**
135
+ * 把「局部改动」并进现有主题词配置。
136
+ *
137
+ * 和 mergePromptConfig 同理:接口拿到的经常只有 minCount 一个字段,
138
+ * 直接 normalize(patch) 会把 stopwords 打回默认值,等于悄悄改了另一项。
139
+ */
140
+ export function mergeTopicConfig(current, patch) {
141
+ const base = normalizeTopicConfig(current) ?? { ...DEFAULT_TOPIC_CONFIG }
142
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return base
143
+ return (
144
+ normalizeTopicConfig({
145
+ minCount: patch.minCount === undefined ? base.minCount : patch.minCount,
146
+ stopwords: typeof patch.stopwords === 'boolean' ? patch.stopwords : base.stopwords,
147
+ }) ?? base
148
+ )
149
+ }
150
+
134
151
  /** 读主题词配置。缺字段按默认补齐。 */
135
152
  export function readTopicConfig(pluginRoot) {
136
153
  return normalizeTopicConfig(readRecord(pluginRoot).topics) ?? { ...DEFAULT_TOPIC_CONFIG }
@@ -162,6 +179,25 @@ export function normalizePromptConfig(raw) {
162
179
  }
163
180
  }
164
181
 
182
+ /**
183
+ * 把「局部改动」并进现有提示词配置。
184
+ *
185
+ * 为什么不直接用 normalizePromptConfig(patch):那样没带的字段会被打回默认值,
186
+ * 等于把用户存好的 override / extra 抹掉。HTTP 接口经常只带一个字段
187
+ * (比如只切 enabled),这里补的正是「没提到就别动」。
188
+ */
189
+ export function mergePromptConfig(current, patch) {
190
+ const base = normalizePromptConfig(current) ?? { ...DEFAULT_PROMPT_CONFIG }
191
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return base
192
+ return (
193
+ normalizePromptConfig({
194
+ enabled: typeof patch.enabled === 'boolean' ? patch.enabled : base.enabled,
195
+ override: typeof patch.override === 'string' ? patch.override : base.override,
196
+ extra: typeof patch.extra === 'string' ? patch.extra : base.extra,
197
+ }) ?? base
198
+ )
199
+ }
200
+
165
201
  /** 读提示词配置。缺字段按默认补齐,超长截断。 */
166
202
  export function readPromptConfig(pluginRoot) {
167
203
  return normalizePromptConfig(readRecord(pluginRoot).prompt) ?? { ...DEFAULT_PROMPT_CONFIG }
package/lib/corpus.js CHANGED
@@ -68,24 +68,73 @@ export function splitFrontmatter(text) {
68
68
  }
69
69
  const match = text.match(FM_RE)
70
70
  if (match === null) return { fields: {}, body: text }
71
+ // 缺收尾 `---` 时,非贪婪正则会一路吃到正文里下一条分隔线,把标题与首段整段吞掉,
72
+ // 而且不报警 —— 模型看到的就是一篇没有开头的小节。
73
+ // 内容不像元数据就当没有:宁可少解析一次,也不能让正文凭空不见。
74
+ if (!looksLikeFields(match[1])) return { fields: {}, body: text }
71
75
  return { fields: parseFields(match[1]), body: text.slice(match[0].length) }
72
76
  }
73
77
 
78
+ /**
79
+ * 一段「像元数据」的文本:每行要么空行、注释、块序列项,要么是 `键: 值`。
80
+ * 用来分辨 `---` 之间那一段到底是 frontmatter,还是正文里碰巧出现的两条分隔线。
81
+ */
82
+ function looksLikeFields(raw) {
83
+ let sawField = false
84
+ for (const line of raw.split(/\r?\n/)) {
85
+ const trimmed = line.trim()
86
+ if (trimmed === '' || trimmed.startsWith('#')) continue
87
+ if (trimmed.startsWith('- ') || trimmed === '-') continue
88
+ if (/^[^\s:#][^:]*:/.test(trimmed)) {
89
+ sawField = true
90
+ continue
91
+ }
92
+ return false
93
+ }
94
+ return sawField
95
+ }
96
+
74
97
  /**
75
98
  * 解析 key: value 行。
76
99
  * 真实库里只有七种值形态:纯文本、数字、`[]`、`[a, b]`、`[{{占位}}]`、日期、带引号。
77
100
  * 不引入 YAML 解析器 —— 这个库的 frontmatter 是 Obsidian 属性面板写出来的,形态极窄。
101
+ *
102
+ * 但「窄」不等于只有行内写法:Obsidian 属性面板给多值属性(标签、别名)落盘时用的是
103
+ * YAML 块序列——
104
+ * 标签:
105
+ * - RAG
106
+ * - 检索
107
+ * 早先只认 `[a, b]`,这几行会被整段丢掉,标签变空串,下游 tags 过滤、别名取页、
108
+ * lint 的字段检查一起失效,而且报成「库里没有」。这里补上:`标签:` 后面值为空时
109
+ * 记住这个键,接下来以 `- ` 开头的行都归它。
78
110
  */
79
111
  function parseFields(raw) {
80
112
  const fields = {}
113
+ let pendingKey = ''
81
114
  for (const line of raw.split(/\r?\n/)) {
82
115
  if (line.trim() === '' || line.trimStart().startsWith('#')) continue
116
+ const trimmed = line.trimStart()
117
+
118
+ // 块序列项:`- 值`,归属上面那个值为空的键
119
+ if (trimmed.startsWith('- ') || trimmed === '-') {
120
+ if (pendingKey === '') continue
121
+ const item = stripQuotes(trimmed.slice(1).trim())
122
+ if (item === '') continue
123
+ const prev = fields[pendingKey]
124
+ if (Array.isArray(prev)) prev.push(item)
125
+ else if (prev === '' || prev === undefined) fields[pendingKey] = [item]
126
+ else fields[pendingKey] = [prev, item]
127
+ continue
128
+ }
129
+
83
130
  const idx = line.indexOf(':')
84
131
  if (idx <= 0) continue
85
132
  const key = line.slice(0, idx).trim()
86
133
  const value = line.slice(idx + 1).trim()
87
134
  if (key === '') continue
88
135
  fields[key] = parseValue(value)
136
+ // 只有「键后面空着」才接受后续的块序列;`标签: [a, b]` 之后再来 `- c` 是无意义输入
137
+ pendingKey = value === '' ? key : ''
89
138
  }
90
139
  return fields
91
140
  }
@@ -137,12 +186,21 @@ function finish(section) {
137
186
  return { title: section.title, text: section.lines.join('\n').trim() }
138
187
  }
139
188
 
140
- /** 正文里的双链:`[[页名]]` 与 `[[页名|显示名]]`,去掉 `#锚点`。 */
189
+ /**
190
+ * 正文里的双链:`[[页名]]` 与 `[[页名|显示名]]`,去掉 `#锚点`。
191
+ *
192
+ * 两处细节都是实测踩出来的:
193
+ * - 表格里写双链要用 `\|` 转义,`[[甲\|别名]]` 早先会把页名读成 `甲\`(多一个反斜杠),
194
+ * 于是每张表格里的链接都变成红链。
195
+ * - 代码块和行内代码里的 `[[...]]` 是示例不是链接,不该进图谱。splitSections 早就剥了围栏,
196
+ * 这里原来没剥,同一条正文两种口径。
197
+ */
141
198
  export function extractLinks(text) {
142
199
  const names = []
143
- const re = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/g
200
+ const plain = String(text ?? '').replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, '')
201
+ const re = /\[\[([^\]|#\\]+)(?:#[^\]|]*)?(?:\\?\|[^\]]*)?\]\]/g
144
202
  let match
145
- while ((match = re.exec(text)) !== null) {
203
+ while ((match = re.exec(plain)) !== null) {
146
204
  const name = match[1].trim()
147
205
  if (name !== '') names.push(name)
148
206
  }
package/lib/engine.js CHANGED
@@ -153,22 +153,11 @@ function isBoilerplate(title) {
153
153
  return BOILERPLATE_TITLES.some((word) => title.includes(word))
154
154
  }
155
155
 
156
- /**
157
- * 挑命中最密的一节交给模型。
158
- *
159
- * 先按「命中了几种检索词」排(覆盖广度比出现次数更能说明这一节在讲什么),再按次数。
160
- * 清单类小节先排除:`§元信息` 里列着 `03-第一讲-要点.md` 这种文件名,词频很高但
161
- * 一个字都没回答「立意怎么写」,早先版本就是被它抢了头名。
162
- */
163
- function pickSection(page, tokens) {
164
- const sections = page.sections
165
- if (sections.length === 0) return { title: '', text: page.body }
166
- const candidates = sections.filter((section) => section.title !== '' && !isBoilerplate(section.title))
167
- const pool = candidates.length > 0 ? candidates : sections.filter((section) => section.title !== '')
168
- const realPool = pool.length > 0 ? pool : sections
156
+ /** 在一组小节里挑命中最密的那节;一个都没命中返回 null。 */
157
+ function bestSectionIn(pool, tokens) {
169
158
  let best = null
170
159
  let bestScore = 0
171
- for (const [index, section] of realPool.entries()) {
160
+ for (const [index, section] of pool.entries()) {
172
161
  let covered = 0
173
162
  let hits = 0
174
163
  for (const token of tokens) {
@@ -180,14 +169,43 @@ function pickSection(page, tokens) {
180
169
  if (covered === 0) continue
181
170
  // 靠前的小节更像「这页在讲什么」:越往后越可能是补充、反例、边角。给一点微弱的顺位分,
182
171
  // 只在命中密度接近时起作用。
183
- const positionBonus = (realPool.length - index) / realPool.length * 6
172
+ const positionBonus = (pool.length - index) / pool.length * 6
184
173
  const score = covered * 10 + Math.min(hits, 30) + positionBonus
185
174
  if (score > bestScore) {
186
175
  bestScore = score
187
176
  best = section
188
177
  }
189
178
  }
190
- return best ?? realPool[0]
179
+ return best
180
+ }
181
+
182
+ /**
183
+ * 挑命中最密的一节交给模型。
184
+ *
185
+ * 先按「命中了几种检索词」排(覆盖广度比出现次数更能说明这一节在讲什么),再按次数。
186
+ * 清单类小节先排除:`§元信息` 里列着 `03-第一讲-要点.md` 这种文件名,词频很高但
187
+ * 一个字都没回答「立意怎么写」,早先版本就是被它抢了头名。
188
+ *
189
+ * 但排除不等于「宁缺毋滥」:如果排除后一个都没命中,得回头在被排除的小节里找,
190
+ * 而不是拿 realPool[0] 顶上 —— 那是一个从未参与打分的无关小节,模型会当成「找到了」。
191
+ */
192
+ function pickSection(page, tokens) {
193
+ const sections = page.sections
194
+ if (sections.length === 0) return { title: '', text: page.body }
195
+ const candidates = sections.filter((section) => section.title !== '' && !isBoilerplate(section.title))
196
+ const pool = candidates.length > 0 ? candidates : sections.filter((section) => section.title !== '')
197
+ const realPool = pool.length > 0 ? pool : sections
198
+
199
+ const primary = bestSectionIn(realPool, tokens)
200
+ if (primary !== null) return primary
201
+
202
+ // 命中的词只落在清单类小节里:给那一节,至少它含查询词
203
+ const excluded = sections.filter((section) => section.title !== '' && isBoilerplate(section.title))
204
+ const fromExcluded = bestSectionIn(excluded, tokens)
205
+ if (fromExcluded !== null) return fromExcluded
206
+
207
+ // 真的一个词都没出现(比如这一页只靠标签/别名命中):给首节,但调用方会看到空命中
208
+ return realPool[0]
191
209
  }
192
210
 
193
211
  function clip(text, limit) {
@@ -528,6 +546,29 @@ export function getLocalDate(date = new Date()) {
528
546
  return `${year}-${month}-${day}`
529
547
  }
530
548
 
549
+ /**
550
+ * 「更新」字段 → 模型能用的判断。
551
+ *
552
+ * 只写一个 2025-03-14,模型没法判断该不该信:三年前的结论和上周的结论长得一样。
553
+ * 所以补上距今天数,超过半年直接说「可能已过时」。
554
+ * 这个信息 compareHits 一直在用(排序第五级就是 updated),但从来没渲染出去 ——
555
+ * 排了序、却不告诉模型为什么这么排。
556
+ */
557
+ export function freshnessOf(updated, now = Date.now()) {
558
+ const text = String(updated ?? '').trim()
559
+ const match = text.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/)
560
+ if (!match) return text
561
+ const stamp = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])).getTime()
562
+ if (!Number.isFinite(stamp)) return text
563
+ const days = Math.floor((now - stamp) / 86400000)
564
+ if (!Number.isFinite(days) || days < 0) return text // 未来日期不解释,原样输出
565
+ if (days === 0) return `${text}(今天更新)`
566
+ if (days === 1) return `${text}(昨天更新)`
567
+ if (days < 31) return `${text}(${days} 天前)`
568
+ if (days <= 180) return `${text}(${Math.floor(days / 30)} 个月前)`
569
+ return `${text}(${Math.floor(days / 30)} 个月前,可能已过时)`
570
+ }
571
+
531
572
  /**
532
573
  * 日志事件类型:不强制枚举(query / ingest / 拍板 / 结构补齐…本来该由调用方表达),
533
574
  * 只挡住会破坏 `## [日期] 类型 | 标题` 这一行结构的东西。
@@ -751,7 +792,78 @@ function bigramSimilarity(a, b) {
751
792
 
752
793
  /* ----------------------- 调用级:参数校验、状态与警告 ----------------------- */
753
794
 
754
- export const MODES = ['search', 'page', 'list', 'overview', 'lint', 'draft']
795
+ /**
796
+ * help:把「这个工具怎么用」做成可查的内容。
797
+ *
798
+ * 工具描述是每回合都要付的固定成本,机制文档只在模型真的要问时付一次。
799
+ * 而且描述写不全、写多了都一样有害:写不全模型猜错模式,写太满挤占别的东西。
800
+ * 这里的内容只讲「怎么用」,不讲这个库有什么 —— 后者是 overview 的事。
801
+ */
802
+ export function help() {
803
+ return {
804
+ mode: 'help',
805
+ sections: [
806
+ {
807
+ title: '它是什么',
808
+ lines: [
809
+ '一个只读的本地知识库检索器:给关键词,返回库里最相关的几页,附命中小节正文与出处。',
810
+ '不改文件、不联网、不生成内容。要写新页先用 mode:"draft" 拿骨架,再自己落盘。',
811
+ ],
812
+ },
813
+ {
814
+ title: '七个 mode',
815
+ lines: [
816
+ 'help:就是这份说明。不确定用哪个 mode、或看不懂某个 status 时先查它 —— 它不读库,不会失败。',
817
+ 'search(默认):1-4 个核心名词,空格分隔做 AND。返回元数据 + index 摘要 + 命中小节正文 + 出处,通常一次就够作答。',
818
+ 'page:传页名取整页;没精确命中会给 5 个候选。',
819
+ 'list:按 type / tags / status 列目录,比读 index.md 省 token。',
820
+ 'overview:总览正文 + 规模 + 最近日志 + 断链统计。',
821
+ 'lint:全库健康检查 —— 孤儿页、断链、缺字段、别名冲突、久未更新、草稿、index 与磁盘不一致。',
822
+ 'draft:给一份落盘骨架(目录、frontmatter、index 那行、log 那条),只返回文本。',
823
+ ],
824
+ },
825
+ {
826
+ title: 'status 怎么读',
827
+ lines: [
828
+ 'ok:正常,内容可信。',
829
+ 'degraded:只有部分检索词命中,已降级成 OR —— 命中面变宽、精度下降,答案要点可能偏。',
830
+ 'partial:看到的不全(有页读不出来 / 目录列不出 / 超大页没参与 / 有同名页)。warnings 说漏了什么。',
831
+ 'no_match:参与比对的页里没有命中。**不能反推全库没有**,换词组或 list 看命名习惯。',
832
+ 'unavailable:库一页都没扫到,通常是路径指错层 —— 该去查配置,不是换关键词。',
833
+ 'invalid_input:参数写错了(空 query、缺 name)。按提示补参数重试,别当成「库里没有」。',
834
+ ],
835
+ },
836
+ {
837
+ title: '输出里的字段',
838
+ lines: [
839
+ 'kind=note 是消化过的笔记(最可信);raw-summary 是原始资料压缩稿;source 是资料页。',
840
+ 'sources 是来源数量,判断证据强度用:1 份和 12 份不是一回事。',
841
+ '更新 后面括号是距今天数;标「可能已过时」的页,引用时要说明时间。',
842
+ '断链 / brokenLinks 非空 = 那处引用了库里不存在的页,说明该判断缺少页级支撑。',
843
+ '§小节 是命中的具体小节,引用时可以指到这个粒度。',
844
+ ],
845
+ },
846
+ {
847
+ title: '参数',
848
+ lines: [
849
+ 'limit:search 返回几页,默认 5、最多 12;lint 时是每组列几条,默认 8。',
850
+ 'sectionChars:search 每页正文上限,默认 900;需要完整段落时调到 1500-2000。',
851
+ 'pageChars:page 正文上限,默认 6000;overview 引用总览时默认 4000。',
852
+ 'staleDays:lint 判「久未更新」的天数,默认 120。',
853
+ ],
854
+ },
855
+ {
856
+ title: '不该用它的时候',
857
+ lines: [
858
+ '纯通用常识、且能从库索引线索确认没有对应内容 —— 查了只会拿到不相干的页。',
859
+ '但你「没看到线索」不等于库里没有:不确定就查一次,一次检索比一个错的结论便宜。',
860
+ ],
861
+ },
862
+ ],
863
+ }
864
+ }
865
+
866
+ export const MODES = ['search', 'page', 'list', 'overview', 'lint', 'draft', 'help']
755
867
 
756
868
  /**
757
869
  * 参数校验:必须在碰语料之前跑完。
@@ -782,6 +894,8 @@ const toCount = (value, fallback = 0) => (Number.isFinite(value) ? value : fallb
782
894
  * status 编码「模型该做什么」,warnings 编码「为什么」,两者都不承担修改结果的责任。
783
895
  */
784
896
  export function decideStatus(corpus, mode, args = {}, result = {}) {
897
+ // help 不碰语料:不该因为「库读不出来」被降级成 partial —— 说明文档和库的状态无关
898
+ if (mode === 'help') return { status: 'ok', warnings: [] }
785
899
  const stats = (corpus && corpus.stats) || {}
786
900
  const pages = toCount(stats.pages)
787
901
  const discovered = toCount(stats.discovered, pages)
@@ -826,6 +940,10 @@ export function decideStatus(corpus, mode, args = {}, result = {}) {
826
940
 
827
941
  const coverageLost = unreadable > 0 || walkFailures > 0 || statFailures > 0
828
942
 
943
+ // 同名页:byName 是 Map,后扫到的覆盖先扫到的,page 会静默返回其中一篇。
944
+ // 这是最难自查的一类错 —— 状态是 ok、正文有内容、引用也写得出来,只是可能引错了版本。
945
+ const dupWarning = duplicatePageWarning(stats, mode, result)
946
+
829
947
  // 空结果按 mode 各取各的字段,不为「统一」虚构字段
830
948
  const empty =
831
949
  mode === 'search' ? (result.hits ?? []).length === 0
@@ -850,12 +968,20 @@ export function decideStatus(corpus, mode, args = {}, result = {}) {
850
968
  : `扫描到 ${discovered} 个文件,但没有一个算作页面(只有 index/log,或被规则跳过)`)
851
969
  return { status: 'unavailable', warnings }
852
970
  }
853
- if (coverageLost) return { status: 'partial', warnings }
971
+ if (coverageLost) {
972
+ if (dupWarning) warnings.push(dupWarning)
973
+ return { status: 'partial', warnings }
974
+ }
975
+ if (dupWarning) {
976
+ // 覆盖没丢,但「拿到的是不是那一篇」不确定:失败模式是引错版本,同样配 partial。
977
+ warnings.push(dupWarning)
978
+ return { status: 'partial', warnings }
979
+ }
854
980
  if (mode === 'search' && result.degraded === true) {
855
981
  // 降级与「超大页可能相关」可以同时成立:状态按约定取 degraded,但两条事实都要输出 ——
856
982
  // 别让一个状态值把覆盖缺口吞掉。
857
983
  if (oversizedHit) warnings.push(oversizedWarning)
858
- warnings.push('只命中部分检索词,已降级为 OR:命中面变宽,精度下降')
984
+ warnings.push('只命中部分检索词,已降级为 OR:命中面变宽、精度下降;想收窄就改用页面标题或更少的词重查一次')
859
985
  return { status: 'degraded', warnings }
860
986
  }
861
987
  if (oversizedHit) {
@@ -873,6 +999,22 @@ function viaText(via) {
873
999
  return '标题或 index 摘要命中查询词'
874
1000
  }
875
1001
 
1002
+ /**
1003
+ * 同名页提示:byName 只留最后一个,page 命中的可能不是模型以为的那一页。
1004
+ * 返回空串表示这次没有这个风险(别的 mode、没取到页、名字唯一)。
1005
+ */
1006
+ function duplicatePageWarning(stats, mode, result) {
1007
+ if (mode !== 'page') return ''
1008
+ const found = result && result.found
1009
+ if (!found || !found.name) return ''
1010
+ const dups = Array.isArray(stats.duplicateNames) ? stats.duplicateNames : []
1011
+ const same = dups.filter((item) => item.name === found.name)
1012
+ if (same.length < 2) return ''
1013
+ const others = same.map((item) => item.file).filter((file) => file && file !== found.file)
1014
+ const rest = others.length > 0 ? `;另外还有 ${others.join('、')}` : ''
1015
+ return `库里有 ${same.length} 篇同名页「${found.name}」,这次返回的是 ${found.file}${rest} —— 引用前请确认是哪一篇,或先把同名页改名`
1016
+ }
1017
+
876
1018
  /** 统一入口:工具只暴露一个函数,六个 mode 分派到这里。 */
877
1019
  export function run(corpus, args = {}) {
878
1020
  const mode = typeof args.mode === 'string' && args.mode.trim() !== '' ? args.mode.trim() : 'search'
@@ -911,6 +1053,9 @@ export function run(corpus, args = {}) {
911
1053
  case 'draft':
912
1054
  result = draft(corpus, args)
913
1055
  break
1056
+ case 'help':
1057
+ result = help()
1058
+ break
914
1059
  }
915
1060
 
916
1061
  const verdict = decideStatus(corpus, mode, args, result)
package/lib/index.js CHANGED
@@ -13,12 +13,12 @@
13
13
  */
14
14
 
15
15
  import path from 'node:path'
16
- import { statSync, watch } from 'node:fs'
16
+ import { mkdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'
17
17
  import { fileURLToPath } from 'node:url'
18
18
 
19
19
  import { asList, loadCorpus } from './corpus.js'
20
- import { normalizeTopicConfig, readTopicConfig, writeTopicConfig } from './config.js'
21
- import { run } from './engine.js'
20
+ import { mergePromptConfig, mergeTopicConfig, normalizeTopicConfig, readTopicConfig, writeTopicConfig } from './config.js'
21
+ import { MODES, freshnessOf, lint, run } from './engine.js'
22
22
  import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
23
23
 
24
24
  export const name = 'wiki-notes'
@@ -57,44 +57,81 @@ function sendJson(res, status, payload) {
57
57
  res.end(body)
58
58
  }
59
59
 
60
- /** 请求体很小(一个路径字符串),限量读,别让谁塞一个大 body 进来。 */
60
+ /** 请求体很小(一个路径字符串),限量读,别让谁塞一个大 body 进来。
61
+ *
62
+ * 三种返回:空 body → null;合法 JSON → 解析结果;非法 JSON → undefined。
63
+ * 原来把「解析失败」也归成 null,POST 接口拿不到字段就一路按默认值写盘,
64
+ * 等于一次手滑的请求把用户配好的东西清空,还回 200。 */
61
65
  function readBody(req, limit = 64 * 1024) {
62
66
  return new Promise((resolve, reject) => {
63
67
  let size = 0
68
+ let tooLarge = false
64
69
  const chunks = []
65
70
  req.on('data', (chunk) => {
66
71
  size += chunk.length
67
72
  if (size > limit) {
68
- reject(new Error('请求体过大'))
69
- req.destroy()
73
+ // 早先这里直接 destroy 连接:调用方拿到的是「连接被重置」,不知道是自己发大了。
74
+ // 现在把超限记下来、后面的字节丢掉,读完再回 413 —— 错误得说清楚是哪一步错。
75
+ tooLarge = true
76
+ chunks.length = 0
70
77
  return
71
78
  }
72
- chunks.push(chunk)
79
+ if (!tooLarge) chunks.push(chunk)
73
80
  })
74
81
  req.on('end', () => {
82
+ if (tooLarge) {
83
+ const error = new Error(`请求体超过 ${limit} 字节上限`)
84
+ error.code = 'BODY_TOO_LARGE'
85
+ return reject(error)
86
+ }
75
87
  const text = Buffer.concat(chunks).toString('utf8').trim()
76
88
  if (text === '') return resolve(null)
77
89
  try {
78
90
  resolve(JSON.parse(text))
79
91
  } catch {
80
- resolve(null)
92
+ resolve(undefined)
81
93
  }
82
94
  })
83
95
  req.on('error', reject)
84
96
  })
85
97
  }
86
98
 
99
+ /**
100
+ * 跨源写配置的闸。
101
+ *
102
+ * 本机服务没有鉴权,浏览器里的任何网页都能往 127.0.0.1 发 POST —— 一个恶意页面
103
+ * 就能把库路径改走、把提示词换掉。拦的判据很窄:带 Origin 且 Origin 主机不是回环地址
104
+ * 就拒。不带 Origin 的请求(curl、命令行、插件自己)照旧放行,那是本机程序不是网页。
105
+ * 没有做 CSRF token:Setting 页是宿主的,改不动它的请求,先挡住最实的一层。
106
+ */
107
+ function blockedOrigin(req) {
108
+ const origin = req.headers?.origin
109
+ if (typeof origin !== 'string' || origin === '') return false
110
+ // 沙箱 iframe / file:// 页面发的是字符串 'null'。DSH 的设置页若被宿主放进
111
+ // 不透传来源的 iframe,这里放行才不至于把用户自己的保存按钮挡掉 ——
112
+ // 代价是不透明来源挡不住,但那类页面本来也拿不到响应,只能盲写。
113
+ if (origin === 'null') return false
114
+ try {
115
+ const host = new URL(origin).hostname
116
+ return !['127.0.0.1', 'localhost', '::1', '[::1]'].includes(host)
117
+ } catch {
118
+ return true
119
+ }
120
+ }
121
+
87
122
  const PARAMETERS = {
88
123
  type: 'object',
89
124
  properties: {
90
125
  mode: {
91
126
  type: 'string',
92
- enum: ['search', 'page', 'list', 'overview', 'lint', 'draft'],
93
- description: 'search=关键词检索(默认);page=按页名取整页;list=按类型/标签列目录;overview=库总览与健康状态;lint=全库健康检查(孤儿页/断链/缺字段/别名冲突/久未更新);draft=生成「把好答案回写成新页」的落盘骨架(不写文件)',
127
+ // 枚举只有一个来源:engine 的 MODES。新增 mode 时漏改这里,
128
+ // 描述教会了模型、schema 却把它挡在门外 —— 那是最难查的一种错。
129
+ enum: MODES,
130
+ description: 'search=关键词检索(默认);page=整页;list=目录;overview=总览;lint=健康检查;draft=落盘骨架;help=用法与状态说明',
94
131
  },
95
132
  query: {
96
133
  type: 'string',
97
- description: 'mode=search 时的检索词:1-4 个核心名词,空格分隔即 AND。不要传整句问话——先自己把问话拆成名词(「什么是逻辑填空」应传「逻辑填空」)。',
134
+ description: 'mode=search 时的检索词:1-4 个核心名词,空格分隔即 AND。不要传整句问话——先自己把问话拆成名词(「什么是向量检索」应传「向量检索」)。',
98
135
  },
99
136
  name: {
100
137
  type: 'string',
@@ -154,26 +191,25 @@ const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任
154
191
  何时必须调用(命中任一):
155
192
  - 问题涉及库内已知线索:页名、别名、标签,或系统提示里注入的主题词;
156
193
  - 问个人记录(「我之前怎么记的」「笔记里写了什么」);
157
- - 考公、行测、申论、政治理论相关;
194
+ - 涉及你笔记库里长期整理、反复出现的学科或领域(注入的主题词就是从高频标签取的);
158
195
  - 点名具体工具、框架、模型、项目、论文;
159
- - 要求引用、转述、核对笔记原文。
196
+ - 要求引用、转述、核对笔记原文;
197
+ - 正要下判断、正要写结论,或要把答案回写成新页之前:先查一遍再动笔,别写完再补。
160
198
 
161
199
  何时可以不查:纯通用常识,且根据库索引线索能确认没有对应内容(如「水」「三角形」)。
162
200
  只是没看到线索,不等于库里没有;拿不准先查,别靠自信跳过。
163
201
 
164
202
  mode 用法:
165
- - search(默认):传 1-4 个关键词,空格分隔做 AND。返回每页的元数据 + index.md 一句话摘要 + **命中小节完整正文** + citation。通常一次调用就够作答,不用再去读文件。
166
- - page:传页名取整页。没精确命中会返回 5 个候选,挑一个再查。
167
- - list:按 type / tags / status 列目录,比读 index.md 更省 token。
168
- - overview:总览正文 + 规模行 + 最近 5 条日志 + 断链统计。
169
- - lint:全库健康检查(只读)——孤儿页、断链名字、缺 frontmatter 字段、别名冲突、久未更新、无出链、草稿、index.md 与磁盘不一致。用户在整理/维护笔记、或问「库里有什么问题」时用。
170
- - draft:把本次的好答案回写成新页时,先要一份落盘骨架(目录、frontmatter 七字段、index.md 那一行、log.md 那一条)。本工具只返回文本,写文件要用你自己的写文件工具。
203
+ - search(默认):传 1-4 个关键词,空格分隔做 AND,别传整句问话。
204
+ - page / list / overview / lint / draft:取整页 / 列目录 / 看总览 / 查健康 / 拿落盘骨架。
205
+
206
+ 机制说明、每个 mode 的返回格式、status 各取值的含义、全部参数 —— 用 mode:"help" 查一次。
207
+ 描述只讲「什么时候该调」,讲不全的细节都在 help 里,不确定就查,比猜便宜。
171
208
 
172
209
  怎么读结果:
173
210
  - kind=note 是消化过的笔记(最可信);raw-summary 是原始资料的压缩稿;source 是资料页。
174
211
  - sources 是「来源数量」,判断证据强度用:1 份和 12 份不是一回事。
175
- - status=草稿 的页可能只是骨架。
176
- - brokenLinks 非空 = 这一节引用了库里不存在的页(红链),说明该处判断缺少页级支撑,转述时要标明。
212
+ - 每条带「更新」时间与距今天数;标了「可能已过时」的页,引用时要说明时间,别当成最新结论。
177
213
  - 一条都没命中不代表话题不存在,换同义词(中文/英文/缩写)或先用 list 看目录再搜。`
178
214
 
179
215
  /** 知识层的候选目录名:路径指到上一层时,自动下钻到这些名字。 */
@@ -216,12 +252,15 @@ export function apply(ctx, config = {}) {
216
252
  let cache = null
217
253
  let cachedAt = 0
218
254
  let inflight = null
255
+ /** 每次作废 +1。扫描结束时对比它,才知道「这份结果是不是已经被作废了」。 */
256
+ let generation = 0
219
257
 
220
258
  /** 换库 / 重扫时把缓存一起作废,否则设置页说「已切换」,模型那边还在看旧库。 */
221
259
  function invalidate() {
222
260
  cache = null
223
261
  cachedAt = 0
224
262
  inflight = null
263
+ generation += 1
225
264
  }
226
265
 
227
266
  /* ---------------------- 目录监听:库是活的 ---------------------- */
@@ -371,7 +410,8 @@ export function apply(ctx, config = {}) {
371
410
  const now = Date.now()
372
411
  if (cache !== null && now - cachedAt < CACHE_TTL_MS) return cache
373
412
  if (inflight !== null) return inflight
374
- inflight = (async () => {
413
+ const gen = generation
414
+ const task = (async () => {
375
415
  // 用户很容易把路径指到 LLM-Wiki 根(那里有 AGENTS.md、raw 与模板),
376
416
  // 扫出来数字虚高、还混进不该读的原始资料。这里自动下钻到真正的知识层。
377
417
  const drilled = drillTarget(root)
@@ -379,14 +419,22 @@ export function apply(ctx, config = {}) {
379
419
  const corpus = await loadCorpus(target)
380
420
  if (target !== root) corpus.drilledFrom = root
381
421
  scannedRoot = target
422
+ // 扫描期间被 invalidate 过(换库 / 重扫 / 文件变动):这份结果对应的是旧状态,
423
+ // 直接交给本次调用方,但绝不回写缓存 —— 否则「刚点过重新扫描」之后,
424
+ // 30 秒内所有查询都会读到作废前的旧快照。
425
+ if (gen !== generation) return corpus
382
426
  refreshTopics(corpus)
383
427
  cache = corpus
384
428
  cachedAt = Date.now()
385
429
  return corpus
386
- })().finally(() => {
387
- inflight = null
388
- })
389
- return inflight
430
+ })()
431
+ inflight = task
432
+ // 只清自己那一份:慢扫描结束时,inflight 可能已经是后来那次扫描了。
433
+ task.then(
434
+ () => { if (inflight === task) inflight = null },
435
+ () => { if (inflight === task) inflight = null },
436
+ )
437
+ return task
390
438
  }
391
439
 
392
440
  // 启动时探一次库:路径写错的话,日志里会立刻出现,而不是等模型调用时才失败。
@@ -478,6 +526,10 @@ export function apply(ctx, config = {}) {
478
526
  path: API_PREFIX,
479
527
  handler: async (req, res) => {
480
528
  const route = (req.url ?? '').split('?')[0].slice(API_PREFIX.length) || '/'
529
+ // 写操作先过跨源闸;GET /state 是只读,不拦。
530
+ if (req.method === 'POST' && blockedOrigin(req)) {
531
+ return sendJson(res, 403, { error: '拒绝跨源请求:写配置只接受本机页面或命令行' })
532
+ }
481
533
  try {
482
534
  if (route === '/state' && req.method === 'GET') {
483
535
  return sendJson(res, 200, await buildState())
@@ -488,7 +540,15 @@ export function apply(ctx, config = {}) {
488
540
  }
489
541
  if (route === '/save' && req.method === 'POST') {
490
542
  const body = await readBody(req)
491
- const typed = typeof body?.root === 'string' ? body.root.trim() : ''
543
+ // 和 /topics、/prompt 一样:坏 JSON 直接拒。少了这条,半截请求体会落进
544
+ // 「root 是空串」的分支,把用户配好的库路径从配置文件里删掉还回 200。
545
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
546
+ // 缺字段同样拒。「清掉配置」必须显式传空字符串 —— 那是设置页灰按钮的意图,
547
+ // 而「没带 root」只说明调用方写错了,不能当成同一个意思。
548
+ if (typeof body?.root !== 'string') {
549
+ return sendJson(res, 400, { error: '缺少 root 字段(要清空配置请显式传空字符串)' })
550
+ }
551
+ const typed = body.root.trim()
492
552
  // 统一存成绝对路径(用户可能写成正斜杠或相对路径),空串 = 清配置回到上一层
493
553
  const next = typed === '' ? '' : path.resolve(typed)
494
554
  // 先试扫再落盘:打错一个字符就把坏路径写进配置文件,等于让整个插件查不到库,
@@ -508,18 +568,17 @@ export function apply(ctx, config = {}) {
508
568
  }
509
569
  if (route === '/topics' && req.method === 'POST') {
510
570
  const body = await readBody(req)
511
- topicCfg = writeTopicConfig(pluginRoot, body).config
571
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
572
+ topicCfg = writeTopicConfig(pluginRoot, mergeTopicConfig(topicCfg, body)).config
512
573
  invalidate()
513
574
  sendJson(res, 200, await buildState())
514
575
  return
515
576
  }
516
577
  if (route === '/prompt' && req.method === 'POST') {
517
578
  const body = await readBody(req)
518
- promptCfg = writePromptConfig(pluginRoot, {
519
- enabled: body?.enabled !== false,
520
- override: typeof body?.override === 'string' ? body.override : '',
521
- extra: typeof body?.extra === 'string' ? body.extra : '',
522
- }).config
579
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
580
+ // 局部合并:没带的字段保持原值,只改提到的那几项
581
+ promptCfg = writePromptConfig(pluginRoot, mergePromptConfig(promptCfg, body)).config
523
582
  // 不用 invalidate():提示词和语料无关,下一回合读 text() 就是新值
524
583
  return sendJson(res, 200, await buildState())
525
584
  }
@@ -529,6 +588,9 @@ export function apply(ctx, config = {}) {
529
588
  }
530
589
  return sendJson(res, 404, { error: `未知路由 ${route}` })
531
590
  } catch (error) {
591
+ if (error?.code === 'BODY_TOO_LARGE') {
592
+ return sendJson(res, 413, { error: String(error.message ?? error) })
593
+ }
532
594
  return sendJson(res, 500, { error: String(error?.message ?? error) })
533
595
  }
534
596
  },
@@ -545,6 +607,9 @@ export function apply(ctx, config = {}) {
545
607
  ctx.systemPrompt?.context?.({
546
608
  name: 'wiki-notes:topics',
547
609
  order: 240,
610
+ // 关掉变量插值:这段文本里可能有用户自己写的提示词(extra / override),
611
+ // 里面的 {{...}} 是普通文字,不该被宿主当变量解析成空串或报错。
612
+ interpolate: false,
548
613
  text: () => buildTopicText(),
549
614
  })
550
615
  } catch (error) {
@@ -567,6 +632,13 @@ export function apply(ctx, config = {}) {
567
632
  if (result !== null && typeof result === 'object') {
568
633
  result.scanned = corpus.stats.pages
569
634
  result.root = root
635
+ if (result.mode === 'lint') {
636
+ try {
637
+ result.sinceLast = recordLintRun(corpus, args ?? {}, pluginRoot)
638
+ } catch {
639
+ // 历史文件坏了不该让体检失败:少一行对比,其它照报
640
+ }
641
+ }
570
642
  if (typeof corpus.drilledFrom === 'string') result.drilledFrom = corpus.drilledFrom
571
643
  result.ms = Date.now() - started
572
644
  }
@@ -609,6 +681,59 @@ export function apply(ctx, config = {}) {
609
681
  })
610
682
  }
611
683
 
684
+ /* ------------------------- 体检历史(lint 的对比基线) ------------------------- */
685
+
686
+ /** 需要动手的项。不含「久未更新」:它随时间自己变,进 diff 只会产生噪音。 */
687
+ function lintIssueKeys(value) {
688
+ const keys = new Set()
689
+ for (const row of value.orphans ?? []) keys.add(`孤儿页 ${row}`)
690
+ for (const row of value.brokenTargets ?? []) keys.add(`断链 ${row.name}`)
691
+ for (const row of value.missingFields ?? []) keys.add(`缺字段 ${row.name}`)
692
+ for (const row of value.aliasConflicts ?? []) keys.add(`别名冲突 ${row.alias}`)
693
+ for (const row of value.noLinks ?? []) keys.add(`无出链 ${row}`)
694
+ return keys
695
+ }
696
+
697
+ /**
698
+ * 记下这次体检,并和上一次比。
699
+ *
700
+ * 单次报告只说明「现在有什么」,说不出「库在变好还是变坏」——
701
+ * 修了三处、又坏了五处,和一处没动,在单次报告里长得一样。
702
+ * 对比用的那份用大 limit 重算一次:报告的 items 是截断的,拿截断结果做 diff 会漏项。
703
+ */
704
+ function recordLintRun(corpus, args, pluginRoot) {
705
+ const file = path.join(path.dirname(configPath(pluginRoot)), 'lint-history.json')
706
+ const full = lint(corpus, { ...args, limit: 500 })
707
+ const keys = lintIssueKeys(full)
708
+
709
+ let previous = null
710
+ try {
711
+ previous = JSON.parse(readFileSync(file, 'utf8'))
712
+ } catch {
713
+ previous = null // 第一次跑,或文件坏了:都当作没有基线
714
+ }
715
+
716
+ const before = new Set(Array.isArray(previous?.keys) ? previous.keys : [])
717
+ const added = [...keys].filter((key) => !before.has(key))
718
+ const fixed = [...before].filter((key) => !keys.has(key))
719
+
720
+ try {
721
+ mkdirSync(path.dirname(file), { recursive: true })
722
+ writeFileSync(file, JSON.stringify({ at: new Date().toISOString(), keys: [...keys] }), 'utf8')
723
+ } catch {
724
+ // 写不进去(只读家目录)不该影响体检本身
725
+ }
726
+
727
+ return {
728
+ at: previous?.at ?? '',
729
+ first: previous === null,
730
+ added: added.slice(0, 5),
731
+ addedTotal: added.length,
732
+ fixed: fixed.slice(0, 5),
733
+ fixedTotal: fixed.length,
734
+ }
735
+ }
736
+
612
737
  /* ------------------------------- 渲染 ------------------------------- */
613
738
 
614
739
  function renderValue(args, value) {
@@ -642,6 +767,9 @@ function renderValue(args, value) {
642
767
  case 'draft':
643
768
  body = renderDraft(value)
644
769
  break
770
+ case 'help':
771
+ body = renderHelp(value)
772
+ break
645
773
  default:
646
774
  body = JSON.stringify(value, null, 2)
647
775
  }
@@ -668,6 +796,18 @@ function renderLint(value) {
668
796
  `库健康检查(只读)· ${stats.pages ?? 0} 页 · ${stats.resources ?? 0} 份资料 · 扫描 ${stats.scannedMs ?? 0} ms`,
669
797
  ]
670
798
 
799
+ const since = value.sinceLast
800
+ if (since && since.first !== true) {
801
+ // 单次报告只有「现在」,说不出趋势:修了三处又坏五处,和一处没动长得一样
802
+ const parts = []
803
+ if (since.addedTotal > 0) parts.push(`新增 ${since.addedTotal} 项(${since.added.join(';')})`)
804
+ if (since.fixedTotal > 0) parts.push(`已修 ${since.fixedTotal} 项(${since.fixed.join(';')})`)
805
+ if (parts.length === 0) parts.push('没有变化')
806
+ lines.push(`与上次(${String(since.at).slice(0, 10)})相比:${parts.join(',')}`)
807
+ } else if (since && since.first === true) {
808
+ lines.push('(第一次记录基线,下次起会显示相对上次的变化)')
809
+ }
810
+
671
811
  const block = (title, total, rows, format) => {
672
812
  if (!total) return
673
813
  lines.push('')
@@ -693,6 +833,20 @@ function renderLint(value) {
693
833
  }
694
834
 
695
835
  /** draft 的渲染:要能整段复制去落盘,所以顺序是「未落盘声明 → 文件 → 内容 → 三件收尾」。 */
836
+ /**
837
+ * help 的渲染:纯静态文本,按小节铺开。
838
+ * 不放 markdown 表格 —— 模型读的是文本,表格的对齐空白是白付的 token。
839
+ */
840
+ function renderHelp(value) {
841
+ const out = ['【wiki_recall 用法】']
842
+ for (const section of value.sections ?? []) {
843
+ out.push('')
844
+ out.push(`■ ${section.title}`)
845
+ for (const line of section.lines ?? []) out.push(line)
846
+ }
847
+ return out.join('\n')
848
+ }
849
+
696
850
  function renderDraft(value) {
697
851
  const out = []
698
852
  // 最重要的事实放第一行:模型会截断、摘要或转述,末尾的说明最先被省掉
@@ -723,7 +877,8 @@ function metaLine(hit) {
723
877
  if (hit.type) parts.push(hit.type)
724
878
  if (hit.status) parts.push(hit.status)
725
879
  if (hit.sources !== null && hit.sources !== undefined) parts.push(`${hit.sources} 源`)
726
- if (hit.updated) parts.push(hit.updated)
880
+ // 光给日期模型判断不了该不该信:三年前的结论和上周的结论长得一模一样。
881
+ if (hit.updated) parts.push(freshnessOf(hit.updated))
727
882
  if (hit.kind && KIND_LABEL[hit.kind]) parts.push(KIND_LABEL[hit.kind])
728
883
  return parts.join(' · ')
729
884
  }
@@ -771,7 +926,8 @@ function renderSearch(value) {
771
926
  // 超大页的正文从来没读过,标题和摘要不沾边也推不出正文不沾边。
772
927
  out.push(`当前可检索范围内没有命中:已比对 ${value.considered ?? scanned} 页的内容${gap}。`)
773
928
  out.push('这只说明参与比对的页面里没有,不能反推全库没有。')
774
- out.push('换同义词(中文/英文/缩写)再试,或用 mode:"list" 看有哪些页。')
929
+ out.push('下一步:① 用页面标题或术语原文重试(别用整句问话);② 换同义词 / 英文 / 缩写;③ mode:"list" 看这个库的命名习惯。')
930
+ out.push('三条都试过仍然没有,才可以说「笔记里没有这个主题」。')
775
931
  }
776
932
  return out.join('\n')
777
933
  }
@@ -831,7 +987,10 @@ function renderList(value) {
831
987
  if (value.scale) out.push(`规模:${value.scale}`)
832
988
  const rows = Array.isArray(value.rows) ? value.rows : []
833
989
  for (const row of rows) {
834
- const meta = [row.type, row.status, row.sources === null ? '' : `${row.sources} 源`, row.updated]
990
+ // 和 search / page 一样把「多久以前」算出来:目录里最常被误读的就是一串裸日期,
991
+ // 看不出哪页是上个月改的、哪页是两年前的。
992
+ const updated = row.updated ? freshnessOf(row.updated) : ''
993
+ const meta = [row.type, row.status, row.sources === null ? '' : `${row.sources} 源`, updated]
835
994
  .filter((part) => part !== '' && part !== null && part !== undefined)
836
995
  .join(' · ')
837
996
  out.push(`- ${row.name} ⟨${meta}⟩${row.summary ? ` ${row.summary}` : ''}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-wiki-notes",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "type": "module",
5
5
  "description": "Read-only Markdown knowledge-base retrieval for DeepSeek Harness: one wiki_recall tool (search/page/list/overview/lint/draft) returning the matching section's full text with page-level citations. 中文:本地 Markdown 笔记库检索插件,一次调用返回命中小节正文与出处,另带健康检查与回写骨架。",
6
6
  "keywords": [
@@ -37,8 +37,9 @@
37
37
  "node": ">=20.13.0"
38
38
  },
39
39
  "scripts": {
40
- "test": "node tests/smoke.mjs && node tests/status.mjs && node tests/params.mjs && node tests/fields.mjs && node tests/lint.mjs && node tests/config.mjs && node tests/topics.mjs && node tests/draft.mjs && node tests/watch.mjs && node tests/client.mjs",
41
- "cli": "node bin/cli.mjs"
40
+ "test": "node tests/smoke.mjs && node tests/status.mjs && node tests/params.mjs && node tests/fields.mjs && node tests/robust.mjs && node tests/lint.mjs && node tests/lintdiff.mjs && node tests/config.mjs && node tests/cli.mjs && node tests/api.mjs && node tests/help.mjs && node tests/contract.mjs && node tests/topics.mjs && node tests/draft.mjs && node tests/watch.mjs && node tests/client.mjs",
41
+ "cli": "node bin/cli.mjs",
42
+ "probe": "node tools/probe.mjs"
42
43
  },
43
44
  "peerDependencies": {
44
45
  "@deepseek-ai/cordis": "^4.0.1",