dsh-wiki-notes 1.4.3 → 1.5.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/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.657.md +657 -0
- package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.661.md +661 -0
- package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.final.md +661 -0
- package/docs/superpowers/specs/2026-11-07-wiki-verification-governance-design.md +661 -0
- package/lib/bridge.js +10 -0
- package/lib/calls.js +13 -96
- package/lib/client.js +114 -1
- package/lib/governance.js +849 -0
- package/lib/index.js +207 -15
- package/lib/jsonl-store.js +137 -0
- package/package.json +3 -3
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
|
-
/**
|
|
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,6 +201,36 @@ const PARAMETERS = {
|
|
|
200
201
|
required: ['mode'],
|
|
201
202
|
}
|
|
202
203
|
|
|
204
|
+
/**
|
|
205
|
+
* 四个工具各自的硬触发句。抽成常量,测试可以逐条核对:
|
|
206
|
+
* 系统提示只能承载稳定规则,而工具 description 是静态字符串,
|
|
207
|
+
* 「必须 / 不得 / 先…再…」这几条得真的落在模型看得见的描述里。
|
|
208
|
+
*/
|
|
209
|
+
const RECALL_TRIGGERS =
|
|
210
|
+
'涉及本地知识、笔记原文或需要引用库内依据时,必须先调用 wiki_recall 检索;不得靠自信跳过。'
|
|
211
|
+
const CONTEXT_TRIGGERS =
|
|
212
|
+
'要引用笔记原文回答、判断依据够不够或找缺口时,必须调用 wiki_context 取带证据的上下文;不得自己连续调 wiki_recall 拼证据。'
|
|
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_context 取一份带证据、缺口与回答约束的上下文,不要自己连续调 wiki_recall 拼证据。',
|
|
227
|
+
'- 候选答案含数字、引文或未填槽位时,输出最终答案之前必须用 wiki_verify 核验;不得绕过 violations_found。',
|
|
228
|
+
'- 流程:Context → 生成候选答案 → Verify → 修正 → 再 Verify → 输出最终答案;超过 4 轮仍有违规必须披露,不能悄悄收尾。',
|
|
229
|
+
'- 多页 / 多来源时须披露证据边界与来源独立性;不承诺核验一般性跨页推导。',
|
|
230
|
+
'- status.support 为 partial / insufficient 时必须走 wiki_verify,不得当成已证实。',
|
|
231
|
+
'- 纯通用常识且回答不依赖本地知识库时,可以跳过检索。凡涉及本地知识、笔记原文或需要引用库内依据的内容,应先检索。检索无结果不代表知识库不存在对应内容。',
|
|
232
|
+
].join('\n')
|
|
233
|
+
|
|
203
234
|
const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任何文件)。
|
|
204
235
|
|
|
205
236
|
何时必须调用(命中任一):
|
|
@@ -210,8 +241,9 @@ const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任
|
|
|
210
241
|
- 要求引用、转述、核对笔记原文;
|
|
211
242
|
- 正要下判断、正要写结论,或要把答案回写成新页之前:先查一遍再动笔,别写完再补。
|
|
212
243
|
|
|
213
|
-
|
|
214
|
-
|
|
244
|
+
何时可以不查:纯通用常识且回答不依赖本地知识库时,可以跳过检索。
|
|
245
|
+
凡涉及本地知识、笔记原文或需要引用库内依据的内容,应先检索;检索无结果不代表知识库不存在对应内容。
|
|
246
|
+
${RECALL_TRIGGERS}
|
|
215
247
|
|
|
216
248
|
mode 用法:
|
|
217
249
|
- search(默认):传 1-4 个关键词,空格分隔做 AND,别传整句问话。
|
|
@@ -275,6 +307,16 @@ export function apply(ctx, config = {}) {
|
|
|
275
307
|
enabled: callsCfg.enabled,
|
|
276
308
|
})
|
|
277
309
|
|
|
310
|
+
/**
|
|
311
|
+
* 治理观察账本。与 calls.jsonl 并列,但只记 Context / Verify 的生命周期事件,
|
|
312
|
+
* 不记回答原文、引文或页面路径。位置同样优先读环境变量(测试与临时排查)。
|
|
313
|
+
*/
|
|
314
|
+
const governance = createGovernance({
|
|
315
|
+
file: process.env.DSH_WIKI_GOVERNANCE_LOG || path.join(pluginRoot, 'governance.jsonl'),
|
|
316
|
+
enabled: callsCfg.enabled,
|
|
317
|
+
sessionScope: ctx.sessions?.scopeOf?.(ctx) ?? 'unscoped',
|
|
318
|
+
})
|
|
319
|
+
|
|
278
320
|
/**
|
|
279
321
|
* 记一条调用。旁路:记账失败绝不能变成工具失败 ——
|
|
280
322
|
* 审计的价值远小于「查库还能用」,坏了就让它坏在暗处。
|
|
@@ -287,6 +329,25 @@ export function apply(ctx, config = {}) {
|
|
|
287
329
|
}
|
|
288
330
|
}
|
|
289
331
|
|
|
332
|
+
/**
|
|
333
|
+
* 清空两个账本与内存里的待核验状态。
|
|
334
|
+
*
|
|
335
|
+
* 顺序是硬的:先 setEnabled(false) 把闸关死,再 clear()。否则清空途中
|
|
336
|
+
* 异步工具调用仍会把旧观察周期的事件写回文件,重开时又浮出来。
|
|
337
|
+
* keepEnabled=true 时清完立刻开闸,governance 会切到新的观察周期,
|
|
338
|
+
* 不补造任何历史。关闭路径则留在 disabled,指标返回「没有数据」。
|
|
339
|
+
*/
|
|
340
|
+
function clearObservation(keepEnabled) {
|
|
341
|
+
calls.setEnabled(false)
|
|
342
|
+
governance.setEnabled(false)
|
|
343
|
+
calls.clear()
|
|
344
|
+
governance.clear()
|
|
345
|
+
if (keepEnabled) {
|
|
346
|
+
calls.setEnabled(true)
|
|
347
|
+
governance.setEnabled(true)
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
290
351
|
let cache = null
|
|
291
352
|
let cachedAt = 0
|
|
292
353
|
let inflight = null
|
|
@@ -653,24 +714,38 @@ export function apply(ctx, config = {}) {
|
|
|
653
714
|
})
|
|
654
715
|
}
|
|
655
716
|
// 调用审计:账本只读得回最近的调用,够回答「模型到底查没查、查了什么、查到没有」。
|
|
717
|
+
// governance 是同一份插件侧统计,页面与 wiki_observe 看到的是同一个对象形状。
|
|
656
718
|
if (route === '/calls' && req.method === 'GET') {
|
|
657
719
|
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
658
720
|
const limit = Number(parsed.searchParams.get('limit'))
|
|
659
|
-
|
|
721
|
+
const days = Number(parsed.searchParams.get('days'))
|
|
722
|
+
const audit = calls.read({
|
|
660
723
|
limit: Number.isFinite(limit) ? limit : undefined,
|
|
661
724
|
source: parsed.searchParams.get('source') ?? 'all',
|
|
662
725
|
only: parsed.searchParams.get('only') ?? 'all',
|
|
663
|
-
})
|
|
726
|
+
})
|
|
727
|
+
return sendJson(res, 200, {
|
|
728
|
+
...audit,
|
|
729
|
+
governance: governance.stats({ days: Number.isFinite(days) && days > 0 ? days : undefined }),
|
|
730
|
+
})
|
|
664
731
|
}
|
|
665
732
|
if (route === '/calls/config' && req.method === 'POST') {
|
|
666
733
|
const body = await readBody(req)
|
|
667
734
|
if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
|
|
668
735
|
callsCfg = writeCallsConfig(pluginRoot, { ...callsCfg, ...body }).config
|
|
669
|
-
|
|
670
|
-
|
|
736
|
+
if (callsCfg.enabled !== true) {
|
|
737
|
+
// 关闭 = 破坏性清空:先关闸再清两个账本和 pending,指标随即进入 disabled。
|
|
738
|
+
clearObservation(false)
|
|
739
|
+
return sendJson(res, 200, { enabled: false, cleared: true, governance_state: 'disabled' })
|
|
740
|
+
}
|
|
741
|
+
// 开启 = 新观察周期,不补造关闭期间的历史。
|
|
742
|
+
calls.setEnabled(true)
|
|
743
|
+
governance.setEnabled(true)
|
|
744
|
+
return sendJson(res, 200, { enabled: true })
|
|
671
745
|
}
|
|
672
746
|
if (route === '/calls/clear' && req.method === 'POST') {
|
|
673
|
-
|
|
747
|
+
// 手动清空与关闭共用同一实现:保持当前开关状态,清完切到新观察周期。
|
|
748
|
+
clearObservation(callsCfg.enabled !== false)
|
|
674
749
|
return sendJson(res, 200, { ok: true })
|
|
675
750
|
}
|
|
676
751
|
if (route === '/check' && req.method === 'POST') {
|
|
@@ -704,6 +779,12 @@ export function apply(ctx, config = {}) {
|
|
|
704
779
|
invalidate()
|
|
705
780
|
// 换了库,旧库的 context_id ↔ observe_id 对就指错地方了,清掉。
|
|
706
781
|
observeIds.clear()
|
|
782
|
+
// 旧库的待核验状态同样不能留:清账本但保持当前观察开关。
|
|
783
|
+
try {
|
|
784
|
+
clearObservation(callsCfg.enabled !== false)
|
|
785
|
+
} catch (error) {
|
|
786
|
+
ctx.logger?.warn?.(`[wiki-notes] 换库后清治理账本失败:${String(error?.message ?? error)}`)
|
|
787
|
+
}
|
|
707
788
|
startWatch()
|
|
708
789
|
return sendJson(res, 200, await buildState())
|
|
709
790
|
}
|
|
@@ -757,6 +838,19 @@ export function apply(ctx, config = {}) {
|
|
|
757
838
|
ctx.logger?.warn?.(`[wiki-notes] 主题提示注册失败:${String(error?.message ?? error)}`)
|
|
758
839
|
}
|
|
759
840
|
|
|
841
|
+
// 治理总纲:独立于主题词那一段。关掉主题提示 / 整段覆盖都不影响它,
|
|
842
|
+
// 因为核验纪律是稳定规则,不该跟着用户可编辑的那一行一起消失。
|
|
843
|
+
try {
|
|
844
|
+
ctx.systemPrompt?.context?.({
|
|
845
|
+
name: 'wiki-notes:governance',
|
|
846
|
+
order: 241,
|
|
847
|
+
interpolate: false,
|
|
848
|
+
text: () => GOVERNANCE_TEXT,
|
|
849
|
+
})
|
|
850
|
+
} catch (error) {
|
|
851
|
+
ctx.logger?.warn?.(`[wiki-notes] 治理提示注册失败:${String(error?.message ?? error)}`)
|
|
852
|
+
}
|
|
853
|
+
|
|
760
854
|
/**
|
|
761
855
|
* 知识网关的两个工具:把判断交给 Python 管线。
|
|
762
856
|
*
|
|
@@ -820,6 +914,10 @@ function renderContext(args, value) {
|
|
|
820
914
|
// observe_id 也露出来:观察日志靠它把 verify 记录挂回这条 context。
|
|
821
915
|
// 插件会自动转发它,所以模型不用管;但写出来,模型想显式传参时手里有。
|
|
822
916
|
if (value.observe_id) lines.push(`observe_id:${value.observe_id}`)
|
|
917
|
+
// 必核清单只从这份 Context 的真实证据 / 缺口 / 约束派生:
|
|
918
|
+
// 不写页面路径、标题、引文或具体数值,也不推断事实。错误信封没有清单。
|
|
919
|
+
const checks = buildRequiredChecks(value)
|
|
920
|
+
if (checks.count > 0) lines.push('', ...checks.lines)
|
|
823
921
|
return lines.join('\n')
|
|
824
922
|
}
|
|
825
923
|
|
|
@@ -843,9 +941,78 @@ function renderVerify(args, value) {
|
|
|
843
941
|
if (notices.length > 0) {
|
|
844
942
|
lines.push(`提示 ${notices.length} 条:${notices.map((n) => n.rule ?? '').join('、')}`)
|
|
845
943
|
}
|
|
944
|
+
// 违规处置纪律:ok 只说明这次核验没发现越界,不等于逐项必核规则都查过;
|
|
945
|
+
// 发现违规就必须改答案再核验一次,不能带着 violations_found 直接收尾。
|
|
946
|
+
if (violations.length > 0 || value.status === 'violations_found') {
|
|
947
|
+
lines.push('', '不得绕过 violations_found:修正答案后再跑一次 wiki_verify,仍有违规须披露。')
|
|
948
|
+
}
|
|
846
949
|
return lines.join('\n')
|
|
847
950
|
}
|
|
848
951
|
|
|
952
|
+
/** 治理指标的一行:value 为 null 时绝不伪装成 0%。 */
|
|
953
|
+
function governanceMetricLine(label, metric) {
|
|
954
|
+
if (!metric || typeof metric !== 'object') return ` ${label}:没有数据`
|
|
955
|
+
const ratio = `${metric.numerator ?? '?'} / ${metric.denominator ?? '?'}`
|
|
956
|
+
const rate = typeof metric.value === 'number' && Number.isFinite(metric.value)
|
|
957
|
+
? `${(metric.value * 100).toFixed(1)}%`
|
|
958
|
+
: '没有数据'
|
|
959
|
+
const samples = `有效样本 ${metric.effective_samples ?? '?'} / 排除 ${metric.excluded_count ?? 0}`
|
|
960
|
+
const reasons = Array.isArray(metric.exclude_reasons) && metric.exclude_reasons.length > 0
|
|
961
|
+
? `(${metric.exclude_reasons.join('、')})`
|
|
962
|
+
: ''
|
|
963
|
+
return ` ${label}:${ratio}(${rate})· ${samples}${reasons}`
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* 治理账本摘要:只渲染 observe 成功返回里附带的 governance 字段。
|
|
968
|
+
* 关闭观察与「零违规」是两种不同状态,不能都显示成 0%;断言数量恒为数据不可用。
|
|
969
|
+
*/
|
|
970
|
+
function renderGovernanceLines(g) {
|
|
971
|
+
if (!g || typeof g !== 'object') return []
|
|
972
|
+
const lines = ['', '治理观察(插件侧账本,与 Python 观察日志分开):']
|
|
973
|
+
lines.push(` 观察是否启用:${g.observe_enabled === true ? '已启用' : '未启用'}`)
|
|
974
|
+
if (g.state === 'disabled' || g.state === 'unavailable' || g.observe_enabled === false) {
|
|
975
|
+
lines.push(` 观察窗口:${g.window?.days ?? 7} 天`)
|
|
976
|
+
lines.push(` ${g.message || '没有启用观察,因此没有数据'}`)
|
|
977
|
+
lines.push(' 断言数量:数据不可用')
|
|
978
|
+
lines.push(' 观察到的核验链收敛率:没有启用观察,因此没有数据')
|
|
979
|
+
return lines
|
|
980
|
+
}
|
|
981
|
+
const metrics = g.metrics ?? {}
|
|
982
|
+
lines.push(` 观察窗口:${g.window?.days ?? 7} 天`)
|
|
983
|
+
const trigger = metrics.required_check_verification_trigger_rate
|
|
984
|
+
lines.push(governanceMetricLine('必核项 Context 核验触发率', trigger))
|
|
985
|
+
const group = trigger?.groups?.partial_insufficient
|
|
986
|
+
if (group && typeof group === 'object') {
|
|
987
|
+
lines.push(governanceMetricLine(' └ partial / insufficient 分组', group))
|
|
988
|
+
}
|
|
989
|
+
const discovery = metrics.effective_verify_violation_discovery_rate
|
|
990
|
+
const discoveryLine = discovery?.numerator === 0 && discovery?.denominator > 0
|
|
991
|
+
? ` 有效 Verify 违规发现率:0 次违规(0.0%)· 有效样本 ${discovery.denominator} / 排除 ${discovery.excluded_count ?? 0}`
|
|
992
|
+
: governanceMetricLine('有效 Verify 违规发现率', discovery)
|
|
993
|
+
lines.push(discoveryLine)
|
|
994
|
+
lines.push(governanceMetricLine('观察覆盖率', metrics.observation_coverage))
|
|
995
|
+
lines.push(' 断言数量:数据不可用')
|
|
996
|
+
const conv = g.convergence ?? {}
|
|
997
|
+
if (typeof conv.converged === 'number' || typeof conv.unresolved === 'number' || typeof conv.not_rechecked === 'number') {
|
|
998
|
+
lines.push(` 观察到的核验链收敛率:已收敛 ${conv.converged ?? 0} / 仍未收敛 ${conv.unresolved ?? 0} / 未复核 ${conv.not_rechecked ?? 0}`)
|
|
999
|
+
lines.push(' 收敛只表示观察到的核验链,不等于最终回答已证明可靠。')
|
|
1000
|
+
} else {
|
|
1001
|
+
lines.push(' 观察到的核验链收敛率:没有数据')
|
|
1002
|
+
}
|
|
1003
|
+
const ex = g.excluded ?? {}
|
|
1004
|
+
const reasons = []
|
|
1005
|
+
for (const [key, value] of Object.entries(ex.context_samples ?? {})) {
|
|
1006
|
+
if (typeof value === 'number' && value > 0) reasons.push(`${key}×${value}`)
|
|
1007
|
+
}
|
|
1008
|
+
for (const [key, value] of Object.entries(ex.verify_calls ?? {})) {
|
|
1009
|
+
if (typeof value === 'number' && value > 0) reasons.push(`${key}×${value}`)
|
|
1010
|
+
}
|
|
1011
|
+
if (typeof ex.late_verify === 'number' && ex.late_verify > 0) reasons.push(`late_verify×${ex.late_verify}`)
|
|
1012
|
+
lines.push(` 排除原因:${reasons.length > 0 ? reasons.join('、') : '无'}`)
|
|
1013
|
+
return lines
|
|
1014
|
+
}
|
|
1015
|
+
|
|
849
1016
|
/** observe 统计摘要:只报分布,不下结论,也不参与回答。 */
|
|
850
1017
|
function renderObserve(args, value) {
|
|
851
1018
|
if (!value || typeof value !== 'object') return '(没有结果)'
|
|
@@ -882,6 +1049,9 @@ function renderObserve(args, value) {
|
|
|
882
1049
|
}
|
|
883
1050
|
}
|
|
884
1051
|
if (totals.legacy) lines.push(`另有 ${totals.legacy} 条早期记录(无事件字段,未计入统计)`)
|
|
1052
|
+
if (value.governance && typeof value.governance === 'object') {
|
|
1053
|
+
lines.push(...renderGovernanceLines(value.governance))
|
|
1054
|
+
}
|
|
885
1055
|
return lines.join('\n')
|
|
886
1056
|
}
|
|
887
1057
|
|
|
@@ -934,7 +1104,8 @@ const registerGateway = () => {
|
|
|
934
1104
|
+ '要引用笔记原文回答、或需要知道「有没有依据 / 依据够不够 / 哪里是缺口」时用它,'
|
|
935
1105
|
+ '而不是自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
|
|
936
1106
|
+ 'support 说的是「知识够不够」,degraded 说的是「引擎有没有坏」,后者为真时不能把 support 当结论。'
|
|
937
|
-
+ '返回的 context_id 可交给 wiki_verify 核验后续回答。'
|
|
1107
|
+
+ '返回的 context_id 可交给 wiki_verify 核验后续回答。'
|
|
1108
|
+
+ CONTEXT_TRIGGERS,
|
|
938
1109
|
parameters: {
|
|
939
1110
|
type: 'object',
|
|
940
1111
|
properties: {
|
|
@@ -959,6 +1130,7 @@ const registerGateway = () => {
|
|
|
959
1130
|
if (query === '') {
|
|
960
1131
|
return errorEnvelope('E_QUERY_EMPTY', 'query 不能为空', 'validate')
|
|
961
1132
|
}
|
|
1133
|
+
const cycle = governance.cycle()
|
|
962
1134
|
const value = await callBridge('context', {
|
|
963
1135
|
query: query.slice(0, MAX_QUERY_CHARS * 4),
|
|
964
1136
|
limit: args?.limit,
|
|
@@ -970,6 +1142,13 @@ const registerGateway = () => {
|
|
|
970
1142
|
if (value && value.kind === 'context' && value.context_id && value.observe_id) {
|
|
971
1143
|
rememberObserve(value.context_id, value.observe_id)
|
|
972
1144
|
}
|
|
1145
|
+
// 只记成功生成的 Context;错误信封不进账本,也不制造 pending。
|
|
1146
|
+
// cycle 是调用前取的观察周期号,关闭后旧周期的迟到结果会被丢弃。
|
|
1147
|
+
try {
|
|
1148
|
+
governance.recordContext(value, cycle)
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
ctx.logger?.warn?.(`[wiki-notes] 治理账本记 Context 失败:${String(error?.message ?? error)}`)
|
|
1151
|
+
}
|
|
973
1152
|
return value
|
|
974
1153
|
},
|
|
975
1154
|
}))
|
|
@@ -980,7 +1159,8 @@ const registerGateway = () => {
|
|
|
980
1159
|
'拿一份已有的 wiki_context 结果去核验一段回答,不重新检索。'
|
|
981
1160
|
+ '写完答案后自查(尤其含数字、范围、年份、题量分值这类主张时)用它。'
|
|
982
1161
|
+ '返回 status 与 violations:violations 非空说明回答越过了证据允许的边界;'
|
|
983
|
-
+ 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
|
|
1162
|
+
+ 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
|
|
1163
|
+
+ VERIFY_TRIGGERS,
|
|
984
1164
|
parameters: {
|
|
985
1165
|
type: 'object',
|
|
986
1166
|
properties: {
|
|
@@ -1014,11 +1194,20 @@ const registerGateway = () => {
|
|
|
1014
1194
|
// 记录和它的 context 拆成两条互不相认的日志。
|
|
1015
1195
|
const explicit = typeof args?.observe_id === 'string' ? args.observe_id.trim() : ''
|
|
1016
1196
|
const observeId = explicit || lookupObserve(contextId)
|
|
1017
|
-
|
|
1197
|
+
const cycle = governance.cycle()
|
|
1198
|
+
const value = await callBridge('verify', {
|
|
1018
1199
|
context_id: contextId,
|
|
1019
1200
|
answer,
|
|
1020
1201
|
...(observeId ? { observe_id: observeId } : {}),
|
|
1021
1202
|
})
|
|
1203
|
+
// 事件记账旁路:返回值原样交回调用方,不污染 context/verify 契约。
|
|
1204
|
+
// 不可用 Verify 由账本按调用级原因排除,不改动所属 Context 的处置状态。
|
|
1205
|
+
try {
|
|
1206
|
+
governance.recordVerify(contextId, value, cycle)
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
ctx.logger?.warn?.(`[wiki-notes] 治理账本记 Verify 失败:${String(error?.message ?? error)}`)
|
|
1209
|
+
}
|
|
1210
|
+
return value
|
|
1022
1211
|
},
|
|
1023
1212
|
}))
|
|
1024
1213
|
|
|
@@ -1026,7 +1215,8 @@ const registerGateway = () => {
|
|
|
1026
1215
|
name: 'wiki_observe',
|
|
1027
1216
|
description:
|
|
1028
1217
|
'查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
|
|
1029
|
-
+ 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
|
|
1218
|
+
+ 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
|
|
1219
|
+
+ OBSERVE_TRIGGERS,
|
|
1030
1220
|
parameters: {
|
|
1031
1221
|
type: 'object',
|
|
1032
1222
|
properties: {
|
|
@@ -1040,7 +1230,9 @@ const registerGateway = () => {
|
|
|
1040
1230
|
render: (args, value) => [{ type: 'text', text: renderObserve(args, value) }],
|
|
1041
1231
|
},
|
|
1042
1232
|
async execute(args) {
|
|
1043
|
-
|
|
1233
|
+
const base = await callBridge('observe', { days: args?.days, limit: args?.limit })
|
|
1234
|
+
if (!isObserveResult(base)) return base // error_envelope 不带任何额外键
|
|
1235
|
+
return { ...base, governance: governance.stats({ days: args?.days }) }
|
|
1044
1236
|
},
|
|
1045
1237
|
}))
|
|
1046
1238
|
|
|
@@ -0,0 +1,137 @@
|
|
|
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, 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
|
+
export function countLines(file) {
|
|
72
|
+
try {
|
|
73
|
+
return parseLines(readFileSync(file, 'utf8')).length
|
|
74
|
+
} catch {
|
|
75
|
+
return 0
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 给测试与排查用:账本文件现在有多少行。 */
|
|
80
|
+
export function lineCountOf(file) {
|
|
81
|
+
return existsSync(file) ? countLines(file) : 0
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 建一个 JSONL 账本。同一个文件可以有多个实例(宿主一个、测试一个),
|
|
86
|
+
* 它们各记各的内存缓冲,文件是共享的。
|
|
87
|
+
*/
|
|
88
|
+
export function createJsonlStore({ file, maxLines = MAX_LINES, keepLines = KEEP_LINES, tailBytes = TAIL_BYTES } = {}) {
|
|
89
|
+
let lineCount = null
|
|
90
|
+
|
|
91
|
+
function rotateIfNeeded() {
|
|
92
|
+
if (lineCount === null) lineCount = countLines(file)
|
|
93
|
+
if (lineCount <= maxLines) return
|
|
94
|
+
let kept = []
|
|
95
|
+
try {
|
|
96
|
+
kept = parseLines(readFileSync(file, 'utf8')).slice(-keepLines)
|
|
97
|
+
} catch {
|
|
98
|
+
kept = []
|
|
99
|
+
}
|
|
100
|
+
writeFileSync(file, kept.map((row) => JSON.stringify(row) + '\n').join(''))
|
|
101
|
+
lineCount = kept.length
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function append(entry) {
|
|
105
|
+
if (file === undefined || file === null || file === '') return
|
|
106
|
+
rotateIfNeeded()
|
|
107
|
+
appendFileSync(file, JSON.stringify(entry) + '\n')
|
|
108
|
+
lineCount = (lineCount ?? 0) + 1
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 尾部读(调用账本用):只认最后一段。 */
|
|
112
|
+
function readRows() {
|
|
113
|
+
return parseLines(readTail(file, tailBytes))
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 全量读(观察事件账本用):指标要重放全部事实,不能只看尾巴。 */
|
|
117
|
+
function readAllRows() {
|
|
118
|
+
try {
|
|
119
|
+
return parseLines(readFileSync(file, 'utf8'))
|
|
120
|
+
} catch {
|
|
121
|
+
return readRows()
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function clear() {
|
|
126
|
+
lineCount = 0
|
|
127
|
+
if (file === undefined || file === null || file === '') return
|
|
128
|
+
writeFileSync(file, '')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 写失败后让行数缓存失效,下次 append 重新数一遍。 */
|
|
132
|
+
function invalidate() {
|
|
133
|
+
lineCount = null
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { append, readRows, readAllRows, clear, invalidate, lineCount: () => lineCount }
|
|
137
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-wiki-notes",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
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": [
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"./package.json": "./package.json"
|
|
25
25
|
},
|
|
26
26
|
"bin": {
|
|
27
|
-
"wiki-notes": "
|
|
27
|
+
"wiki-notes": "bin/cli.mjs"
|
|
28
28
|
},
|
|
29
29
|
"files": [
|
|
30
30
|
"lib",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"node": ">=20.13.0"
|
|
40
40
|
},
|
|
41
41
|
"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/watch.mjs && node tests/client.mjs",
|
|
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
43
|
"cli": "node bin/cli.mjs",
|
|
44
44
|
"probe": "node tools/probe.mjs"
|
|
45
45
|
},
|