dsh-wiki-notes 1.4.2 → 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/README.md +43 -0
- package/docs/README.md +1 -1
- package/docs/superpowers/plans/2026-11-05-wiki-call-audit.md +553 -0
- package/docs/superpowers/specs/2026-11-05-wiki-call-audit-design.md +164 -0
- 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/docs//345/245/221/347/272/246-stage0/samples/_verify_probe.json +1 -1
- package/docs//345/245/221/347/272/246-stage0/samples/{context.cq-shenlun.json → context.sample-cache.json} +80 -80
- package/docs//345/245/221/347/272/246-stage0/samples/verify.fabricated-quote.json +3 -3
- package/docs//345/245/221/347/272/246-stage0/samples/verify.scope-mismatch.json +3 -3
- package/docs//345/245/221/347/272/246-stage0/samples/verify.wrong-five.json +9 -9
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2650-/345/256/241/350/256/241/344/270/216/345/245/221/347/272/246.md +10 -10
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2651-/346/225/260/345/200/274/345/210/244/346/215/256/344/270/216/345/274/225/346/223/216/347/212/266/346/200/201.md +9 -9
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2652-/345/277/253/347/205/247/344/270/216TTL.md +3 -3
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2653-/346/224/257/346/214/201/345/216/237/345/233/240.md +3 -3
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2654-/346/217/222/344/273/266/346/216/245/345/205/245.md +1 -1
- package/docs//345/245/221/347/272/246-stage0//351/230/266/346/256/2655-/350/247/202/345/257/237/351/227/255/347/216/257/344/270/216/345/256/236/346/210/230/351/252/214/346/224/266.md +10 -10
- package/lib/bridge.js +10 -0
- package/lib/calls.js +167 -0
- package/lib/client.js +463 -11
- package/lib/config.js +33 -0
- package/lib/governance.js +849 -0
- package/lib/index.js +298 -14
- package/lib/jsonl-store.js +137 -0
- package/package.json +7 -5
package/lib/index.js
CHANGED
|
@@ -19,15 +19,17 @@ import { mkdirSync, readFileSync, statSync, watch, writeFileSync } from 'node:fs
|
|
|
19
19
|
import { fileURLToPath } from 'node:url'
|
|
20
20
|
|
|
21
21
|
import { asList, loadCorpus } from './corpus.js'
|
|
22
|
-
import {
|
|
22
|
+
import { createCallLog } from './calls.js'
|
|
23
|
+
import { buildRequiredChecks, createGovernance } from './governance.js'
|
|
24
|
+
import { mergePromptConfig, mergeTopicConfig, normalizeTopicConfig, readBridgeConfig, readCallsConfig, readTopicConfig, writeCallsConfig, writeTopicConfig } from './config.js'
|
|
23
25
|
import { MODES, freshnessOf, lint, run } from './engine.js'
|
|
24
26
|
import { configPath, DEFAULT_WIKI_ROOT, NOT_CONFIGURED_HINT, readConfigFile, normalizePromptConfig, readPromptConfig, resolveWikiRootInfo, writeConfigFile, writePromptConfig } from './config.js'
|
|
25
|
-
import { errorEnvelope, runBridge } from './bridge.js'
|
|
27
|
+
import { errorEnvelope, isObserveResult, runBridge } from './bridge.js'
|
|
26
28
|
|
|
27
29
|
export const name = 'wiki-notes'
|
|
28
30
|
|
|
29
|
-
/**
|
|
30
|
-
export const inject = ['tools', 'webServer', 'systemPrompt']
|
|
31
|
+
/** 工具是主职。Cordis 是严格注入:apply() 直接读到的每个 ctx.* 服务都必须在这里声明,漏一个就在激活期抛 without inject。 */
|
|
32
|
+
export const inject = ['tools', 'webServer', 'systemPrompt', 'sessions']
|
|
31
33
|
|
|
32
34
|
/** 库扫描结果缓存时长:扫描 70 页约 40ms,但同一回合常连着问好几遍。 */
|
|
33
35
|
const CACHE_TTL_MS = 30_000
|
|
@@ -199,6 +201,36 @@ const PARAMETERS = {
|
|
|
199
201
|
required: ['mode'],
|
|
200
202
|
}
|
|
201
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
|
+
|
|
202
234
|
const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任何文件)。
|
|
203
235
|
|
|
204
236
|
何时必须调用(命中任一):
|
|
@@ -209,8 +241,9 @@ const DESCRIPTION = `本地 LLM-Wiki 知识库检索(只读,不会改动任
|
|
|
209
241
|
- 要求引用、转述、核对笔记原文;
|
|
210
242
|
- 正要下判断、正要写结论,或要把答案回写成新页之前:先查一遍再动笔,别写完再补。
|
|
211
243
|
|
|
212
|
-
|
|
213
|
-
|
|
244
|
+
何时可以不查:纯通用常识且回答不依赖本地知识库时,可以跳过检索。
|
|
245
|
+
凡涉及本地知识、笔记原文或需要引用库内依据的内容,应先检索;检索无结果不代表知识库不存在对应内容。
|
|
246
|
+
${RECALL_TRIGGERS}
|
|
214
247
|
|
|
215
248
|
mode 用法:
|
|
216
249
|
- search(默认):传 1-4 个关键词,空格分隔做 AND,别传整句问话。
|
|
@@ -262,6 +295,59 @@ export function apply(ctx, config = {}) {
|
|
|
262
295
|
let promptCfg = normalizePromptConfig(config?.prompt) ?? readPromptConfig(pluginRoot)
|
|
263
296
|
let topicCfg = normalizeTopicConfig(config?.topics) ?? readTopicConfig(pluginRoot)
|
|
264
297
|
|
|
298
|
+
/**
|
|
299
|
+
* 调用账本。
|
|
300
|
+
*
|
|
301
|
+
* 位置优先级:DSH_WIKI_CALLS_LOG(测试与临时排查)> 配置里的 calls.log > 插件目录旁的
|
|
302
|
+
* calls.jsonl。绝不写进知识库本体 —— 库是用户的,插件只能在库外面留账。
|
|
303
|
+
*/
|
|
304
|
+
let callsCfg = readCallsConfig(pluginRoot)
|
|
305
|
+
const calls = createCallLog({
|
|
306
|
+
file: process.env.DSH_WIKI_CALLS_LOG || callsCfg.log || path.join(pluginRoot, 'calls.jsonl'),
|
|
307
|
+
enabled: callsCfg.enabled,
|
|
308
|
+
})
|
|
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
|
+
|
|
320
|
+
/**
|
|
321
|
+
* 记一条调用。旁路:记账失败绝不能变成工具失败 ——
|
|
322
|
+
* 审计的价值远小于「查库还能用」,坏了就让它坏在暗处。
|
|
323
|
+
*/
|
|
324
|
+
function recordCall(entry) {
|
|
325
|
+
try {
|
|
326
|
+
calls.record(entry)
|
|
327
|
+
} catch {
|
|
328
|
+
// 吞掉:账本写不进去不该影响检索
|
|
329
|
+
}
|
|
330
|
+
}
|
|
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
|
+
|
|
265
351
|
let cache = null
|
|
266
352
|
let cachedAt = 0
|
|
267
353
|
let inflight = null
|
|
@@ -610,6 +696,15 @@ export function apply(ctx, config = {}) {
|
|
|
610
696
|
limit: clampLimit(parsed.searchParams.get('limit')),
|
|
611
697
|
explain: true,
|
|
612
698
|
})
|
|
699
|
+
recordCall({
|
|
700
|
+
source: 'panel',
|
|
701
|
+
tool: 'wiki_recall',
|
|
702
|
+
mode: 'search',
|
|
703
|
+
query,
|
|
704
|
+
hits: Array.isArray(result?.hits) ? result.hits.length : 0,
|
|
705
|
+
ms: Date.now() - started,
|
|
706
|
+
ok: true,
|
|
707
|
+
})
|
|
613
708
|
return sendJson(res, 200, {
|
|
614
709
|
...result,
|
|
615
710
|
// 面板要的分母:扫了多少页、扫描本身花了多久、这次查询花了多久
|
|
@@ -618,6 +713,41 @@ export function apply(ctx, config = {}) {
|
|
|
618
713
|
elapsedMs: Date.now() - started,
|
|
619
714
|
})
|
|
620
715
|
}
|
|
716
|
+
// 调用审计:账本只读得回最近的调用,够回答「模型到底查没查、查了什么、查到没有」。
|
|
717
|
+
// governance 是同一份插件侧统计,页面与 wiki_observe 看到的是同一个对象形状。
|
|
718
|
+
if (route === '/calls' && req.method === 'GET') {
|
|
719
|
+
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
720
|
+
const limit = Number(parsed.searchParams.get('limit'))
|
|
721
|
+
const days = Number(parsed.searchParams.get('days'))
|
|
722
|
+
const audit = calls.read({
|
|
723
|
+
limit: Number.isFinite(limit) ? limit : undefined,
|
|
724
|
+
source: parsed.searchParams.get('source') ?? 'all',
|
|
725
|
+
only: parsed.searchParams.get('only') ?? 'all',
|
|
726
|
+
})
|
|
727
|
+
return sendJson(res, 200, {
|
|
728
|
+
...audit,
|
|
729
|
+
governance: governance.stats({ days: Number.isFinite(days) && days > 0 ? days : undefined }),
|
|
730
|
+
})
|
|
731
|
+
}
|
|
732
|
+
if (route === '/calls/config' && req.method === 'POST') {
|
|
733
|
+
const body = await readBody(req)
|
|
734
|
+
if (body === undefined) return sendJson(res, 400, { error: '请求体不是合法 JSON' })
|
|
735
|
+
callsCfg = writeCallsConfig(pluginRoot, { ...callsCfg, ...body }).config
|
|
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 })
|
|
745
|
+
}
|
|
746
|
+
if (route === '/calls/clear' && req.method === 'POST') {
|
|
747
|
+
// 手动清空与关闭共用同一实现:保持当前开关状态,清完切到新观察周期。
|
|
748
|
+
clearObservation(callsCfg.enabled !== false)
|
|
749
|
+
return sendJson(res, 200, { ok: true })
|
|
750
|
+
}
|
|
621
751
|
if (route === '/check' && req.method === 'POST') {
|
|
622
752
|
const body = await readBody(req)
|
|
623
753
|
return sendJson(res, 200, await probeRoot(body?.root))
|
|
@@ -649,6 +779,12 @@ export function apply(ctx, config = {}) {
|
|
|
649
779
|
invalidate()
|
|
650
780
|
// 换了库,旧库的 context_id ↔ observe_id 对就指错地方了,清掉。
|
|
651
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
|
+
}
|
|
652
788
|
startWatch()
|
|
653
789
|
return sendJson(res, 200, await buildState())
|
|
654
790
|
}
|
|
@@ -702,6 +838,19 @@ export function apply(ctx, config = {}) {
|
|
|
702
838
|
ctx.logger?.warn?.(`[wiki-notes] 主题提示注册失败:${String(error?.message ?? error)}`)
|
|
703
839
|
}
|
|
704
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
|
+
|
|
705
854
|
/**
|
|
706
855
|
* 知识网关的两个工具:把判断交给 Python 管线。
|
|
707
856
|
*
|
|
@@ -765,6 +914,10 @@ function renderContext(args, value) {
|
|
|
765
914
|
// observe_id 也露出来:观察日志靠它把 verify 记录挂回这条 context。
|
|
766
915
|
// 插件会自动转发它,所以模型不用管;但写出来,模型想显式传参时手里有。
|
|
767
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)
|
|
768
921
|
return lines.join('\n')
|
|
769
922
|
}
|
|
770
923
|
|
|
@@ -788,9 +941,78 @@ function renderVerify(args, value) {
|
|
|
788
941
|
if (notices.length > 0) {
|
|
789
942
|
lines.push(`提示 ${notices.length} 条:${notices.map((n) => n.rule ?? '').join('、')}`)
|
|
790
943
|
}
|
|
944
|
+
// 违规处置纪律:ok 只说明这次核验没发现越界,不等于逐项必核规则都查过;
|
|
945
|
+
// 发现违规就必须改答案再核验一次,不能带着 violations_found 直接收尾。
|
|
946
|
+
if (violations.length > 0 || value.status === 'violations_found') {
|
|
947
|
+
lines.push('', '不得绕过 violations_found:修正答案后再跑一次 wiki_verify,仍有违规须披露。')
|
|
948
|
+
}
|
|
791
949
|
return lines.join('\n')
|
|
792
950
|
}
|
|
793
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
|
+
|
|
794
1016
|
/** observe 统计摘要:只报分布,不下结论,也不参与回答。 */
|
|
795
1017
|
function renderObserve(args, value) {
|
|
796
1018
|
if (!value || typeof value !== 'object') return '(没有结果)'
|
|
@@ -827,14 +1049,30 @@ function renderObserve(args, value) {
|
|
|
827
1049
|
}
|
|
828
1050
|
}
|
|
829
1051
|
if (totals.legacy) lines.push(`另有 ${totals.legacy} 条早期记录(无事件字段,未计入统计)`)
|
|
1052
|
+
if (value.governance && typeof value.governance === 'object') {
|
|
1053
|
+
lines.push(...renderGovernanceLines(value.governance))
|
|
1054
|
+
}
|
|
830
1055
|
return lines.join('\n')
|
|
831
1056
|
}
|
|
832
1057
|
|
|
833
1058
|
/** 统一的 Bridge 调用包装:配置从插件配置读,错就错在明处。 */
|
|
834
1059
|
async function callBridge(command, payload) {
|
|
1060
|
+
const started = Date.now()
|
|
835
1061
|
const cfg = readBridgeConfig(pluginRoot)
|
|
836
1062
|
const rootInfo = resolveWikiRootInfo(pluginRoot, root)
|
|
1063
|
+
/** 网关这条路上「一次调用」的记账:三个工具都从这里过,记在一处不散。 */
|
|
1064
|
+
const note = (hits, ok) => recordCall({
|
|
1065
|
+
tool: `wiki_${command}`,
|
|
1066
|
+
mode: typeof payload?.engine === 'string' ? payload.engine : '',
|
|
1067
|
+
query: typeof payload?.query === 'string' ? payload.query : '',
|
|
1068
|
+
// 只有 context 会产生「命中了几页证据」;verify 是核对、observe 是读统计,
|
|
1069
|
+
// 记成 0 会把命中率的分母悄悄稀释,所以记 null。
|
|
1070
|
+
hits: command === 'context' ? hits : null,
|
|
1071
|
+
ms: Date.now() - started,
|
|
1072
|
+
ok,
|
|
1073
|
+
})
|
|
837
1074
|
if (rootInfo.root === '') {
|
|
1075
|
+
note(null, false)
|
|
838
1076
|
return errorEnvelope('E_WIKI_ROOT_MISSING', NOT_CONFIGURED_HINT, 'validate')
|
|
839
1077
|
}
|
|
840
1078
|
const result = await runBridge({
|
|
@@ -847,8 +1085,13 @@ async function callBridge(command, payload) {
|
|
|
847
1085
|
env: cfg.observeLog ? { WIKI_OBSERVE_LOG: cfg.observeLog } : {},
|
|
848
1086
|
pluginVersion: PLUGIN_VERSION,
|
|
849
1087
|
})
|
|
850
|
-
if (!result.ok)
|
|
851
|
-
|
|
1088
|
+
if (!result.ok) {
|
|
1089
|
+
note(null, false)
|
|
1090
|
+
return result.error
|
|
1091
|
+
}
|
|
1092
|
+
const data = result.data ?? errorEnvelope('E_BRIDGE_CRASH', 'Bridge 返回了空结果', 'bridge')
|
|
1093
|
+
note(Array.isArray(data?.evidence) ? data.evidence.length : 0, true)
|
|
1094
|
+
return data
|
|
852
1095
|
}
|
|
853
1096
|
|
|
854
1097
|
const registerGateway = () => {
|
|
@@ -861,7 +1104,8 @@ const registerGateway = () => {
|
|
|
861
1104
|
+ '要引用笔记原文回答、或需要知道「有没有依据 / 依据够不够 / 哪里是缺口」时用它,'
|
|
862
1105
|
+ '而不是自己连续调 wiki_recall。返回里 status.support 与 status.degraded 必须分别看待:'
|
|
863
1106
|
+ 'support 说的是「知识够不够」,degraded 说的是「引擎有没有坏」,后者为真时不能把 support 当结论。'
|
|
864
|
-
+ '返回的 context_id 可交给 wiki_verify 核验后续回答。'
|
|
1107
|
+
+ '返回的 context_id 可交给 wiki_verify 核验后续回答。'
|
|
1108
|
+
+ CONTEXT_TRIGGERS,
|
|
865
1109
|
parameters: {
|
|
866
1110
|
type: 'object',
|
|
867
1111
|
properties: {
|
|
@@ -886,6 +1130,7 @@ const registerGateway = () => {
|
|
|
886
1130
|
if (query === '') {
|
|
887
1131
|
return errorEnvelope('E_QUERY_EMPTY', 'query 不能为空', 'validate')
|
|
888
1132
|
}
|
|
1133
|
+
const cycle = governance.cycle()
|
|
889
1134
|
const value = await callBridge('context', {
|
|
890
1135
|
query: query.slice(0, MAX_QUERY_CHARS * 4),
|
|
891
1136
|
limit: args?.limit,
|
|
@@ -897,6 +1142,13 @@ const registerGateway = () => {
|
|
|
897
1142
|
if (value && value.kind === 'context' && value.context_id && value.observe_id) {
|
|
898
1143
|
rememberObserve(value.context_id, value.observe_id)
|
|
899
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
|
+
}
|
|
900
1152
|
return value
|
|
901
1153
|
},
|
|
902
1154
|
}))
|
|
@@ -907,7 +1159,8 @@ const registerGateway = () => {
|
|
|
907
1159
|
'拿一份已有的 wiki_context 结果去核验一段回答,不重新检索。'
|
|
908
1160
|
+ '写完答案后自查(尤其含数字、范围、年份、题量分值这类主张时)用它。'
|
|
909
1161
|
+ '返回 status 与 violations:violations 非空说明回答越过了证据允许的边界;'
|
|
910
|
-
+ 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
|
|
1162
|
+
+ 'context_expired / context_missing 是快照问题,不等于回答错了,需要重新取上下文再核验。'
|
|
1163
|
+
+ VERIFY_TRIGGERS,
|
|
911
1164
|
parameters: {
|
|
912
1165
|
type: 'object',
|
|
913
1166
|
properties: {
|
|
@@ -941,11 +1194,20 @@ const registerGateway = () => {
|
|
|
941
1194
|
// 记录和它的 context 拆成两条互不相认的日志。
|
|
942
1195
|
const explicit = typeof args?.observe_id === 'string' ? args.observe_id.trim() : ''
|
|
943
1196
|
const observeId = explicit || lookupObserve(contextId)
|
|
944
|
-
|
|
1197
|
+
const cycle = governance.cycle()
|
|
1198
|
+
const value = await callBridge('verify', {
|
|
945
1199
|
context_id: contextId,
|
|
946
1200
|
answer,
|
|
947
1201
|
...(observeId ? { observe_id: observeId } : {}),
|
|
948
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
|
|
949
1211
|
},
|
|
950
1212
|
}))
|
|
951
1213
|
|
|
@@ -953,7 +1215,8 @@ const registerGateway = () => {
|
|
|
953
1215
|
name: 'wiki_observe',
|
|
954
1216
|
description:
|
|
955
1217
|
'查观察日志的统计:这段时间 wiki_context 被问过多少次、支持状态怎么分布、'
|
|
956
|
-
+ 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
|
|
1218
|
+
+ 'wiki_verify 挑出过哪些违规类型。只读诊断,不参与回答,也不改检索行为。'
|
|
1219
|
+
+ OBSERVE_TRIGGERS,
|
|
957
1220
|
parameters: {
|
|
958
1221
|
type: 'object',
|
|
959
1222
|
properties: {
|
|
@@ -967,7 +1230,9 @@ const registerGateway = () => {
|
|
|
967
1230
|
render: (args, value) => [{ type: 'text', text: renderObserve(args, value) }],
|
|
968
1231
|
},
|
|
969
1232
|
async execute(args) {
|
|
970
|
-
|
|
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 }) }
|
|
971
1236
|
},
|
|
972
1237
|
}))
|
|
973
1238
|
|
|
@@ -999,8 +1264,27 @@ const registerGateway = () => {
|
|
|
999
1264
|
if (typeof corpus.drilledFrom === 'string') result.drilledFrom = corpus.drilledFrom
|
|
1000
1265
|
result.ms = Date.now() - started
|
|
1001
1266
|
}
|
|
1002
|
-
|
|
1267
|
+
const value = result ?? { mode: 'error', error: '查询没有返回结果(mode 可能传错了)' }
|
|
1268
|
+
recordCall({
|
|
1269
|
+
tool: 'wiki_recall',
|
|
1270
|
+
mode: typeof value?.mode === 'string' ? value.mode : '',
|
|
1271
|
+
query: typeof args?.query === 'string' ? args.query : '',
|
|
1272
|
+
// 只有 search 有「命中几页」这回事。page/list 是「读到了就是读到了」,
|
|
1273
|
+
// 记成 0 会把命中率的分子分母一起带歪,所以记 null 让它不进统计。
|
|
1274
|
+
hits: value?.mode === 'search' && Array.isArray(value.hits) ? value.hits.length : null,
|
|
1275
|
+
ms: Date.now() - started,
|
|
1276
|
+
ok: value?.mode !== 'error',
|
|
1277
|
+
})
|
|
1278
|
+
return value
|
|
1003
1279
|
} catch (error) {
|
|
1280
|
+
recordCall({
|
|
1281
|
+
tool: 'wiki_recall',
|
|
1282
|
+
mode: typeof args?.mode === 'string' ? args.mode : '',
|
|
1283
|
+
query: typeof args?.query === 'string' ? args.query : '',
|
|
1284
|
+
hits: null,
|
|
1285
|
+
ms: Date.now() - started,
|
|
1286
|
+
ok: false,
|
|
1287
|
+
})
|
|
1004
1288
|
// 工具层不往上抛:把「库读不出来」变成一条模型看得懂、能转告用户的错误,
|
|
1005
1289
|
// 而不是一次工具调用失败。库里 0 页和库里没有这个词,是两回事。
|
|
1006
1290
|
// 这里只剩两类:没配路径(用户该去设置页),以及真正的程序异常(该转告)。
|
|
@@ -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,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-wiki-notes",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Read-only
|
|
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": [
|
|
7
7
|
"deepseek",
|
|
8
8
|
"deepseek-harness",
|
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
"notes",
|
|
13
13
|
"markdown",
|
|
14
14
|
"retrieval",
|
|
15
|
-
"obsidian"
|
|
15
|
+
"obsidian",
|
|
16
|
+
"knowledge-base",
|
|
17
|
+
"llm"
|
|
16
18
|
],
|
|
17
19
|
"main": "lib/index.js",
|
|
18
20
|
"exports": {
|
|
@@ -22,7 +24,7 @@
|
|
|
22
24
|
"./package.json": "./package.json"
|
|
23
25
|
},
|
|
24
26
|
"bin": {
|
|
25
|
-
"wiki-notes": "
|
|
27
|
+
"wiki-notes": "bin/cli.mjs"
|
|
26
28
|
},
|
|
27
29
|
"files": [
|
|
28
30
|
"lib",
|
|
@@ -37,7 +39,7 @@
|
|
|
37
39
|
"node": ">=20.13.0"
|
|
38
40
|
},
|
|
39
41
|
"scripts": {
|
|
40
|
-
"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/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",
|
|
41
43
|
"cli": "node bin/cli.mjs",
|
|
42
44
|
"probe": "node tools/probe.mjs"
|
|
43
45
|
},
|