dsh-wiki-notes 1.5.0 → 1.6.1

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/lib/config.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /** config.js —— 库位置解析与保存。插件、CLI、设置页共用同一套规则,避免三处跑出不同结果。 */
2
2
 
3
- import { readFileSync, writeFileSync } from 'node:fs'
3
+ import { readFileSync, writeFileSync, existsSync, renameSync, copyFileSync } from 'node:fs'
4
4
  import path from 'node:path'
5
+ import { clipChars } from './text.js'
5
6
 
6
7
  /**
7
8
  * 内置默认库路径。
@@ -72,12 +73,27 @@ export function configPath(pluginRoot) {
72
73
  return pluginRoot === '' ? '' : path.join(pluginRoot, CONFIG_FILE)
73
74
  }
74
75
 
76
+ /**
77
+ * UTF-8 BOM 是编码标记,不是 JSON 内容。PowerShell 的 `Out-File -Encoding utf8`
78
+ * (PS 5.1)写出的是带 BOM 的文件,直接 JSON.parse 会失败 —— 后果不是「读不到」这么
79
+ * 简单:readRecord 把整份配置当空对象,界面显示「还没配库」;下一次写入又把这份
80
+ * 其实完好的配置当成坏文件备份成 .broken,用户的主题词/桥路径被埋进备份里。
81
+ * 读 JSON 的地方统一先剥掉开头那一个 BOM;中间的 U+FEFF 属于内容,不动。
82
+ *
83
+ * 导出给宿主半复用:package.json 与 lint-history.json 若裸 JSON.parse,带 BOM 时
84
+ * 分别会退化成「版本 unknown」和「第一次记录基线」,同样是静默丢信息。
85
+ */
86
+ export function readJsonFile(file) {
87
+ const raw = readFileSync(file, 'utf8')
88
+ return JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw)
89
+ }
90
+
75
91
  /** 读整个配置文件。文件缺失或坏掉都当空对象 —— 不能因为配置问题让工具消失。 */
