dsh-wiki-notes 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/config.js ADDED
@@ -0,0 +1,176 @@
1
+ /** config.js —— 库位置解析与保存。插件、CLI、设置页共用同一套规则,避免三处跑出不同结果。 */
2
+
3
+ import { readFileSync, writeFileSync } from 'node:fs'
4
+ import path from 'node:path'
5
+
6
+ /**
7
+ * 内置默认库路径。
8
+ *
9
+ * 故意留空:插件不该猜你把笔记放在哪。留空时插件会明确报「未配置」,
10
+ * 并在设置页(设置 → 知识库)里给一个输入框,而不是默默扫一个不存在的目录
11
+ * 然后让模型以为「库里没有这条」。
12
+ *
13
+ * 想给团队内部分发一份带默认值的版本,把绝对路径填在这里即可;
14
+ * 它仍然是优先级最低的一层,用户配过配置文件就覆盖它。
15
+ */
16
+ export const DEFAULT_WIKI_ROOT = ''
17
+
18
+ /** 配置文件名(放在插件目录旁,不进库,也不进 profile 的 patch)。 */
19
+ export const CONFIG_FILE = 'wiki-notes.config.json'
20
+
21
+ const SOURCE_LABEL = {
22
+ inline: '插件 config.root',
23
+ env: '环境变量 DSH_WIKI_ROOT',
24
+ file: '配置文件 wiki-notes.config.json',
25
+ default: '内置默认',
26
+ unset: '未配置',
27
+ }
28
+
29
+ /**
30
+ * 解析库位置,并说明这个值从哪来 —— 设置页要显示「当前生效的是哪一层」,
31
+ * 否则用户改了配置文件却发现被环境变量盖着,会以为没生效。
32
+ *
33
+ * 优先级:插件 config.root > 环境变量 DSH_WIKI_ROOT > 插件目录旁的配置文件 > 内置默认。
34
+ * 四层都没有 → 返回 root:'' 与 source:'unset',由调用方给出「请先配置」的提示。
35
+ */
36
+ export function resolveWikiRootInfo(pluginRoot, inlineRoot = '') {
37
+ const fromInline = typeof inlineRoot === 'string' ? inlineRoot.trim() : ''
38
+ if (fromInline !== '') return { root: path.resolve(fromInline), source: 'inline', label: SOURCE_LABEL.inline }
39
+
40
+ const fromEnv = typeof process.env.DSH_WIKI_ROOT === 'string' ? process.env.DSH_WIKI_ROOT.trim() : ''
41
+ if (fromEnv !== '') return { root: path.resolve(fromEnv), source: 'env', label: SOURCE_LABEL.env }
42
+
43
+ const saved = readConfigFile(pluginRoot)
44
+ if (saved !== '') return { root: path.resolve(saved), source: 'file', label: SOURCE_LABEL.file }
45
+
46
+ if (DEFAULT_WIKI_ROOT !== '') {
47
+ return { root: path.resolve(DEFAULT_WIKI_ROOT), source: 'default', label: SOURCE_LABEL.default }
48
+ }
49
+
50
+ return { root: '', source: 'unset', label: SOURCE_LABEL.unset }
51
+ }
52
+
53
+ /** 未配置库路径时统一的提示语:工具、CLI、设置页三处共用,避免说法不一致。 */
54
+ export const NOT_CONFIGURED_HINT =
55
+ '还没配置知识库路径。请在「设置 → 知识库」里填一个目录(含 .md 笔记的文件夹),' +
56
+ '或设置环境变量 DSH_WIKI_ROOT、或写插件目录旁的 wiki-notes.config.json。'
57
+
58
+ /** 只要路径时的薄封装(工具与 CLI 用,保持旧的调用形状)。 */
59
+ export function resolveWikiRoot(pluginRoot, inlineRoot = '') {
60
+ return resolveWikiRootInfo(pluginRoot, inlineRoot).root
61
+ }
62
+
63
+ /**
64
+ * 配置文件的实际位置:插件目录旁的那一份。
65
+ *
66
+ * 环境变量 DSH_WIKI_CONFIG 能把它指到别处 —— 测试用它把写入引到临时文件,
67
+ * 免得跑一次 `npm test` 就把你设置页里的库路径和提示词改掉。
68
+ */
69
+ export function configPath(pluginRoot) {
70
+ const override = typeof process.env.DSH_WIKI_CONFIG === 'string' ? process.env.DSH_WIKI_CONFIG.trim() : ''
71
+ if (override !== '') return path.resolve(override)
72
+ return pluginRoot === '' ? '' : path.join(pluginRoot, CONFIG_FILE)
73
+ }
74
+
75
+ /** 读整个配置文件。文件缺失或坏掉都当空对象 —— 不能因为配置问题让工具消失。 */
76
+ function readRecord(pluginRoot) {
77
+ const file = configPath(pluginRoot)
78
+ if (file === '') return {}
79
+ try {
80
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
81
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
82
+ } catch {
83
+ // 没有配置文件或文件坏了,都退回默认值
84
+ }
85
+ return {}
86
+ }
87
+
88
+ /** 写回整个配置文件(保留不认识的字段,别把提示词配置顺手抹掉)。 */
89
+ function writeRecord(pluginRoot, record) {
90
+ const file = configPath(pluginRoot)
91
+ writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`, 'utf8')
92
+ return file
93
+ }
94
+
95
+ /** 读配置文件里的 root;没有文件、文件坏了、字段不对,都返回空串。 */
96
+ export function readConfigFile(pluginRoot) {
97
+ const root = readRecord(pluginRoot).root
98
+ return typeof root === 'string' ? root.trim() : ''
99
+ }
100
+
101
+ /**
102
+ * 写入 root。空串 = 清掉配置、回到默认值。
103
+ * 只写插件目录旁的这一个 JSON,绝不写知识库本体。
104
+ */
105
+ export function writeConfigFile(pluginRoot, root) {
106
+ const value = typeof root === 'string' ? root.trim() : ''
107
+ const record = readRecord(pluginRoot)
108
+ if (value === '') delete record.root
109
+ else record.root = value
110
+ return { file: writeRecord(pluginRoot, record), root: value }
111
+ }
112
+
113
+ /* --------------------- 主题词那一行:阈值与停用词 --------------------- */
114
+
115
+ /**
116
+ * 主题词配置。
117
+ *
118
+ * minCount:只统计出现这么多次以上的标签。=1 就是「不管频次,全都算」。
119
+ * 挡的是「只属于某一篇笔记」的专有名词 —— 人物、朝代、某次会议,
120
+ * 它们对「这个库在研究什么」没有代表性,占掉 5 个名额就是浪费。
121
+ * stopwords:跳过工具泛词(数据 / 工具 / 人物 / 方法…)。这类词哪篇都能打,
122
+ * 一旦挤进前五,模型会觉得「什么话题都沾边」,于是动不动来查库,白烧 token。
123
+ */
124
+ export const DEFAULT_TOPIC_CONFIG = { minCount: 2, stopwords: true }
125
+
126
+ /** 把任意输入规整成主题词配置。不是对象就返回 null;minCount 夹在 1–20。 */
127
+ export function normalizeTopicConfig(raw) {
128
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
129
+ const num = Number(raw.minCount)
130
+ const minCount = Number.isFinite(num) ? Math.max(1, Math.min(Math.trunc(num), 20)) : DEFAULT_TOPIC_CONFIG.minCount
131
+ return { minCount, stopwords: raw.stopwords !== false }
132
+ }
133
+
134
+ /** 读主题词配置。缺字段按默认补齐。 */
135
+ export function readTopicConfig(pluginRoot) {
136
+ return normalizeTopicConfig(readRecord(pluginRoot).topics) ?? { ...DEFAULT_TOPIC_CONFIG }
137
+ }
138
+
139
+ /** 写主题词配置。整块替换 `topics` 字段,其余字段原样保留。 */
140
+ export function writeTopicConfig(pluginRoot, next) {
141
+ const record = readRecord(pluginRoot)
142
+ const clean = normalizeTopicConfig(next) ?? { ...DEFAULT_TOPIC_CONFIG }
143
+ record.topics = clean
144
+ return { file: writeRecord(pluginRoot, record), config: clean }
145
+ }
146
+
147
+ /* --------------------- 提示词那一行:可关、可改、可加 --------------------- */
148
+
149
+ /** 提示词配置:默认开着(自动主题词),可整段换成自己的,也可在末尾追加一句。 */
150
+ export const DEFAULT_PROMPT_CONFIG = { enabled: true, override: '', extra: '' }
151
+
152
+ /** 单段文本上限:注入的东西每回合都在上下文里,不能让它长成一篇小作文。 */
153
+ export const PROMPT_MAX_CHARS = 600
154
+
155
+ /** 把任意输入规整成提示词配置(缺字段按默认补齐,超长截断)。不是对象就返回 null。 */
156
+ export function normalizePromptConfig(raw) {
157
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
158
+ return {
159
+ enabled: raw.enabled !== false,
160
+ override: typeof raw.override === 'string' ? raw.override.slice(0, PROMPT_MAX_CHARS).trim() : '',
161
+ extra: typeof raw.extra === 'string' ? raw.extra.slice(0, PROMPT_MAX_CHARS).trim() : '',
162
+ }
163
+ }
164
+
165
+ /** 读提示词配置。缺字段按默认补齐,超长截断。 */
166
+ export function readPromptConfig(pluginRoot) {
167
+ return normalizePromptConfig(readRecord(pluginRoot).prompt) ?? { ...DEFAULT_PROMPT_CONFIG }
168
+ }
169
+
170
+ /** 写提示词配置。整块替换 `prompt` 字段,其余字段原样保留。 */
171
+ export function writePromptConfig(pluginRoot, next) {
172
+ const record = readRecord(pluginRoot)
173
+ const clean = normalizePromptConfig(next) ?? { ...DEFAULT_PROMPT_CONFIG }
174
+ record.prompt = clean
175
+ return { file: writeRecord(pluginRoot, record), config: clean }
176
+ }
package/lib/corpus.js ADDED
@@ -0,0 +1,471 @@
1
+ /**
2
+ * corpus.js —— 只读地把 LLM-Wiki 知识层读进内存,变成可查询的结构。
3
+ *
4
+ * 设计约束(不要改):
5
+ * 1. 只读。这里没有任何写文件的能力,绝不 import appendFile / writeFile。
6
+ * 2. 零第三方依赖,只用 node: 内置模块。
7
+ * 3. 不碰 原始资料-raw/ 与 Obsidian 目录,只读配置声明的 wiki 层。
8
+ *
9
+ * 解析三样东西:
10
+ * - 每个 .md 页:frontmatter 七个字段 + 按 `##` 切好的小节 + 正文双链
11
+ * - index.md:一行一条目录,附带人工提炼的一句话摘要(比正文片段质量高)
12
+ * - log.md:`## [YYYY-MM-DD] 类型 | 标题` 的时间线
13
+ */
14
+
15
+ import { promises as fs } from 'node:fs'
16
+ import path from 'node:path'
17
+
18
+ /** 单页正文上限:超过就只记元数据,防止某个巨型资料页把内存和上下文吃穿。 */
19
+ const MAX_PAGE_BYTES = 512 * 1024
20
+
21
+ /** 失败明细最多留几条:够定位问题,又不至于让一个坏目录把结果撑大。 */
22
+ const MAX_FAILURE_DETAILS = 20
23
+
24
+ /**
25
+ * 「环境性」文件系统错误:路径不存在、没权限、被占用 —— 这些是这个世界本来的样子,
26
+ * 属于数据缺失,记一条继续扫。不在这张表里的一律当成程序缺陷,必须往上冒。
27
+ *
28
+ * UNKNOWN 只对应一个已确认场景:Windows 上不受信任的 junction / reparse point
29
+ * (ERROR_UNTRUSTED_MOUNT_POINT,0x800701C0),libuv 把它报成 errno -4094。
30
+ * 要给这里加条目,先拿出可复现的来源 —— 别让它慢慢变成「啥都收」的兜底。
31
+ */
32
+ const ENV_ERROR_CODES = new Set([
33
+ 'ENOENT', 'EACCES', 'EPERM', 'ENOTDIR', 'EISDIR', 'EBUSY', 'EINVAL',
34
+ 'EMFILE', 'ENFILE', 'ENAMETOOLONG', 'EIO', 'EPIPE', 'UNKNOWN',
35
+ ])
36
+
37
+ /** 环境故障还是程序故障。纯函数,测试直接喂 Error 对象。 */
38
+ export function classifyFsError(error) {
39
+ const code = error !== null && typeof error === 'object' ? error.code : undefined
40
+ if (typeof code === 'string' && ENV_ERROR_CODES.has(code)) return 'environment'
41
+ return 'program'
42
+ }
43
+
44
+ /**
45
+ * 环境错误 → 一条失败记录(降级为数据缺失);程序错误 → 立刻抛出。
46
+ * 把程序 bug 记成「少读了一页」,会让模型以为覆盖问题已经报备过了 —— 那是这次改造最容易制造的谎言。
47
+ */
48
+ function failureOf(stage, rel, error) {
49
+ if (classifyFsError(error) === 'program') {
50
+ const detail = error !== null && typeof error === 'object' && error.message ? error.message : String(error)
51
+ const wrapped = new Error(`扫描 ${rel} 时发生非预期错误(${stage}):${detail}`)
52
+ wrapped.cause = error
53
+ wrapped.stage = stage
54
+ wrapped.file = rel
55
+ throw wrapped
56
+ }
57
+ const code = error !== null && typeof error === 'object' && typeof error.code === 'string' ? error.code : 'UNKNOWN'
58
+ return { path: rel, stage, code }
59
+ }
60
+
61
+ /** frontmatter 分隔线。允许文件开头有 BOM。 */
62
+ const FM_RE = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?/
63
+
64
+ /** 解析 frontmatter:只在文件开头有 `---` 时才认,避免把正文里的分隔线当元数据。 */
65
+ export function splitFrontmatter(text) {
66
+ if (!text.startsWith('---') && !text.startsWith('\uFEFF---')) {
67
+ return { fields: {}, body: text }
68
+ }
69
+ const match = text.match(FM_RE)
70
+ if (match === null) return { fields: {}, body: text }
71
+ return { fields: parseFields(match[1]), body: text.slice(match[0].length) }
72
+ }
73
+
74
+ /**
75
+ * 解析 key: value 行。
76
+ * 真实库里只有七种值形态:纯文本、数字、`[]`、`[a, b]`、`[{{占位}}]`、日期、带引号。
77
+ * 不引入 YAML 解析器 —— 这个库的 frontmatter 是 Obsidian 属性面板写出来的,形态极窄。
78
+ */
79
+ function parseFields(raw) {
80
+ const fields = {}
81
+ for (const line of raw.split(/\r?\n/)) {
82
+ if (line.trim() === '' || line.trimStart().startsWith('#')) continue
83
+ const idx = line.indexOf(':')
84
+ if (idx <= 0) continue
85
+ const key = line.slice(0, idx).trim()
86
+ const value = line.slice(idx + 1).trim()
87
+ if (key === '') continue
88
+ fields[key] = parseValue(value)
89
+ }
90
+ return fields
91
+ }
92
+
93
+ function parseValue(value) {
94
+ if (value === '') return ''
95
+ if (value.startsWith('[') && value.endsWith(']')) {
96
+ const inner = value.slice(1, -1).trim()
97
+ if (inner === '') return []
98
+ return inner
99
+ .split(/[,,]/)
100
+ .map((item) => stripQuotes(item.trim()))
101
+ .filter((item) => item !== '')
102
+ }
103
+ if (/^-?\d+$/.test(value)) return Number(value)
104
+ return stripQuotes(value)
105
+ }
106
+
107
+ function stripQuotes(value) {
108
+ if (value.length >= 2) {
109
+ const head = value[0]
110
+ const tail = value[value.length - 1]
111
+ if ((head === '"' && tail === '"') || (head === "'" && tail === "'")) {
112
+ return value.slice(1, -1)
113
+ }
114
+ }
115
+ return value
116
+ }
117
+
118
+ /** 把正文按 `## ` 切节;第一个 `##` 之前的部分记为「文首」。 */
119
+ export function splitSections(body) {
120
+ const lines = body.split(/\r?\n/)
121
+ const sections = []
122
+ let current = { title: '', level: 0, lines: [] }
123
+ for (const line of lines) {
124
+ const heading = line.match(/^(#{1,3})\s+(.*)$/)
125
+ if (heading !== null && heading[1].length === 2) {
126
+ if (current.title !== '' || current.lines.some((l) => l.trim() !== '')) sections.push(finish(current))
127
+ current = { title: heading[2].trim(), level: 2, lines: [] }
128
+ continue
129
+ }
130
+ current.lines.push(line)
131
+ }
132
+ if (current.title !== '' || current.lines.some((l) => l.trim() !== '')) sections.push(finish(current))
133
+ return sections
134
+ }
135
+
136
+ function finish(section) {
137
+ return { title: section.title, text: section.lines.join('\n').trim() }
138
+ }
139
+
140
+ /** 正文里的双链:`[[页名]]` 与 `[[页名|显示名]]`,去掉 `#锚点`。 */
141
+ export function extractLinks(text) {
142
+ const names = []
143
+ const re = /\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/g
144
+ let match
145
+ while ((match = re.exec(text)) !== null) {
146
+ const name = match[1].trim()
147
+ if (name !== '') names.push(name)
148
+ }
149
+ return names
150
+ }
151
+
152
+ /**
153
+ * 扫描整个 wiki 层。
154
+ * 返回 { wikiDir, pages, byName, byAlias, indexLines, scaleLine, log, brokenLinks, stats }
155
+ */
156
+ export async function loadCorpus(wikiDir) {
157
+ const startedAt = Date.now()
158
+ const walked = await walkMarkdown(wikiDir)
159
+ const entries = walked.files
160
+ const failures = [...walked.failures]
161
+
162
+ const pages = []
163
+ let skipped = 0
164
+ const indexFile = path.join(wikiDir, 'index.md')
165
+ const logFile = path.join(wikiDir, 'log.md')
166
+
167
+ // 并发读:这里唯一的 IO 等待点是单页 readFile。串行读在大库上会线性变慢
168
+ // (1000 页约 0.4s),分块并发后基本被文件系统缓存吃掉。块大小取 32,
169
+ // 兼顾吞吐与同时打开的句柄数。
170
+ const READ_CHUNK = 32
171
+ const readOne = async (entry) => {
172
+ const base = path.basename(entry.abs)
173
+ // 结构性排除(模板页、目录页)不是损失,单独计数,别混进 unreadable
174
+ if (entry.rel.startsWith('_')) return { skipped: true }
175
+ if (base === 'index.md' || base === 'log.md') return { skipped: true }
176
+ if (entry.size > MAX_PAGE_BYTES) {
177
+ return { page: { name: base.slice(0, -3), file: entry.rel, oversized: true, bytes: entry.size,
178
+ fields: {}, sections: [], body: '', links: [] } }
179
+ }
180
+ let text = ''
181
+ try {
182
+ text = await fs.readFile(entry.abs, 'utf8')
183
+ } catch (error) {
184
+ return { failure: failureOf('read', entry.rel, error) }
185
+ }
186
+ let parsed
187
+ try {
188
+ parsed = splitFrontmatter(text)
189
+ } catch (error) {
190
+ // 解析失败也是「这页没读进来」,但阶段不同:排查方向是文件内容,不是权限
191
+ return { failure: failureOf('parse', entry.rel, error) }
192
+ }
193
+ const { fields: rawFields, body } = parsed
194
+ const fields = normalizeFields(rawFields)
195
+ const name = base.slice(0, -3)
196
+ const page = {
197
+ name,
198
+ file: entry.rel,
199
+ bytes: entry.size,
200
+ mtime: entry.mtime,
201
+ fields,
202
+ // 目录名同时保留(概念/实体/对比/综合/资料),供 list 按类别筛
203
+ dir: path.dirname(entry.rel).split(/[\\/]/).pop(),
204
+ sections: splitSections(body),
205
+ body,
206
+ links: extractLinks(body),
207
+ }
208
+ return { page }
209
+ }
210
+ for (let i = 0; i < entries.length; i += READ_CHUNK) {
211
+ const chunk = await Promise.all(entries.slice(i, i + READ_CHUNK).map(readOne))
212
+ for (const item of chunk) {
213
+ if (item.page !== undefined) pages.push(item.page)
214
+ else if (item.skipped === true) skipped += 1
215
+ else if (item.failure !== undefined) failures.push(item.failure)
216
+ }
217
+ }
218
+
219
+ const byName = new Map()
220
+ const byAlias = new Map()
221
+ const nameCount = new Map()
222
+ for (const page of pages) {
223
+ nameCount.set(page.name, (nameCount.get(page.name) ?? 0) + 1)
224
+ byName.set(page.name, page)
225
+ for (const alias of asList(page.fields['别名'])) {
226
+ const key = alias.toLowerCase()
227
+ if (!byAlias.has(key)) byAlias.set(key, [])
228
+ byAlias.get(key).push(page)
229
+ }
230
+ }
231
+
232
+ // 断链:正文里指向的页不存在。注意别名也算存在。
233
+ // index / log 是结构文件、不参与页面集合,被 [[index]] 链到不算断链。
234
+ const STRUCTURAL_LINKS = new Set(['index', 'log'])
235
+ const brokenLinks = []
236
+ for (const page of pages) {
237
+ const missing = []
238
+ for (const link of page.links) {
239
+ if (link === page.name) continue
240
+ if (STRUCTURAL_LINKS.has(link.toLowerCase())) continue
241
+ if (byName.has(link)) continue
242
+ if (byAlias.has(link.toLowerCase())) continue
243
+ if (!missing.includes(link)) missing.push(link)
244
+ }
245
+ if (missing.length > 0) brokenLinks.push({ name: page.name, missing })
246
+ }
247
+
248
+ const indexData = await readIndex(indexFile)
249
+ const log = await readLog(logFile)
250
+
251
+ // 覆盖口径:discovered = pages + unreadable + skipped(文件级恒等式,tests/status.mjs 里断言)
252
+ const unreadable = failures.filter((item) => item.stage === 'read' || item.stage === 'parse').length
253
+ const oversizedCount = pages.filter((page) => page.oversized === true).length
254
+
255
+ const stats = {
256
+ pages: pages.length,
257
+ resources: pages.filter((p) => p.fields['类型'] === '资料').length,
258
+ brokenPages: brokenLinks.length,
259
+ brokenTotal: brokenLinks.reduce((sum, item) => sum + item.missing.length, 0),
260
+ // 不同目录下的同名页:byName 只会留最后一个,等于静默丢页。
261
+ // 当前这套库没有重名,但别人照抄结构时很容易撞上,统计出来让 overview 提醒一句。
262
+ duplicateNames: pages
263
+ .filter((page) => nameCount.get(page.name) > 1)
264
+ .map((page) => ({ name: page.name, file: page.file })),
265
+ // 扫描覆盖:这四项让「看到多少」可核算,而不是只报一个 pages
266
+ discovered: entries.length,
267
+ skipped,
268
+ unreadable,
269
+ oversized: oversizedCount,
270
+ // 目录数与文件数分开记:walkFailures 是目录数,不参与上面的文件级等式
271
+ walkFailures: walked.walkFailures,
272
+ statFailures: walked.statFailures,
273
+ failuresTotal: failures.length + walked.statFailures,
274
+ failures: failures.slice(0, MAX_FAILURE_DETAILS),
275
+ scannedMs: Date.now() - startedAt,
276
+ wikiDir,
277
+ }
278
+
279
+ return { wikiDir, pages, byName, byAlias, indexLines: indexData.lines, scaleLine: indexData.scale, log, brokenLinks, stats }
280
+ }
281
+
282
+ async function walkMarkdown(root) {
283
+ const files = []
284
+ const failures = []
285
+ let walkFailures = 0
286
+ let statFailures = 0
287
+
288
+ async function walk(dir, relPrefix) {
289
+ let dirents = []
290
+ try {
291
+ dirents = await fs.readdir(dir, { withFileTypes: true })
292
+ } catch (error) {
293
+ // 目录列不出来 = 整棵子树的页都不在结果里。以前这里直接 return,
294
+ // 于是「库少了 30 页」和「库本来只有 60 页」看起来一模一样。
295
+ failures.push(failureOf('walk', relPrefix === '' ? '.' : relPrefix, error))
296
+ walkFailures += 1
297
+ return
298
+ }
299
+ for (const dirent of dirents) {
300
+ const abs = path.join(dir, dirent.name)
301
+ const rel = relPrefix === '' ? dirent.name : `${relPrefix}/${dirent.name}`
302
+ if (dirent.isDirectory()) {
303
+ if (dirent.name.startsWith('.')) continue
304
+ await walk(abs, rel)
305
+ continue
306
+ }
307
+ if (!dirent.isFile()) continue
308
+ if (!dirent.name.toLowerCase().endsWith('.md')) continue
309
+ let size = 0
310
+ let mtime = 0
311
+ try {
312
+ const stat = await fs.stat(abs)
313
+ size = stat.size
314
+ mtime = stat.mtimeMs
315
+ } catch (error) {
316
+ failures.push(failureOf('stat', rel, error))
317
+ statFailures += 1
318
+ continue
319
+ }
320
+ files.push({ abs, rel, size, mtime })
321
+ }
322
+ }
323
+
324
+ await walk(root, '')
325
+ files.sort((a, b) => a.rel.localeCompare(b.rel, 'zh'))
326
+ return { files, failures, walkFailures, statFailures }
327
+ }
328
+
329
+ /**
330
+ * 解析 index.md。
331
+ * 行格式:`- [[页名]] — 一句话摘要(N 份资料,更新于 YYYY-MM-DD)`
332
+ * 这句话是人工提炼的,检索时它比正文片段更值钱,所以单独存一份映射。
333
+ */
334
+ async function readIndex(file) {
335
+ const lines = []
336
+ let scale = ''
337
+ let raw = ''
338
+ try {
339
+ raw = await fs.readFile(file, 'utf8')
340
+ } catch {
341
+ return { lines, scale }
342
+ }
343
+ for (const line of raw.split(/\r?\n/)) {
344
+ if (scale === '') {
345
+ const scaleMatch = line.match(/\*\*当前规模\*\*[::]\s*(.+)$/)
346
+ if (scaleMatch !== null) scale = scaleMatch[1].trim()
347
+ }
348
+ const bullet = line.match(/^\s*[-*]\s+\[\[([^\]|#]+)(?:[^\]]*)\]\](.*)$/)
349
+ if (bullet === null) continue
350
+ const name = bullet[1].trim()
351
+ let rest = (bullet[2] || '').trim()
352
+ let summary = rest
353
+ let sources = null
354
+ let updated = ''
355
+ // 真实库里括号有三种写法:`(2 份资料,2026-11-01)`、`(2 份,2026-11-01)`、
356
+ // `(2 份资料,更新于 2026-11-01)`。都当成尾部的元数据剥掉,剩下的才是摘要。
357
+ const meta = rest.match(/[((]\s*(\d+)\s*(?:份|篇|条|个)\s*(?:资料)?\s*[,,]\s*(?:更新于\s*)?(\d{4}-\d{2}-\d{2})\s*[))]\s*$/)
358
+ // 英文模板写成「(2026-11-02 / 1)」,日期在前、数量在后
359
+ const metaAlt = rest.match(/[((]\s*(\d{4}-\d{2}-\d{2})\s*\/\s*(\d+)\s*[))]\s*$/)
360
+ if (meta !== null) {
361
+ sources = Number(meta[1])
362
+ updated = meta[2]
363
+ summary = rest.slice(0, meta.index).trim()
364
+ } else if (metaAlt !== null) {
365
+ updated = metaAlt[1]
366
+ sources = Number(metaAlt[2])
367
+ summary = rest.slice(0, metaAlt.index).trim()
368
+ }
369
+ summary = summary.replace(/^[—–\-::]\s*/, '').trim()
370
+ lines.push({ name, summary, sources, updated, raw: line.trim() })
371
+ }
372
+ return { lines, scale }
373
+ }
374
+
375
+ /**
376
+ * 字段归一化:英文 frontmatter(title/type/tags/sources/created/updated)与
377
+ * 中文七字段是同一套东西的两种写法。库可能来自不同模板,这里统一译成中文键,
378
+ * 下游(engine / lint / topics)就只用认一套。
379
+ */
380
+ const FIELD_ALIASES = {
381
+ 标题: ['title'],
382
+ 类型: ['type', 'kind', 'category'],
383
+ 标签: ['tags', 'tag', 'keywords'],
384
+ 别名: ['aliases', 'alias', 'alt'],
385
+ 状态: ['status', 'state'],
386
+ 创建: ['created', 'createdAt', 'created_at', 'date'],
387
+ 更新: ['updated', 'updatedAt', 'updated_at', 'modified', 'lastUpdated', 'last_updated'],
388
+ }
389
+ const SOURCE_COUNT_KEYS = ['来源数量', 'sourceCount', 'source_count', 'sourcesCount', 'sources_count']
390
+ const SOURCE_LIST_KEYS = ['sources', 'source', '来源']
391
+ const TYPE_ALIASES = {
392
+ concept: '概念', concepts: '概念',
393
+ entity: '实体', entities: '实体',
394
+ comparison: '对比', comparisons: '对比', compare: '对比',
395
+ synthesis: '综合', syntheses: '综合',
396
+ source: '资料', sources: '资料', material: '资料', materials: '资料', raw: '资料',
397
+ overview: '总览', note: '笔记', notes: '笔记',
398
+ }
399
+
400
+ export function normalizeFields(input) {
401
+ const fields = { ...(input || {}) }
402
+ for (const [canonical, aliases] of Object.entries(FIELD_ALIASES)) {
403
+ if (fields[canonical] !== undefined && fields[canonical] !== '') continue
404
+ for (const alias of aliases) {
405
+ const value = fields[alias]
406
+ if (value !== undefined && value !== '' && !(Array.isArray(value) && value.length === 0)) {
407
+ fields[canonical] = value
408
+ break
409
+ }
410
+ }
411
+ }
412
+ // 来源数量:没有就直接数 sources 列表
413
+ if (fields['来源数量'] === undefined || fields['来源数量'] === '') {
414
+ let count = null
415
+ for (const key of SOURCE_COUNT_KEYS) {
416
+ const value = fields[key]
417
+ if (value !== undefined && value !== '') {
418
+ const num = Number(value)
419
+ if (Number.isFinite(num)) count = num
420
+ break
421
+ }
422
+ }
423
+ if (count === null) {
424
+ for (const key of SOURCE_LIST_KEYS) {
425
+ const list = asList(fields[key])
426
+ if (list.length > 0) { count = list.length; break }
427
+ }
428
+ }
429
+ if (count !== null) fields['来源数量'] = count
430
+ }
431
+ // 类型值:concept → 概念,好让排序分层与 list 的类型筛认得
432
+ const type = fields['类型']
433
+ if (typeof type === 'string') {
434
+ const mapped = TYPE_ALIASES[type.trim().toLowerCase()]
435
+ if (mapped !== undefined) fields['类型'] = mapped
436
+ } else if (Array.isArray(type) && typeof type[0] === 'string') {
437
+ const mapped = TYPE_ALIASES[type[0].trim().toLowerCase()]
438
+ if (mapped !== undefined) fields['类型'] = mapped
439
+ }
440
+ return fields
441
+ }
442
+
443
+ /** 解析 log.md:`## [YYYY-MM-DD] 类型 | 标题`,只取标题行,不碰正文。 */
444
+ async function readLog(file) {
445
+ const entries = []
446
+ let raw = ''
447
+ try {
448
+ raw = await fs.readFile(file, 'utf8')
449
+ } catch {
450
+ return entries
451
+ }
452
+ let current = null
453
+ for (const line of raw.split(/\r?\n/)) {
454
+ const head = line.match(/^##\s+\[(\d{4}-\d{2}-\d{2})\]\s*([^|]*)\|(.*)$/)
455
+ if (head !== null) {
456
+ if (current !== null) entries.push(current)
457
+ current = { date: head[1], type: head[2].trim(), title: head[3].trim(), body: [] }
458
+ continue
459
+ }
460
+ if (current !== null) current.body.push(line)
461
+ }
462
+ if (current !== null) entries.push(current)
463
+ return entries.map((entry) => ({ date: entry.date, type: entry.type, title: entry.title,
464
+ text: entry.body.join('\n').trim() }))
465
+ }
466
+
467
+ export function asList(value) {
468
+ if (Array.isArray(value)) return value.filter((item) => typeof item === 'string')
469
+ if (typeof value === 'string' && value.trim() !== '') return [value.trim()]
470
+ return []
471
+ }