@furongjun1999/dsh-memory 0.9.6 → 0.9.7

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 (216) hide show
  1. package/data/policy.json +38 -38
  2. package/docs/discipline/templates/spec.txt.tmpl +1 -1
  3. package/dsh/cordis.yml.example +139 -139
  4. package/lib/hooks.d.ts +19 -0
  5. package/lib/hooks.js +29 -6
  6. package/lib/index.js +11 -2
  7. package/lib/lib/hook_audit.js +38 -2
  8. package/lib/lib/prompt_safety.js +14 -3
  9. package/lib/tools.d.ts +7 -0
  10. package/lib/tools.js +22 -1
  11. package/md_cg/_guard_kit.py +121 -121
  12. package/md_cg/anchor.py +114 -114
  13. package/md_cg/audit.py +15 -2
  14. package/md_cg/chain.py +3 -2
  15. package/md_cg/config_registry_guard.py +487 -487
  16. package/md_cg/conformance.py +747 -747
  17. package/md_cg/consolidate.py +1793 -1793
  18. package/md_cg/crypto.py +794 -794
  19. package/md_cg/hyperedge.py +262 -262
  20. package/md_cg/interface_schema.py +146 -146
  21. package/md_cg/lifecycle.py +426 -426
  22. package/md_cg/mdcos.py +12 -8
  23. package/md_cg/predict.py +1103 -1103
  24. package/md_cg/protect.py +654 -654
  25. package/md_cg/provenance.py +606 -606
  26. package/md_cg/queue_health.py +130 -130
  27. package/md_cg/refine.py +613 -613
  28. package/md_cg/retrieve.py +128 -128
  29. package/md_cg/revise.py +140 -140
  30. package/md_cg/rollback.py +657 -657
  31. package/md_cg/rollback_cli.py +124 -124
  32. package/md_cg/rotate.py +346 -346
  33. package/md_cg/routing.py +490 -490
  34. package/md_cg/self_surface.py +50 -50
  35. package/md_cg/semantic/canonical.py +144 -144
  36. package/md_cg/semantic/zh_en_atoms.py +141 -141
  37. package/md_cg/sources.py +1091 -1091
  38. package/md_cg/stg.py +3 -2
  39. package/md_cg/test_audit_rotate_parity.py +279 -279
  40. package/md_cg/test_autonomy_modes.py +2013 -2013
  41. package/md_cg/test_cn_recall_grams.py +206 -206
  42. package/md_cg/test_code_kind_forbidden.py +101 -0
  43. package/md_cg/test_condaccept.py +156 -156
  44. package/md_cg/test_condgate.py +141 -141
  45. package/md_cg/test_heartbeat_ledger.py +557 -557
  46. package/md_cg/test_i50e_readside_protection.py +658 -658
  47. package/md_cg/test_issue111_gate_order.py +76 -76
  48. package/md_cg/test_issue111_scoring_contract.py +86 -86
  49. package/md_cg/test_issue121_calibration_bounds.py +293 -293
  50. package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
  51. package/md_cg/test_issue147_pack_id_escape.py +378 -378
  52. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
  53. package/md_cg/test_issue149_accel_default_face.py +248 -248
  54. package/md_cg/test_issue150_empty_query_terms.py +328 -328
  55. package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
  56. package/md_cg/test_issue152_sealed_postings.py +309 -309
  57. package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
  58. package/md_cg/test_issue157b_index_remainder.py +344 -344
  59. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
  60. package/md_cg/test_issue191_import_trust.py +382 -382
  61. package/md_cg/test_issue193_write_scope.py +378 -378
  62. package/md_cg/test_issue212_writeface_gaps.py +349 -349
  63. package/md_cg/test_issue214_reject_sensitivity.py +266 -266
  64. package/md_cg/test_issue215_condition_source_gap.py +272 -272
  65. package/md_cg/test_issue216_clash_routes.py +214 -214
  66. package/md_cg/test_issue217_slot_routes.py +248 -248
  67. package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
  68. package/md_cg/test_issue258_pack_sensitivity.py +468 -468
  69. package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
  70. package/md_cg/test_issue274_read_node_id_none.py +341 -341
  71. package/md_cg/test_issue275_layer_param.py +250 -250
  72. package/md_cg/test_issue277_node_id_traversal.py +384 -384
  73. package/md_cg/test_issue278_neg_separated_tension.py +271 -271
  74. package/md_cg/test_issue278_neg_window.py +294 -294
  75. package/md_cg/test_issue278_negative_layering.py +83 -83
  76. package/md_cg/test_issue284_skip_not_pass.py +291 -291
  77. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
  78. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
  79. package/md_cg/test_issue303_design_boundaries.py +262 -262
  80. package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
  81. package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
  82. package/md_cg/test_issue321_mcp_deep_json.py +304 -304
  83. package/md_cg/test_issue322_node_write_lock.py +727 -727
  84. package/md_cg/test_issue324_write_size_fields.py +214 -214
  85. package/md_cg/test_issue325_audit_poison.py +229 -229
  86. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
  87. package/md_cg/test_issue326_key_perms.py +355 -355
  88. package/md_cg/test_issue326_twin_parser_parity.py +323 -323
  89. package/md_cg/test_issue326_vm_call_frame.py +569 -569
  90. package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
  91. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
  92. package/md_cg/test_issue348_insight_verify_op.py +199 -199
  93. package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
  94. package/md_cg/test_issue350_casefold_collision.py +235 -235
  95. package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
  96. package/md_cg/test_issue352_imgaudit.py +418 -418
  97. package/md_cg/test_issue352_pathsjson.py +537 -537
  98. package/md_cg/test_issue352_refindex.py +412 -412
  99. package/md_cg/test_issue352_rollback.py +604 -604
  100. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
  101. package/md_cg/test_issue354_rust_index_containment.py +571 -571
  102. package/md_cg/test_issue354_rust_wal_containment.py +606 -606
  103. package/md_cg/test_issue358_truncation_observable.py +247 -247
  104. package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
  105. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
  106. package/md_cg/test_issue362_neg_condition.py +468 -468
  107. package/md_cg/test_issue363_lexical_idf.py +275 -275
  108. package/md_cg/test_issue370_readcache_assembly.py +488 -488
  109. package/md_cg/test_issue376_heartbeat_failed.py +293 -293
  110. package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
  111. package/md_cg/test_issue378_protected_floor.py +310 -310
  112. package/md_cg/test_issue383_state_event_write_gate.py +462 -462
  113. package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
  114. package/md_cg/test_issue398_toolface_op_parity.py +511 -511
  115. package/md_cg/test_issue399_hive_json_shape.py +317 -317
  116. package/md_cg/test_issue401_wisdom_codegen.py +295 -295
  117. package/md_cg/test_issue404_heal_receipt.py +389 -389
  118. package/md_cg/test_issue409_compact_index_completeness.py +509 -509
  119. package/md_cg/test_issue410_verify_demote_write.py +366 -366
  120. package/md_cg/test_issue411_scrub_idempotence.py +575 -575
  121. package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
  122. package/md_cg/test_issue413_preimage_failclosed.py +239 -239
  123. package/md_cg/test_issue413_preimage_twin.py +339 -339
  124. package/md_cg/test_issue415_deps_gate_probe.py +357 -357
  125. package/md_cg/test_issue416_entry_key_subset.py +525 -525
  126. package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
  127. package/md_cg/test_issue425_ingest_library_path.py +331 -331
  128. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
  129. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
  130. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
  131. package/md_cg/test_issue427_serve_status_shape.py +191 -191
  132. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
  133. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
  134. package/md_cg/test_issue434_435_float_gate.py +90 -90
  135. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
  136. package/md_cg/test_issue43_default_policy.py +874 -874
  137. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
  138. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
  139. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
  140. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
  141. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
  142. package/md_cg/test_issue451_audit_actor.py +313 -313
  143. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
  144. package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
  145. package/md_cg/test_issue466_basis_registry.py +469 -469
  146. package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
  147. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
  148. package/md_cg/test_issue470_wal_event_durable.py +427 -427
  149. package/md_cg/test_issue471_identity_readable.py +136 -136
  150. package/md_cg/test_issue472_audit_chain.py +90 -90
  151. package/md_cg/test_issue472_prune_ledger.py +105 -105
  152. package/md_cg/test_issue472_rollback_degraded.py +81 -81
  153. package/md_cg/test_issue491_compose_sandbox.py +460 -460
  154. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
  155. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
  156. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
  157. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
  158. package/md_cg/test_issue525_read_null_semantics.py +52 -52
  159. package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
  160. package/md_cg/test_issue547_audit_durable.py +96 -96
  161. package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
  162. package/md_cg/test_issue559_refine_prefix.py +69 -69
  163. package/md_cg/test_issue562_retired_faces.py +150 -0
  164. package/md_cg/test_issue71_queue_backlog.py +376 -376
  165. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
  166. package/md_cg/test_issue82_credential_rules.py +271 -271
  167. package/md_cg/test_issue91_verifier_sandbox.py +314 -314
  168. package/md_cg/test_issue93_remember_redaction.py +282 -282
  169. package/md_cg/test_logref.py +1141 -1141
  170. package/md_cg/test_md_access_parity.py +330 -330
  171. package/md_cg/test_md_cg_no_hive_dep.py +139 -139
  172. package/md_cg/test_mutation_residue.py +119 -119
  173. package/md_cg/test_mutation_rollback.py +835 -835
  174. package/md_cg/test_n123_derive_expiry_chain.py +210 -210
  175. package/md_cg/test_n209_verify_write_face_gates.py +466 -466
  176. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  177. package/md_cg/test_neg_tail_honesty.py +733 -733
  178. package/md_cg/test_p21_tokens.py +294 -294
  179. package/md_cg/test_p27_docindex.py +792 -792
  180. package/md_cg/test_p28_refcheck.py +1053 -1053
  181. package/md_cg/test_p2_six_elements.py +476 -476
  182. package/md_cg/test_p33_ccg_wiring.py +300 -300
  183. package/md_cg/test_p3_legacy_closure.py +438 -438
  184. package/md_cg/test_p40_refine_worklist.py +244 -244
  185. package/md_cg/test_p4_freshness.py +781 -781
  186. package/md_cg/test_p9c_dedup_hints.py +288 -288
  187. package/md_cg/test_policy_required_ccg.py +444 -444
  188. package/md_cg/test_retr_s5.py +312 -312
  189. package/md_cg/test_s1_ast_judge.py +109 -109
  190. package/md_cg/test_state_event_op.py +521 -521
  191. package/md_cg/test_stgidx_index_parity.py +1024 -1024
  192. package/md_cg/test_sustain_bounded.py +652 -652
  193. package/md_cg/test_trust_edge_reachability.py +405 -405
  194. package/md_cg/test_w7_redlines.py +659 -659
  195. package/md_cg/test_write_return_shape.py +919 -919
  196. package/md_cg/test_writepipe.py +228 -228
  197. package/md_cg/trust.py +1114 -1114
  198. package/md_cg/twophase.py +303 -303
  199. package/md_cg/whitebox.py +536 -536
  200. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
  201. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
  202. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
  203. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
  204. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
  205. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
  206. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
  207. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
  208. package/md_cg/writepipe.py +1337 -1337
  209. package/package.json +3 -2
  210. package/scripts/workspace_index.py +328 -0
  211. package/src/hooks.ts +30 -6
  212. package/src/index.ts +14 -5
  213. package/src/lib/hook_audit.ts +282 -256
  214. package/src/lib/mdcg_client.ts +469 -469
  215. package/src/lib/prompt_safety.ts +17 -3
  216. package/src/tools.ts +23 -1