76
92
  function readRecord(pluginRoot) {
77
93
  const file = configPath(pluginRoot)
78
94
  if (file === '') return {}
79
95
  try {
80
- const parsed = JSON.parse(readFileSync(file, 'utf8'))
96
+ const parsed = readJsonFile(file)
81
97
  if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
82
98
  } catch {
83
99
  // 没有配置文件或文件坏了,都退回默认值
@@ -85,10 +101,38 @@ function readRecord(pluginRoot) {
85
101
  return {}
86
102
  }
87
103
 
104
+ /** 现有文件是不是一份可用的配置对象(用来决定覆盖前要不要留备份)。 */
105
+ function isUsableRecord(file) {
106
+ try {
107
+ const parsed = readJsonFile(file)
108
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
109
+ } catch {
110
+ return false
111
+ }
112
+ }
113
+
88
114
  /** 写回整个配置文件(保留不认识的字段,别把提示词配置顺手抹掉)。 */
89
115
  function writeRecord(pluginRoot, record) {
90
116
  const file = configPath(pluginRoot)
91
- writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
117
+ if (file === '') return ''
118
+ const text = `${JSON.stringify(record, null, 2)}\n`
119
+
120
+ // 现有文件若是坏的,直接覆盖等于把用户之前那份配置(主题词、桥路径、提示词)一起埋了 ——
121
+ // 写入前先留一份 `.broken` 备份,随后 readRecord 会把空对象当起点,界面照常能存。
122
+ if (existsSync(file) && !isUsableRecord(file)) {
123
+ try {
124
+ copyFileSync(file, `${file}.broken`)
125
+ } catch {
126
+ // 备份失败(权限、磁盘满)也要继续写,否则设置页直接存不了
127
+ }
128
+ }
129
+
130
+ // 原子写:崩在写一半只会留下 `.tmp`,配置文件本身仍是上一份完整内容。
131
+ // 以前是直写,一次意外断电就可能得到一个被截断的 JSON,而 readRecord 会把坏文件当空对象,
132
+ // 用户看到的是「我配的路径怎么没了」。
133
+ const tmp = `${file}.tmp`
134
+ writeFileSync(tmp, text, 'utf8')
135
+ renameSync(tmp, file)
92
136
  return file
93
137
  }
94
138
 
@@ -163,11 +207,29 @@ export function writeTopicConfig(pluginRoot, next) {
163
207
 
164
208
  /* --------------------- 调用记录:开关与账本位置 --------------------- */
165
209
 
210
+ /**
211
+ * 把「开 / 关」这种输入统一成布尔。
212
+ *
213
+ * 只认显式 false 的写法(`raw.enabled !== false`)有个坑:字符串 `"false"` 是真值,
214
+ * 于是「想关掉观察」的调用会把它**打开** —— 方向反了,而且打开之后就开始往账本里记东西。
215
+ * 这里把常见的写法都认下来,认不出来的保留原值(调用方给的是 undefined 时不改语义)。
216
+ */
217
+ function toFlag(value, fallback) {
218
+ if (typeof value === 'boolean') return value
219
+ if (typeof value === 'number') return value !== 0
220
+ if (typeof value === 'string') {
221
+ const text = value.trim().toLowerCase()
222
+ if (text === 'true' || text === '1' || text === 'on' || text === 'yes') return true
223
+ if (text === 'false' || text === '0' || text === 'off' || text === 'no') return false
224
+ }
225
+ return fallback
226
+ }
227
+
166
228
  /**
167
229
  * 调用记录配置。
168
230
  *
169
- * enabled 只认显式 false —— 这个字段的语义是「要不要记账」,
170
- * 一个拼错的字符串不该让审计悄悄停工。要关它的唯一写法是传 false。
231
+ * enabled 的语义是「要不要记账」:一个拼错的字符串不该让审计悄悄停工,
232
+ * 但也不能把 `"false"` 读成开 —— 见 toFlag。
171
233
  * log 空串表示「用插件根目录下的 calls.jsonl」。
172
234
  */
173
235
  export const DEFAULT_CALLS_CONFIG = { enabled: true, log: '' }
@@ -176,7 +238,7 @@ export const DEFAULT_CALLS_CONFIG = { enabled: true, log: '' }
176
238
  export function normalizeCallsConfig(raw) {
177
239
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
178
240
  return {
179
- enabled: raw.enabled !== false,
241
+ enabled: toFlag(raw.enabled, true),
180
242
  log: typeof raw.log === 'string' ? raw.log.trim() : '',
181
243
  }
182
244
  }
@@ -206,9 +268,9 @@ export const PROMPT_MAX_CHARS = 600
206
268
  export function normalizePromptConfig(raw) {
207
269
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
208
270
  return {
209
- enabled: raw.enabled !== false,
210
- override: typeof raw.override === 'string' ? raw.override.slice(0, PROMPT_MAX_CHARS).trim() : '',
211
- extra: typeof raw.extra === 'string' ? raw.extra.slice(0, PROMPT_MAX_CHARS).trim() : '',
271
+ enabled: toFlag(raw.enabled, true),
272
+ override: typeof raw.override === 'string' ? clipChars(raw.override, PROMPT_MAX_CHARS).trim() : '',
273
+ extra: typeof raw.extra === 'string' ? clipChars(raw.extra, PROMPT_MAX_CHARS).trim() : '',
212
274
  }
213
275
  }
214
276
 
@@ -224,7 +286,7 @@ export function mergePromptConfig(current, patch) {
224
286
  if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return base
225
287
  return (
226
288
  normalizePromptConfig({
227
- enabled: typeof patch.enabled === 'boolean' ? patch.enabled : base.enabled,
289
+ enabled: toFlag(patch.enabled, base.enabled),
228
290
  override: typeof patch.override === 'string' ? patch.override : base.override,
229
291
  extra: typeof patch.extra === 'string' ? patch.extra : base.extra,
230
292
  }) ?? base
package/lib/corpus.js CHANGED
@@ -58,6 +58,18 @@ function failureOf(stage, rel, error) {
58
58
  return { path: rel, stage, code }
59
59
  }
60
60
 
61
+ /**
62
+ * UTF-8 BOM(U+FEFF)是编码标记,不是正文。Windows 的 PowerShell / 记事本写出的
63
+ * .md 常带一个,读进来若不剥,它会粘在首个标题、首个 `##` 小节、index 首条目录、
64
+ * log 首条记录的行首,让「## [日期] 类型 | 标题」这类行首匹配整条失效,
65
+ * 而且不报错 —— 看起来只是「库里没有」。只剥开头那一个:正文中间的 U+FEFF
66
+ * 是零宽不换行空格,属于内容,不能删。splitFrontmatter 里也留着 BOM 容忍,
67
+ * 那是给「不经过 loadCorpus、直接喂字符串」的调用兜底。
68
+ */
69
+ function stripBom(text) {
70
+ return typeof text === 'string' && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
71
+ }
72
+
61
73
  /** frontmatter 分隔线。允许文件开头有 BOM。 */
62
74
  const FM_RE = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?/
63
75
 
@@ -169,8 +181,19 @@ export function splitSections(body) {
169
181
  const lines = body.split(/\r?\n/)
170
182
  const sections = []
171
183
  let current = { title: '', level: 0, lines: [] }
184
+ // 代码围栏里的 `## xxx` 是示例,不是小节:当初只按行首匹配,
185
+ // 于是任何在笔记里贴了一段 markdown / JSON 的页面都会多出一个并不存在的小节,
186
+ // 选节时还可能把那段代码当正文交给模型。
187
+ let fence = null
172
188
  for (const line of lines) {
173
- const heading = line.match(/^(#{1,3})\s+(.*)$/)
189
+ const marker = line.match(/^\s*(`{3,}|~{3,})/)
190
+ if (marker !== null) {
191
+ if (fence === null) fence = marker[1][0]
192
+ else if (marker[1][0] === fence) fence = null
193
+ current.lines.push(line)
194
+ continue
195
+ }
196
+ const heading = fence === null ? line.match(/^(#{1,3})\s+(.*)$/) : null
174
197
  if (heading !== null && heading[1].length === 2) {
175
198
  if (current.title !== '' || current.lines.some((l) => l.trim() !== '')) sections.push(finish(current))
176
199
  current = { title: heading[2].trim(), level: 2, lines: [] }
@@ -186,18 +209,37 @@ function finish(section) {
186
209
  return { title: section.title, text: section.lines.join('\n').trim() }
187
210
  }
188
211
 
212
+ /**
213
+ * 去掉围栏代码块(``` 与 ~~~ 两种都算),行内代码不动 —— 调用方自己处理。
214
+ * 与 splitSections 用同一套围栏判定,避免「同一条正文两种口径」。
215
+ */
216
+ function stripCodeBlocks(text) {
217
+ const kept = []
218
+ let fence = null
219
+ for (const line of String(text ?? '').split(/\r?\n/)) {
220
+ const marker = line.match(/^\s*(`{3,}|~{3,})/)
221
+ if (marker !== null) {
222
+ if (fence === null) fence = marker[1][0]
223
+ else if (marker[1][0] === fence) fence = null
224
+ continue
225
+ }
226
+ if (fence === null) kept.push(line)
227
+ }
228
+ return kept.join('\n')
229
+ }
230
+
189
231
  /**
190
232
  * 正文里的双链:`[[页名]]` 与 `[[页名|显示名]]`,去掉 `#锚点`。
191
233
  *
192
234
  * 两处细节都是实测踩出来的:
193
235
  * - 表格里写双链要用 `\|` 转义,`[[甲\|别名]]` 早先会把页名读成 `甲\`(多一个反斜杠),
194
236
  * 于是每张表格里的链接都变成红链。
195
- * - 代码块和行内代码里的 `[[...]]` 是示例不是链接,不该进图谱。splitSections 早就剥了围栏,
196
- * 这里原来没剥,同一条正文两种口径。
237
+ * - 代码块和行内代码里的 `[[...]]` 是示例不是链接,不该进图谱;早先只认 ``` 一种围栏,
238
+ * 用 ~~~ 写的示例仍会被当链接,现在两种都剥。
197
239
  */
198
240
  export function extractLinks(text) {
199
241
  const names = []
200
- const plain = String(text ?? '').replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, '')
242
+ const plain = stripCodeBlocks(text).replace(/`[^`\n]*`/g, '')
201
243
  const re = /\[\[([^\]|#\\]+)(?:#[^\]|]*)?(?:\\?\|[^\]]*)?\]\]/g
202
244
  let match
203
245
  while ((match = re.exec(plain)) !== null) {
@@ -250,7 +292,7 @@ export async function loadCorpus(wikiDir) {
250
292
  }
251
293
  let text = ''
252
294
  try {
253
- text = await fs.readFile(entry.abs, 'utf8')
295
+ text = stripBom(await fs.readFile(entry.abs, 'utf8'))
254
296
  } catch (error) {
255
297
  return { failure: failureOf('read', entry.rel, error) }
256
298
  }
@@ -317,7 +359,8 @@ export async function loadCorpus(wikiDir) {
317
359
  }
318
360
 
319
361
  const indexData = await readIndex(indexFile)
320
- const log = await readLog(logFile)
362
+ const logInfo = await readLog(logFile)
363
+ const log = logInfo.entries
321
364
 
322
365
  // 覆盖口径:discovered = pages + unreadable + skipped(文件级恒等式,tests/status.mjs 里断言)
323
366
  const unreadable = failures.filter((item) => item.stage === 'read' || item.stage === 'parse').length
@@ -341,6 +384,14 @@ export async function loadCorpus(wikiDir) {
341
384
  // 目录数与文件数分开记:walkFailures 是目录数,不参与上面的文件级等式
342
385
  walkFailures: walked.walkFailures,
343
386
  statFailures: walked.statFailures,
387
+ // 没跟的 junction / symlink:内容没扫,但不是丢页 —— 它们指向本库之外,
388
+ // 扫进来会重复也可能绕圈。留痕是为了让「链接没跟」不被读成「页不见了」。
389
+ linksSkipped: walked.linkSkips.length,
390
+ linkSkips: walked.linkSkips.slice(0, 10),
391
+ // log.md 在不在、解析出几条:两件事分开记。「在但 0 条」是格式对不上,
392
+ // 只看条数会把它读成「最近没有改动」。
393
+ logPresent: logInfo.present,
394
+ logEntries: log.length,
344
395
  failuresTotal: failures.length + walked.statFailures,
345
396
  failures: failures.slice(0, MAX_FAILURE_DETAILS),
346
397
  scannedMs: Date.now() - startedAt,
@@ -360,6 +411,7 @@ export async function loadCorpus(wikiDir) {
360
411
  async function walkMarkdown(root) {
361
412
  const files = []
362
413
  const failures = []
414
+ const linkSkips = []
363
415
  let walkFailures = 0
364
416
  let statFailures = 0
365
417
 
@@ -377,6 +429,13 @@ async function walkMarkdown(root) {
377
429
  for (const dirent of dirents) {
378
430
  const abs = path.join(dir, dirent.name)
379
431
  const rel = relPrefix === '' ? dirent.name : `${relPrefix}/${dirent.name}`
432
+ // junction / symlink 不跟:跟进去会重复扫描同一批页,也可能绕成环(Windows 上
433
+ // 遍历不受信任的装入点还会直接抛 0x800701C0)。但「没跟」必须留痕 ——
434
+ // 否则用户把另一个目录链接进库,看到的现象是「页不见了」而不是「链接没跟」。
435
+ if (dirent.isSymbolicLink()) {
436
+ linkSkips.push(rel)
437
+ continue
438
+ }
380
439
  if (dirent.isDirectory()) {
381
440
  if (dirent.name.startsWith('.')) continue
382
441
  await walk(abs, rel)
@@ -401,7 +460,7 @@ async function walkMarkdown(root) {
401
460
 
402
461
  await walk(root, '')
403
462
  files.sort((a, b) => a.rel.localeCompare(b.rel, 'zh'))
404
- return { files, failures, walkFailures, statFailures }
463
+ return { files, failures, walkFailures, statFailures, linkSkips }
405
464
  }
406
465
 
407
466
  /**
@@ -414,7 +473,7 @@ async function readIndex(file) {
414
473
  let scale = ''
415
474
  let raw = ''
416
475
  try {
417
- raw = await fs.readFile(file, 'utf8')
476
+ raw = stripBom(await fs.readFile(file, 'utf8'))
418
477
  } catch {
419
478
  return { lines, scale }
420
479
  }
@@ -475,8 +534,18 @@ const TYPE_ALIASES = {
475
534
  overview: '总览', note: '笔记', notes: '笔记',
476
535
  }
477
536
 
478
- export function normalizeFields(input) {
479
- const fields = { ...(input || {}) }
537
+ /** 语义上就是列表的字段:允许多种写法,解析后统一成字符串数组。 */
538
+ const LIST_FIELDS = ['标签', '别名']
539
+
540
+ /** `agent, llm` / `agent、llm` / `agent;llm` → 数组;没有分隔符就原样(单标签不该被切)。 */
541
+ function splitListText(text) {
542
+ const raw = String(text).trim()
543
+ if (raw === '') return raw
544
+ const parts = raw.split(/[,,、;;]\s*/).map((part) => part.trim()).filter((part) => part !== '')
545
+ return parts.length > 1 ? parts : raw
546
+ }
547
+
548
+ export function normalizeFields(input) { const fields = { ...(input || {}) }
480
549
  for (const [canonical, aliases] of Object.entries(FIELD_ALIASES)) {
481
550
  if (fields[canonical] !== undefined && fields[canonical] !== '') continue
482
551
  for (const alias of aliases) {
@@ -506,6 +575,15 @@ export function normalizeFields(input) {
506
575
  }
507
576
  if (count !== null) fields['来源数量'] = count
508
577
  }
578
+ // 标签 / 别名:本库约定写成 `[a, b]`,但人手写时经常只写 `a, b`。
579
+ // YAML 会把裸标量整串当**一个**标签,结果「标签里明明有 agent,按标签筛却筛不到这页」——
580
+ // 打分那边 String.includes 能沾上,筛选那边精确比就漏了,两套口径不一致。
581
+ // 所以在解析层就统一成数组:有分隔符才切,单值原样留。
582
+ for (const key of LIST_FIELDS) {
583
+ if (fields[key] === undefined) continue
584
+ if (Array.isArray(fields[key])) continue
585
+ if (typeof fields[key] === 'string') fields[key] = splitListText(fields[key])
586
+ }
509
587
  // 类型值:concept → 概念,好让排序分层与 list 的类型筛认得
510
588
  const type = fields['类型']
511
589
  if (typeof type === 'string') {
@@ -522,10 +600,14 @@ export function normalizeFields(input) {
522
600
  async function readLog(file) {
523
601
  const entries = []
524
602
  let raw = ''
603
+ // present 和「解析出几条」必须分开报:log.md 在、但格式对不上时,
604
+ // 只交出一个空数组,读起来就成了「库里最近没有改动」。
605
+ let present = false
525
606
  try {
526
- raw = await fs.readFile(file, 'utf8')
607
+ raw = stripBom(await fs.readFile(file, 'utf8'))
608
+ present = true
527
609
  } catch {
528
- return entries
610
+ return { entries, present }
529
611
  }
530
612
  let current = null
531
613
  for (const line of raw.split(/\r?\n/)) {
@@ -538,8 +620,11 @@ async function readLog(file) {
538
620
  if (current !== null) current.body.push(line)
539
621
  }
540
622
  if (current !== null) entries.push(current)
541
- return entries.map((entry) => ({ date: entry.date, type: entry.type, title: entry.title,
542
- text: entry.body.join('\n').trim() }))
623
+ return {
624
+ entries: entries.map((entry) => ({ date: entry.date, type: entry.type, title: entry.title,
625
+ text: entry.body.join('\n').trim() })),
626
+ present,
627
+ }
543
628
  }
544
629
 
545
630
  export function asList(value) {