dsh-wiki-notes 1.4.3 → 1.6.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/index.js CHANGED
@@ -20,15 +20,16 @@ import { fileURLToPath } from 'node:url'
20
20
 
21
21
  import { asList, loadCorpus } from './corpus.js'
22
22
  import { createCallLog } from './calls.js'
23
+ import { buildRequiredChecks, createGovernance } from './governance.js'
23
24
  import { mergePromptConfig, mergeTopicConfig, normalizeTopicConfig, readBridgeConfig, readCallsConfig, readTopicConfig, writeCallsConfig, writeTopicConfig } from './config.js'
24
25
  import { MODES, freshnessOf, lint, run } from './engine.js'
25
26
  import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
26
- import { errorEnvelope, runBridge } from './bridge.js'
27
+ import { errorEnvelope, isObserveResult, runBridge } from './bridge.js'
27
28
 
28
29
  export const name = 'wiki-notes'
29
30
 
30
- /** 工具是主职;webServer 只给设置页用,缺了也还能检索(只是设置页读不到状态)。 */
31
- export const inject = ['tools', 'webServer', 'systemPrompt']
31
+ /** 工具是主职。Cordis 是严格注入:apply() 直接读到的每个 ctx.* 服务都必须在这里声明,漏一个就在激活期抛 without inject。 */
32
+ export const inject = ['tools', 'webServer', 'systemPrompt', 'sessions']
32
33
 
33
34
  /** 库扫描结果缓存时长:扫描 70 页约 40ms,但同一回合常连着问好几遍。 */
34
35
  const CACHE_TTL_MS = 30_000
@@ -200,31 +201,60 @@ const PARAMETERS = {
200
201
  required: ['mode'],
201
202
  }
202
203
 
204
+ /**
205
+ * 四个工具各自的硬触发句。抽成常量,测试可以逐条核对:
206
+ * 系统提示只能承载稳定规则,而工具 description 是静态字符串,
207
+ * 「必须 / 不得 / 先…再…」这几条得真的落在模型看得见的描述里。
208
+ */
209
+ const RECALL_TRIGGERS =
210
+ '涉及本地知识、笔记原文或需要引用库内依据时,必须且只调用一次 wiki_recall;不得反复检索,不得在普通快速回答里自动转去 wiki_context / wiki_verify。'
211
+ const CONTEXT_TRIGGERS =
212
+ '用户明确要求查看原文时,必须且仅按需调用一次 wiki_context;明确要求核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突时,必须先调用 wiki_context 再进入深度核验;不得在普通快速回答里自动调用 wiki_context。'
213
+ const VERIFY_TRIGGERS =
214
+ '只有进入深度核验模式,才必须用 wiki_verify 核验候选答案;不得因答案含数字、引文或未填槽位就在快速回答里自动核验,不得绕过 violations_found。'
215
+ const OBSERVE_TRIGGERS =
216
+ '要查核验链有没有收敛、违规有没有被改正时,必须用 wiki_observe 看观察统计;不得用日志缺行反推结论。'
217
+
218
+ /**
219
+ * L1 治理总纲:单独注册进 systemPrompt 的稳定文本。
220
+ * 不含主题词、不含库内容,prompt.enabled / override 都碰不到它;
221
+ * 每个拟议模型步骤重算 text 时拿到的都是同一段常量。
222
+ */
223
+ const GOVERNANCE_TEXT = [
224
+ '本地知识网关的双模式纪律(凡用到本地知识库就适用):',
225
+ '- 默认快速回答:命中库内已知线索、个人记录、长期整理的领域,或要求引用 / 转述 / 核对笔记原文时,先调用一次 wiki_recall 查库再作答;纯通用常识且回答不依赖本地知识库时可跳过检索,检索无结果不代表知识库不存在对应内容。',
226
+ '- 快速回答只调用一次 wiki_recall,据检索结果直接作答;不得自动调用 wiki_context / wiki_verify,不反复检索、不自我验证。',
227
+ '- 快速回答结尾加一句简短可信度提醒;status 非 ok、warnings 非空、零命中或正文被截断时须明说资料不足,不为回答而编造,也不偷偷启动多轮检索。',
228
+ '- 深度核验按需启用:用户只想查看原文时,可仅按需调用一次 wiki_context;明确要求核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突时,才先调用 wiki_context 取结构化证据,再用 wiki_verify 核验候选答案;普通数字题、概念题不升级。',
229
+ '- 深度核验发现违规时定向修正答案,不得绕过 violations_found;最多再核验一次,复核仍有违规即停止并披露,不得无限循环、不能悄悄收尾。',
230
+ '- 多页 / 多来源时须披露证据边界与来源独立性;不承诺核验一般性跨页推导。数字或引文本身不触发强制核验,只有进入深度模式才核验。',
231
+ ].join('\n')
232
+
203
233
  const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任何文件)。
