dsh-wiki-notes 1.3.0 → 1.4.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.
Files changed (23) hide show
  1. package/README.md +104 -24
  2. package/docs/README.md +70 -0
  3. package/docs//345/245/221/347/272/246-stage0/knowledge-gateway.v1.schema.json +1180 -0
  4. package/docs//345/245/221/347/272/246-stage0/samples/_verify_probe.json +46 -0
  5. package/docs//345/245/221/347/272/246-stage0/samples/context.cq-shenlun.json +612 -0
  6. package/docs//345/245/221/347/272/246-stage0/samples/verify.context-corrupt.json +20 -0
  7. package/docs//345/245/221/347/272/246-stage0/samples/verify.context-expired.json +20 -0
  8. package/docs//345/245/221/347/272/246-stage0/samples/verify.fabricated-quote.json +31 -0
  9. package/docs//345/245/221/347/272/246-stage0/samples/verify.right-with-limit.json +14 -0
  10. package/docs//345/245/221/347/272/246-stage0/samples/verify.scope-mismatch.json +27 -0
  11. package/docs//345/245/221/347/272/246-stage0/samples/verify.wrong-five.json +43 -0
  12. package/docs//345/245/221/347/272/246-stage0//350/247/202/345/257/237/346/234/237/346/226/271/346/241/210.md +81 -0
  13. 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 +204 -0
  14. 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 +107 -0
  15. 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 +84 -0
  16. 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 +98 -0
  17. 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 +143 -0
  18. 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 +109 -0
  19. package/lib/bridge.js +210 -0
  20. package/lib/client.js +1 -1
  21. package/lib/config.js +59 -0
  22. package/lib/index.js +268 -4
  23. package/package.json +2 -2
