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/index.js CHANGED
@@ -15,7 +15,7 @@
15
15
  */
16
16
 
17
17
  import path from 'node:path'
18
- import { mkdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs'
18
+ import { mkdirSync, statSync, watch, writeFileSync } from 'node:fs'
19
19
  import { fileURLToPath } from 'node:url'
20
20
 
21
21
  import { asList, loadCorpus } from './corpus.js'
@@ -23,8 +23,9 @@ import { createCallLog } from './calls.js'
23
23
  import { buildRequiredChecks, createGovernance } from './governance.js'
24
24
  import { mergePromptConfig, mergeTopicConfig, normalizeTopicConfig, readBridgeConfig, readCallsConfig, readTopicConfig, writeCallsConfig, writeTopicConfig } from './config.js'
25
25
  import { MODES, freshnessOf, lint, run } from './engine.js'
26
- import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
26
+ import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, readJsonFile, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
27
27
  import { errorEnvelope, isObserveResult, runBridge } from './bridge.js'
28
+ import { clipChars } from './text.js'
28
29
 
29
30
  export const name = 'wiki-notes'
30
31
 
@@ -207,11 +208,11 @@ const PARAMETERS = {
207
208
  * 「必须 / 不得 / 先…再…」这几条得真的落在模型看得见的描述里。
208
209
  */
209
210
  const RECALL_TRIGGERS =
210
- '涉及本地知识、笔记原文或需要引用库内依据时,必须先调用 wiki_recall 检索;不得靠自信跳过。'
211
+ '涉及本地知识、笔记原文或需要引用库内依据时,必须且只调用一次 wiki_recall;不得反复检索,不得在普通快速回答里自动转去 wiki_context / wiki_verify。'
211
212
  const CONTEXT_TRIGGERS =
212
- '要引用笔记原文回答、判断依据够不够或找缺口时,必须调用 wiki_context 取带证据的上下文;不得自己连续调 wiki_recall 拼证据。'
213
+ '用户明确要求查看原文时,必须且仅按需调用一次 wiki_context;明确要求核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突时,必须先调用 wiki_context 再进入深度核验;不得在普通快速回答里自动调用 wiki_context。'
213
214
  const VERIFY_TRIGGERS =
214
- '候选答案含数字、引文或未填槽位时,输出最终答案之前必须用 wiki_verify 核验;不得绕过 violations_found。'
215
+ '只有进入深度核验模式,才必须用 wiki_verify 核验候选答案;不得因答案含数字、引文或未填槽位就在快速回答里自动核验,不得绕过 violations_found。'
215
216
  const OBSERVE_TRIGGERS =
216
217
  '要查核验链有没有收敛、违规有没有被改正时,必须用 wiki_observe 看观察统计;不得用日志缺行反推结论。'
217
218
 
@@ -221,42 +222,40 @@ const OBSERVE_TRIGGERS =
221
222
  * 每个拟议模型步骤重算 text 时拿到的都是同一段常量。
222
223
  */
223
224
  const GOVERNANCE_TEXT = [
224
- '本地知识网关的核验纪律(凡用到本地知识库就适用):',
225
- '- 命中库内已知线索、个人记录、长期整理的领域,或要求引用 / 转述 / 核对笔记原文时,先调用 wiki_recall 查库再作答。',
226
- '- 需要引用笔记原文、判断依据够不够或找缺口时,先用 wiki_context 取一份带证据、缺口与回答约束的上下文,不要自己连续调 wiki_recall 拼证据。',
227
- '- 候选答案含数字、引文或未填槽位时,输出最终答案之前必须用 wiki_verify 核验;不得绕过 violations_found。',
228
- '- 流程:Context → 生成候选答案 → Verify → 修正 → 再 Verify → 输出最终答案;超过 4 轮仍有违规必须披露,不能悄悄收尾。',
229
- '- 多页 / 多来源时须披露证据边界与来源独立性;不承诺核验一般性跨页推导。',
230
- '- status.support 为 partial / insufficient 时必须走 wiki_verify,不得当成已证实。',
231
- '- 纯通用常识且回答不依赖本地知识库时,可以跳过检索。凡涉及本地知识、笔记原文或需要引用库内依据的内容,应先检索。检索无结果不代表知识库不存在对应内容。',
225
+ '本地知识网关的双模式纪律(凡用到本地知识库就适用):',
226
+ '- 默认快速回答:命中库内已知线索、个人记录、长期整理的领域,或要求引用 / 转述 / 核对笔记原文时,先调用一次 wiki_recall 查库再作答;纯通用常识且回答不依赖本地知识库时可跳过检索,检索无结果不代表知识库不存在对应内容。',
227
+ '- 快速回答只调用一次 wiki_recall,据检索结果直接作答;不得自动调用 wiki_context / wiki_verify,不反复检索、不自我验证。',
228
+ '- 快速回答结尾加一句简短可信度提醒;status 非 ok、warnings 非空、零命中或正文被截断时须明说资料不足,不为回答而编造,也不偷偷启动多轮检索。',
229
+ '- 深度核验按需启用:用户只想查看原文时,可仅按需调用一次 wiki_context;明确要求核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突时,才先调用 wiki_context 取结构化证据,再用 wiki_verify 核验候选答案;普通数字题、概念题不升级。',
230
+ '- 深度核验发现违规时定向修正答案,不得绕过 violations_found;最多再核验一次,复核仍有违规即停止并披露,不得无限循环、不能悄悄收尾。',
231
+ '- 多页 / 多来源时须披露证据边界与来源独立性;不承诺核验一般性跨页推导。数字或引文本身不触发强制核验,只有进入深度模式才核验。',
232
232
  ].join('\n')
233
233
 
234
234
  const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任何文件)。
235
235
 
236
236
  何时必须调用(命中任一):
237
- - 问题涉及库内已知线索:页名、别名、标签,或系统提示里注入的主题词;
237
+ - 涉及库内已知线索:页名、别名、标签或注入的主题词;
238
238
  - 问个人记录(「我之前怎么记的」「笔记里写了什么」);
239
- - 涉及你笔记库里长期整理、反复出现的学科或领域(注入的主题词就是从高频标签取的);
239
+ - 涉及长期整理的学科或领域;
240
240
  - 点名具体工具、框架、模型、项目、论文;
241
241
  - 要求引用、转述、核对笔记原文;
242
- - 正要下判断、正要写结论,或要把答案回写成新页之前:先查一遍再动笔,别写完再补。
242
+ - 下判断、写结论或回写新页之前:先查再动笔。
243
243
 
244
- 何时可以不查:纯通用常识且回答不依赖本地知识库时,可以跳过检索。
245
- 凡涉及本地知识、笔记原文或需要引用库内依据的内容,应先检索;检索无结果不代表知识库不存在对应内容。
244
+ 何时可以不查:纯通用常识且不依赖本地知识库时跳过。
245
+ 默认快速回答:只调用一次 wiki_recall,据结果直接答,不自动调 wiki_context / wiki_verify、不反复检索或自我验证;结尾加一句简短可信度提醒,资料不足就明说不足、不编造、不偷偷多轮检索。
246
246
  ${RECALL_TRIGGERS}
247
247
 
248
248
  mode 用法:
249
- - search(默认):传 1-4 个关键词,空格分隔做 AND,别传整句问话。
249
+ - search(默认):1-4 个关键词,空格分隔做 AND,别传整句问话。
250
250
  - page / list / overview / lint / draft:取整页 / 列目录 / 看总览 / 查健康 / 拿落盘骨架。
251
-
252
- 机制说明、每个 mode 的返回格式、status 各取值的含义、全部参数 —— 用 mode:"help" 查一次。
253
- 描述只讲「什么时候该调」,讲不全的细节都在 help 里,不确定就查,比猜便宜。
251
+ 机制、返回格式、status 与全部参数 —— 用 mode:"help" 查一次。
254
252
 
255
253
  怎么读结果:
256
- - kind=note 是消化过的笔记(最可信);raw-summary 是原始资料的压缩稿;source 是资料页。
254
+ - kind=note 是消化过的笔记(最可信);raw-summary 是资料压缩稿;source 是资料页。
257
255
  - sources 是「来源数量」,判断证据强度用:1 份和 12 份不是一回事。
258
- - 每条带「更新」时间与距今天数;标了「可能已过时」的页,引用时要说明时间,别当成最新结论。
259
- - 一条都没命中不代表话题不存在,换同义词(中文/英文/缩写)或先用 list 看目录再搜。`
256
+ - 标了「可能已过时」的页,引用时说明时间。
257
+ - 一次 search 给元数据 + 摘要 + 命中小节正文,不是整页全文;status 非 ok、warnings 非空、零命中或正文被截断时须披露资料不足。
258
+ - 一条都没命中不代表话题不存在,换同义词或先用 list 看目录再搜。`
260
259
 
261
260
  /** 知识层的候选目录名:路径指到上一层时,自动下钻到这些名字。 */
262
261
  const DRILL_DIRS = ['知识层-wiki', '知识层', 'wiki', 'Wiki']
@@ -536,7 +535,13 @@ export function apply(ctx, config = {}) {
536
535
  async function getCorpus() {
537
536
  // 没配库路径就直接说清楚。别让它扫出一个空库 —— 模型会把「0 页」当成
538
537
  // 「你笔记里没有这条」,然后自信地给你编答案。
539
- if (root === '') throw new Error(NOT_CONFIGURED_HINT)
538
+ // 这条错误带码:HTTP 侧要把它当「请求还缺配置」回 400,
539
+ // 而不是回 500 —— 500 读起来像「插件坏了,重试看看」。
540
+ if (root === '') {
541
+ const error = new Error(NOT_CONFIGURED_HINT)
542
+ error.code = 'NOT_CONFIGURED'
543
+ throw error
544
+ }
540
545
  const now = Date.now()
541
546
  if (cache !== null && now - cachedAt < CACHE_TTL_MS) return cache
542
547
  if (inflight !== null) return inflight
@@ -574,7 +579,7 @@ export function apply(ctx, config = {}) {
574
579
  getCorpus()
575
580
  .then((corpus) => {
576
581
  ctx.logger?.info?.(
577
- `LLM-Wiki 检索就绪:${corpus.stats.pages} 页 / ${corpus.stats.resources} 份资料 / ${corpus.stats.brokenPages} 页存在红链(${root},首次扫描 ${Date.now() - warmStarted} ms)`,
582
+ `LLM-Wiki 检索就绪:${corpus.stats.pages} 页 / 其中资料页 ${corpus.stats.resources} 个 / ${corpus.stats.brokenPages} 页存在红链(${root},首次扫描 ${Date.now() - warmStarted} ms)`,
578
583
  )
579
584
  })
580
585
  .catch((error) => {
@@ -642,6 +647,15 @@ export function apply(ctx, config = {}) {
642
647
  const started = Date.now()
643
648
  const target = String(candidate ?? '').trim() || root
644
649
  if (target === '') return { ok: false, root: '', ms: Date.now() - started, error: NOT_CONFIGURED_HINT }
650
+ // 指到文件而不是目录时,loadCorpus 只会扫出 0 页,于是提示「这个目录里没有任何页面」——
651
+ // 但用户明明给了路径,说错方向会让人以为路径写对了只是库是空的。
652
+ try {
653
+ if (!statSync(target).isDirectory()) {
654
+ return { ok: false, root: target, ms: Date.now() - started, error: '这个路径不是一个目录(指向了文件)。要填的是装着 .md 笔记的那个文件夹' }
655
+ }
656
+ } catch {
657
+ // 不存在 / 没权限:交给 loadCorpus 去报,它的失败明细更具体
658
+ }
645
659
  try {
646
660
  const corpus = await loadCorpus(target)
647
661
  const stats = statsOf(corpus)
@@ -685,7 +699,7 @@ export function apply(ctx, config = {}) {
685
699
  // explain 只在服务端打开;工具 schema 里没有这个参数,模型触发不到。
686
700
  if (route === '/search' && req.method === 'GET') {
687
701
  const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
688
- const query = (parsed.searchParams.get('q') ?? '').trim().slice(0, MAX_QUERY_CHARS)
702
+ const query = clipChars((parsed.searchParams.get('q') ?? '').trim(), MAX_QUERY_CHARS)
689
703
  // 空查询不当作错误让面板弹红字:面板要显示的是「库现在什么样」,那是 /state 的事。
690
704
  if (query === '') return sendJson(res, 400, { error: '缺少 q 参数(要查什么)' })
691
705
  const started = Date.now()
@@ -750,6 +764,9 @@ export function apply(ctx, config = {}) {
750
764
  }
751
765
  if (route === '/check' && req.method === 'POST') {
752
766
  const body = await readBody(req)
767
+ // 坏 JSON 以前会退化成「测试当前库」,于是「我测的是新路径」与
768
+ // 「刚才那次其实是旧路径」看不出区别 —— 宁可 400。
769
+ if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
753
770
  return sendJson(res, 200, await probeRoot(body?.root))
754
771
  }
755
772
  if (route === '/save' && req.method === 'POST') {
@@ -813,6 +830,10 @@ export function apply(ctx, config = {}) {
813
830
  if (error?.code === 'BODY_TOO_LARGE') {
814
831
  return sendJson(res, 413, { error: String(error.message ?? error) })
815
832
  }
833
+ // 「还没配库」是请求缺条件,不是服务端坏了:回 400,别让界面/日志把它读成插件故障
834
+ if (error?.code === 'NOT_CONFIGURED') {
835
+ return sendJson(res, 400, { error: String(error.message ?? error) })
836
+ }
816
837
  return sendJson(res, 500, { error: String(error?.message ?? error) })
817
838
  }
818
839
  },
@@ -862,7 +883,8 @@ export function apply(ctx, config = {}) {
862
883
  /** 读插件自己的版本号,用于契约里的 plugin_version。读不到就写 unknown。 */
863
884
  function readPluginVersion(pluginRoot) {
864
885
  try {
865
- const pkg = JSON.parse(readFileSync(path.join(pluginRoot, 'package.json'), 'utf8'))
886
+ // 走统一的读 JSON 入口:带 BOM 的 package.json 裸 JSON.parse 会失败,版本号静默变 unknown
887
+ const pkg = readJsonFile(path.join(pluginRoot, 'package.json'))
866
888
  return typeof pkg.version === 'string' ? pkg.version : 'unknown'
867
889
  } catch {
868
890
  return 'unknown'
@@ -872,12 +894,23 @@ function readPluginVersion(pluginRoot) {
872
894
  /** 插件版本:契约里要填,读一次就够。 */
873
895
  const PLUGIN_VERSION = readPluginVersion(pluginRoot)
874
896
 
897
+ /**
898
+ * Bridge 的错误信封比别处多一层:{kind:'error', contract_version, bridge_version, error:{code,message}}。
899
+ * 直接取 value.error.code 会拿到 undefined,模型就只能看到「失败:? — 」,等于没给原因。
900
+ */
901
+ function errorBrief(value) {
902
+ const outer = value?.error ?? {}
903
+ const inner = outer.error ?? outer
904
+ const code = inner.code ?? '?'
905
+ const message = inner.message ?? ''
906
+ return message === '' ? code : `${code} — ${message}`
907
+ }
908
+
875
909
  /** context 结果的一行摘要:先给结论面,细节交给结构化字段。 */
876
910
  function renderContext(args, value) {
877
911
  if (!value || typeof value !== 'object') return '(没有结果)'
878
912
  if (value.kind === 'error') {
879
- const e = value.error ?? {}
880
- return `知识网关调用失败:${e.code ?? '?'} — ${e.message ?? ''}`
913
+ return `知识网关调用失败:${errorBrief(value)}`
881
914
  }
882
915
  const status = value.status ?? {}
883
916
  const lines = [
@@ -925,8 +958,7 @@ function renderContext(args, value) {
925
958
  function renderVerify(args, value) {
926
959
  if (!value || typeof value !== 'object') return '(没有结果)'
927
960
  if (value.kind === 'error') {
928
- const e = value.error ?? {}
929
- return `核验没跑成:${e.code ?? '?'} — ${e.message ?? ''}`
961
+ return `核验没跑成:${errorBrief(value)}`
930
962
  }
931
963
  const lines = [`核验状态:${value.status ?? '?'}`]
932
964
  const violations = value.violations ?? []
@@ -942,9 +974,9 @@ function renderVerify(args, value) {
942
974
  lines.push(`提示 ${notices.length} 条:${notices.map((n) => n.rule ?? '').join('、')}`)
943
975
  }
944
976
  // 违规处置纪律:ok 只说明这次核验没发现越界,不等于逐项必核规则都查过;
945
- // 发现违规就必须改答案再核验一次,不能带着 violations_found 直接收尾。
977
+ // 发现违规就定向改答案,最多复核一次;复核仍有违规即停止并披露,不再循环。
946
978
  if (violations.length > 0 || value.status === 'violations_found') {
947
- lines.push('', '不得绕过 violations_found:修正答案后再跑一次 wiki_verify,仍有违规须披露。')
979
+ lines.push('', '不得绕过 violations_found:定向修正答案后最多再跑一次 wiki_verify;复核仍有违规即停止并披露,不再循环核验。')
948
980
  }
949
981
  return lines.join('\n')
950
982
  }
@@ -1017,8 +1049,7 @@ function renderGovernanceLines(g) {
1017
1049
  function renderObserve(args, value) {
1018
1050
  if (!value || typeof value !== 'object') return '(没有结果)'
1019
1051
  if (value.kind === 'error') {
1020
- const e = value.error ?? {}
1021
- return `观察统计没跑成:${e.code ?? '?'} — ${e.message ?? ''}`
1052
+ return `观察统计没跑成:${errorBrief(value)}`
1022
1053
  }
1023
1054
  const totals = value.totals ?? {}
1024
1055
  const window = value.window ?? {}
@@ -1101,8 +1132,8 @@ const registerGateway = () => {
1101
1132
  name: 'wiki_context',
1102
1133
  description:
1103
1134
  '向本地知识库要一份「带证据的上下文」:检索、抽证据、标缺口、给回答约束,一次完成。'
1104
- + '要引用笔记原文回答、或需要知道「有没有依据 / 依据够不够 / 哪里是缺口」时用它,'
1105
- + '而不是自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
1135
+ + '仅在按需深度证据时使用:用户明确要求查看原文 / 核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突;普通快速回答不要调用,'
1136
+ + '也不要自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
1106
1137
  + 'support 说的是「知识够不够」,degraded 说的是「引擎有没有坏」,后者为真时不能把 support 当结论。'
1107
1138
  + '返回的 context_id 可交给 wiki_verify 核验后续回答。'
1108
1139
  + CONTEXT_TRIGGERS,
@@ -1132,7 +1163,7 @@ const registerGateway = () => {
1132
1163
  }
1133
1164
  const cycle = governance.cycle()
1134
1165
  const value = await callBridge('context', {
1135
- query: query.slice(0, MAX_QUERY_CHARS * 4),
1166
+ query: clipChars(query, MAX_QUERY_CHARS * 4),
1136
1167
  limit: args?.limit,
1137
1168
  engine: args?.engine,
1138
1169
  ttl_seconds: args?.ttl_seconds,
@@ -1157,7 +1188,7 @@ const registerGateway = () => {
1157
1188
  name: 'wiki_verify',
1158
1189
  description:
1159
1190
  '拿一份已有的 wiki_context 结果去核验一段回答,不重新检索。'
1160
- + '写完答案后自查(尤其含数字、范围、年份、题量分值这类主张时)用它。'
1191
+ + '仅在深度核验模式下使用:写完候选答案后按需自查,不因答案含数字、范围、年份或引文就在快速回答里自动调用。'
1161
1192
  + '返回 status 与 violations:violations 非空说明回答越过了证据允许的边界;'
1162
1193
  + 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
1163
1194
  + VERIFY_TRIGGERS,
@@ -1214,7 +1245,8 @@ const registerGateway = () => {
1214
1245
  disposers.push(ctx.tools.register({
1215
1246
  name: 'wiki_observe',
1216
1247
  description:
1217
- '查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
1248
+ '仅诊断深度核验链的观察统计。'
1249
+ + '查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
1218
1250
  + 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
1219
1251
  + OBSERVE_TRIGGERS,
1220
1252
  parameters: {
@@ -1365,7 +1397,9 @@ function recordLintRun(corpus, args, pluginRoot) {
1365
1397
 
1366
1398
  let previous = null
1367
1399
  try {
1368
- previous = JSON.parse(readFileSync(file, 'utf8'))
1400
+ // 统一读 JSON 入口:PowerShell 写出的 lint-history.json 可能带 BOM,
1401
+ // 裸 JSON.parse 会抛错 → previous=null → first=true,历史对比被静默重置成「第一次」。
1402
+ previous = readJsonFile(file)
1369
1403
  } catch {
1370
1404
  previous = null // 第一次跑,或文件坏了:都当作没有基线
1371
1405
  }
@@ -1450,7 +1484,9 @@ function renderLint(value) {
1450
1484
  const stats = value.stats || {}
1451
1485
  const counts = value.counts || {}
1452
1486
  const lines = [
1453
- `库健康检查(只读)· ${stats.pages ?? 0} 页 · ${stats.resources ?? 0} 份资料 · 扫描 ${stats.scannedMs ?? 0} ms`,
1487
+ // stats.resources 是「类型: 资料」的页数,不是原始资料份数(份数在每页的「来源数量」里)。
1488
+ // 与 renderOverview 同口径:写成「N 份资料」会让模型把库里的原文数量报小四倍。
1489
+ `库健康检查(只读)· ${stats.pages ?? 0} 页 · 其中资料页 ${stats.resources ?? 0} 个 · 扫描 ${stats.scannedMs ?? 0} ms`,
1454
1490
  ]
1455
1491
 
1456
1492
  const since = value.sinceLast
@@ -1478,6 +1514,8 @@ function renderLint(value) {
1478
1514
  block('🧩 缺 frontmatter 字段', counts.missingFields, value.missingFields, (row) => `${row.name}:缺 ${row.missing.join('、')}`)
1479
1515
  block('🏷 别名冲突 —— 同一别名挂在多页,检索排序会漂', counts.aliasConflicts, value.aliasConflicts, (row) => `${row.alias} → ${row.pages.join(' / ')}`)
1480
1516
  block(`⏳ 久未更新(> ${value.staleDays} 天)`, counts.stale, value.stale, (row) => `${row.name}(${row.updated},${row.days} 天前)`)
1517
+ // 「更新」写成别的格式的页,上面那项算不进去:不单独列出来,读的人会以为全库都新
1518
+ block('❓ 更新日期读不出来 —— 久未更新检查跳过了这些页', counts.staleUnknown, value.staleUnknown, (row) => `${row.name}(写的是「${row.updated}」)`)
1481
1519
  block('🚪 无出链 —— 正文里没有任何 [[双链]]', counts.noLinks, value.noLinks, (name) => name)
1482
1520
  block('📝 草稿状态', counts.drafts, value.drafts, (name) => name)
1483
1521
  block('📇 index.md 登记了、磁盘上没有', counts.indexOnly, value.consistency?.indexOnly, (name) => name)
@@ -1513,6 +1551,10 @@ function renderDraft(value) {
1513
1551
  ? ''
1514
1552
  : `(⚠ 已有同名页 ${value.exists.file},直接写会覆盖它 —— 换个名字,或确认就是要改那一页)`
1515
1553
  out.push(`回写骨架:${value.file}${warn}`)
1554
+ // 文件名建不出来的问题必须在动笔之前说:等正文写完才发现,代价是整篇白写
1555
+ if (value.nameWarning) out.push(`⚠ ${value.nameWarning}`)
1556
+ // 类型没有目录时,frontmatter 的「类型」与落盘目录会自相矛盾(提交时会被 lint 拦下)
1557
+ if (value.typeWarning) out.push(`⚠ ${value.typeWarning}`)
1516
1558
  out.push('')
1517
1559
  out.push(value.frontmatter)
1518
1560
  out.push('')
@@ -1569,9 +1611,11 @@ function renderSearch(value) {
1569
1611
  // 这里是「这个具体的词在库里一页都没沾到」—— 后者才指着该换哪个词。
1570
1612
  const missed = Array.isArray(value.missedTerms) ? value.missedTerms : []
1571
1613
  if (missed.length > 0) out.push(`没沾到:${missed.join('、')}(这些词在库里一页都没命中,换同义词或干脆去掉)`)
1572
- // 降级说明已由 warnings 承载(degraded 时必有一条);只有老调用方(结果里没有 status 字段)
1573
- // 才需要这里的 note —— 否则同一句话模型会读两遍。
1574
- if (value.note && value.status === undefined) out.push(`⚠️ ${value.note}`)
1614
+ // 降级说明已由 warnings 承载(degraded 时必有一条,用的就是同一段文字);只有 status 仍是 ok
1615
+ // 或老调用方(结果里没有 status 字段)才需要这里的 note —— 否则同一句话模型会读两遍。
1616
+ // ok 也要放行:单字查询「这个字到处都有、排序没有区分度」是 ok 状态下唯一能说这句话的出口,
1617
+ // 而 ok 按契约不带 warnings 键(tests/status.mjs 守着「正常路径零额外 token」)。
1618
+ if (value.note && (value.status === undefined || value.status === 'ok')) out.push(`⚠️ ${value.note}`)
1575
1619
 
1576
1620
  const hits = Array.isArray(value.hits) ? value.hits : []
1577
1621
  if (hits.length === 0) {
@@ -1603,6 +1647,10 @@ function renderSearch(value) {
1603
1647
  const body = stripLeadingH1(hit.section.text, hit.name)
1604
1648
  if (hit.section.title) out.push(` §${hit.section.title}`)
1605
1649
  out.push(body)
1650
+ // 片段被砍过就说清楚:不然「表格只到一半」会被当成整节内容引用
1651
+ if (hit.section.truncated === true) {
1652
+ out.push(` (本节正文已截断:全文 ${hit.section.chars ?? '?'} 字符;要整节用 page 取「${hit.name}」)`)
1653
+ }
1606
1654
  }
1607
1655
  if (Array.isArray(hit.brokenLinks) && hit.brokenLinks.length > 0) {
1608
1656
  out.push(` ⚠️ 红链:${hit.brokenLinks.slice(0, 6).join('、')}(库里没有这些页)`)
@@ -1629,6 +1677,7 @@ function renderPage(value) {
1629
1677
  }
1630
1678
  const page = value.found
1631
1679
  out.push(`【${page.name}】⟨${metaLine(page)}⟩`)
1680
+ if (value.note && value.status === 'ok') out.push(`⚠️ ${value.note}`)
1632
1681
  if (page.summary) out.push(`摘要:${page.summary}`)
1633
1682
  if (Array.isArray(page.aliases) && page.aliases.length > 0) out.push(`别名:${page.aliases.join(' / ')}`)
1634
1683
  if (Array.isArray(page.sections) && page.sections.length > 0) out.push(`小节:${page.sections.join(' / ')}`)
@@ -1669,7 +1718,9 @@ function renderOverview(value) {
1669
1718
  if (value.scale) out.push(`规模:${value.scale}`)
1670
1719
  const stats = value.stats ?? {}
1671
1720
  const oversizedCount = Number(stats.oversized ?? 0)
1672
- out.push(`扫描:${stats.pages ?? '?'} 页 / ${stats.resources ?? '?'} 份资料 / ${stats.brokenPages ?? 0} 页有红链(共 ${stats.brokenTotal ?? 0} 处)${oversizedCount > 0 ? ` / ${oversizedCount} 页超大未读正文` : ''}`)
1721
+ // resources 数的是「类型: 资料」的页数,不是原始资料份数(份数在每页的「来源数量」里)。
1722
+ // 写成「N 份资料」会让模型以为库里只有 N 份原文,所以标清楚是页数。
1723
+ out.push(`扫描:${stats.pages ?? '?'} 页 / 其中资料页 ${stats.resources ?? '?'} 个 / ${stats.brokenPages ?? 0} 页有红链(共 ${stats.brokenTotal ?? 0} 处)${oversizedCount > 0 ? ` / ${oversizedCount} 页超大未读正文` : ''}`)
1673
1724
 
1674
1725
  const consistency = value.consistency ?? {}
1675
1726
  if ((consistency.indexOnlyTotal ?? 0) > 0) {
@@ -1682,6 +1733,13 @@ function renderOverview(value) {
1682
1733
  if (dupNames.length > 0) {
1683
1734
  out.push(`⚠️ 重名页(只保留最后一个,其余查不到):${dupNames.slice(0, 6).map((item) => `${item.name}(${item.file})`).join('、')}`)
1684
1735
  }
1736
+ // 链接目录没跟进去:不写明的话,链接里的页看起来就是「库里没有」
1737
+ const linkSkips = Array.isArray(stats.linkSkips) ? stats.linkSkips : []
1738
+ if (Number(stats.linksSkipped ?? 0) > 0) {
1739
+ const shown = linkSkips.slice(0, 5).join('、')
1740
+ const more = Number(stats.linksSkipped) > linkSkips.length ? ` …共 ${stats.linksSkipped} 个` : ''
1741
+ out.push(`⚠️ 跳过了链接目录/文件(junction、symlink 不跟进去扫描):${shown}${more}`)
1742
+ }
1685
1743
 
1686
1744
  if (value.overview !== null && value.overview !== undefined) {
1687
1745
  out.push('')
@@ -1693,7 +1751,7 @@ function renderOverview(value) {
1693
1751
  const log = Array.isArray(value.recentLog) ? value.recentLog : []
1694
1752
  if (log.length > 0) {
1695
1753
  out.push('')
1696
- out.push('最近日志:')
1754
+ out.push('最近日志(由旧到新,最后一条最新):')
1697
1755
  for (const entry of log) out.push(`- [${entry.date}] ${entry.type} | ${entry.title}`)
1698
1756
  }
1699
1757
 
@@ -8,7 +8,7 @@
8
8
  * 纪律:写失败一律抛给调用方,由调用方决定 warn 还是静默 ——
9
9
  * 账本永远是旁路,不能改变工具返回值。
10
10
  */
11
- import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, statSync, writeFileSync } from 'node:fs'
11
+ import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from 'node:fs'
12
12
 
13
13
  /** 超过这么多行就轮转。 */
14
14
  export const MAX_LINES = 5000
@@ -68,6 +68,20 @@ export function parseLines(text) {
68
68
  return rows
69
69
  }
70
70
 
71
+ /**
72
+ * 数「物理行」,不是「能解析的行」。
73
+ *
74
+ * 轮转看的是文件会不会无限长,所以坏行也算一行 —— 否则一份满是坏行的账本
75
+ * 永远数出 0 行,轮转一辈子不触发。
76
+ */
77
+ export function countPhysicalLines(file) {
78
+ try {
79
+ return readFileSync(file, 'utf8').split('\n').filter((line) => line.trim() !== '').length
80
+ } catch {
81
+ return 0
82
+ }
83
+ }
84
+
71
85
  export function countLines(file) {
72
86
  try {
73
87
  return parseLines(readFileSync(file, 'utf8')).length
@@ -85,27 +99,67 @@ export function lineCountOf(file) {
85
99
  * 建一个 JSONL 账本。同一个文件可以有多个实例(宿主一个、测试一个),
86
100
  * 它们各记各的内存缓冲,文件是共享的。
87
101
  */
88
- export function createJsonlStore({ file, maxLines = MAX_LINES, keepLines = KEEP_LINES, tailBytes = TAIL_BYTES } = {}) {
102
+ export function createJsonlStore({ file, maxLines = MAX_LINES, keepLines = KEEP_LINES, tailBytes = TAIL_BYTES, onRotate = null } = {}) {
89
103
  let lineCount = null
90
104
 
91
105
  function rotateIfNeeded() {
92
- if (lineCount === null) lineCount = countLines(file)
93
- if (lineCount <= maxLines) return
106
+ if (lineCount === null) lineCount = countPhysicalLines(file)
107
+ // 到 maxLines 就先轮转再写:这样文件永远不超过 maxLines。
108
+ // (原来写的是 `<=`,于是 5000 行上限实际会先长到 5001 行才收。)
109
+ if (lineCount < maxLines) return
94
110
  let kept = []
95
111
  try {
96
112
  kept = parseLines(readFileSync(file, 'utf8')).slice(-keepLines)
97
113
  } catch {
98
114
  kept = []
99
115
  }
100
- writeFileSync(file, kept.map((row) => JSON.stringify(row) + '\n').join(''))
116
+ // 先写临时文件再 rename:账本被清空一半比不轮转更糟(并发读的人要么看到旧的、要么看到新的)。
117
+ const tmp = `${file}.tmp`
118
+ writeFileSync(tmp, kept.map((row) => JSON.stringify(row) + '\n').join(''))
119
+ renameSync(tmp, file)
101
120
  lineCount = kept.length
121
+ // 轮转把更旧的行从文件里裁掉了。调用方若还把它们留在内存缓冲里,
122
+ // 展示时又会补回列表(窗口越读越长,还都是已经不存在于账本里的行)——
123
+ // 所以这里给一个钩子,让它能同步裁掉自己那份副本。
124
+ if (typeof onRotate === 'function') {
125
+ try {
126
+ onRotate({ kept: kept.length, maxLines, keepLines })
127
+ } catch {
128
+ // 钩子出错不能连带把记账搞坏
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * 文件是不是以换行结尾。
135
+ *
136
+ * 上一次写到一半被 kill 时,最后那行没有换行符;直接 append 会把新记录
137
+ * 粘在坏行后面(`{"broken":{"ok":3}`)——**坏行毁掉的是新写进去的那条**,
138
+ * 而它正是唯一还在内存里的。所以写之前先补一个换行,让坏行自己坏掉。
139
+ */
140
+ function endsWithNewline() {
141
+ try {
142
+ const size = statSync(file).size
143
+ if (size === 0) return true
144
+ const fd = openSync(file, 'r')
145
+ try {
146
+ const one = Buffer.alloc(1)
147
+ readSync(fd, one, 0, 1, size - 1)
148
+ return one[0] === 0x0a
149
+ } finally {
150
+ closeSync(fd)
151
+ }
152
+ } catch {
153
+ return true
154
+ }
102
155
  }
103
156
 
104
157
  function append(entry) {
105
158
  if (file === undefined || file === null || file === '') return
106
159
  rotateIfNeeded()
107
- appendFileSync(file, JSON.stringify(entry) + '\n')
108
- lineCount = (lineCount ?? 0) + 1
160
+ const prefix = endsWithNewline() ? '' : '\n'
161
+ appendFileSync(file, `${prefix}${JSON.stringify(entry)}\n`)
162
+ lineCount = Math.min((lineCount ?? 0) + 1, maxLines)
109
163
  }
110
164
 
111
165
  /** 尾部读(调用账本用):只认最后一段。 */
package/lib/text.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 按「字符」截断,但绝不把表情或扩展区汉字切成半个。
3
+ *
4
+ * 为什么要单独一个函数:JS 的 `String.length` 数的是 UTF-16 码元,
5
+ * 一个 😀 或一个扩展 B 区汉字(如 𠮷)占两个码元。`slice(0, 200)` 正好切在
6
+ * 前半截时,得到的是一个孤立高位代理(`\uD83D`),JSON 序列化后变成 `\ud83d`,
7
+ * 渲染出来就是「�」。截断点是否踩到代理对取决于字数,人工测不出来,
8
+ * 所以所有按长度截断的地方都要走这里。
9
+ */
10
+ export function clipChars(value, max) {
11
+ const text = typeof value === 'string' ? value : String(value ?? '')
12
+ const limit = Number.isFinite(max) ? Math.floor(max) : 0
13
+ // 上限不是正数时返回空串:这个函数只回答「能放下几个字符」,
14
+ // 「不截断」是调用方的事(engine 的 clip 自己判 limit <= 0)。
15
+ if (limit <= 0) return ''
16
+ if (text.length <= limit) return text
17
+ // 切点前一个码元若高位代理,说明这一刀落在字符中间:退一格,宁可少一个字
18
+ const before = text.charCodeAt(limit - 1)
19
+ return text.slice(0, before >= 0xd800 && before <= 0xdbff ? limit - 1 : limit)
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-wiki-notes",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "type": "module",
5
5
  "description": "Read-only knowledge gateway over a local Markdown vault for DeepSeek Harness — recall, evidence pack, answer verification, call audit | 本地 Markdown 笔记库的只读知识网关:检索、证据包、核验、调用审计",
6
6
  "keywords": [
@@ -33,13 +33,14 @@
33
33
  "examples",
34
34
  "cordis.patch.yml",
35
35
  "README.md",
36
- "LICENSE"
36
+ "LICENSE",
37
+ "CHANGELOG.md"
37
38
  ],
38
39
  "engines": {
39
40
  "node": ">=20.13.0"
40
41
  },
41
42
  "scripts": {
42
- "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/explain.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/calls.mjs && node tests/governance.mjs && node tests/inject.mjs && node tests/watch.mjs && node tests/client.mjs",
43
+ "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/explain.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/calls.mjs && node tests/governance.mjs && node tests/inject.mjs && node tests/watch.mjs && node tests/client.mjs && node tests/tier.mjs && node tests/render.mjs && node tests/calls-read.mjs && node tests/store.mjs && node tests/bridge.mjs && node tests/text.mjs && node tests/parse.mjs && node tests/fingerprint.mjs && node tests/bom.mjs",
43
44
  "cli": "node bin/cli.mjs",
44
45
  "probe": "node tools/probe.mjs"
45
46
  },