dsh-wiki-notes 1.1.1 → 1.1.2

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/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/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
@@ -75,17 +75,43 @@ export function splitFrontmatter(text) {
75
75
  * 解析 key: value 行。
76
76
  * 真实库里只有七种值形态:纯文本、数字、`[]`、`[a, b]`、`[{{占位}}]`、日期、带引号。
77
77
  * 不引入 YAML 解析器 —— 这个库的 frontmatter 是 Obsidian 属性面板写出来的,形态极窄。
78
+ *
79
+ * 但「窄」不等于只有行内写法:Obsidian 属性面板给多值属性(标签、别名)落盘时用的是
80
+ * YAML 块序列——
81
+ * 标签:
82
+ * - RAG
83
+ * - 检索
84
+ * 早先只认 `[a, b]`,这几行会被整段丢掉,标签变空串,下游 tags 过滤、别名取页、
85
+ * lint 的字段检查一起失效,而且报成「库里没有」。这里补上:`标签:` 后面值为空时
86
+ * 记住这个键,接下来以 `- ` 开头的行都归它。
78
87
  */
79
88
  function parseFields(raw) {
80
89
  const fields = {}
90
+ let pendingKey = ''
81
91
  for (const line of raw.split(/\r?\n/)) {
82
92
  if (line.trim() === '' || line.trimStart().startsWith('#')) continue
93
+ const trimmed = line.trimStart()
94
+
95
+ // 块序列项:`- 值`,归属上面那个值为空的键
96
+ if (trimmed.startsWith('- ') || trimmed === '-') {
97
+ if (pendingKey === '') continue
98
+ const item = stripQuotes(trimmed.slice(1).trim())
99
+ if (item === '') continue
100
+ const prev = fields[pendingKey]
101
+ if (Array.isArray(prev)) prev.push(item)
102
+ else if (prev === '' || prev === undefined) fields[pendingKey] = [item]
103
+ else fields[pendingKey] = [prev, item]
104
+ continue
105
+ }
106
+
83
107
  const idx = line.indexOf(':')
84
108
  if (idx <= 0) continue
85
109
  const key = line.slice(0, idx).trim()
86
110
  const value = line.slice(idx + 1).trim()
87
111
  if (key === '') continue
88
112
  fields[key] = parseValue(value)
113
+ // 只有「键后面空着」才接受后续的块序列;`标签: [a, b]` 之后再来 `- c` 是无意义输入
114
+ pendingKey = value === '' ? key : ''
89
115
  }
90
116
  return fields
91
117
  }
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) {
package/lib/index.js CHANGED
@@ -17,7 +17,7 @@ import { statSync, watch } 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'
20
+ import { mergePromptConfig, mergeTopicConfig, normalizeTopicConfig, readTopicConfig, writeTopicConfig } from './config.js'
21
21
  import { 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
 
@@ -57,7 +57,11 @@ 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
@@ -77,7 +81,7 @@ function readBody(req, limit = 64 * 1024) {
77
81
  try {
78
82
  resolve(JSON.parse(text))
79
83
  } catch {
80
- resolve(null)
84
+ resolve(undefined)
81
85
  }
82
86
  })
83
87
  req.on('error', reject)
@@ -94,7 +98,7 @@ const PARAMETERS = {
94
98
  },
95
99
  query: {
96
100
  type: 'string',
97
- description: 'mode=search 时的检索词:1-4 个核心名词,空格分隔即 AND。不要传整句问话——先自己把问话拆成名词(「什么是逻辑填空」应传「逻辑填空」)。',
101
+ description: 'mode=search 时的检索词:1-4 个核心名词,空格分隔即 AND。不要传整句问话——先自己把问话拆成名词(「什么是向量检索」应传「向量检索」)。',
98
102
  },
99
103
  name: {
100
104
  type: 'string',
@@ -154,7 +158,7 @@ const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任
154
158
  何时必须调用(命中任一):
155
159
  - 问题涉及库内已知线索:页名、别名、标签,或系统提示里注入的主题词;
156
160
  - 问个人记录(「我之前怎么记的」「笔记里写了什么」);
157
- - 考公、行测、申论、政治理论相关;
161
+ - 涉及你笔记库里长期整理、反复出现的学科或领域(注入的主题词就是从高频标签取的);
158
162
  - 点名具体工具、框架、模型、项目、论文;
159
163
  - 要求引用、转述、核对笔记原文。
160
164
 
@@ -216,12 +220,15 @@ export function apply(ctx, config = {}) {
216
220
  let cache = null
217
221
  let cachedAt = 0
218
222
  let inflight = null
223
+ /** 每次作废 +1。扫描结束时对比它,才知道「这份结果是不是已经被作废了」。 */
224
+ let generation = 0
219
225
 
220
226
  /** 换库 / 重扫时把缓存一起作废,否则设置页说「已切换」,模型那边还在看旧库。 */
221
227
  function invalidate() {
222
228
  cache = null
223
229
  cachedAt = 0
224
230
  inflight = null
231
+ generation += 1
225
232
  }
226
233
 
227
234
  /* ---------------------- 目录监听:库是活的 ---------------------- */
@@ -371,7 +378,8 @@ export function apply(ctx, config = {}) {
371
378
  const now = Date.now()
372
379
  if (cache !== null && now - cachedAt < CACHE_TTL_MS) return cache
373
380
  if (inflight !== null) return inflight
374
- inflight = (async () => {
381
+ const gen = generation
382
+ const task = (async () => {
375
383
  // 用户很容易把路径指到 LLM-Wiki 根(那里有 AGENTS.md、raw 与模板),
376
384
  // 扫出来数字虚高、还混进不该读的原始资料。这里自动下钻到真正的知识层。
377
385
  const drilled = drillTarget(root)
@@ -379,14 +387,22 @@ export function apply(ctx, config = {}) {
379
387
  const corpus = await loadCorpus(target)
380
388
  if (target !== root) corpus.drilledFrom = root
381
389
  scannedRoot = target
390
+ // 扫描期间被 invalidate 过(换库 / 重扫 / 文件变动):这份结果对应的是旧状态,
391
+ // 直接交给本次调用方,但绝不回写缓存 —— 否则「刚点过重新扫描」之后,
392
+ // 30 秒内所有查询都会读到作废前的旧快照。
393
+ if (gen !== generation) return corpus
382
394
  refreshTopics(corpus)
383
395
  cache = corpus
384
396
  cachedAt = Date.now()
385
397
  return corpus
386
- })().finally(() => {
387
- inflight = null
388
- })
389
- return inflight
398
+ })()
399
+ inflight = task
400
+ // 只清自己那一份:慢扫描结束时,inflight 可能已经是后来那次扫描了。
401
+ task.then(
402
+ () => { if (inflight === task) inflight = null },
403
+ () => { if (inflight === task) inflight = null },
404
+ )
405
+ return task
390
406
  }
391
407
 
392
408
  // 启动时探一次库:路径写错的话,日志里会立刻出现,而不是等模型调用时才失败。
@@ -488,7 +504,15 @@ export function apply(ctx, config = {}) {
488
504
  }
489
505
  if (route === '/save' && req.method === 'POST') {
490
506
  const body = await readBody(req)
491
- const typed = typeof body?.root === 'string' ? body.root.trim() : ''
507
+ // 和 /topics、/prompt 一样:坏 JSON 直接拒。少了这条,半截请求体会落进
508
+ // 「root 是空串」的分支,把用户配好的库路径从配置文件里删掉还回 200。
509
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
510
+ // 缺字段同样拒。「清掉配置」必须显式传空字符串 —— 那是设置页灰按钮的意图,
511
+ // 而「没带 root」只说明调用方写错了,不能当成同一个意思。
512
+ if (typeof body?.root !== 'string') {
513
+ return sendJson(res, 400, { error: '缺少 root 字段(要清空配置请显式传空字符串)' })
514
+ }
515
+ const typed = body.root.trim()
492
516
  // 统一存成绝对路径(用户可能写成正斜杠或相对路径),空串 = 清配置回到上一层
493
517
  const next = typed === '' ? '' : path.resolve(typed)
494
518
  // 先试扫再落盘:打错一个字符就把坏路径写进配置文件,等于让整个插件查不到库,
@@ -508,18 +532,17 @@ export function apply(ctx, config = {}) {
508
532
  }
509
533
  if (route === '/topics' && req.method === 'POST') {
510
534
  const body = await readBody(req)
511
- topicCfg = writeTopicConfig(pluginRoot, body).config
535
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
536
+ topicCfg = writeTopicConfig(pluginRoot, mergeTopicConfig(topicCfg, body)).config
512
537
  invalidate()
513
538
  sendJson(res, 200, await buildState())
514
539
  return
515
540
  }
516
541
  if (route === '/prompt' && req.method === 'POST') {
517
542
  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
543
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
544
+ // 局部合并:没带的字段保持原值,只改提到的那几项
545
+ promptCfg = writePromptConfig(pluginRoot, mergePromptConfig(promptCfg, body)).config
523
546
  // 不用 invalidate():提示词和语料无关,下一回合读 text() 就是新值
524
547
  return sendJson(res, 200, await buildState())
525
548
  }
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.2",
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,7 +37,7 @@
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",
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/cli.mjs && node tests/api.mjs && node tests/topics.mjs && node tests/draft.mjs && node tests/watch.mjs && node tests/client.mjs",
41
41
  "cli": "node bin/cli.mjs"
42
42
  },
43
43
  "peerDependencies": {