@@ -0,0 +1,98 @@
1
+ # 阶段 3:`support_reason` —— 支持状态的可解释性(F3)
2
+
3
+ > 阶段:F3(用户 2026-11-05 06:22 定边界)
4
+ > 状态:已实现、已验收(34/34)、全量回归零漂移
5
+ > 契约:`knowledge-gateway.v1.schema.json` 的 `$defs.support_reason`(context 的可选字段,不进 required)
6
+
7
+ ## 1. 边界(用户原话,作为验收标准)
8
+
9
+ > `support_reason` 解释 Context Builder 为什么得出当前 `support_status`,让调用者不仅知道结果,
10
+ > 还知道结果是由哪些具体条件导致的。它不负责判断用户答案是否正确。
11
+
12
+ - 只解释现有判定,**不改** `support_status`、证据、`provenance`、`answer_policy` 结论。
13
+ - 不重复包装别的字段:缺什么看 `missing`,引擎怎样看 `engine_states`,冲突怎样看 `conflict_status`。
14
+ - 一个状态可以有多个原因:`primary` 解释状态本身,`reasons[]` 保留其余诊断。
15
+ - 不引入语义推断:每条原因都能指回具体槽位 / 引擎 / 管线阶段。
16
+
17
+ ## 2. 字段
18
+
19
+ ```jsonc
20
+ "support_reason": {
21
+ "primary": "partial_slot_coverage", // 主原因码(解释 support_status 本身)
22
+ "primary_label": "部分槽位有证据、部分缺失",
23
+ "reasons": [ // 全部原因,按严重度排序,不因 primary 而丢弃
24
+ {"code": "partial_slot_coverage", "label": "…", "detail": "缺失 1 个槽位:题量", "slots": ["numeric"]},
25
+ {"code": "engine_degraded", "label": "…", "detail": "wiki_recall error(…);search.py 仍返回了结果",
26
+ "engines": ["wiki_recall"]}
27
+ ]
28
+ }
29
+ ```
30
+
31
+ `detail` 必须是人能读懂的一句话且能追溯(带槽位名/引擎名/错误串),不允许「看起来合理但无依据」的解释。
32
+
33
+ ## 3. 原因码(11 个)
34
+
35
+ | code | 触发条件(只读现有字段) | 与状态的对应 |
36
+ |---|---|---|
37
+ | `conflicting_evidence` | `conflict_status == "conflicting"` 且有 `conflicts` | 优先于一切 |
38
+ | `no_candidates` | `metrics.candidate_count == 0` | 多半 insufficient |
39
+ | `no_usable_evidence` | 有候选但 `readable_count == 0`,或可读但 `evidence_count == 0` | 多半 insufficient |
40
+ | `recorded_unresolved` | `missing[].reason == "recorded_unresolved"` | insufficient / partial |
41
+ | `required_slots_missing` | 有证据但槽位没被覆盖(`missing` 非空且非 unresolved) | insufficient |
42
+ | `partial_slot_coverage` | 同上但 `support_status == partial` | partial |
43
+ | `conditional_evidence_only` | `evidence[].supports[].quote_support == "conditional"` 且未达 sufficient | partial |
44
+ | `scope_gap` | `incomparable` 非空(同槽位证据因范围/时间不可比) | 任意,**不是冲突** |
45
+ | `conflict_candidate` | `conflict_status == "candidate"` | 任意,**尚未确认** |
46
+ | `engine_degraded` | `engines[*].status ∈ {error, timeout}` | 任意,是附加诊断 |
47
+ | `all_required_slots_supported` | `support_status == "sufficient"` | sufficient |
48
+
49
+ 说明两点与用户建议清单的差异:
50
+
51
+ - 新增 `recorded_unresolved`:用户清单里没有,但 `missing.reason` 早已有这个状态,且它和「库里没覆盖」
52
+ 是**性质不同**的两件事(有知识但未裁决),压进 `required_slots_missing` 会误导。
53
+ - 新增 `engine_degraded`:用户清单里没有,但验收第 3 条要求「引擎异常但另一引擎仍有证据时,原因能准确反映降级」,
54
+ 必须有个码承载它。它永远不参与决定 `support_status`(F1 已经保证这一点),只做诊断。
55
+ - `scope_gap` 的实现依据是 `conflict_check` 的 `incomparable`,**不是**新做的范围比较——不做跨句/语义推断。
56
+
57
+ ## 4. 排序(为什么 primary 是它)
58
+
59
+ ```
60
+ conflicting_evidence 0 → no_candidates 1 → no_usable_evidence 2 → recorded_unresolved 3
61
+ → required_slots_missing 4 → partial_slot_coverage 5 → conditional_evidence_only 6
62
+ → scope_gap 7 → conflict_candidate 8 → engine_degraded 9 → all_required_slots_supported 10
63
+ ```
64
+
65
+ 规则:**根源码(没候选 / 没可用证据)排在「缺槽位」之前**——槽位缺失是后果,不是原因。
66
+ 真实效果:库外题 `support=insufficient, stage=no_candidates`,`primary` 由「缺 1 个槽位」纠正为 `no_candidates`,
67
+ `required_slots_missing` 仍留在 `reasons[]` 里不丢信息。
68
+
69
+ ## 5. 实现
70
+
71
+ - 新文件 `<你的库根目录>\工具-tools\support_reason.py`:`explain(ctx) -> dict`(纯函数,只读 ctx)、
72
+ `contract_text(ctx)`(给 LLM 的一句话翻译,不新增约束)。
73
+ - 接入点 `context_builder.py`:`ctx_out` 组装完、`answer_policy` 之前调用;**解释失败不拖垮检索**,
74
+ 异常时落 `{"primary":"unknown","reasons":[{"code":"unknown","detail":str(exc)}]}`。
75
+ - 契约:`$defs.support_reason` / `$defs.support_reason_item`(code 用 enum 锁死),
76
+ `context.properties.support_reason` 为**可选**——老调用方不传不报错。样例 `samples/context.cq-shenlun.json` 已带实现值。
77
+
78
+ ## 6. 验收(`_tools/eval/eval_support_reason.py`,34/34)
79
+
80
+ 对应用户六条:
81
+
82
+ 1. 四种状态各自正确原因:sufficient / partial / insufficient(有证据缺槽)/ conflicting 各 1–3 条断言。
83
+ 2. 三种不足可区分:无候选(`no_candidates`)、页面读不出(`no_usable_evidence`)、有页面无证据(`no_usable_evidence` 但 detail 不同)、槽位缺失(`required_slots_missing`)。
84
+ 3. 引擎故障:`wiki_recall error` + `search.py ok` → 有 `engine_degraded`,detail 同时写出「哪个挂了」和「谁还活着」,主因仍是覆盖不足。
85
+ 4. 不被误判:`incomparable` 只出 `scope_gap`,不出 `conflicting_evidence`;`candidate` 只出 `conflict_candidate` 且措辞带「尚未确认」;两者都不夺走主因。
86
+ 5. 稳定性:同一 ctx 连跑两次 `explain` 逐字节相同;真 ctx 重跑与 build 内的结果一致。
87
+ 6. 无副作用:`support_status` / `evidence` / `provenance` / `answer_policy` 前后深比较相等。
88
+
89
+ ## 7. 已知局限
90
+
91
+ 1. `conditional_evidence_only` 依赖 `supports[].quote_support`;抽不到 conditional 标记时不会报。
92
+ 2. `scope_gap` 只反映 `conflict_check` 认定的「不可比」,不做独立的范围比对;真正的范围判断在 `numeric_claim`(F2),两者不互相调用(依赖方向保持单向)。
93
+ 3. `reasons[]` 目前只进 `contract_text` 文案,**没有**变成 `answer_policy` 的新规则——不新增拦截。
94
+ 4. 原因码是稳定枚举,新增必须同步 schema 的 enum,否则契约校验会挂。
95
+
96
+ ## 8. 本轮没碰
97
+
98
+ F5 子查询漂移、考试类型别名扩展、`page_changed` 是否降级、自动知识维护、SHA-256 措辞(「完整性校验失败」而非「人为修改」,仍待改)。
@@ -0,0 +1,143 @@
1
+ # 阶段 4:插件接入(wiki_context / wiki_verify)
2
+
3
+ > 日期:2026-11-05 | 插件:dsh-wiki-notes **1.4.0** | Bridge:`wiki_bridge.py` **0.1.0** | 契约:**1.0** | 管线:**2026-11-05**
4
+
5
+ ## 这一阶段到底改了什么
6
+
7
+ 插件从「Markdown 检索插件」变成「知识网关」:多了两个工具,但**判断逻辑一行没搬进来**。
8
+
9
+ ```
10
+ 模型 → wiki_context(query) → 插件校验参数 + 找库路径 → spawn Python wiki_bridge.py context
11
+ → 读取一行 JSON → 原样交给模型(渲染成人看的文本)
12
+ 模型 → wiki_verify(context_id, answer) → 同一个 Bridge → 快照里取回原 context 复核
13
+ ```
14
+
15
+ 插件负责:MCP 注册、参数校验、库路径发现、错误隔离、把异常翻成结构化错误。
16
+ Python 负责:检索规划、排序、证据抽取、support 判定、冲突、Answer Policy、回答核验、快照。
17
+
18
+ - `wiki_recall` **保留不动**,仍是"把命中小节原文给我"的简单入口。
19
+ - 两个新工具只在**配置了 `bridge.toolsRoot`** 时才注册可用;没配就报 `E_PYTHON_UNAVAILABLE` 并指路。
20
+
21
+ ## 进程协议
22
+
23
+ | 项 | 约定 |
24
+ |---|---|
25
+ | 调用 | `spawn(python, [wiki_bridge.py, <command>])`,`cwd = toolsRoot` |
26
+ | 输入 | stdin **一行 JSON**(`{query, limit, engine, ttl_seconds, plugin_version}` 或 `{context_id, answer}`) |
27
+ | 输出 | stdout **一行 JSON**,可能是 context / verify / error 三种信封之一 |
28
+ | 诊断 | 只走 stderr(`[diag] …`),插件丢弃不解析 |
29
+ | 退出码 | 业务失败也返回 **0** + `error` 信封;非 0 才算 Bridge 崩了 |
30
+ | 命令 | `context` / `verify` / `ping`(ping 是内部健康检查,**不进契约**) |
31
+ | 编码 | 两侧都强制 utf-8(`PYTHONIOENCODING`/`PYTHONUTF8` + Python 侧 `reconfigure`) |
32
+
33
+ stdout 解析取**最后一行能 parse 的 JSON**,容忍 Python 偶尔往 stdout 漏杂音。
34
+
35
+ ## 文件清单
36
+
37
+ **Python 侧(`<你的库根目录>\工具-tools`)**
38
+
39
+ | 文件 | 作用 |
40
+ |---|---|
41
+ | `wiki_bridge.py`(新,约 330 行) | 契约整形层:`shape_context()` / `_engine_slot()` / `_violation_norm()` / `_error_envelope()` |
42
+ | `context_snapshot.py` | 加 `_json_safe()`,清 lone surrogate 再落盘 |
43
+ | `answer_policy.py:216` | `numeric.check_failed` 的 type 改为 `numeric_check_failed`(契约 enum 只认这个) |
44
+
45
+ **插件侧(`<插件仓库目录>`)**
46
+
47
+ | 文件 | 改动 |
48
+ |---|---|
49
+ | `lib/bridge.js`(新,约 210 行) | `runBridge()` 进程管理 + 错误分类,`errorEnvelope()` 与 Python 同形 |
50
+ | `lib/config.js` | `DEFAULT_BRIDGE_CONFIG = {python, toolsRoot, timeoutMs: 120000, ttlSeconds: 1800}`、`readBridgeConfig` / `writeBridgeConfig`(支持 `DSH_WIKI_TOOLS`、`DSH_WIKI_PYTHON` 覆盖) |
51
+ | `lib/index.js` | `registerGateway()` 注册两工具、`callBridge()`、`renderContext()` / `renderVerify()`、`readPluginVersion()`、`gatewayDisposers` 单独 try/dispose |
52
+ | `package.json` | 1.3.0 → **1.4.0**,描述补两工具 |
53
+ | `tests/gateway.mjs`(新) | 22 项端到端,含跨通道逐字段一致 |
54
+
55
+ **运行时目录 `<DSH 运行时插件目录>\` 与源码仓库是 junction(同一批文件)**——改源码即改运行时,但**必须重启 DSH 才重新加载**。
56
+
57
+ ## 契约映射要点
58
+
59
+ | Python 输出 | 契约字段 | 处理 |
60
+ |---|---|---|
61
+ | `engines["search.py"]` | `engines.search` | key 改名(契约里不叫 `search.py`) |
62
+ | `engines["wiki_recall"]` | `engines.wiki_recall` | 同名 |
63
+ | 未跑到的引擎 | `status: disabled` | `not_run` 翻成 `disabled`,**不和 empty 合并** |
64
+ | `pipeline.{stage,degraded,degraded_sources}` | `status.{stage,degraded,degraded_sources}` | 直接搬 |
65
+ | `evidence[].supports[].quote` | 同名 | **不裁剪、不截断**(阶段 0 的样例脚本裁到 110 字,生产路径不裁) |
66
+ | `_violation_norm(v)` | `violations[]` | 11 条 rule 映射成 11 个 type,未映射的走前缀兜底并在 reason 前标 `[未映射规则 X]` |
67
+ | `snapshot` | `snapshot{context_id, expires_at, saved}` | 保存失败时自造 `ctx_<uuid16>` 并明说 `saved:false` |
68
+
69
+ 四版本各自独立写在响应里:`plugin_version`(插件 package.json)、`bridge_version`、`contract_version`、`pipeline_version`。
70
+
71
+ ## 错误码与降级矩阵
72
+
73
+ | 情况 | 码 | 模型看到的效果 |
74
+ |---|---|---|
75
+ | 没配 toolsRoot / python 路径不存在 | `E_PYTHON_UNAVAILABLE` | 只有错误信封,**没有 status、没有 evidence** |
76
+ | python 起了但崩了 | `E_BRIDGE_CRASH` | 同上 |
77
+ | 输出不是 JSON | `E_BRIDGE_BAD_JSON` | 同上 |
78
+ | 超过 120s | `E_BRIDGE_TIMEOUT`(retryable) | 同上 |
79
+ | 库没配置 | `E_WIKI_ROOT_MISSING` | 提示去配置根目录 |
80
+ | query 为空 / answer 为空 / 缺 context_id | `E_QUERY_EMPTY` / `E_VERIFY_EMPTY_ANSWER` / `E_CONTEXT_NOT_FOUND` | 插件层就挡住,不启动子进程 |
81
+ | 某个引擎故障(另一个正常) | 无码,`status.degraded=true` | `engines.search.status=error` + `degraded_sources`,证据照出 |
82
+
83
+ **铁律**:Python 不可用 ≠ 知识不足。前者是环境故障(只有 error 信封),后者是 `status.support=insufficient`(有完整 context)。两者在响应形状上就不一样。
84
+
85
+ ## 配置
86
+
87
+ 两份 `wiki-notes.config.json`(源码仓库 + 运行时目录)都加了:
88
+
89
+ ```json
90
+ "bridge": {
91
+ "python": "C:\\Users\\<用户名>\\python\\python.exe",
92
+ "toolsRoot": "<你的库根目录>\\工具-tools",
93
+ "timeoutMs": 120000,
94
+ "ttlSeconds": 1800
95
+ }
96
+ ```
97
+
98
+ ## 测试
99
+
100
+ **Python 侧**
101
+
102
+ | 脚本 | 结果 |
103
+ |---|---|
104
+ | `eval_bridge_contract.py`(新,51 项) | 51/51:context/verify 三类/4 种错误信封/两次调用稳定/ping,每类都过 schema |
105
+ | `eval_answer_policy` | 8/8 |
106
+ | `eval_numeric_claim` | 13/13 |
107
+ | `eval_support` | 3 passed |
108
+ | `eval_engine_state` | 6/6 |
109
+ | `eval_4d` | 7/7 |
110
+ | `eval_support_reason` | 34/34 |
111
+ | `eval_snapshot` | 12/12 |
112
+ | `eval_conflicts` / `eval_dedup` | 8 / 8 |
113
+ | `eval_method` / `eval_blocks` | 7/7、9/9 |
114
+ | `e2e_check --check` | 8 题漂移 0(重庆申论页入库后重录 1 条基线,非回归) |
115
+ | `protect.py` | 35 条漂移 0 |
116
+
117
+ **插件侧**:`tests/gateway.mjs` 22/22;原有 17 个测试全绿(smoke/help/topics/lintdiff/lint/params/fields/robust/api/explain/cli/contract/draft/watch/client/status),旧测试只把 mock 改成按名取 `wiki_recall`(注册方式改成按名取后,旧 mock 的「取第一个工具」假设过期了)。
118
+
119
+ **实测开销**(本机,冷启动):`ping` 117ms(纯 spawn + import),完整 `context` 993ms(内部 855ms)。一次问答可接受;高频短问答建议后续做常驻或连接复用。
120
+
121
+ ## 踩过的坑
122
+
123
+ 1. **中文 query 变乱码** → payload 里出现 lone surrogate → 快照写盘 `UnicodeEncodeError`。修:两侧强制 utf-8 + `_json_safe()`。
124
+ 2. **`build(root=字符串)` 炸 `'str' object has no attribute 'rglob'`** → 必须传 `Path`。
125
+ 3. **`quote_support: "clue"` 不在 schema enum 里** → 实跑就撞上,补进枚举。
126
+ 4. **`verify.status` 两套叫法**(实现 `context_missing`、schema `context_not_found`)→ 统一为 `context_missing`。
127
+ 5. **插件注册 3 个工具后旧测试拿到的是最后一个** → mock 按名过滤。
128
+ 6. **gateway 测试硬编码 `1.3.0`** → 改为从 `package.json` 读。
129
+
130
+ ## 已知局限(照实写)
131
+
132
+ 1. **页面读取有两处实现**:`wiki_recall` 走 JS 的 corpus 读盘,`wiki_context` 走 Python 的 `read_page`。用户要求"只能有一个权威实现",这一条**尚未做到**——两条链路各有各的清洗与截断规则,同一页可能给出略有差异的正文。收口方式待定(要么 wiki_recall 也转 Python,要么 Python 复用 JS 的语料索引)。
133
+ 2. **插件不校验 schema**:只透传 + 基础参数校验,字段形状靠测试兜底,运行时不拦。模型不会因为 Bridge 多写一个字段就报错。
134
+ 3. **无常驻进程**:每次都 spawn,`python -c import` 就吃掉约 120ms。
135
+ 4. **timeout 固定 120s**,不按命令区分(context 与 verify 的实际耗时差一个量级)。
136
+ 5. **`ping` 不进契约**:它是内部健康检查,schema 的 `oneOf` 里没有它。
137
+ 6. **错误码靠字符串对齐**:Python 与 JS 各写一份同名字符串,没有生成式校验;改一处忘另一处,只有测试能发现。
138
+
139
+ ## 下一步(阶段 3 原计划)
140
+
141
+ - `wiki_observe` 自动记录(现在 `observe_id` 恒为 null,观察链路还没接上)。
142
+ - 降级策略细化:单引擎 error 时是否给模型一条「本次只有一路召回」的显式提示。
143
+ - 第 1 条局限的收口:页面读取单一权威实现。
@@ -0,0 +1,109 @@
1
+ # 阶段 5:读取一致性、观察闭环与实战验收
2
+
3
+ > 本轮只做三件事:量一次「两套读取到底差在哪」、把观察闭环接上、拿五类真实问题压一遍。
4
+ > 判据与检索打分一行没动(除抽取补齐的两处:字数对象词、表格行借用页面标题)。
5
+
6
+ ## 一、页面读取一致性(`eval_read_parity.py`)
7
+
8
+ 对比两条真实链路:
9
+
10
+ - JS:`node bin/cli.mjs page <页名> --root <库> --chars 20000`(`lib/corpus.js` + `lib/engine.js`)
11
+ - Python:`context_builder.read_page()`
12
+
13
+ 抽样:五个目录各 3 页 + 含代码块/表格的页补足,共抽 20 页,其中 15 页有可比正文。逐项比较规范化正文(CRLF→LF、行内空白压缩、去空行)、截断、章节集合、结构元素计数(标题/表格行/代码围栏/wikilink/callout)、frontmatter 类型。报告:`_tools/eval/READ-PARITY.md`。
14
+
15
+ ### 结果
16
+
17
+ | 维度 | 结论 |
18
+ |---|---|
19
+ | 正文 | **逐字一致(15/15)** |
20
+ | 结构元素计数 | 一致,0 差异 |
21
+ | 截断 | 本批样本都在 6000 字以下,未触发 |
22
+ | frontmatter 列表 | **15/15 不一致** |
23
+ | sections 集合 | 2 页章节名不同(容器章节消失),其余一致 |
24
+ | 可读文件集合 | 不同(`index.md` / `log.md` / `_` 前缀) |
25
+
26
+ ### 三条真实差异
27
+
28
+ 1. **frontmatter 列表未解析**:Python 只做 `k, v = line.split(":", 1)`,把
29
+ `别名: [重庆省考申论, 重庆市考申论]` 读成字符串 `"[重庆省考申论, 重庆市考申论]"`;
30
+ JS 的 `asList()` 正常解析成数组。今天这不影响证据(证据只从正文抽),
31
+ 但别名匹配、标签过滤这类能力在 Python 侧等于没有。
32
+ 2. **sections 语义不同**:JS 只按 `## `(level 2)切;Python 认 2–4 级,
33
+ 且 `sections` 只收**含正文行的章节**——纯容器章节(下面直接跟 `###` 的那种)会消失。
34
+ 3. **可读文件集合不同**:`lib/corpus.js:245-246` 明确跳过 `_` 前缀、`index.md`、`log.md`;
35
+ Python `find_page()` 全盘 rglob,`log.md` 能被当普通页读到(实测 JS `found=False` / Python `found=True`)。
36
+
37
+ ### 统一方向(待拍板)
38
+
39
+ - **选项 A:以 Python 为唯一实现**,`wiki_recall` 也改读 Python 版。——彻底,但要动检索主链,风险大。
40
+ - **选项 B:Python 对齐 JS 的规范化**(解析 frontmatter 列表、跳过同三个文件名、section 只按 `## ` 切)。——改动小,不动检索。
41
+
42
+ 我的建议是 **B**:正文已经逐字一致,差异全在「结构解读」,而结构解读目前只有 JS 侧在服务检索。
43
+ 先把 Python 侧对齐,等以后真要合并成一份实现时,A 才有干净的地基。
44
+ 两个选项都不在本轮范围内——这属于「要不要改 wiki_recall 的读取」,需要你点头。
45
+
46
+ ## 二、观察闭环(`observe_id` 接通)
47
+
48
+ ```
49
+ wiki_context ──► context_id(快照)+ observe_id(观察记录)
50
+ │ │
51
+ └──► wiki_verify ────┴──► 追加 verify 记录(parent_observe_id 指回 context)
52
+ │
53
+ └──► wiki_observe 查统计
54
+ ```
55
+
56
+ - 记录写在 `WIKI_OBSERVE_LOG`(默认 `_tools/eval/observe_log.jsonl`),一行一个 JSON。
57
+ - `event` 字段区分 `context` / `verify`;早期 CLI 写法没有该字段的记录计入 `legacy`,不混进统计。
58
+ - **观察是旁路**:记录失败只写 stderr,`context` / `verify` 照常返回(已验证:日志路径故意指向不可写位置,context 仍然成功且照常返回 `observe_id`)。
59
+ - **不存引文**:记录里只有「问了什么、走了哪条路、支持到哪一步、挑出了哪类违规」,没有 `quote` / `evidence` 字段。日志不是第二个库。
60
+ - **不干预回答**:观察层不拦截、不拒答、不改写,只做计数与分布。
61
+
62
+ `wiki_observe` 返回(`$defs.observe_stats`):
63
+
64
+ | 字段 | 含义 |
65
+ |---|---|
66
+ | `totals` | `contexts` / `verifies` / `legacy` / `malformed` |
67
+ | `support_distribution` | sufficient / partial / insufficient 各多少次 |
68
+ | `retrieval_distribution` | 检索状态分布 |
69
+ | `support_reason_distribution` | 主要卡在哪类原因 |
70
+ | `violation_types` | 各违规类型被挑出几次 |
71
+ | `recent` | 最近若干条(id / 事件 / 时间 / 问题 / 状态) |
72
+
73
+ 验收 `eval_observe_loop.py`:**21/21**(含跨进程查得到、追得回、计数准、不含引文、写不进也不影响主链路、两次调用不串用)。
74
+
75
+ ## 三、五类问题实战验收(`eval_acceptance.py`)
76
+
77
+ 链路与 MCP 工具同一条(`wiki_bridge.py`)。完整报告:`_tools/eval/ACCEPTANCE-2026-11-05.md`。
78
+
79
+ | # | 类型 | 问题 | support | verify 命中 | 结论 |
80
+ |---|---|---|---|---|---|
81
+ | A | 直接事实 | 重庆申论考几道题 | partial(条件性证据) | `review_flag_missing` | ✅ 放行,只要求标复核 |
82
+ | B | 证据不足 | 重庆事业单位综合知识考几道题 | **insufficient** | `answered_unfilled_slot`、`gap_not_disclosed` | ✅ 承认缺口,编的数字被拦 |
83
+ | C | 范围混淆 | 重庆申论考几道题(答国考口径) | partial | 3 × `unsupported_numeric_claim`(均 contradicted) | ✅ 三个数字全被抓 |
84
+ | D | 多证据冲突 | 重庆申论作文多少字(答 800 字) | partial | `unsupported_numeric_claim`(contradicted) | ✅ 与库内 1000–1200 字冲突被指出 |
85
+ | E | 错误答案 | 重庆申论考五道题 | partial | `unsupported_numeric_claim`(contradicted) | ✅ 数字错、单位对、范围对,仍被抓 |
86
+
87
+ **5/5 符合预期。** 首轮暴露的两个真问题(A 误拦、D 漏报)已修,修法记在这份文档末尾(判据放宽、主张范围继承、区间比较、表格证据补齐),细节见各阶段的验收记录。
88
+
89
+ 1. `unverifiable` 不再升 violation,只进 `notices`——「说不清」不等于「说错了」。
90
+ 2. 主张范围继承整段回答——中文答句句首声明「重庆……」,后面分句省略主语。
91
+ 3. 支持区间写法(`1000–1200 字`),单值对区间比相交。
92
+ 4. 证据抽取补两处:`字数` 对象词 + 表格行允许借用页面标题满足地域约束(行内已有别的地域则不借)。
93
+
94
+ ## 四、三层能力对照(回答「DSH 现在具备什么」)
95
+
96
+ | 层 | 现在能回答的问题 | 落点 |
97
+ |---|---|---|
98
+ | 检索层 | 哪些页面可能相关 | `wiki_recall`、`search.py`、`query_planner`(子查询按问的对象细化) |
99
+ | 证据治理层 | 够不够、缺什么、范围对不对、有没有争议 | `support_status`、`missing`、`support_reason`(11 个原因码)、`numeric_claim`(五维四态)、`conflict_check` |
100
+ | 回答核验层 | 这段答案有没有越过证据边界 | `wiki_verify`(快照 + TTL,不重新检索)、`answer_policy` 9 条规则 + 数值判据 |
101
+
102
+ ## 五、已知局限(照实写)
103
+
104
+ 1. **读取仍是两套实现**——差在结构解读层,见第一节;统一方向待拍板。
105
+ 2. **`unverifiable` 只在 `notices` 里**:模型若只看 `violations`,会漏掉「这个数字我核实不了」。需要模型侧读 notices。
106
+ 3. **区间只支持「A–B 单位」**:`一千到一千二百字` 这类中文区间仍抽不出。
107
+ 4. **`numeric_claim` 不做跨句推理**:主张散落在两句里(「作文 40 分。」「字数 1000–1200。」)时,靠整段口径继承兜底,不做句间绑定。
108
+ 5. **观察日志无轮转**:只追加,不清理;`legacy` 计数会随时间变大,需要时手工归档。
109
+ 6. **快照不自动清理**,也没有滑动续期。
package/lib/bridge.js ADDED
@@ -0,0 +1,210 @@
1
+ /**
2
+ * bridge.js —— 插件这侧的「打电话」代码。
3
+ *
4
+ * 这里只做三件事:起一个 python 子进程、把参数写进它的 stdin、把 stdout 当 JSON 读回来。
5
+ * 任何判断(检索、证据、范围、支持度、核验)都不在这里做 —— 那是 Python 管线的活。
6
+ * 插件唯一有权判的是「这次调用本身成没成」,所以这里只产出两类结果:
7
+ * 1) 管线正常回话(哪怕它说 support=insufficient)→ 原样返回;
8
+ * 2) 通路坏了(没 python、超时、崩了、吐的不是 JSON)→ 生成 error 信封,
9
+ * 并且带 stage='bridge'。绝不能把第 2 类伪装成「知识库里没有」。
10
+ */
11
+ import { spawn } from 'node:child_process'
12
+ import path from 'node:path'
13
+
14
+ export const BRIDGE_VERSION = '0.1.0'
15
+ export const CONTRACT_VERSION = '1.0'
16
+
17
+ /** 单次 stdout 上限:管线正常输出也就几十 KB,超过这个数说明出事了。 */
18
+ const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
19
+
20
+ /** 生成与 Python 侧同形的 error 信封,插件与模型看到的形状保持一致。 */
21
+ export function errorEnvelope(code, message, stage = 'bridge', detail = null, retryable = false) {
22
+ return {
23
+ kind: 'error',
24
+ contract_version: CONTRACT_VERSION,
25
+ bridge_version: BRIDGE_VERSION,
26
+ error: {
27
+ code,
28
+ message,
29
+ stage,
30
+ retryable: retryable === true,
31
+ detail: detail === null || detail === undefined ? null : String(detail).slice(0, 2000),
32
+ },
33
+ }
34
+ }
35
+
36
+ function tail(text, n = 600) {
37
+ const s = String(text ?? '')
38
+ return s.length <= n ? s : `…${s.slice(-n)}`
39
+ }
40
+
41
+ /**
42
+ * 跑一次 Bridge 命令。
43
+ *
44
+ * @returns {Promise<{ok:boolean, data:object|null, error:object|null, stderr:string, ms:number}>}
45
+ * ok=true 时 data 是管线返回的 JSON(可能是 context / verify / ping,也可能是 Python 侧的 error 信封)
46
+ */
47
+ export function runBridge({
48
+ command,
49
+ payload,
50
+ python = 'python',
51
+ toolsRoot = '',
52
+ timeoutMs = 120000,
53
+ pluginVersion = 'unknown',
54
+ env = {},
55
+ } = {}) {
56
+ const started = Date.now()
57
+
58
+ if (!toolsRoot) {
59
+ return Promise.resolve({
60
+ ok: false,
61
+ data: null,
62
+ stderr: '',
63
+ ms: 0,
64
+ error: errorEnvelope('E_PYTHON_UNAVAILABLE',
65
+ '还没配置工具目录(Python 管线所在文件夹)。请在插件配置里填 bridge.toolsRoot。',
66
+ 'bridge'),
67
+ })
68
+ }
69
+
70
+ const script = path.join(toolsRoot, 'wiki_bridge.py')
71
+ const body = JSON.stringify({ ...(payload ?? {}), plugin_version: pluginVersion })
72
+ const pythonExe = python || 'python'
73
+
74
+ return new Promise((resolve) => {
75
+ let child
76
+ try {
77
+ child = spawn(pythonExe, [script, command], {
78
+ cwd: toolsRoot,
79
+ windowsHide: true,
80
+ env: {
81
+ ...process.env,
82
+ PYTHONIOENCODING: 'utf-8',
83
+ PYTHONUTF8: '1',
84
+ WIKI_PLUGIN_VERSION: pluginVersion,
85
+ ...env,
86
+ },
87
+ stdio: ['pipe', 'pipe', 'pipe'],
88
+ })
89
+ } catch (error) {
90
+ resolve({
91
+ ok: false, data: null, stderr: '', ms: Date.now() - started,
92
+ error: errorEnvelope('E_BRIDGE_SPAWN_FAILED', '起不了 Python 进程',
93
+ 'bridge', error?.message ?? error),
94
+ })
95
+ return
96
+ }
97
+
98
+ const out = []
99
+ const err = []
100
+ let outBytes = 0
101
+ let settled = false
102
+ let timer = null
103
+
104
+ const finish = (result) => {
105
+ if (settled) return
106
+ settled = true
107
+ if (timer) clearTimeout(timer)
108
+ resolve({ ...result, ms: Date.now() - started })
109
+ }
110
+
111
+ timer = setTimeout(() => {
112
+ try {
113
+ child.kill()
114
+ } catch {
115
+ // 已经退了就算了
116
+ }
117
+ finish({
118
+ ok: false, data: null, stderr: err.join(''),
119
+ error: errorEnvelope('E_BRIDGE_TIMEOUT',
120
+ `Python 管线超过 ${timeoutMs}ms 没回话(检索本身可能很慢,可以先调大 bridge.timeoutMs)`,
121
+ 'bridge', tail(err.join('')), true),
122
+ })
123
+ }, Math.max(1000, Number(timeoutMs) || 120000))
124
+
125
+ child.on('error', (error) => {
126
+ // ENOENT = 这台机器上没这个 python;其它算起进程失败
127
+ const notFound = error?.code === 'ENOENT'
128
+ finish({
129
+ ok: false, data: null, stderr: err.join(''),
130
+ error: errorEnvelope(
131
+ notFound ? 'E_PYTHON_UNAVAILABLE' : 'E_BRIDGE_SPAWN_FAILED',
132
+ notFound
133
+ ? `找不到 Python 解释器「${pythonExe}」。请在插件配置里填 bridge.python 的绝对路径。`
134
+ : '起不了 Python 进程',
135
+ 'bridge', error?.message ?? error, notFound),
136
+ })
137
+ })
138
+
139
+ child.stdout.on('data', (chunk) => {
140
+ outBytes += chunk.length
141
+ if (outBytes > MAX_OUTPUT_BYTES) {
142
+ try {
143
+ child.kill()
144
+ } catch {
145
+ // 同上
146
+ }
147
+ finish({
148
+ ok: false, data: null, stderr: err.join(''),
149
+ error: errorEnvelope('E_BRIDGE_CRASH', 'Python 输出超过上限,已中止', 'bridge'),
150
+ })
151
+ return
152
+ }
153
+ out.push(chunk)
154
+ })
155
+
156
+ child.stderr.on('data', (chunk) => {
157
+ // 诊断只留最后一段,够定位就行,不要把它灌给模型
158
+ err.push(chunk.toString('utf8'))
159
+ if (err.join('').length > 20000) err.splice(0, err.length - 8)
160
+ })
161
+
162
+ child.on('close', (code) => {
163
+ const stdout = Buffer.concat(out).toString('utf8').trim()
164
+ const stderr = err.join('')
165
+
166
+ if (stdout === '') {
167
+ finish({
168
+ ok: false, data: null, stderr,
169
+ error: errorEnvelope('E_BRIDGE_CRASH',
170
+ `Python 没有输出(退出码 ${code})`, 'bridge', tail(stderr)),
171
+ })
172
+ return
173
+ }
174
+
175
+ // stdout 只应有一行 JSON;万一有杂音,取最后一行能解析的
176
+ let parsed = null
177
+ let parseError = null
178
+ const lines = stdout.split(/\r?\n/).filter((line) => line.trim() !== '')
179
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
180
+ try {
181
+ parsed = JSON.parse(lines[i])
182
+ break
183
+ } catch (error) {
184
+ parseError = error
185
+ }
186
+ }
187
+
188
+ if (parsed === null || typeof parsed !== 'object') {
189
+ finish({
190
+ ok: false, data: null, stderr,
191
+ error: errorEnvelope('E_BRIDGE_BAD_JSON', 'Python 输出不是合法 JSON',
192
+ 'bridge', `${parseError?.message ?? ''} | ${tail(stdout, 300)}`),
193
+ })
194
+ return
195
+ }
196
+
197
+ finish({ ok: true, data: parsed, stderr, error: null })
198
+ })
199
+
200
+ try {
201
+ child.stdin.end(body, 'utf8')
202
+ } catch (error) {
203
+ finish({
204
+ ok: false, data: null, stderr: err.join(''),
205
+ error: errorEnvelope('E_BRIDGE_CRASH', '写不进 Python 的 stdin',
206
+ 'bridge', error?.message ?? error),
207
+ })
208
+ }
209
+ })
210
+ }
package/lib/client.js CHANGED
@@ -582,7 +582,7 @@ window.__ModuleLoader__.load({
582
582
  value: draft,
583
583
  spellCheck: false,
584
584
  'aria-label': '知识库目录路径',
585
- placeholder: '例如 D:\\笔记\\我的知识库 或 /home/me/notes',
585
+ placeholder: '例如 /home/me/notes 或 <你的库根目录>\\知识层-wiki',
586
586
  onChange: function (event) {
587
587
  setDraft(event.target.value)
588
588
  // 换了路径,上一次「扫不出页面」的结论就不再指同一个东西了。
package/lib/config.js CHANGED
@@ -210,3 +210,62 @@ export function writePromptConfig(pluginRoot, next) {
210
210
  record.prompt = clean
211
211
  return { file: writeRecord(pluginRoot, record), config: clean }
212
212
  }
213
+
214
+ /* ------------------- 知识网关:Python Bridge 的那一行 ------------------- */
215
+
216
+ /**
217
+ * Bridge 配置。
218
+ *
219
+ * toolsRoot 是「Python 管线所在目录」(里面要有 wiki_bridge.py)。
220
+ * 故意不给内置默认值:猜错目录比没配更糟 —— 猜错时插件会起一个
221
+ * 根本不存在的脚本,报出来的错还像是库坏了。留空就明确说「没配」。
222
+ *
223
+ * python 留空表示用 PATH 里的 `python`;Windows 上多版本共存时建议填绝对路径。
224
+ * timeoutMs 默认 120s:本机实测一次 context 约 10–25 秒,留足余量但不至于挂死。
225
+ */
226
+ export const DEFAULT_BRIDGE_CONFIG = {
227
+ python: '',
228
+ toolsRoot: '',
229
+ observeLog: '',
230
+ timeoutMs: 120000,
231
+ ttlSeconds: 1800,
232
+ }
233
+
234
+ /** 把任意输入规整成 Bridge 配置:缺字段补默认,数字夹在合理区间。 */
235
+ export function normalizeBridgeConfig(raw) {
236
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
237
+ const num = (v, def, min, max) => {
238
+ const n = Number(v)
239
+ if (!Number.isFinite(n)) return def
240
+ return Math.max(min, Math.min(Math.trunc(n), max))
241
+ }
242
+ return {
243
+ python: typeof raw.python === 'string' ? raw.python.trim() : '',
244
+ toolsRoot: typeof raw.toolsRoot === 'string' ? raw.toolsRoot.trim() : '',
245
+ observeLog: typeof raw.observeLog === 'string' ? raw.observeLog.trim() : '',
246
+ timeoutMs: num(raw.timeoutMs, DEFAULT_BRIDGE_CONFIG.timeoutMs, 5000, 600000),
247
+ ttlSeconds: num(raw.ttlSeconds, DEFAULT_BRIDGE_CONFIG.ttlSeconds, 60, 86400),
248
+ }
249
+ }
250
+
251
+ /** 读 Bridge 配置。环境变量能盖过文件(方便临时换 python)。 */
252
+ export function readBridgeConfig(pluginRoot) {
253
+ const base = normalizeBridgeConfig(readRecord(pluginRoot).bridge) ?? { ...DEFAULT_BRIDGE_CONFIG }
254
+ const envRoot = typeof process.env.DSH_WIKI_TOOLS === 'string' ? process.env.DSH_WIKI_TOOLS.trim() : ''
255
+ const envPython = typeof process.env.DSH_WIKI_PYTHON === 'string' ? process.env.DSH_WIKI_PYTHON.trim() : ''
256
+ const envObserve = typeof process.env.DSH_WIKI_OBSERVE_LOG === 'string' ? process.env.DSH_WIKI_OBSERVE_LOG.trim() : ''
257
+ return {
258
+ ...base,
259
+ toolsRoot: envRoot || base.toolsRoot,
260
+ python: envPython || base.python,
261
+ observeLog: envObserve || base.observeLog,
262
+ }
263
+ }
264
+
265
+ /** 写 Bridge 配置。整块替换 `bridge` 字段,其余字段原样保留。 */
266
+ export function writeBridgeConfig(pluginRoot, next) {
267
+ const record = readRecord(pluginRoot)
268
+ const clean = normalizeBridgeConfig(next) ?? { ...DEFAULT_BRIDGE_CONFIG }
269
+ record.bridge = clean
270
+ return { file: writeRecord(pluginRoot, record), config: clean }
271
+ }