204
234
 
205
235
  何时必须调用(命中任一):
206
- - 问题涉及库内已知线索:页名、别名、标签,或系统提示里注入的主题词;
236
+ - 涉及库内已知线索:页名、别名、标签或注入的主题词;
207
237
  - 问个人记录(「我之前怎么记的」「笔记里写了什么」);
208
- - 涉及你笔记库里长期整理、反复出现的学科或领域(注入的主题词就是从高频标签取的);
238
+ - 涉及长期整理的学科或领域;
209
239
  - 点名具体工具、框架、模型、项目、论文;
210
240
  - 要求引用、转述、核对笔记原文;
211
- - 正要下判断、正要写结论,或要把答案回写成新页之前:先查一遍再动笔,别写完再补。
241
+ - 下判断、写结论或回写新页之前:先查再动笔。
212
242
 
213
- 何时可以不查:纯通用常识,且根据库索引线索能确认没有对应内容(如「水」「三角形」)。
214
- 只是没看到线索,不等于库里没有;拿不准先查,别靠自信跳过。
243
+ 何时可以不查:纯通用常识且不依赖本地知识库时跳过。
244
+ 默认快速回答:只调用一次 wiki_recall,据结果直接答,不自动调 wiki_context / wiki_verify、不反复检索或自我验证;结尾加一句简短可信度提醒,资料不足就明说不足、不编造、不偷偷多轮检索。
245
+ ${RECALL_TRIGGERS}
215
246
 
216
247
  mode 用法:
217
- - search(默认):传 1-4 个关键词,空格分隔做 AND,别传整句问话。
248
+ - search(默认):1-4 个关键词,空格分隔做 AND,别传整句问话。
218
249
  - page / list / overview / lint / draft:取整页 / 列目录 / 看总览 / 查健康 / 拿落盘骨架。
219
-
220
- 机制说明、每个 mode 的返回格式、status 各取值的含义、全部参数 —— 用 mode:"help" 查一次。
221
- 描述只讲「什么时候该调」,讲不全的细节都在 help 里,不确定就查,比猜便宜。
250
+ 机制、返回格式、status 与全部参数 —— 用 mode:"help" 查一次。
222
251
 
223
252
  怎么读结果:
224
- - kind=note 是消化过的笔记(最可信);raw-summary 是原始资料的压缩稿;source 是资料页。
253
+ - kind=note 是消化过的笔记(最可信);raw-summary 是资料压缩稿;source 是资料页。
225
254
  - sources 是「来源数量」,判断证据强度用:1 份和 12 份不是一回事。
226
- - 每条带「更新」时间与距今天数;标了「可能已过时」的页,引用时要说明时间,别当成最新结论。
227
- - 一条都没命中不代表话题不存在,换同义词(中文/英文/缩写)或先用 list 看目录再搜。`
255
+ - 标了「可能已过时」的页,引用时说明时间。
256
+ - 一次 search 给元数据 + 摘要 + 命中小节正文,不是整页全文;status 非 ok、warnings 非空、零命中或正文被截断时须披露资料不足。
257
+ - 一条都没命中不代表话题不存在,换同义词或先用 list 看目录再搜。`
228
258
 
229
259
  /** 知识层的候选目录名:路径指到上一层时,自动下钻到这些名字。 */
230
260
  const DRILL_DIRS = ['知识层-wiki', '知识层', 'wiki', 'Wiki']
@@ -275,6 +305,16 @@ export function apply(ctx, config = {}) {
275
305
  enabled: callsCfg.enabled,
276
306
  })
277
307
 