package/md_cg/whitebox.py CHANGED
@@ -1,537 +1,537 @@
1
- # -*- coding: utf-8 -*-
2
- """md_cg · 白箱能力调用与验证(显式调用层)。
3
-
4
- 架构定位(2026-09-10 修订)
5
- --------------------------
6
- · md_cg = 记忆操作系统 / **唯一真源**:负责记忆的写、读、裁决、留痕。
7
- · 白箱知识库 = **随主仓自带**(`md_cg/whitebox_kb/`,原理论仓 `aeis/wisdom`
8
- 等内迁):不再需要外部 `aeis` 包,也不再需要跨库调用。
9
- · AEIS = **身体 / 世界模型库**:本层不再依赖它(自带内核中 vision / body /
10
- world_model 等均为方法内惰性导入,缺失即自动降级)。
11
-
12
- 为什么单独成层
13
- --------------
14
- 白箱需要一个可审计的调用入口。本模块是「md_cg 调用白箱」的**唯一显式入口**:
15
- · 调用方式:**进程内**直调自带引擎(默认,见 `LocalWhiteboxClient`);
16
- 仅当显式设置 `MDCG_WHITEBOX_CMD` / `MDCG_WHITEBOX_ARGS` 时,
17
- 才回退外部 MCP stdio 子进程(legacy 路径)。
18
- · 调用结果:验证结论写回认知图(self 层,tags 含 `whitebox:verify`),可追溯。
19
-
20
- 显式调用映射(详见 docs/mdcg/功能调用映射表_v0.1.md)
21
- ------------------------------------------------
22
- 功能 → 代码 → MCP
23
- 白箱问答 → md_cg.whitebox.ask → cg(op=whitebox, action=ask)
24
- 白箱编码 → md_cg.whitebox.remember → cg(op=whitebox, action=remember)
25
- 验证编码能力 → md_cg.whitebox.verify_encoding → cg(op=whitebox, action=verify_encoding)
26
- 验证已有知识回答能力 → md_cg.whitebox.verify_existing → cg(op=whitebox, action=verify_existing)
27
- 白箱能力验证报告 → md_cg.whitebox.report → cg(op=whitebox, action=report)
28
- 白箱连通性探测 → md_cg.whitebox.ping → cg(op=whitebox, action=ping)
29
-
30
- 环境变量
31
- --------
32
- WHITEBOX_DB / MDCG_WHITEBOX_DB 白箱图库路径
33
- (默认 MDCG_ROOT/data/whitebox/graph.db;
34
- 独立运行时落 ~/.md_cg/whitebox/graph.db,
35
- 首次以随包云库为底 + 卡源播种)
36
- MDCG_WHITEBOX_CMD 外部白箱启动命令(设置后走 legacy 子进程路径)
37
- MDCG_WHITEBOX_ARGS 外部白箱启动参数(同上,默认 "-m aeis.mcp.server")
38
- MDCG_WHITEBOX_TIMEOUT 子进程单次调用超时秒数(默认 60)
39
- """
40
-
41
- from __future__ import annotations
42
-
43
- import json
44
- import os
45
- import queue
46
- import subprocess
47
- import sys
48
- import threading
49
- import time
50
-
51
- PROTOCOL_VERSION = "2024-11-05"
52
- CLIENT_NAME = "md_cg-whitebox"
53
- VERIFY_TAG = "whitebox:verify"
54
-
55
- #: 已有知识回答能力的默认探针(白箱应能从自身知识库直接作答)。
56
- DEFAULT_KNOWLEDGE_PROBES = [
57
- "你是谁?请用一句话介绍你自己。",
58
- "什么是条件论?",
59
- ]
60
-
61
-
62
- # --------------------------------------------------------------------------
63
- # 启动命令
64
- # --------------------------------------------------------------------------
65
-
66
- # 生效条件:无必需形参;exe 取 MDCG_WHITEBOX_CMD,该值为假时取 sys.executable、再为假时取 "python",args 取 MDCG_WHITEBOX_ARGS.split()(该值为真时)否则 ["-m","aeis.mcp.server"],返回 [exe]+args。
67
- def _launch_cmd():
68
- """外部白箱 MCP server 启动命令(legacy 路径,需显式配置)。
69
-
70
- 主仓自带白箱知识库后,本路径**不再默认启用**(见 `WhiteboxClient` 工厂)。
71
- 默认参数 `-m aeis.mcp.server` 仅为兼容既有部署保留。
72
- """
73
- exe = os.environ.get("MDCG_WHITEBOX_CMD") or sys.executable or "python"
74
- raw = os.environ.get("MDCG_WHITEBOX_ARGS")
75
- args = raw.split() if raw else ["-m", "aeis.mcp.server"]
76
- return [exe] + args
77
-
78
-
79
- # --------------------------------------------------------------------------
80
- # 白箱 MCP stdio 客户端(零第三方依赖)
81
- # --------------------------------------------------------------------------
82
-
83
- # 生效条件:类无自定义 __init__(无必需构造形参);实例化后仅当子类覆写 call 时 ask/remember 才走通,否则 call 抛 NotImplementedError。
84
- class _WhiteboxApi:
85
- """白箱业务接口(`ask` / `remember`)。
86
-
87
- 两种载体共享同一实现,保证行为**按构造方式一致**(验证结论不受载体影响):
88
- · `LocalWhiteboxClient` —— 进程内直调自带引擎(默认)
89
- · `_SubprocessWhiteboxClient` —— MCP stdio 子进程(legacy,显式配置时)
90
- """
91
-
92
- # 生效条件:以 required 形参 name 与 args 调用该抽象方法时无条件抛出 NotImplementedError,不产生任何返回。
93
- def call(self, name, args):
94
- """调用白箱工具,返回 {isError, text, data}。"""
95
- raise NotImplementedError
96
-
97
- # 生效条件:给定 required 形参 message(session_id 省略时取默认 "md_cg-whitebox-verify")即转调 self.call("wisdom_chat", {...}),按返回 r 组装 {ok: not r["isError"], route: _extract_route(data), reply: _extract_reply(data, r.get("text")), raw},其中 data 由 r.get("data") or {} 得到(data 缺失或为假值时为 {}),故 raw 恒取该 data、不回落到 r.get("text")。
98
- def ask(self, message, session_id="md_cg-whitebox-verify"):
99
- """白箱问答(wisdom_chat)。返回归一化的 {ok, route, reply, raw}。"""
100
- r = self.call("wisdom_chat", {"message": message, "session_id": session_id})
101
- data = r.get("data") or {}
102
- return {"ok": not r["isError"],
103
- "route": _extract_route(data),
104
- "reply": _extract_reply(data, r.get("text")),
105
- "raw": data if data is not None else r.get("text")}
106
-
107
- # 生效条件:给定 required 形参 content(importance 省略时取 0.9 并 float() 转换;tags 为 None/[]/"" 等假值时按 tags or ["md_cg","whitebox-probe"] 回落为 list(["md_cg","whitebox-probe"]))即转调 self.call("remember", {...}),返回 {ok: not r["isError"], raw: r.get("data") or r.get("text")}。
108
- def remember(self, content, importance=0.9, tags=None):
109
- """白箱编码(remember):把一条知识交给白箱写入其记忆库。"""
110
- r = self.call("remember", {"content": content,
111
- "importance": float(importance),
112
- "tags": list(tags or ["md_cg", "whitebox-probe"])})
113
- return {"ok": not r["isError"], "raw": r.get("data") or r.get("text")}
114
-
115
-
116
- # 生效条件:以假值 cmd(None/空序列)构造时 self.cmd 取 _launch_cmd(),真值 cmd 时取 list(cmd);timeout 与 MDCG_WHITEBOX_TIMEOUT 环境变量都取假值时 self.timeout 为 float(60.0),否则取其中首个真值;env 为真值时按 str(v) 合并进 os.environ 副本,假值时 self.env 仅为 os.environ 副本。
117
- class _SubprocessWhiteboxClient(_WhiteboxApi):
118
- """外部白箱 MCP stdio 客户端(legacy 路径,需显式配置才启用)。
119
-
120
- 只做一件事:把 md_cg 的显式调用翻译成 MCP `tools/call`。
121
- 进程懒启动、调用串行化、超时即杀(下次调用自动重启)。
122
- """
123
-
124
- # 生效条件:cmd 为真值时 self.cmd=list(cmd),否则回落 _launch_cmd();timeout 为真值则直接用,否则回落 os.environ.get("MDCG_WHITEBOX_TIMEOUT"),再否则 60.0;env 为真值时其键值经 str() 合并进 os.environ 副本。
125
- def __init__(self, cmd=None, env=None, timeout=None):
126
- self.cmd = list(cmd) if cmd else _launch_cmd()
127
- self.timeout = float(timeout or os.environ.get("MDCG_WHITEBOX_TIMEOUT") or 60.0)
128
- self.env = dict(os.environ)
129
- if env:
130
- self.env.update({k: str(v) for k, v in env.items()})
131
- self.proc = None
132
- self._q = queue.Queue()
133
- self._next_id = 1
134
- self._lock = threading.Lock()
135
-
136
- # -- 生命周期 ---------------------------------------------------------
137
- # 生效条件:当 self.proc 非 None 且 self.proc.poll() 为 None 时直接返回 self;否则启动 self.cmd 子进程并以模块级常量 PROTOCOL_VERSION 与 CLIENT_NAME 发 initialize 请求和 notifications/initialized 通知后返回 self。
138
- def start(self):
139
- if self.proc is not None and self.proc.poll() is None:
140
- return self
141
- self.proc = subprocess.Popen(
142
- self.cmd,
143
- stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
144
- text=True, encoding="utf-8", errors="replace", bufsize=1, env=self.env)
145
- threading.Thread(target=self._reader, daemon=True).start()
146
- self._request("initialize", {
147
- "protocolVersion": PROTOCOL_VERSION,
148
- "capabilities": {},
149
- "clientInfo": {"name": CLIENT_NAME, "version": "0.1.0"},
150
- })
151
- self._notify("notifications/initialized", {})
152
- return self
153
-
154
- # 生效条件:幂等、可重复调用;self.proc 为 None 时直接返回;否则先关 stdin 再 terminate 并 wait(timeout=3),超时或异常则 kill 兜底;无返回值、不抛异常;
155
- def close(self):
156
- proc, self.proc = self.proc, None
157
- if proc is None:
158
- return
159
- try:
160
- if proc.stdin:
161
- proc.stdin.close()
162
- except Exception:
163
- pass
164
- try:
165
- proc.terminate()
166
- proc.wait(timeout=3)
167
- except Exception:
168
- try:
169
- proc.kill()
170
- except Exception:
171
- pass
172
-
173
- # -- 内部 IO ----------------------------------------------------------
174
- # 生效条件:self.proc 为 None 或 proc.stdout 为 None 时直接返回;否则逐行 strip 后跳过空行,非空行 json.loads 成功则放入 self._q,抛 ValueError 则跳过该行。
175
- def _reader(self):
176
- stream = self.proc.stdout if self.proc else None
177
- if stream is None:
178
- return
179
- for line in stream:
180
- line = line.strip()
181
- if not line:
182
- continue
183
- try:
184
- self._q.put(json.loads(line))
185
- except ValueError:
186
- continue
187
-
188
- # 生效条件:给定 required 形参 payload 时,若 self.proc is None 或 self.proc.poll() is not None 则抛 RuntimeError("白箱进程未运行(启动失败或已退出)"),否则把 json.dumps(payload, ensure_ascii=False) + "\n" 写入 self.proc.stdin 并 flush,无返回。
189
- def _write(self, payload):
190
- if self.proc is None or self.proc.poll() is not None:
191
- raise RuntimeError("白箱进程未运行(启动失败或已退出)")
192
- self.proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
193
- self.proc.stdin.flush()
194
-
195
- # 生效条件:给定 required 形参 method 与 params 时,以 {"jsonrpc": "2.0", "method": method, "params": params}(无 id)调用 self._write,自身无返回。
196
- def _notify(self, method, params):
197
- self._write({"jsonrpc": "2.0", "method": method, "params": params})
198
-
199
- # 生效条件:给定 required 形参 method 与 params 时在 self._lock 内取自增 id 并写入请求,随后循环取 self._q:remain <= 0 或 queue.Empty 时先 self.close() 再抛 TimeoutError,msg.get("id") 不等于 rid 时 continue,msg.get("error") 为真时抛 RuntimeError,id 匹配且无 error 时返回 msg.get("result")(缺 "result" 键返回 None)。
200
- def _request(self, method, params):
201
- with self._lock:
202
- rid = self._next_id
203
- self._next_id += 1
204
- self._write({"jsonrpc": "2.0", "id": rid, "method": method,
205
- "params": params})
206
- deadline = time.time() + self.timeout
207
- while True:
208
- remain = deadline - time.time()
209
- if remain <= 0:
210
- self.close()
211
- raise TimeoutError(f"白箱调用超时({self.timeout}s):{method}")
212
- try:
213
- msg = self._q.get(timeout=remain)
214
- except queue.Empty:
215
- self.close()
216
- raise TimeoutError(f"白箱调用超时({self.timeout}s):{method}")
217
- if msg.get("id") != rid:
218
- continue
219
- if msg.get("error"):
220
- raise RuntimeError(f"白箱返回错误:{msg['error']}")
221
- return msg.get("result")
222
-
223
- # -- 业务接口 ---------------------------------------------------------
224
- # 生效条件:给定 required 形参 name 与 args(args 为假值时按 {"name": name, "arguments": args or {}} 发空字典)即以 "tools/call" 发请求,把结果 content 中 type=="text" 的块文本拼接后 json.loads,失败(ValueError/TypeError)则 data=None,返回 {"isError": bool((result or {}).get("isError")), "text": text, "data": data}。
225
- def call(self, name, args):
226
- """调用白箱 MCP 工具,返回 {isError, text, data}。"""
227
- result = self._request("tools/call", {"name": name, "arguments": args or {}})
228
- text = ""
229
- for block in (result or {}).get("content", []) or []:
230
- if isinstance(block, dict) and block.get("type") == "text":
231
- text += block.get("text") or ""
232
- try:
233
- data = json.loads(text)
234
- except (ValueError, TypeError):
235
- data = None
236
- return {"isError": bool((result or {}).get("isError")),
237
- "text": text, "data": data}
238
-
239
- # --------------------------------------------------------------------------
240
- # 进程内白箱客户端(默认路径)+ 客户端工厂
241
- # --------------------------------------------------------------------------
242
-
243
- class LocalWhiteboxClient(_WhiteboxApi):
244
- """白箱**进程内**客户端(默认载体)。
245
-
246
- 白箱知识库已随主仓自带(`md_cg/whitebox_kb/`),直接调用其引擎:
247
- 无子进程、无 MCP、无理论仓依赖。接口与子进程版完全一致,
248
- 故 `ask / remember / ping / verify_*` 及其留痕逻辑无需任何改动。
249
- """
250
-
251
- # 生效条件:db_path 为 None 时由引擎按默认路径取库;_ignored 吞掉子进程版遗留形参以保持接口同形;构造只记录路径、不加载引擎(延迟到 self.engine 首次访问);
252
- def __init__(self, db_path=None, **_ignored):
253
- self.db_path = db_path
254
- self._engine = None
255
-
256
- @property
257
- # 生效条件:self._engine 为 None 时调用 _load_get_engine()(db_path=self.db_path) 创建并缓存后返回它,非 None 时直接返回缓存实例。
258
- def engine(self):
259
- if self._engine is None:
260
- self._engine = _load_get_engine()(db_path=self.db_path)
261
- return self._engine
262
-
263
- # -- 生命周期(与子进程版语义对齐:start 即确保可用,失败即抛) --------
264
- # 生效条件:先取 self.engine(首次访问才真正加载知识库)并调 service_info() 以确认可服务,不可用即抛;成功后返回 self,可重复调用;
265
- def start(self):
266
- _ = self.engine.service_info()
267
- return self
268
-
269
- # 生效条件:幂等;self._engine 为 None 时直接返回,否则关闭引擎并置 None(只释放句柄,不删除落盘数据);
270
- def close(self):
271
- if self._engine is not None:
272
- self._engine.close()
273
- self._engine = None
274
-
275
- # -- 业务接口 ---------------------------------------------------------
276
- # 生效条件:给定 required 形参 name 与 args 时直接转调 self.engine.call_tool(name, args) 并返回其结果,不做任何形参改写或校验。
277
- def call(self, name, args):
278
- """调用白箱工具,返回 {isError, text, data}(形状对齐 MCP)。"""
279
- return self.engine.call_tool(name, args)
280
-
281
-
282
- # 生效条件:无必需形参;包内 from .whitebox_kb.engine import get_engine 成功时返回它,ImportError 时改为 from whitebox_kb.engine import get_engine 并返回。
283
- def _load_get_engine():
284
- """兼容两种导入方式(包内 / 平铺)。"""
285
- try:
286
- from .whitebox_kb.engine import get_engine
287
- except ImportError: # pragma: no cover - 平铺运行场景
288
- from whitebox_kb.engine import get_engine
289
- return get_engine
290
-
291
-
292
- # 生效条件:cmd 或 env 为真,或 MDCG_WHITEBOX_CMD / MDCG_WHITEBOX_ARGS 为真时返回 _SubprocessWhiteboxClient(cmd=cmd, env=env, timeout=timeout),否则返回 LocalWhiteboxClient(db_path=db_path)。
293
- def WhiteboxClient(cmd=None, env=None, timeout=None, db_path=None):
294
- """白箱客户端工厂。
295
-
296
- 默认返回 `LocalWhiteboxClient`(进程内 · 随仓自带知识库)。
297
- 仅当显式给出 `cmd` / `env`,或设置了 `MDCG_WHITEBOX_CMD` /
298
- `MDCG_WHITEBOX_ARGS` 时,才返回 legacy 的外部 MCP 子进程客户端。
299
- """
300
- if cmd or env or os.environ.get("MDCG_WHITEBOX_CMD") \
301
- or os.environ.get("MDCG_WHITEBOX_ARGS"):
302
- return _SubprocessWhiteboxClient(cmd=cmd, env=env, timeout=timeout)
303
- return LocalWhiteboxClient(db_path=db_path)
304
-
305
-
306
- # --------------------------------------------------------------------------
307
- # 结果归一化
308
- # --------------------------------------------------------------------------
309
-
310
- # 生效条件:data 为 dict 时按 route、mode、path 顺序取首个非空 str 值返回,否则(含 data 非 dict、三键均无或均为空/非 str)返回 ""。
311
- def _extract_route(data):
312
- if isinstance(data, dict):
313
- for key in ("route", "mode", "path"):
314
- val = data.get(key)
315
- if isinstance(val, str) and val:
316
- return val
317
- return ""
318
-
319
-
320
- # 生效条件:data 为 dict 时先按 reply/answer/text/response/content/message 取首个 strip 后非空的 str 返回,再对 result、data 两键的 dict 值递归取非空结果,均无则返回 fallback or ""。
321
- def _extract_reply(data, fallback=""):
322
- if isinstance(data, dict):
323
- for key in ("reply", "answer", "text", "response", "content", "message"):
324
- val = data.get(key)
325
- if isinstance(val, str) and val.strip():
326
- return val
327
- for key in ("result", "data"):
328
- val = data.get(key)
329
- if isinstance(val, dict):
330
- nested = _extract_reply(val, "")
331
- if nested:
332
- return nested
333
- return fallback or ""
334
-
335
-
336
- # --------------------------------------------------------------------------
337
- # 验证:编码能力 / 已有知识回答能力
338
- # --------------------------------------------------------------------------
339
-
340
- # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;marker、fact、question 为假值时分别用带毫秒时间戳的默认口令、默认事实、默认追问,cg 仅传给 _record(cg 为 None 则 node_id 为 None,不自建 client),异常时返回 ok=False 并同样 _record。
341
- def verify_encoding(cg=None, client=None, marker=None, fact=None,
342
- question=None, session_id="md_cg-whitebox-verify"):
343
- """验证白箱「编码能力」。
344
-
345
- 步骤:remember 一条带唯一口令的事实 → 追问口令 → 命中即通过。
346
- """
347
- own = client is None
348
- cli = client or WhiteboxClient()
349
- marker = marker or ("白箱探针" + str(int(time.time() * 1000)))
350
- fact = fact or f"md_cg 白箱编码验证:本次口令是 {marker},请记住。"
351
- question = question or "请只回答刚才记住的口令本身,不要解释。"
352
- try:
353
- cli.start()
354
- enc = cli.remember(fact, importance=0.95, tags=["md_cg", "whitebox-probe"])
355
- ans = cli.ask(question, session_id=session_id)
356
- hit = marker in (ans.get("reply") or "")
357
- out = {"kind": "encoding", "ok": bool(enc["ok"] and hit),
358
- "marker": marker, "encoded": bool(enc["ok"]),
359
- "recalled": hit, "route": ans.get("route"),
360
- "reply": (ans.get("reply") or "")[:300]}
361
- out["node_id"] = _record(cg, "encoding", out["ok"], out)
362
- return out
363
- except Exception as exc: # 白箱不可用:如实记录失败,不抛断调用方
364
- out = {"kind": "encoding", "ok": False, "marker": marker,
365
- "error": f"{type(exc).__name__}: {exc}"}
366
- out["node_id"] = _record(cg, "encoding", False, out)
367
- return out
368
- finally:
369
- if own:
370
- cli.close()
371
-
372
-
373
- # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;questions 为假值(None 或空)时用 DEFAULT_KNOWLEDGE_PROBES,逐问后仅当至少一问 reply 非空且 route 为 self 或 self_fallback 时 ok=True,异常返回 ok=False。
374
- def verify_existing(cg=None, client=None, questions=None,
375
- session_id="md_cg-whitebox-verify"):
376
- """验证白箱「已有知识回答能力」。
377
-
378
- 步骤:问白箱本应已知的问题 → route=self 且回答非空即通过(至少一问命中)。
379
- """
380
- own = client is None
381
- cli = client or WhiteboxClient()
382
- questions = list(questions or DEFAULT_KNOWLEDGE_PROBES)
383
- try:
384
- cli.start()
385
- probes = []
386
- for q in questions:
387
- ans = cli.ask(q, session_id=session_id)
388
- route = ans.get("route") or ""
389
- reply = ans.get("reply") or ""
390
- probes.append({"question": q, "route": route,
391
- "answered": bool(reply.strip()),
392
- "self_route": route in ("self", "self_fallback"),
393
- "reply": reply[:300]})
394
- ok = any(p["answered"] and p["self_route"] for p in probes)
395
- out = {"kind": "existing_knowledge", "ok": ok, "probes": probes}
396
- out["node_id"] = _record(cg, "existing_knowledge", ok, out)
397
- return out
398
- except Exception as exc:
399
- out = {"kind": "existing_knowledge", "ok": False,
400
- "error": f"{type(exc).__name__}: {exc}"}
401
- out["node_id"] = _record(cg, "existing_knowledge", False, out)
402
- return out
403
- finally:
404
- if own:
405
- cli.close()
406
-
407
-
408
- # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;依次对 service_info、mdcg_service_info、info 调用 call,首个 isError 为假即返回 ok=True 与该 tool/info,全部不可用返回 ok=False,start 或整体异常返回 ok=False。
409
- def ping(client=None, session_id="md_cg-whitebox-ping"):
410
- """白箱连通性探测:调 service_info(或 info)判断能力库是否在线。"""
411
- own = client is None
412
- cli = client or WhiteboxClient()
413
- try:
414
- cli.start()
415
- for name in ("service_info", "mdcg_service_info", "info"):
416
- try:
417
- r = cli.call(name, {})
418
- if not r["isError"]:
419
- return {"ok": True, "tool": name,
420
- "info": r.get("data") or r.get("text")}
421
- except Exception:
422
- continue
423
- return {"ok": False, "error": "白箱在线但未找到 service_info/info 工具"}
424
- except Exception as exc:
425
- return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
426
- finally:
427
- if own:
428
- cli.close()
429
-
430
-
431
- # 生效条件:client 为 None 时以 WhiteboxClient(timeout=kw.get("timeout")) 自建并在 finally 关闭;随后 cli.start() 并返回 cli.ask(message, session_id=session_id)。
432
- def ask(message, session_id="md_cg-whitebox-verify", client=None, **kw):
433
- """显式调用白箱回答一个问题。"""
434
- own = client is None
435
- cli = client or WhiteboxClient(timeout=kw.get("timeout"))
436
- try:
437
- cli.start()
438
- return cli.ask(message, session_id=session_id)
439
- finally:
440
- if own:
441
- cli.close()
442
-
443
-
444
- # 生效条件:client 为 None 时以 WhiteboxClient(timeout=kw.get("timeout")) 自建并在 finally 关闭;随后 cli.start() 并返回 cli.remember(content, importance=importance, tags=tags)。
445
- def remember(content, importance=0.9, tags=None, client=None, **kw):
446
- """显式调用白箱编码一条知识。"""
447
- own = client is None
448
- cli = client or WhiteboxClient(timeout=kw.get("timeout"))
449
- try:
450
- cli.start()
451
- return cli.remember(content, importance=importance, tags=tags)
452
- finally:
453
- if own:
454
- cli.close()
455
-
456
-
457
- # --------------------------------------------------------------------------
458
- # 留痕与报告
459
- # --------------------------------------------------------------------------
460
-
461
- # 生效条件:cg 为 None 时返回 None;否则以 whitebox_verify_{kind}_{毫秒时间戳} 为 id 调 cg.add 写入 self 层,成功返回该 nid,cg.add 抛异常时返回 None。
462
- def _record(cg, kind, ok, payload):
463
- """把验证结论写入认知图(self 层)。失败不阻断验证本身。"""
464
- if cg is None:
465
- return None
466
- nid = f"whitebox_verify_{kind}_{int(time.time() * 1000)}"
467
- body = json.dumps(payload, ensure_ascii=False, default=str)[:1800]
468
- try:
469
- # 2026-10-18:补条件空间四维——此前只有 time_window(autofill),
470
- # 三条 whitebox_verify_* 因此判 legacy_blindspot。
471
- # 同样是"自述产生过程"而非内容推断:它确实是系统自验、用该验证器、
472
- # 在"验证已执行且库可写"的前提下产生的记录。
473
- cg.add(nid, f"[白箱能力验证·{kind}] ok={ok} {body}",
474
- layer="self", tags=[VERIFY_TAG, f"whitebox:{kind}"],
475
- condition_space={
476
- "observation_position": "self:lingshu",
477
- "observation_tool": "whitebox.verify_%s" % kind,
478
- "existence_constraint": "库内可写且验证已执行",
479
- },
480
- importance=0.6, verification_basis="test",
481
- consistency=False)
482
- return nid
483
- except Exception:
484
- return None
485
-
486
-
487
- # 生效条件:cg 为 None 时返回 {'ok': False, 'error': '需要 cg 实例'};否则以 k=int(limit or 20)(limit 为 0/空串/None 时 k 变 20)调 cg.search("白箱能力验证", layer="self", record=False),只保留 tags 中任一以 "whitebox:" 开头的项并返回 count 与 items。
488
- def report(cg=None, limit=20):
489
- """汇总最近的「白箱能力验证」留痕。"""
490
- if cg is None:
491
- return {"ok": False, "error": "需要 cg 实例"}
492
- res, _meta = cg.search("白箱能力验证", layer="self",
493
- k=int(limit or 20), record=False)
494
- items = []
495
- for node, score, _q in res:
496
- fm = node.get("frontmatter") or {}
497
- tags = fm.get("tags") or []
498
- if not any(isinstance(t, str) and t.startswith("whitebox:") for t in tags):
499
- continue
500
- items.append({"id": node.get("id"), "score": score, "tags": tags,
501
- "content": (node.get("content") or "")[:800]})
502
- return {"ok": True, "count": len(items), "items": items}
503
-
504
-
505
- # --------------------------------------------------------------------------
506
- # MCP 统一入口(由 mcp_server._whitebox_call 调用)
507
- # --------------------------------------------------------------------------
508
-
509
- # 生效条件:action=(args.action or "ping") 小写后,ask/chat/query 走 ask(question/message/query 均假则传 ""),remember/encode/write 走 remember 且 importance=float(a.get("importance", 0.9)),verify_encoding/encoding 走 verify_encoding,verify_existing/existing/knowledge 走 verify_existing(questions 取 a.questions 或 a.question 单元素列表),report/history 走 report(limit=int(a.get("limit") or 20)),ping/status/info 走 ping(),其余抛 ValueError。
510
- def dispatch(cg, args):
511
- """cg(op=whitebox) 的分发:action=ask|remember|verify_encoding|verify_existing|ping|report。"""
512
- a = args or {}
513
- action = (a.get("action") or "ping").strip().lower()
514
- if action in ("ask", "chat", "query"):
515
- return ask(a.get("question") or a.get("message") or a.get("query") or "",
516
- session_id=a.get("session_id") or "md_cg-whitebox-verify")
517
- if action in ("remember", "encode", "write"):
518
- return remember(a.get("content") or a.get("text") or "",
519
- importance=float(a.get("importance", 0.9)),
520
- tags=a.get("tags"))
521
- if action in ("verify_encoding", "encoding"):
522
- return verify_encoding(cg, marker=a.get("marker"), fact=a.get("fact"),
523
- question=a.get("question"),
524
- session_id=a.get("session_id") or "md_cg-whitebox-verify")
525
- if action in ("verify_existing", "existing", "knowledge"):
526
- qs = a.get("questions") or ([a["question"]] if a.get("question") else None)
527
- return verify_existing(cg, questions=qs,
528
- session_id=a.get("session_id") or "md_cg-whitebox-verify")
529
- if action in ("report", "history"):
530
- return report(cg, limit=int(a.get("limit") or 20))
531
- if action in ("ping", "status", "info"):
532
- return ping()
533
- raise ValueError(f"whitebox 未知 action:{action}")
534
-
535
-
536
- if __name__ == "__main__": # 手动自检:python -m md_cg.whitebox
1
+ # -*- coding: utf-8 -*-
2
+ """md_cg · 白箱能力调用与验证(显式调用层)。
3
+
4
+ 架构定位(2026-09-10 修订)
5
+ --------------------------
6
+ · md_cg = 记忆操作系统 / **唯一真源**:负责记忆的写、读、裁决、留痕。
7
+ · 白箱知识库 = **随主仓自带**(`md_cg/whitebox_kb/`,原理论仓 `aeis/wisdom`
8
+ 等内迁):不再需要外部 `aeis` 包,也不再需要跨库调用。
9
+ · AEIS = **身体 / 世界模型库**:本层不再依赖它(自带内核中 vision / body /
10
+ world_model 等均为方法内惰性导入,缺失即自动降级)。
11
+
12
+ 为什么单独成层
13
+ --------------
14
+ 白箱需要一个可审计的调用入口。本模块是「md_cg 调用白箱」的**唯一显式入口**:
15
+ · 调用方式:**进程内**直调自带引擎(默认,见 `LocalWhiteboxClient`);
16
+ 仅当显式设置 `MDCG_WHITEBOX_CMD` / `MDCG_WHITEBOX_ARGS` 时,
17
+ 才回退外部 MCP stdio 子进程(legacy 路径)。
18
+ · 调用结果:验证结论写回认知图(self 层,tags 含 `whitebox:verify`),可追溯。
19
+
20
+ 显式调用映射(详见 docs/mdcg/功能调用映射表_v0.1.md)
21
+ ------------------------------------------------
22
+ 功能 → 代码 → MCP
23
+ 白箱问答 → md_cg.whitebox.ask → cg(op=whitebox, action=ask)
24
+ 白箱编码 → md_cg.whitebox.remember → cg(op=whitebox, action=remember)
25
+ 验证编码能力 → md_cg.whitebox.verify_encoding → cg(op=whitebox, action=verify_encoding)
26
+ 验证已有知识回答能力 → md_cg.whitebox.verify_existing → cg(op=whitebox, action=verify_existing)
27
+ 白箱能力验证报告 → md_cg.whitebox.report → cg(op=whitebox, action=report)
28
+ 白箱连通性探测 → md_cg.whitebox.ping → cg(op=whitebox, action=ping)
29
+
30
+ 环境变量
31
+ --------
32
+ WHITEBOX_DB / MDCG_WHITEBOX_DB 白箱图库路径
33
+ (默认 MDCG_ROOT/data/whitebox/graph.db;
34
+ 独立运行时落 ~/.md_cg/whitebox/graph.db,
35
+ 首次以随包云库为底 + 卡源播种)
36
+ MDCG_WHITEBOX_CMD 外部白箱启动命令(设置后走 legacy 子进程路径)
37
+ MDCG_WHITEBOX_ARGS 外部白箱启动参数(同上,默认 "-m aeis.mcp.server")
38
+ MDCG_WHITEBOX_TIMEOUT 子进程单次调用超时秒数(默认 60)
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import os
45
+ import queue
46
+ import subprocess
47
+ import sys
48
+ import threading
49
+ import time
50
+
51
+ PROTOCOL_VERSION = "2024-11-05"
52
+ CLIENT_NAME = "md_cg-whitebox"
53
+ VERIFY_TAG = "whitebox:verify"
54
+
55
+ #: 已有知识回答能力的默认探针(白箱应能从自身知识库直接作答)。
56
+ DEFAULT_KNOWLEDGE_PROBES = [
57
+ "你是谁?请用一句话介绍你自己。",
58
+ "什么是条件论?",
59
+ ]
60
+
61
+
62
+ # --------------------------------------------------------------------------
63
+ # 启动命令
64
+ # --------------------------------------------------------------------------
65
+
66
+ # 生效条件:无必需形参;exe 取 MDCG_WHITEBOX_CMD,该值为假时取 sys.executable、再为假时取 "python",args 取 MDCG_WHITEBOX_ARGS.split()(该值为真时)否则 ["-m","aeis.mcp.server"],返回 [exe]+args。
67
+ def _launch_cmd():
68
+ """外部白箱 MCP server 启动命令(legacy 路径,需显式配置)。
69
+
70
+ 主仓自带白箱知识库后,本路径**不再默认启用**(见 `WhiteboxClient` 工厂)。
71
+ 默认参数 `-m aeis.mcp.server` 仅为兼容既有部署保留。
72
+ """
73
+ exe = os.environ.get("MDCG_WHITEBOX_CMD") or sys.executable or "python"
74
+ raw = os.environ.get("MDCG_WHITEBOX_ARGS")
75
+ args = raw.split() if raw else ["-m", "aeis.mcp.server"]
76
+ return [exe] + args
77
+
78
+
79
+ # --------------------------------------------------------------------------
80
+ # 白箱 MCP stdio 客户端(零第三方依赖)
81
+ # --------------------------------------------------------------------------
82
+
83
+ # 生效条件:类无自定义 __init__(无必需构造形参);实例化后仅当子类覆写 call 时 ask/remember 才走通,否则 call 抛 NotImplementedError。
84
+ class _WhiteboxApi:
85
+ """白箱业务接口(`ask` / `remember`)。
86
+
87
+ 两种载体共享同一实现,保证行为**按构造方式一致**(验证结论不受载体影响):
88
+ · `LocalWhiteboxClient` —— 进程内直调自带引擎(默认)
89
+ · `_SubprocessWhiteboxClient` —— MCP stdio 子进程(legacy,显式配置时)
90
+ """
91
+
92
+ # 生效条件:以 required 形参 name 与 args 调用该抽象方法时无条件抛出 NotImplementedError,不产生任何返回。
93
+ def call(self, name, args):
94
+ """调用白箱工具,返回 {isError, text, data}。"""
95
+ raise NotImplementedError
96
+
97
+ # 生效条件:给定 required 形参 message(session_id 省略时取默认 "md_cg-whitebox-verify")即转调 self.call("wisdom_chat", {...}),按返回 r 组装 {ok: not r["isError"], route: _extract_route(data), reply: _extract_reply(data, r.get("text")), raw},其中 data 由 r.get("data") or {} 得到(data 缺失或为假值时为 {}),故 raw 恒取该 data、不回落到 r.get("text")。
98
+ def ask(self, message, session_id="md_cg-whitebox-verify"):
99
+ """白箱问答(wisdom_chat)。返回归一化的 {ok, route, reply, raw}。"""
100
+ r = self.call("wisdom_chat", {"message": message, "session_id": session_id})
101
+ data = r.get("data") or {}
102
+ return {"ok": not r["isError"],
103
+ "route": _extract_route(data),
104
+ "reply": _extract_reply(data, r.get("text")),
105
+ "raw": data if data is not None else r.get("text")}
106
+
107
+ # 生效条件:给定 required 形参 content(importance 省略时取 0.9 并 float() 转换;tags 为 None/[]/"" 等假值时按 tags or ["md_cg","whitebox-probe"] 回落为 list(["md_cg","whitebox-probe"]))即转调 self.call("remember", {...}),返回 {ok: not r["isError"], raw: r.get("data") or r.get("text")}。
108
+ def remember(self, content, importance=0.9, tags=None):
109
+ """白箱编码(remember):把一条知识交给白箱写入其记忆库。"""
110
+ r = self.call("remember", {"content": content,
111
+ "importance": float(importance),
112
+ "tags": list(tags or ["md_cg", "whitebox-probe"])})
113
+ return {"ok": not r["isError"], "raw": r.get("data") or r.get("text")}
114
+
115
+
116
+ # 生效条件:以假值 cmd(None/空序列)构造时 self.cmd 取 _launch_cmd(),真值 cmd 时取 list(cmd);timeout 与 MDCG_WHITEBOX_TIMEOUT 环境变量都取假值时 self.timeout 为 float(60.0),否则取其中首个真值;env 为真值时按 str(v) 合并进 os.environ 副本,假值时 self.env 仅为 os.environ 副本。
117
+ class _SubprocessWhiteboxClient(_WhiteboxApi):
118
+ """外部白箱 MCP stdio 客户端(legacy 路径,需显式配置才启用)。
119
+
120
+ 只做一件事:把 md_cg 的显式调用翻译成 MCP `tools/call`。
121
+ 进程懒启动、调用串行化、超时即杀(下次调用自动重启)。
122
+ """
123
+
124
+ # 生效条件:cmd 为真值时 self.cmd=list(cmd),否则回落 _launch_cmd();timeout 为真值则直接用,否则回落 os.environ.get("MDCG_WHITEBOX_TIMEOUT"),再否则 60.0;env 为真值时其键值经 str() 合并进 os.environ 副本。
125
+ def __init__(self, cmd=None, env=None, timeout=None):
126
+ self.cmd = list(cmd) if cmd else _launch_cmd()
127
+ self.timeout = float(timeout or os.environ.get("MDCG_WHITEBOX_TIMEOUT") or 60.0)
128
+ self.env = dict(os.environ)
129
+ if env:
130
+ self.env.update({k: str(v) for k, v in env.items()})
131
+ self.proc = None
132
+ self._q = queue.Queue()
133
+ self._next_id = 1
134
+ self._lock = threading.Lock()
135
+
136
+ # -- 生命周期 ---------------------------------------------------------
137
+ # 生效条件:当 self.proc 非 None 且 self.proc.poll() 为 None 时直接返回 self;否则启动 self.cmd 子进程并以模块级常量 PROTOCOL_VERSION 与 CLIENT_NAME 发 initialize 请求和 notifications/initialized 通知后返回 self。
138
+ def start(self):
139
+ if self.proc is not None and self.proc.poll() is None:
140
+ return self
141
+ self.proc = subprocess.Popen(
142
+ self.cmd,
143
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
144
+ text=True, encoding="utf-8", errors="replace", bufsize=1, env=self.env)
145
+ threading.Thread(target=self._reader, daemon=True).start()
146
+ self._request("initialize", {
147
+ "protocolVersion": PROTOCOL_VERSION,
148
+ "capabilities": {},
149
+ "clientInfo": {"name": CLIENT_NAME, "version": "0.1.0"},
150
+ })
151
+ self._notify("notifications/initialized", {})
152
+ return self
153
+
154
+ # 生效条件:幂等、可重复调用;self.proc 为 None 时直接返回;否则先关 stdin 再 terminate 并 wait(timeout=3),超时或异常则 kill 兜底;无返回值、不抛异常;
155
+ def close(self):
156
+ proc, self.proc = self.proc, None
157
+ if proc is None:
158
+ return
159
+ try:
160
+ if proc.stdin:
161
+ proc.stdin.close()
162
+ except Exception:
163
+ pass
164
+ try:
165
+ proc.terminate()
166
+ proc.wait(timeout=3)
167
+ except Exception:
168
+ try:
169
+ proc.kill()
170
+ except Exception:
171
+ pass
172
+
173
+ # -- 内部 IO ----------------------------------------------------------
174
+ # 生效条件:self.proc 为 None 或 proc.stdout 为 None 时直接返回;否则逐行 strip 后跳过空行,非空行 json.loads 成功则放入 self._q,抛 ValueError 则跳过该行。
175
+ def _reader(self):
176
+ stream = self.proc.stdout if self.proc else None
177
+ if stream is None:
178
+ return
179
+ for line in stream:
180
+ line = line.strip()
181
+ if not line:
182
+ continue
183
+ try:
184
+ self._q.put(json.loads(line))
185
+ except ValueError:
186
+ continue
187
+
188
+ # 生效条件:给定 required 形参 payload 时,若 self.proc is None 或 self.proc.poll() is not None 则抛 RuntimeError("白箱进程未运行(启动失败或已退出)"),否则把 json.dumps(payload, ensure_ascii=False) + "\n" 写入 self.proc.stdin 并 flush,无返回。
189
+ def _write(self, payload):
190
+ if self.proc is None or self.proc.poll() is not None:
191
+ raise RuntimeError("白箱进程未运行(启动失败或已退出)")
192
+ self.proc.stdin.write(json.dumps(payload, ensure_ascii=False) + "\n")
193
+ self.proc.stdin.flush()
194
+
195
+ # 生效条件:给定 required 形参 method 与 params 时,以 {"jsonrpc": "2.0", "method": method, "params": params}(无 id)调用 self._write,自身无返回。
196
+ def _notify(self, method, params):
197
+ self._write({"jsonrpc": "2.0", "method": method, "params": params})
198
+
199
+ # 生效条件:给定 required 形参 method 与 params 时在 self._lock 内取自增 id 并写入请求,随后循环取 self._q:remain <= 0 或 queue.Empty 时先 self.close() 再抛 TimeoutError,msg.get("id") 不等于 rid 时 continue,msg.get("error") 为真时抛 RuntimeError,id 匹配且无 error 时返回 msg.get("result")(缺 "result" 键返回 None)。
200
+ def _request(self, method, params):
201
+ with self._lock:
202
+ rid = self._next_id
203
+ self._next_id += 1
204
+ self._write({"jsonrpc": "2.0", "id": rid, "method": method,
205
+ "params": params})
206
+ deadline = time.time() + self.timeout
207
+ while True:
208
+ remain = deadline - time.time()
209
+ if remain <= 0:
210
+ self.close()
211
+ raise TimeoutError(f"白箱调用超时({self.timeout}s):{method}")
212
+ try:
213
+ msg = self._q.get(timeout=remain)
214
+ except queue.Empty:
215
+ self.close()
216
+ raise TimeoutError(f"白箱调用超时({self.timeout}s):{method}")
217
+ if msg.get("id") != rid:
218
+ continue
219
+ if msg.get("error"):
220
+ raise RuntimeError(f"白箱返回错误:{msg['error']}")
221
+ return msg.get("result")
222
+
223
+ # -- 业务接口 ---------------------------------------------------------
224
+ # 生效条件:给定 required 形参 name 与 args(args 为假值时按 {"name": name, "arguments": args or {}} 发空字典)即以 "tools/call" 发请求,把结果 content 中 type=="text" 的块文本拼接后 json.loads,失败(ValueError/TypeError)则 data=None,返回 {"isError": bool((result or {}).get("isError")), "text": text, "data": data}。
225
+ def call(self, name, args):
226
+ """调用白箱 MCP 工具,返回 {isError, text, data}。"""
227
+ result = self._request("tools/call", {"name": name, "arguments": args or {}})
228
+ text = ""
229
+ for block in (result or {}).get("content", []) or []:
230
+ if isinstance(block, dict) and block.get("type") == "text":
231
+ text += block.get("text") or ""
232
+ try:
233
+ data = json.loads(text)
234
+ except (ValueError, TypeError):
235
+ data = None
236
+ return {"isError": bool((result or {}).get("isError")),
237
+ "text": text, "data": data}
238
+
239
+ # --------------------------------------------------------------------------
240
+ # 进程内白箱客户端(默认路径)+ 客户端工厂
241
+ # --------------------------------------------------------------------------
242
+
243
+ class LocalWhiteboxClient(_WhiteboxApi):
244
+ """白箱**进程内**客户端(默认载体)。
245
+
246
+ 白箱知识库已随主仓自带(`md_cg/whitebox_kb/`),直接调用其引擎:
247
+ 无子进程、无 MCP、无理论仓依赖。接口与子进程版完全一致,
248
+ 故 `ask / remember / ping / verify_*` 及其留痕逻辑无需任何改动。
249
+ """
250
+
251
+ # 生效条件:db_path 为 None 时由引擎按默认路径取库;_ignored 吞掉子进程版遗留形参以保持接口同形;构造只记录路径、不加载引擎(延迟到 self.engine 首次访问);
252
+ def __init__(self, db_path=None, **_ignored):
253
+ self.db_path = db_path
254
+ self._engine = None
255
+
256
+ @property
257
+ # 生效条件:self._engine 为 None 时调用 _load_get_engine()(db_path=self.db_path) 创建并缓存后返回它,非 None 时直接返回缓存实例。
258
+ def engine(self):
259
+ if self._engine is None:
260
+ self._engine = _load_get_engine()(db_path=self.db_path)
261
+ return self._engine
262
+
263
+ # -- 生命周期(与子进程版语义对齐:start 即确保可用,失败即抛) --------
264
+ # 生效条件:先取 self.engine(首次访问才真正加载知识库)并调 service_info() 以确认可服务,不可用即抛;成功后返回 self,可重复调用;
265
+ def start(self):
266
+ _ = self.engine.service_info()
267
+ return self
268
+
269
+ # 生效条件:幂等;self._engine 为 None 时直接返回,否则关闭引擎并置 None(只释放句柄,不删除落盘数据);
270
+ def close(self):
271
+ if self._engine is not None:
272
+ self._engine.close()
273
+ self._engine = None
274
+
275
+ # -- 业务接口 ---------------------------------------------------------
276
+ # 生效条件:给定 required 形参 name 与 args 时直接转调 self.engine.call_tool(name, args) 并返回其结果,不做任何形参改写或校验。
277
+ def call(self, name, args):
278
+ """调用白箱工具,返回 {isError, text, data}(形状对齐 MCP)。"""
279
+ return self.engine.call_tool(name, args)
280
+
281
+
282
+ # 生效条件:无必需形参;包内 from .whitebox_kb.engine import get_engine 成功时返回它,ImportError 时改为 from whitebox_kb.engine import get_engine 并返回。
283
+ def _load_get_engine():
284
+ """兼容两种导入方式(包内 / 平铺)。"""
285
+ try:
286
+ from .whitebox_kb.engine import get_engine
287
+ except ImportError: # pragma: no cover - 平铺运行场景
288
+ from whitebox_kb.engine import get_engine
289
+ return get_engine
290
+
291
+
292
+ # 生效条件:cmd 或 env 为真,或 MDCG_WHITEBOX_CMD / MDCG_WHITEBOX_ARGS 为真时返回 _SubprocessWhiteboxClient(cmd=cmd, env=env, timeout=timeout),否则返回 LocalWhiteboxClient(db_path=db_path)。
293
+ def WhiteboxClient(cmd=None, env=None, timeout=None, db_path=None):
294
+ """白箱客户端工厂。
295
+
296
+ 默认返回 `LocalWhiteboxClient`(进程内 · 随仓自带知识库)。
297
+ 仅当显式给出 `cmd` / `env`,或设置了 `MDCG_WHITEBOX_CMD` /
298
+ `MDCG_WHITEBOX_ARGS` 时,才返回 legacy 的外部 MCP 子进程客户端。
299
+ """
300
+ if cmd or env or os.environ.get("MDCG_WHITEBOX_CMD") \
301
+ or os.environ.get("MDCG_WHITEBOX_ARGS"):
302
+ return _SubprocessWhiteboxClient(cmd=cmd, env=env, timeout=timeout)
303
+ return LocalWhiteboxClient(db_path=db_path)
304
+
305
+
306
+ # --------------------------------------------------------------------------
307
+ # 结果归一化
308
+ # --------------------------------------------------------------------------
309
+
310
+ # 生效条件:data 为 dict 时按 route、mode、path 顺序取首个非空 str 值返回,否则(含 data 非 dict、三键均无或均为空/非 str)返回 ""。
311
+ def _extract_route(data):
312
+ if isinstance(data, dict):
313
+ for key in ("route", "mode", "path"):
314
+ val = data.get(key)
315
+ if isinstance(val, str) and val:
316
+ return val
317
+ return ""
318
+
319
+
320
+ # 生效条件:data 为 dict 时先按 reply/answer/text/response/content/message 取首个 strip 后非空的 str 返回,再对 result、data 两键的 dict 值递归取非空结果,均无则返回 fallback or ""。
321
+ def _extract_reply(data, fallback=""):
322
+ if isinstance(data, dict):
323
+ for key in ("reply", "answer", "text", "response", "content", "message"):
324
+ val = data.get(key)
325
+ if isinstance(val, str) and val.strip():
326
+ return val
327
+ for key in ("result", "data"):
328
+ val = data.get(key)
329
+ if isinstance(val, dict):
330
+ nested = _extract_reply(val, "")
331
+ if nested:
332
+ return nested
333
+ return fallback or ""
334
+
335
+
336
+ # --------------------------------------------------------------------------
337
+ # 验证:编码能力 / 已有知识回答能力
338
+ # --------------------------------------------------------------------------
339
+
340
+ # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;marker、fact、question 为假值时分别用带毫秒时间戳的默认口令、默认事实、默认追问,cg 仅传给 _record(cg 为 None 则 node_id 为 None,不自建 client),异常时返回 ok=False 并同样 _record。
341
+ def verify_encoding(cg=None, client=None, marker=None, fact=None,
342
+ question=None, session_id="md_cg-whitebox-verify"):
343
+ """验证白箱「编码能力」。
344
+
345
+ 步骤:remember 一条带唯一口令的事实 → 追问口令 → 命中即通过。
346
+ """
347
+ own = client is None
348
+ cli = client or WhiteboxClient()
349
+ marker = marker or ("白箱探针" + str(int(time.time() * 1000)))
350
+ fact = fact or f"md_cg 白箱编码验证:本次口令是 {marker},请记住。"
351
+ question = question or "请只回答刚才记住的口令本身,不要解释。"
352
+ try:
353
+ cli.start()
354
+ enc = cli.remember(fact, importance=0.95, tags=["md_cg", "whitebox-probe"])
355
+ ans = cli.ask(question, session_id=session_id)
356
+ hit = marker in (ans.get("reply") or "")
357
+ out = {"kind": "encoding", "ok": bool(enc["ok"] and hit),
358
+ "marker": marker, "encoded": bool(enc["ok"]),
359
+ "recalled": hit, "route": ans.get("route"),
360
+ "reply": (ans.get("reply") or "")[:300]}
361
+ out["node_id"] = _record(cg, "encoding", out["ok"], out)
362
+ return out
363
+ except Exception as exc: # 白箱不可用:如实记录失败,不抛断调用方
364
+ out = {"kind": "encoding", "ok": False, "marker": marker,
365
+ "error": f"{type(exc).__name__}: {exc}"}
366
+ out["node_id"] = _record(cg, "encoding", False, out)
367
+ return out
368
+ finally:
369
+ if own:
370
+ cli.close()
371
+
372
+
373
+ # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;questions 为假值(None 或空)时用 DEFAULT_KNOWLEDGE_PROBES,逐问后仅当至少一问 reply 非空且 route 为 self 或 self_fallback 时 ok=True,异常返回 ok=False。
374
+ def verify_existing(cg=None, client=None, questions=None,
375
+ session_id="md_cg-whitebox-verify"):
376
+ """验证白箱「已有知识回答能力」。
377
+
378
+ 步骤:问白箱本应已知的问题 → route=self 且回答非空即通过(至少一问命中)。
379
+ """
380
+ own = client is None
381
+ cli = client or WhiteboxClient()
382
+ questions = list(questions or DEFAULT_KNOWLEDGE_PROBES)
383
+ try:
384
+ cli.start()
385
+ probes = []
386
+ for q in questions:
387
+ ans = cli.ask(q, session_id=session_id)
388
+ route = ans.get("route") or ""
389
+ reply = ans.get("reply") or ""
390
+ probes.append({"question": q, "route": route,
391
+ "answered": bool(reply.strip()),
392
+ "self_route": route in ("self", "self_fallback"),
393
+ "reply": reply[:300]})
394
+ ok = any(p["answered"] and p["self_route"] for p in probes)
395
+ out = {"kind": "existing_knowledge", "ok": ok, "probes": probes}
396
+ out["node_id"] = _record(cg, "existing_knowledge", ok, out)
397
+ return out
398
+ except Exception as exc:
399
+ out = {"kind": "existing_knowledge", "ok": False,
400
+ "error": f"{type(exc).__name__}: {exc}"}
401
+ out["node_id"] = _record(cg, "existing_knowledge", False, out)
402
+ return out
403
+ finally:
404
+ if own:
405
+ cli.close()
406
+
407
+
408
+ # 生效条件:client 为 None 时自建 WhiteboxClient() 并在 finally 关闭;依次对 service_info、mdcg_service_info、info 调用 call,首个 isError 为假即返回 ok=True 与该 tool/info,全部不可用返回 ok=False,start 或整体异常返回 ok=False。
409
+ def ping(client=None, session_id="md_cg-whitebox-ping"):
410
+ """白箱连通性探测:调 service_info(或 info)判断能力库是否在线。"""
411
+ own = client is None
412
+ cli = client or WhiteboxClient()
413
+ try:
414
+ cli.start()
415
+ for name in ("service_info", "mdcg_service_info", "info"):
416
+ try:
417
+ r = cli.call(name, {})
418
+ if not r["isError"]:
419
+ return {"ok": True, "tool": name,
420
+ "info": r.get("data") or r.get("text")}
421
+ except Exception:
422
+ continue
423
+ return {"ok": False, "error": "白箱在线但未找到 service_info/info 工具"}
424
+ except Exception as exc:
425
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
426
+ finally:
427
+ if own:
428
+ cli.close()
429
+
430
+
431
+ # 生效条件:client 为 None 时以 WhiteboxClient(timeout=kw.get("timeout")) 自建并在 finally 关闭;随后 cli.start() 并返回 cli.ask(message, session_id=session_id)。
432
+ def ask(message, session_id="md_cg-whitebox-verify", client=None, **kw):
433
+ """显式调用白箱回答一个问题。"""
434
+ own = client is None
435
+ cli = client or WhiteboxClient(timeout=kw.get("timeout"))
436
+ try:
437
+ cli.start()
438
+ return cli.ask(message, session_id=session_id)
439
+ finally:
440
+ if own:
441
+ cli.close()
442
+
443
+
444
+ # 生效条件:client 为 None 时以 WhiteboxClient(timeout=kw.get("timeout")) 自建并在 finally 关闭;随后 cli.start() 并返回 cli.remember(content, importance=importance, tags=tags)。
445
+ def remember(content, importance=0.9, tags=None, client=None, **kw):
446
+ """显式调用白箱编码一条知识。"""
447
+ own = client is None
448
+ cli = client or WhiteboxClient(timeout=kw.get("timeout"))
449
+ try:
450
+ cli.start()
451
+ return cli.remember(content, importance=importance, tags=tags)
452
+ finally:
453
+ if own:
454
+ cli.close()
455
+
456
+
457
+ # --------------------------------------------------------------------------
458
+ # 留痕与报告
459
+ # --------------------------------------------------------------------------
460
+
461
+ # 生效条件:cg 为 None 时返回 None;否则以 whitebox_verify_{kind}_{毫秒时间戳} 为 id 调 cg.add 写入 self 层,成功返回该 nid,cg.add 抛异常时返回 None。
462
+ def _record(cg, kind, ok, payload):
463
+ """把验证结论写入认知图(self 层)。失败不阻断验证本身。"""
464
+ if cg is None:
465
+ return None
466
+ nid = f"whitebox_verify_{kind}_{int(time.time() * 1000)}"
467
+ body = json.dumps(payload, ensure_ascii=False, default=str)[:1800]
468
+ try:
469
+ # 2026-10-18:补条件空间四维——此前只有 time_window(autofill),
470
+ # 三条 whitebox_verify_* 因此判 legacy_blindspot。
471
+ # 同样是"自述产生过程"而非内容推断:它确实是系统自验、用该验证器、
472
+ # 在"验证已执行且库可写"的前提下产生的记录。
473
+ cg.add(nid, f"[白箱能力验证·{kind}] ok={ok} {body}",
474
+ layer="self", tags=[VERIFY_TAG, f"whitebox:{kind}"],
475
+ condition_space={
476
+ "observation_position": "self:lingshu",
477
+ "observation_tool": "whitebox.verify_%s" % kind,
478
+ "existence_constraint": "库内可写且验证已执行",
479
+ },
480
+ importance=0.6, verification_basis="test",
481
+ consistency=False)
482
+ return nid
483
+ except Exception:
484
+ return None
485
+
486
+
487
+ # 生效条件:cg 为 None 时返回 {'ok': False, 'error': '需要 cg 实例'};否则以 k=int(limit or 20)(limit 为 0/空串/None 时 k 变 20)调 cg.search("白箱能力验证", layer="self", record=False),只保留 tags 中任一以 "whitebox:" 开头的项并返回 count 与 items。
488
+ def report(cg=None, limit=20):
489
+ """汇总最近的「白箱能力验证」留痕。"""
490
+ if cg is None:
491
+ return {"ok": False, "error": "需要 cg 实例"}
492
+ res, _meta = cg.search("白箱能力验证", layer="self",
493
+ k=int(limit or 20), record=False)
494
+ items = []
495
+ for node, score, _q in res:
496
+ fm = node.get("frontmatter") or {}
497
+ tags = fm.get("tags") or []
498
+ if not any(isinstance(t, str) and t.startswith("whitebox:") for t in tags):
499
+ continue
500
+ items.append({"id": node.get("id"), "score": score, "tags": tags,
501
+ "content": (node.get("content") or "")[:800]})
502
+ return {"ok": True, "count": len(items), "items": items}
503
+
504
+
505
+ # --------------------------------------------------------------------------
506
+ # MCP 统一入口(由 mcp_server._whitebox_call 调用)
507
+ # --------------------------------------------------------------------------
508
+
509
+ # 生效条件:action=(args.action or "ping") 小写后,ask/chat/query 走 ask(question/message/query 均假则传 ""),remember/encode/write 走 remember 且 importance=float(a.get("importance", 0.9)),verify_encoding/encoding 走 verify_encoding,verify_existing/existing/knowledge 走 verify_existing(questions 取 a.questions 或 a.question 单元素列表),report/history 走 report(limit=int(a.get("limit") or 20)),ping/status/info 走 ping(),其余抛 ValueError。
510
+ def dispatch(cg, args):
511
+ """cg(op=whitebox) 的分发:action=ask|remember|verify_encoding|verify_existing|ping|report。"""
512
+ a = args or {}
513
+ action = (a.get("action") or "ping").strip().lower()
514
+ if action in ("ask", "chat", "query"):
515
+ return ask(a.get("question") or a.get("message") or a.get("query") or "",
516
+ session_id=a.get("session_id") or "md_cg-whitebox-verify")
517
+ if action in ("remember", "encode", "write"):
518
+ return remember(a.get("content") or a.get("text") or "",
519
+ importance=float(a.get("importance", 0.9)),
520
+ tags=a.get("tags"))
521
+ if action in ("verify_encoding", "encoding"):
522
+ return verify_encoding(cg, marker=a.get("marker"), fact=a.get("fact"),
523
+ question=a.get("question"),
524
+ session_id=a.get("session_id") or "md_cg-whitebox-verify")
525
+ if action in ("verify_existing", "existing", "knowledge"):
526
+ qs = a.get("questions") or ([a["question"]] if a.get("question") else None)
527
+ return verify_existing(cg, questions=qs,
528
+ session_id=a.get("session_id") or "md_cg-whitebox-verify")
529
+ if action in ("report", "history"):
530
+ return report(cg, limit=int(a.get("limit") or 20))
531
+ if action in ("ping", "status", "info"):
532
+ return ping()
533
+ raise ValueError(f"whitebox 未知 action:{action}")
534
+
535
+
536
+ if __name__ == "__main__": # 手动自检:python -m md_cg.whitebox
537
537
  print(json.dumps(ping(), ensure_ascii=False, indent=2))