308
+ /**
309
+ * 治理观察账本。与 calls.jsonl 并列,但只记 Context / Verify 的生命周期事件,
310
+ * 不记回答原文、引文或页面路径。位置同样优先读环境变量(测试与临时排查)。
311
+ */
312
+ const governance = createGovernance({
313
+ file: process.env.DSH_WIKI_GOVERNANCE_LOG || path.join(pluginRoot, 'governance.jsonl'),
314
+ enabled: callsCfg.enabled,
315
+ sessionScope: ctx.sessions?.scopeOf?.(ctx) ?? 'unscoped',
316
+ })
317
+
278
318
  /**
279
319
  * 记一条调用。旁路:记账失败绝不能变成工具失败 ——
280
320
  * 审计的价值远小于「查库还能用」,坏了就让它坏在暗处。
@@ -287,6 +327,25 @@ export function apply(ctx, config = {}) {
287
327
  }
288
328
  }
289
329
 
330
+ /**
331
+ * 清空两个账本与内存里的待核验状态。
332
+ *
333
+ * 顺序是硬的:先 setEnabled(false) 把闸关死,再 clear()。否则清空途中
334
+ * 异步工具调用仍会把旧观察周期的事件写回文件,重开时又浮出来。
335
+ * keepEnabled=true 时清完立刻开闸,governance 会切到新的观察周期,
336
+ * 不补造任何历史。关闭路径则留在 disabled,指标返回「没有数据」。
337
+ */
338
+ function clearObservation(keepEnabled) {
339
+ calls.setEnabled(false)
340
+ governance.setEnabled(false)
341
+ calls.clear()
342
+ governance.clear()
343
+ if (keepEnabled) {
344
+ calls.setEnabled(true)
345
+ governance.setEnabled(true)
346
+ }
347
+ }
348
+
290
349
  let cache = null
291
350
  let cachedAt = 0
292
351
  let inflight = null
@@ -653,24 +712,38 @@ export function apply(ctx, config = {}) {
653
712
  })
654
713
  }
655
714
  // 调用审计:账本只读得回最近的调用,够回答「模型到底查没查、查了什么、查到没有」。
715
+ // governance 是同一份插件侧统计,页面与 wiki_observe 看到的是同一个对象形状。
656
716
  if (route === '/calls' && req.method === 'GET') {
657
717
  const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
658
718
  const limit = Number(parsed.searchParams.get('limit'))
659
- return sendJson(res, 200, calls.read({
719
+ const days = Number(parsed.searchParams.get('days'))
720
+ const audit = calls.read({
660
721
  limit: Number.isFinite(limit) ? limit : undefined,
661
722
  source: parsed.searchParams.get('source') ?? 'all',
662
723
  only: parsed.searchParams.get('only') ?? 'all',
663
- }))
724
+ })
725
+ return sendJson(res, 200, {
726
+ ...audit,
727
+ governance: governance.stats({ days: Number.isFinite(days) && days > 0 ? days : undefined }),
728
+ })
664
729
  }
665
730
  if (route === '/calls/config' && req.method === 'POST') {
666
731
  const body = await readBody(req)
667
732
  if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
668
733
  callsCfg = writeCallsConfig(pluginRoot, { ...callsCfg, ...body }).config
669
- calls.setEnabled(callsCfg.enabled)
670
- return sendJson(res, 200, { enabled: callsCfg.enabled })
734
+ if (callsCfg.enabled !== true) {
735
+ // 关闭 = 破坏性清空:先关闸再清两个账本和 pending,指标随即进入 disabled。
736
+ clearObservation(false)
737
+ return sendJson(res, 200, { enabled: false, cleared: true, governance_state: 'disabled' })
738
+ }
739
+ // 开启 = 新观察周期,不补造关闭期间的历史。
740
+ calls.setEnabled(true)
741
+ governance.setEnabled(true)
742
+ return sendJson(res, 200, { enabled: true })
671
743
  }
672
744
  if (route === '/calls/clear' && req.method === 'POST') {
673
- calls.clear()
745
+ // 手动清空与关闭共用同一实现:保持当前开关状态,清完切到新观察周期。
746
+ clearObservation(callsCfg.enabled !== false)
674
747
  return sendJson(res, 200, { ok: true })
675
748
  }
676
749
  if (route === '/check' && req.method === 'POST') {
@@ -704,6 +777,12 @@ export function apply(ctx, config = {}) {
704
777
  invalidate()
705
778
  // 换了库,旧库的 context_id ↔ observe_id 对就指错地方了,清掉。
706
779
  observeIds.clear()
780
+ // 旧库的待核验状态同样不能留:清账本但保持当前观察开关。
781
+ try {
782
+ clearObservation(callsCfg.enabled !== false)
783
+ } catch (error) {
784
+ ctx.logger?.warn?.(`[wiki-notes] 换库后清治理账本失败:${String(error?.message ?? error)}`)
785
+ }
707
786
  startWatch()
708
787
  return sendJson(res, 200, await buildState())
709
788
  }
@@ -757,6 +836,19 @@ export function apply(ctx, config = {}) {
757
836
  ctx.logger?.warn?.(`[wiki-notes] 主题提示注册失败:${String(error?.message ?? error)}`)
758
837
  }
759
838
 
839
+ // 治理总纲:独立于主题词那一段。关掉主题提示 / 整段覆盖都不影响它,
840
+ // 因为核验纪律是稳定规则,不该跟着用户可编辑的那一行一起消失。
841
+ try {
842
+ ctx.systemPrompt?.context?.({
843
+ name: 'wiki-notes:governance',
844
+ order: 241,
845
+ interpolate: false,
846
+ text: () => GOVERNANCE_TEXT,
847
+ })
848
+ } catch (error) {
849
+ ctx.logger?.warn?.(`[wiki-notes] 治理提示注册失败:${String(error?.message ?? error)}`)
850
+ }
851
+
760
852
  /**
761
853
  * 知识网关的两个工具:把判断交给 Python 管线。
762
854
  *
@@ -778,12 +870,23 @@ function readPluginVersion(pluginRoot) {
778
870
  /** 插件版本:契约里要填,读一次就够。 */
779
871
  const PLUGIN_VERSION = readPluginVersion(pluginRoot)
780
872
 
873
+ /**
874
+ * Bridge 的错误信封比别处多一层:{kind:'error', contract_version, bridge_version, error:{code,message}}。
875
+ * 直接取 value.error.code 会拿到 undefined,模型就只能看到「失败:? — 」,等于没给原因。
876
+ */
877
+ function errorBrief(value) {
878
+ const outer = value?.error ?? {}
879
+ const inner = outer.error ?? outer
880
+ const code = inner.code ?? '?'
881
+ const message = inner.message ?? ''
882
+ return message === '' ? code : `${code} — ${message}`
883
+ }
884
+
781
885
  /** context 结果的一行摘要:先给结论面,细节交给结构化字段。 */
782
886
  function renderContext(args, value) {
783
887
  if (!value || typeof value !== 'object') return '(没有结果)'
784
888
  if (value.kind === 'error') {
785
- const e = value.error ?? {}
786
- return `知识网关调用失败:${e.code ?? '?'} — ${e.message ?? ''}`
889
+ return `知识网关调用失败:${errorBrief(value)}`
787
890
  }
788
891
  const status = value.status ?? {}
789
892
  const lines = [
@@ -820,6 +923,10 @@ function renderContext(args, value) {
820
923
  // observe_id 也露出来:观察日志靠它把 verify 记录挂回这条 context。
821
924
  // 插件会自动转发它,所以模型不用管;但写出来,模型想显式传参时手里有。
822
925
  if (value.observe_id) lines.push(`observe_id:${value.observe_id}`)
926
+ // 必核清单只从这份 Context 的真实证据 / 缺口 / 约束派生:
927
+ // 不写页面路径、标题、引文或具体数值,也不推断事实。错误信封没有清单。
928
+ const checks = buildRequiredChecks(value)
929
+ if (checks.count > 0) lines.push('', ...checks.lines)
823
930
  return lines.join('\n')
824
931
  }
825
932
 
@@ -827,8 +934,7 @@ function renderContext(args, value) {
827
934
  function renderVerify(args, value) {
828
935
  if (!value || typeof value !== 'object') return '(没有结果)'
829
936
  if (value.kind === 'error') {
830
- const e = value.error ?? {}
831
- return `核验没跑成:${e.code ?? '?'} — ${e.message ?? ''}`
937
+ return `核验没跑成:${errorBrief(value)}`
832
938
  }
833
939
  const lines = [`核验状态:${value.status ?? '?'}`]
834
940
  const violations = value.violations ?? []
@@ -843,15 +949,83 @@ function renderVerify(args, value) {
843
949
  if (notices.length > 0) {
844
950
  lines.push(`提示 ${notices.length} 条:${notices.map((n) => n.rule ?? '').join('、')}`)
845
951
  }
952
+ // 违规处置纪律:ok 只说明这次核验没发现越界,不等于逐项必核规则都查过;
953
+ // 发现违规就定向改答案,最多复核一次;复核仍有违规即停止并披露,不再循环。
954
+ if (violations.length > 0 || value.status === 'violations_found') {
955
+ lines.push('', '不得绕过 violations_found:定向修正答案后最多再跑一次 wiki_verify;复核仍有违规即停止并披露,不再循环核验。')
956
+ }
846
957
  return lines.join('\n')
847
958
  }
848
959
 
960
+ /** 治理指标的一行:value 为 null 时绝不伪装成 0%。 */
961
+ function governanceMetricLine(label, metric) {
962
+ if (!metric || typeof metric !== 'object') return ` ${label}:没有数据`
963
+ const ratio = `${metric.numerator ?? '?'} / ${metric.denominator ?? '?'}`
964
+ const rate = typeof metric.value === 'number' && Number.isFinite(metric.value)
965
+ ? `${(metric.value * 100).toFixed(1)}%`
966
+ : '没有数据'
967
+ const samples = `有效样本 ${metric.effective_samples ?? '?'} / 排除 ${metric.excluded_count ?? 0}`
968
+ const reasons = Array.isArray(metric.exclude_reasons) && metric.exclude_reasons.length > 0
969
+ ? `(${metric.exclude_reasons.join('、')})`
970
+ : ''
971
+ return ` ${label}:${ratio}(${rate})· ${samples}${reasons}`
972
+ }
973
+
974
+ /**
975
+ * 治理账本摘要:只渲染 observe 成功返回里附带的 governance 字段。
976
+ * 关闭观察与「零违规」是两种不同状态,不能都显示成 0%;断言数量恒为数据不可用。
977
+ */
978
+ function renderGovernanceLines(g) {
979
+ if (!g || typeof g !== 'object') return []
980
+ const lines = ['', '治理观察(插件侧账本,与 Python 观察日志分开):']
981
+ lines.push(` 观察是否启用:${g.observe_enabled === true ? '已启用' : '未启用'}`)
982
+ if (g.state === 'disabled' || g.state === 'unavailable' || g.observe_enabled === false) {
983
+ lines.push(` 观察窗口:${g.window?.days ?? 7} 天`)
984
+ lines.push(` ${g.message || '没有启用观察,因此没有数据'}`)
985
+ lines.push(' 断言数量:数据不可用')
986
+ lines.push(' 观察到的核验链收敛率:没有启用观察,因此没有数据')
987
+ return lines
988
+ }
989
+ const metrics = g.metrics ?? {}
990
+ lines.push(` 观察窗口:${g.window?.days ?? 7} 天`)
991
+ const trigger = metrics.required_check_verification_trigger_rate
992
+ lines.push(governanceMetricLine('必核项 Context 核验触发率', trigger))
993
+ const group = trigger?.groups?.partial_insufficient
994
+ if (group && typeof group === 'object') {
995
+ lines.push(governanceMetricLine(' └ partial / insufficient 分组', group))
996
+ }
997
+ const discovery = metrics.effective_verify_violation_discovery_rate
998
+ const discoveryLine = discovery?.numerator === 0 && discovery?.denominator > 0
999
+ ? ` 有效 Verify 违规发现率:0 次违规(0.0%)· 有效样本 ${discovery.denominator} / 排除 ${discovery.excluded_count ?? 0}`
1000
+ : governanceMetricLine('有效 Verify 违规发现率', discovery)
1001
+ lines.push(discoveryLine)
1002
+ lines.push(governanceMetricLine('观察覆盖率', metrics.observation_coverage))
1003
+ lines.push(' 断言数量:数据不可用')
1004
+ const conv = g.convergence ?? {}
1005
+ if (typeof conv.converged === 'number' || typeof conv.unresolved === 'number' || typeof conv.not_rechecked === 'number') {
1006
+ lines.push(` 观察到的核验链收敛率:已收敛 ${conv.converged ?? 0} / 仍未收敛 ${conv.unresolved ?? 0} / 未复核 ${conv.not_rechecked ?? 0}`)
1007
+ lines.push(' 收敛只表示观察到的核验链,不等于最终回答已证明可靠。')
1008
+ } else {
1009
+ lines.push(' 观察到的核验链收敛率:没有数据')
1010
+ }
1011
+ const ex = g.excluded ?? {}
1012
+ const reasons = []
1013
+ for (const [key, value] of Object.entries(ex.context_samples ?? {})) {
1014
+ if (typeof value === 'number' && value > 0) reasons.push(`${key}×${value}`)
1015
+ }
1016
+ for (const [key, value] of Object.entries(ex.verify_calls ?? {})) {
1017
+ if (typeof value === 'number' && value > 0) reasons.push(`${key}×${value}`)
1018
+ }
1019
+ if (typeof ex.late_verify === 'number' && ex.late_verify > 0) reasons.push(`late_verify×${ex.late_verify}`)
1020
+ lines.push(` 排除原因:${reasons.length > 0 ? reasons.join('、') : '无'}`)
1021
+ return lines
1022
+ }
1023
+
849
1024
  /** observe 统计摘要:只报分布,不下结论,也不参与回答。 */
850
1025
  function renderObserve(args, value) {
851
1026
  if (!value || typeof value !== 'object') return '(没有结果)'
852
1027
  if (value.kind === 'error') {
853
- const e = value.error ?? {}
854
- return `观察统计没跑成:${e.code ?? '?'} — ${e.message ?? ''}`
1028
+ return `观察统计没跑成:${errorBrief(value)}`
855
1029
  }
856
1030
  const totals = value.totals ?? {}
857
1031
  const window = value.window ?? {}
@@ -882,6 +1056,9 @@ function renderObserve(args, value) {
882
1056
  }
883
1057
  }
884
1058
  if (totals.legacy) lines.push(`另有 ${totals.legacy} 条早期记录(无事件字段,未计入统计)`)
1059
+ if (value.governance && typeof value.governance === 'object') {
1060
+ lines.push(...renderGovernanceLines(value.governance))
1061
+ }
885
1062
  return lines.join('\n')
886
1063
  }
887
1064
 
@@ -931,10 +1108,11 @@ const registerGateway = () => {
931
1108
  name: 'wiki_context',
932
1109
  description:
933
1110
  '向本地知识库要一份「带证据的上下文」:检索、抽证据、标缺口、给回答约束,一次完成。'
934
- + '要引用笔记原文回答、或需要知道「有没有依据 / 依据够不够 / 哪里是缺口」时用它,'
935
- + '而不是自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
1111
+ + '仅在按需深度证据时使用:用户明确要求查看原文 / 核验,或问题涉及高风险、后果重大的重要事实,或库内存在复杂冲突;普通快速回答不要调用,'
1112
+ + '也不要自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
936
1113
  + 'support 说的是「知识够不够」,degraded 说的是「引擎有没有坏」,后者为真时不能把 support 当结论。'
937
- + '返回的 context_id 可交给 wiki_verify 核验后续回答。',
1114
+ + '返回的 context_id 可交给 wiki_verify 核验后续回答。'
1115
+ + CONTEXT_TRIGGERS,
938
1116
  parameters: {
939
1117
  type: 'object',
940
1118
  properties: {
@@ -959,6 +1137,7 @@ const registerGateway = () => {
959
1137
  if (query === '') {
960
1138
  return errorEnvelope('E_QUERY_EMPTY', 'query 不能为空', 'validate')
961
1139
  }
1140
+ const cycle = governance.cycle()
962
1141
  const value = await callBridge('context', {
963
1142
  query: query.slice(0, MAX_QUERY_CHARS * 4),
964
1143
  limit: args?.limit,
@@ -970,6 +1149,13 @@ const registerGateway = () => {
970
1149
  if (value && value.kind === 'context' && value.context_id && value.observe_id) {
971
1150
  rememberObserve(value.context_id, value.observe_id)
972
1151
  }
1152
+ // 只记成功生成的 Context;错误信封不进账本,也不制造 pending。
1153
+ // cycle 是调用前取的观察周期号,关闭后旧周期的迟到结果会被丢弃。
1154
+ try {
1155
+ governance.recordContext(value, cycle)
1156
+ } catch (error) {
1157
+ ctx.logger?.warn?.(`[wiki-notes] 治理账本记 Context 失败:${String(error?.message ?? error)}`)
1158
+ }
973
1159
  return value
974
1160
  },
975
1161
  }))
@@ -978,9 +1164,10 @@ const registerGateway = () => {
978
1164
  name: 'wiki_verify',
979
1165
  description:
980
1166
  '拿一份已有的 wiki_context 结果去核验一段回答,不重新检索。'
981
- + '写完答案后自查(尤其含数字、范围、年份、题量分值这类主张时)用它。'
1167
+ + '仅在深度核验模式下使用:写完候选答案后按需自查,不因答案含数字、范围、年份或引文就在快速回答里自动调用。'
982
1168
  + '返回 status 与 violations:violations 非空说明回答越过了证据允许的边界;'
983
- + 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。',
1169
+ + 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
1170
+ + VERIFY_TRIGGERS,
984
1171
  parameters: {
985
1172
  type: 'object',
986
1173
  properties: {
@@ -1014,19 +1201,30 @@ const registerGateway = () => {
1014
1201
  // 记录和它的 context 拆成两条互不相认的日志。
1015
1202
  const explicit = typeof args?.observe_id === 'string' ? args.observe_id.trim() : ''
1016
1203
  const observeId = explicit || lookupObserve(contextId)
1017
- return callBridge('verify', {
1204
+ const cycle = governance.cycle()
1205
+ const value = await callBridge('verify', {
1018
1206
  context_id: contextId,
1019
1207
  answer,
1020
1208
  ...(observeId ? { observe_id: observeId } : {}),
1021
1209
  })
1210
+ // 事件记账旁路:返回值原样交回调用方,不污染 context/verify 契约。
1211
+ // 不可用 Verify 由账本按调用级原因排除,不改动所属 Context 的处置状态。
1212
+ try {
1213
+ governance.recordVerify(contextId, value, cycle)
1214
+ } catch (error) {
1215
+ ctx.logger?.warn?.(`[wiki-notes] 治理账本记 Verify 失败:${String(error?.message ?? error)}`)
1216
+ }
1217
+ return value
1022
1218
  },
1023
1219
  }))
1024
1220
 
1025
1221
  disposers.push(ctx.tools.register({
1026
1222
  name: 'wiki_observe',
1027
1223
  description:
1028
- '查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
1029
- + 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。',
1224
+ '仅诊断深度核验链的观察统计。'
1225
+ + '查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
1226
+ + 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
1227
+ + OBSERVE_TRIGGERS,
1030
1228
  parameters: {
1031
1229
  type: 'object',
1032
1230
  properties: {
@@ -1040,7 +1238,9 @@ const registerGateway = () => {
1040
1238
  render: (args, value) => [{ type: 'text', text: renderObserve(args, value) }],
1041
1239
  },
1042
1240
  async execute(args) {
1043
- return callBridge('observe', { days: args?.days, limit: args?.limit })
1241
+ const base = await callBridge('observe', { days: args?.days, limit: args?.limit })
1242
+ if (!isObserveResult(base)) return base // error_envelope 不带任何额外键
1243
+ return { ...base, governance: governance.stats({ days: args?.days }) }
1044
1244
  },
1045
1245
  }))
1046
1246
 
@@ -1377,9 +1577,11 @@ function renderSearch(value) {
1377
1577
  // 这里是「这个具体的词在库里一页都没沾到」—— 后者才指着该换哪个词。
1378
1578
  const missed = Array.isArray(value.missedTerms) ? value.missedTerms : []
1379
1579
  if (missed.length > 0) out.push(`没沾到:${missed.join('、')}(这些词在库里一页都没命中,换同义词或干脆去掉)`)
1380
- // 降级说明已由 warnings 承载(degraded 时必有一条);只有老调用方(结果里没有 status 字段)
1381
- // 才需要这里的 note —— 否则同一句话模型会读两遍。
1382
- if (value.note && value.status === undefined) out.push(`⚠️ ${value.note}`)
1580
+ // 降级说明已由 warnings 承载(degraded 时必有一条,用的就是同一段文字);只有 status 仍是 ok
1581
+ // 或老调用方(结果里没有 status 字段)才需要这里的 note —— 否则同一句话模型会读两遍。
1582
+ // ok 也要放行:单字查询「这个字到处都有、排序没有区分度」是 ok 状态下唯一能说这句话的出口,
1583
+ // 而 ok 按契约不带 warnings 键(tests/status.mjs 守着「正常路径零额外 token」)。
1584
+ if (value.note && (value.status === undefined || value.status === 'ok')) out.push(`⚠️ ${value.note}`)
1383
1585
 
1384
1586
  const hits = Array.isArray(value.hits) ? value.hits : []
1385
1587
  if (hits.length === 0) {
@@ -1437,6 +1639,7 @@ function renderPage(value) {
1437
1639
  }
1438
1640
  const page = value.found
1439
1641
  out.push(`【${page.name}】⟨${metaLine(page)}⟩`)
1642
+ if (value.note && value.status === 'ok') out.push(`⚠️ ${value.note}`)
1440
1643
  if (page.summary) out.push(`摘要:${page.summary}`)
1441
1644
  if (Array.isArray(page.aliases) && page.aliases.length > 0) out.push(`别名:${page.aliases.join(' / ')}`)
1442
1645
  if (Array.isArray(page.sections) && page.sections.length > 0) out.push(`小节:${page.sections.join(' / ')}`)
@@ -0,0 +1,191 @@
1
+ /**
2
+ * jsonl-store.js —— 追加写 JSONL 的公共底座。
3
+ *
4
+ * calls.js(调用账本)与 governance.js(观察事件账本)共用同一套
5
+ * 「尾部读 / 追加写 / 轮转」逻辑。抽出来是为了不让两份账本在
6
+ * 「坏行怎么跳、写失败怎么办、什么时候截断」上各走各的。
7
+ *
8
+ * 纪律:写失败一律抛给调用方,由调用方决定 warn 还是静默 ——
9
+ * 账本永远是旁路,不能改变工具返回值。
10
+ */
11
+ import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from 'node:fs'
12
+
13
+ /** 超过这么多行就轮转。 */
14
+ export const MAX_LINES = 5000
15
+ /** 轮转后留最后这么多行。 */
16
+ export const KEEP_LINES = 2500
17
+ /** 尾部读的默认字节数。 */
18
+ export const TAIL_BYTES = 262144
19
+
20
+ /** 读文件尾部;文件不存在或读不了就返回空串,由调用方退回内存缓冲。 */
21
+ export function readTail(file, bytes = TAIL_BYTES) {
22
+ let size = 0
23
+ try {
24
+ size = statSync(file).size
25
+ } catch {
26
+ return ''
27
+ }
28
+ if (size === 0) return ''
29
+ if (size <= bytes) {
30
+ try {
31
+ return readFileSync(file, 'utf8')
32
+ } catch {
33
+ return ''
34
+ }
35
+ }
36
+ let fd = null
37
+ try {
38
+ fd = openSync(file, 'r')
39
+ const length = Math.min(bytes, fstatSync(fd).size)
40
+ const buffer = Buffer.alloc(length)
41
+ readSync(fd, buffer, 0, length, size - length)
42
+ return buffer.toString('utf8')
43
+ } catch {
44
+ return ''
45
+ } finally {
46
+ if (fd !== null) {
47
+ try {
48
+ closeSync(fd)
49
+ } catch {
50
+ /* 关不掉也只是句柄,不影响读到的内容 */
51
+ }
52
+ }
53
+ }
54
+ }
55
+
56
+ /** 逐行 parse;进程写到一半被杀留下的半行,跳过而不是整页白掉。 */
57
+ export function parseLines(text) {
58
+ const rows = []
59
+ for (const line of String(text ?? '').split('\n')) {
60
+ const trimmed = line.trim()
61
+ if (trimmed === '') continue
62
+ try {
63
+ rows.push(JSON.parse(trimmed))
64
+ } catch {
65
+ // 坏行不进统计,也不影响其它行。
66
+ }
67
+ }
68
+ return rows
69
+ }
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
+
85
+ export function countLines(file) {
86
+ try {
87
+ return parseLines(readFileSync(file, 'utf8')).length
88
+ } catch {
89
+ return 0
90
+ }
91
+ }
92
+
93
+ /** 给测试与排查用:账本文件现在有多少行。 */
94
+ export function lineCountOf(file) {
95
+ return existsSync(file) ? countLines(file) : 0
96
+ }
97
+
98
+ /**
99
+ * 建一个 JSONL 账本。同一个文件可以有多个实例(宿主一个、测试一个),
100
+ * 它们各记各的内存缓冲,文件是共享的。
101
+ */
102
+ export function createJsonlStore({ file, maxLines = MAX_LINES, keepLines = KEEP_LINES, tailBytes = TAIL_BYTES, onRotate = null } = {}) {
103
+ let lineCount = null
104
+
105
+ function rotateIfNeeded() {
106
+ if (lineCount === null) lineCount = countPhysicalLines(file)
107
+ // 到 maxLines 就先轮转再写:这样文件永远不超过 maxLines。
108
+ // (原来写的是 `<=`,于是 5000 行上限实际会先长到 5001 行才收。)
109
+ if (lineCount < maxLines) return
110
+ let kept = []
111
+ try {
112
+ kept = parseLines(readFileSync(file, 'utf8')).slice(-keepLines)
113
+ } catch {
114
+ kept = []
115
+ }
116
+ // 先写临时文件再 rename:账本被清空一半比不轮转更糟(并发读的人要么看到旧的、要么看到新的)。
117
+ const tmp = `${file}.tmp`
118
+ writeFileSync(tmp, kept.map((row) => JSON.stringify(row) + '\n').join(''))
119
+ renameSync(tmp, file)
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
+ }
155
+ }
156
+
157
+ function append(entry) {
158
+ if (file === undefined || file === null || file === '') return
159
+ rotateIfNeeded()
160
+ const prefix = endsWithNewline() ? '' : '\n'
161
+ appendFileSync(file, `${prefix}${JSON.stringify(entry)}\n`)
162
+ lineCount = Math.min((lineCount ?? 0) + 1, maxLines)
163
+ }
164
+
165
+ /** 尾部读(调用账本用):只认最后一段。 */
166
+ function readRows() {
167
+ return parseLines(readTail(file, tailBytes))
168
+ }
169
+
170
+ /** 全量读(观察事件账本用):指标要重放全部事实,不能只看尾巴。 */
171
+ function readAllRows() {
172
+ try {
173
+ return parseLines(readFileSync(file, 'utf8'))
174
+ } catch {
175
+ return readRows()
176
+ }
177
+ }
178
+
179
+ function clear() {
180
+ lineCount = 0
181
+ if (file === undefined || file === null || file === '') return
182
+ writeFileSync(file, '')
183
+ }
184
+
185
+ /** 写失败后让行数缓存失效,下次 append 重新数一遍。 */
186
+ function invalidate() {
187
+ lineCount = null
188
+ }
189
+
190
+ return { append, readRows, readAllRows, clear, invalidate, lineCount: () => lineCount }
191
+ }