@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/routing.py CHANGED
@@ -1,491 +1,491 @@
1
- # -*- coding: utf-8 -*-
2
- """md 认知图 · 路由键归一化(风险1)
3
-
4
- 普查结论(wisdom-book-cloud-new.db, 3048 节点):
5
- - 原始 condition_space 四元组作分桶键 → 3037 桶 / 3048 节点,99.9% 单例桶。
6
- 根因:observation_position 实际格式是「<域> 知识点(<实例名>)」,把节点特有的
7
- 实例名嵌进了条件字段,3033 种取值 ≈ 唯一。按它分桶 = 一节点一桶,查询侧
8
- 构造不出精确匹配的情境 → 命中率≈0,召回归零(比退化成全量更糟)。
9
- - observation_tool(93% 集中) / existence_constraint(95% 集中) 去掉 position 后
10
- 塌缩成单个巨桶。
11
- - time_window 实测仅 3 种取值,进哈希键是纯噪声。
12
- - tags 的 domain: 标签 → 95 桶 / 最大桶 5.4% / 期望扫描 1.8%,是唯一健康的键。
13
-
14
- 因此路由键 = 归一化提取的「域」,而非四元组哈希。写入侧与查询侧共用本模块,
15
- 保证两侧同构(风险2 的前提:查询构造的键必须与写入键落在同一空间)。
16
- """
17
- import math
18
- import re
19
- import hashlib
20
- import unicodedata
21
-
22
- # observation_position 的实例名尾巴:「知识点(xxx)」「概念(xxx)」等
23
- _INSTANCE_TAIL = re.compile(
24
- r"\s*(知识点|概念|条目|卡片|节点|规律|定理|公式)\s*[((].*?[))]\s*$"
25
- )
26
- # 骨架填充类后缀:「高中物理知识点内容(按骨架填充)」→「高中物理」
27
- _SKELETON_TAIL = re.compile(r"(知识点)?内容\s*[((]按骨架填充[))]\s*$")
28
-
29
- ORPHAN = "orphan"
30
-
31
-
32
- # 生效条件:text 为任意对象(None 按空串)时返回 str(text) 的 NFKC 归一结果;不 strip、不改大小写——**本仓 NFKC 口径的唯一单点**。
33
- def nfkc_text(text) -> str:
34
- """NFKC 归一的**唯一单点**(全角/半角、兼容字形收口,issue #362b/c)。
35
-
36
- `normalize_domain`(路由键)与 `mdcg.neg_condition_hits` / `mdcg.strip_boundary_terms`
37
- (负条件判据与边界摘词面)都经此函数取 NFKC。为什么必须抽成函数:本仓的返工教训
38
- 是「两份实现 + 注释写着同源 = 口径必分叉」(见 `mdcg.py` 里 `_ccg_line` 的副本案)。
39
- 仓内**不得**再出现第二处 NFKC 归一实现(本模块的单点是唯一入口)——由
40
- `md_cg/test_issue362_neg_condition.py` 的 E 组做源码面单点断言钉死。
41
- """
42
- return unicodedata.normalize("NFKC", "" if text is None else str(text))
43
-
44
-
45
- #: 繁→简折叠表(#362c:**机制在位、数据待补**)。
46
- #:
47
- #: 为什么是空表:仓内**没有**既有的繁简映射表(证据与检索口径见
48
- #: `md_cg/test_issue362_neg_condition.py` 的 C 组注释)。而「只覆盖本 issue 语料的
49
- #: 最小表」会在守卫里全绿、在真实流量上静默漏拒——那是**假绿**,比没有表更坏。
50
- #: 故按 Lead 裁定(2026-10-14):**c 项本轮挂起**,只落机制单点;表默认空 ⇒
51
- #: 生产行为一字不动。注入点见 `trad_to_simp()` / `set_trad_to_simp()`。
52
- TRAD_TO_SIMP = {}
53
-
54
-
55
- # 生效条件:无参时返回当前生效的繁→简折叠表({单字符 str: 单字符 str});默认即模块级 `TRAD_TO_SIMP`(空表)。
56
- def trad_to_simp() -> dict:
57
- """繁简折叠表的**读取单点**(#362c 注入点之一)。"""
58
- return TRAD_TO_SIMP
59
-
60
-
61
- # 生效条件:table 为 {单字符 str: 单字符 str} 映射时把它设为当前折叠表并返回旧表;table 为假值时复原为空表(返回旧表)。
62
- def set_trad_to_simp(table) -> dict:
63
- """繁简折叠表的**写入单点**(#362c):真源一旦确定,只在此处接入。
64
-
65
- 守卫用它注入 2~3 条**测试用**映射,证明「表一旦有,c 项链路就是通的」——
66
- 这条非恒真对照要证明的是**机制到位**,而不是「现在没有表」。
67
- """
68
- global TRAD_TO_SIMP
69
- old = TRAD_TO_SIMP
70
- TRAD_TO_SIMP = dict(table or {})
71
- return old
72
-
73
-
74
- # 生效条件:text 为任意对象(None 按空串)时返回「NFKC → casefold → 繁简折叠(表非空时)」的结果;不删空白、不改标点,除这三步外不做任何其它归一。
75
- def fold_variants(text) -> str:
76
- """检索/判据面的**字符归一人**(#362b/c):NFKC → casefold → 繁简折叠。
77
-
78
- NFKC 走与 `normalize_domain` 同一个 `nfkc_text` 单点,故两侧**同口径**;
79
- casefold 追加大小写折叠(`4G`/`4g`、`PDF`/`pdf`);繁简折叠表**当前为空**
80
- (见 `TRAD_TO_SIMP`),表非空时逐字符替换。
81
-
82
- 刻意**不做**超出这三步的任何归一(不删标点、不并同音、不做拼音)——过度归一
83
- 与归一缺失同样是缺陷:守卫 K 组有 `C++`/`A-B`/`Ⅳ`/`ß` 的非恒真对照把
84
- 「哪些改写是可接受的既有口径、哪些是越界」逐条钉住。
85
- """
86
- s = nfkc_text(text).casefold()
87
- table = trad_to_simp()
88
- if table:
89
- s = "".join(table.get(ch, ch) for ch in s)
90
- return s
91
-
92
-
93
- # 生效条件:raw 为真值时按 NFKC 归一化并 strip,最多 3 轮剥离 _INSTANCE_TAIL(无变化即停)、再剥 _SKELETON_TAIL、空白转下划线后返回;raw 为假值(None/空串)或处理后为空串时返回 ORPHAN。
94
- def normalize_domain(raw: str) -> str:
95
- """把自由文本的域描述归一化成稳定的短键。
96
-
97
- 「工程学 知识点(内力与截面法)」 → 工程学
98
- 「高中物理知识点内容(按骨架填充)」 → 高中物理
99
- 「数学分析知识点内容(按骨架填充) 知识点(贝塞尔不等式)」 → 数学分析
100
- """
101
- if not raw:
102
- return ORPHAN
103
- s = nfkc_text(raw).strip()
104
- # 反复剥离实例名尾巴(可能叠加两层,见上面第三个例子)
105
- for _ in range(3):
106
- new = _INSTANCE_TAIL.sub("", s)
107
- if new == s:
108
- break
109
- s = new.strip()
110
- s = _SKELETON_TAIL.sub("", s).strip()
111
- s = re.sub(r"\s+", "_", s)
112
- return s or ORPHAN
113
-
114
-
115
- # 生效条件:tags 为真值时取其中首个 str(t) 以 "domain:" 开头的项,返回其前缀后内容的 normalize_domain 结果;无此标签且 condition_space 为真值时返回 normalize_domain(condition_space.get("observation_position"))(缺键即 None 归一为 ORPHAN);tags 为假值且 condition_space 为假值时返回 ORPHAN。
116
- def route_key(condition_space: dict = None, tags=None) -> str:
117
- """导出条件路由键。优先级:tags 的 domain: > observation_position 归一化 > orphan。
118
-
119
- domain: 标签是显式声明的域,普查证明它分布最健康(95 桶/最大桶 5.4%),
120
- 所以优先。没有标签时才回退到从 observation_position 提取。
121
- """
122
- for t in tags or []:
123
- t = str(t)
124
- if t.startswith("domain:"):
125
- return normalize_domain(t[len("domain:"):])
126
- if condition_space:
127
- return normalize_domain(condition_space.get("observation_position"))
128
- return ORPHAN
129
-
130
-
131
- # 生效条件:key 等于 ORPHAN 时原样返回 ORPHAN;否则返回 "cond_" + 把 key 中非[\w中文-]字符替换为下划线并截前 24 字符的串 + "_" + key 的 sha256(utf-8)前 8 位十六进制。
132
- def bucket_dir(key: str) -> str:
133
- """路由键 → 目录名。中文键保留可读前缀 + 短哈希,避免文件系统非法字符/超长。"""
134
- if key == ORPHAN:
135
- return ORPHAN
136
- safe = re.sub(r"[^\w\u4e00-\u9fff-]", "_", key)[:24]
137
- h = hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]
138
- return f"cond_{safe}_{h}"
139
-
140
-
141
- # 14 大域代表词表(白箱第 2 篇第 5 章 + 第 3 篇第 4 章:「56 学科卡 → 14 大域
142
- # → 域内 KCCS」两阶段并行收敛。本表用作阶段 1 的大域并行打分依据——
143
- # 当 query 没有显式 context 但 query 词能落进某个大域时,先收敛到大域再查。
144
- #
145
- # 词的选取原则:覆盖白箱工程文档里出现的高频学科关键词,且不互相吞并。
146
- # 同一个词可以出现在多个大域(如「公式」在数学与物理都常见),这是合理的:
147
- # 大域并行打分阶段就是让多域同分,再由阶段 2 的 KCCS 进一步区分。
148
- BIG_DOMAINS = {
149
- "数学": {"数学", "算术", "几何", "代数", "微积分", "概率", "统计", "集合", "矩阵",
150
- "线性", "拓扑", "数论", "公式", "定理", "证明", "函数", "导数", "积分",
151
- "极限", "方程", "不等式", "贝塞尔", "二分", "素数", "微元"},
152
- "物理": {"物理", "力学", "电磁", "光学", "热学", "量子", "相对论", "能量", "动量",
153
- "质量", "速度", "加速度", "电荷", "电压", "电流", "沸点", "海拔",
154
- "大气压", "压强", "温度", "牛顿", "惯性", "引力"},
155
- "化学": {"化学", "元素", "分子", "原子", "化合物", "反应", "酸", "碱", "盐",
156
- "氧化", "还原", "有机", "无机", "离子", "键", "浓度", "溶液"},
157
- "生物": {"生物", "细胞", "基因", "蛋白质", "酶", "光合", "呼吸", "植物", "动物",
158
- "进化", "免疫", "神经", "细菌", "病毒", "代谢", "染色", "分裂"},
159
- "计算机": {"计算机", "算法", "数据结构", "编程", "代码", "软件", "网络", "数据库",
160
- "系统", "排序", "递归", "图论", "哈希", "索引", "查询", "排序", "锁",
161
- "事务", "内存", "进程", "线程"},
162
- "语言": {"语言", "中文", "英文", "语法", "词汇", "语义", "修辞", "文学", "写作",
163
- "阅读", "拼音", "字", "词", "句"},
164
- "历史": {"历史", "朝代", "战争", "文明", "政治", "经济史", "文化史", "古代",
165
- "近代", "现代", "王朝", "革命", "改革"},
166
- "地理": {"地理", "地形", "气候", "人口", "城市", "国家", "地图", "板块",
167
- "洋流", "经度", "纬度", "海拔带", "流域"},
168
- "艺术": {"艺术", "绘画", "音乐", "雕塑", "电影", "设计", "色彩", "构图",
169
- "旋律", "节奏", "摄影"},
170
- "经济": {"经济", "市场", "金融", "货币", "投资", "股票", "债券", "GDP",
171
- "通胀", "财政", "税收", "供需"},
172
- "心理": {"心理", "认知", "情感", "记忆", "学习", "性格", "行为", "意识",
173
- "动机", "人格", "焦虑"},
174
- "医学": {"医学", "疾病", "治疗", "药物", "诊断", "外科", "内科", "儿科",
175
- "中医", "症状", "病理", "处方"},
176
- "工程": {"工程", "建筑", "结构", "材料", "机械", "电子", "土木", "桥梁",
177
- "内力", "截面", "梁", "柱", "应力"},
178
- "通用": {"常识", "生活", "日常", "通用", "礼仪", "礼貌", "文明", "规则"},
179
- }
180
-
181
-
182
- # 生效条件:terms 为真值时对 BIG_DOMAINS 每个大域统计命中词数,最高分为 0 或 terms 为假值(None/空)时返回 None,否则返回最高分大域名(并列取 BIG_DOMAINS 迭代序首个最高分)。
183
- def big_domain_classify(terms) -> str | None:
184
- """阶段 1:14 大域并行打分 → 收敛到 top-1。
185
-
186
- terms 是 expand_query_terms 返回的扩展词集合。
187
- 大域打分 = query 词命中大域代表词的次数(多词同域累加)。
188
- 并行在认知结构意义上:即使底层串行计算,14 个大域同时独立评估。
189
-
190
- 返回最匹配的大域名(多个 0 分 → 返回 None,走原 bucket_dir 路由)。
191
- """
192
- if not terms:
193
- return None
194
- scores = {}
195
- for d, vocab in BIG_DOMAINS.items():
196
- scores[d] = sum(1 for t in terms
197
- if any(w in t or t in w for w in vocab))
198
- best = max(scores.items(), key=lambda x: x[1])
199
- if best[1] == 0:
200
- return None
201
- # 多大域并列最高分时,按字典序取第一个稳定结果(避免浮点不确定)
202
- return best[0]
203
-
204
-
205
- # 生效条件:terms 为假值(None/空)时返回 {每个 BIG_DOMAINS 域: 0};terms 为真值时返回 {大域: 该域词表命中 terms 中词的个数}。
206
- def big_domain_score_breakdown(terms) -> dict:
207
- """暴露打分明细,便于审计与回归测试。"""
208
- if not terms:
209
- return {d: 0 for d in BIG_DOMAINS}
210
- return {d: sum(1 for t in terms if any(w in t or t in w for w in vocab))
211
- for d, vocab in BIG_DOMAINS.items()}
212
-
213
-
214
- # ---------------------------------------------------------------------------
215
- # 分级隶属度(模糊控制「隶属函数」的手写版)
216
- #
217
- # 上面的 big_domain_classify 是二值控制:`w in t or t in w` 命中即计 1。
218
- # 下面是同一套规则库的**分级**版本——命中程度是 0~1 的连续值,并乘 IDF:
219
- # · 隶属度 membership(t, w):完全相同 1.0;包含关系取长度比(覆盖越全越高)
220
- # · IDF:一个代表词覆盖的大域越少,区分度越高(「贝塞尔」只在数学出现,
221
- # 权重高于「公式」这种跨域通用词)
222
- # 老函数保持不动 → P0/P1 基线可比性不受影响;新函数只供新路径(fuzzy)使用。
223
- # ---------------------------------------------------------------------------
224
-
225
- # 生效条件:term 或 word 为假值(None/空串)返回 0.0;相等返回 1.0;word 是 term 子串返回 len(word)/len(term);term 是 word 子串返回 len(term)/len(word);二者无包含关系返回 0.0。
226
- def membership(term: str, word: str) -> float:
227
- """词 term 对代表词 word 的隶属度(0.0~1.0,越接近 1 越隶属)。
228
-
229
- 完全相同 → 1.0
230
- term 包含 word → len(word)/len(term)(覆盖越全越隶属)
231
- word 包含 term → len(term)/len(word)
232
- 无包含关系 → 0.0
233
- """
234
- if not term or not word:
235
- return 0.0
236
- if term == word:
237
- return 1.0
238
- if word in term:
239
- return len(word) / len(term)
240
- if term in word:
241
- return len(term) / len(word)
242
- return 0.0
243
-
244
-
245
- # 生效条件:无入参,恒遍历模块级常量 BIG_DOMAINS 的各域代表词表,返回 {代表词: 包含该词的域个数}。
246
- def _build_domain_df() -> dict:
247
- """代表词 → 覆盖它的大域数(IDF 的分母)。"""
248
- df = {}
249
- for vocab in BIG_DOMAINS.values():
250
- for w in vocab:
251
- df[w] = df.get(w, 0) + 1
252
- return df
253
-
254
-
255
- _DOMAIN_DF = _build_domain_df()
256
-
257
-
258
- # 生效条件:恒返回 math.log(1.0 + len(BIG_DOMAINS) / _DOMAIN_DF.get(word, 1)),即 word 在 _DOMAIN_DF 中取其覆盖域数,缺键(含任何未登记值)时按 _DOMAIN_DF.get 的默认 1 代入。
259
- def domain_idf(word: str) -> float:
260
- """代表词的区分度权重:log(1 + 大域总数 / 覆盖它的大域数)。
261
-
262
- 只在一个大域出现的词(如「贝塞尔」)≈ log(15)=2.71;
263
- 14 个大域都出现的词(如「公式」)≈ log(2)=0.69。
264
- """
265
- return math.log(1.0 + len(BIG_DOMAINS) / _DOMAIN_DF.get(word, 1))
266
-
267
-
268
- # 生效条件:terms 是 dict 时以其条目(键 str(t) 以 "__" 开头者剔除、值为 float)为词权重并忽略 weights,否则以 wmap.get(t, 1.0) 为权重(weights 为假值即 None/空 dict 时 wmap 为空、全部权重取 1.0,terms 为假值则词集为空);逐域累加「词权重 × 该词在域词表内最大(membership × domain_idf)」,权重 <=0 的词跳过,返回 {大域: round(得分, 6)}。
269
- def big_domain_score_weighted(terms, weights=None) -> dict:
270
- """阶段 1(分级版):14 大域并行打分,按「隶属度 × IDF」加权。
271
-
272
- terms: 可迭代的词集合,或 {词: 权重}(expand_query_terms_weighted 的输出,
273
- 调用方需先剔除 "__source__" 等元数据键)。
274
- weights: terms 为可迭代时的可选权重表;terms 已是 dict 时忽略。
275
- 返回 {大域: 得分},得分不再是整数计数,而是连续值。
276
- """
277
- if isinstance(terms, dict):
278
- tw = {str(t): float(w) for t, w in terms.items()
279
- if not str(t).startswith("__")}
280
- else:
281
- wmap = weights or {}
282
- tw = {str(t): float(wmap.get(t, 1.0)) for t in (terms or [])}
283
- out = {}
284
- for d, vocab in BIG_DOMAINS.items():
285
- s = 0.0
286
- for t, tw_ in tw.items():
287
- if tw_ <= 0:
288
- continue
289
- best = 0.0
290
- for w in vocab:
291
- m = membership(t, w)
292
- if m > 0.0:
293
- best = max(best, m * domain_idf(w))
294
- s += tw_ * best
295
- out[d] = round(s, 6)
296
- return out
297
-
298
-
299
- # 生效条件:以 terms、weights 计算各域加权得分(terms 为假值时各域均为 0.0),得分为空或最高分 <= min_score(默认 0.0)时返回 None,否则返回最高分大域名。
300
- def big_domain_classify_weighted(terms, weights=None, min_score: float = 0.0):
301
- """阶段 1(分级版)收敛到 top-1;全部低于 min_score → None。"""
302
- scores = big_domain_score_weighted(terms, weights)
303
- if not scores:
304
- return None
305
- best = max(scores.items(), key=lambda kv: kv[1])
306
- if best[1] <= min_score:
307
- return None
308
- return best[0]
309
-
310
-
311
- # 生效条件:a 或 b 为假值(None/空串)返回 0.0;相等返回 1.0;a 是 b 子串返回 len(a)/len(b);b 是 a 子串返回 len(b)/len(a);否则按二者二元组字符集合的 Jaccard 返回 len(ga & gb)/len(ga | gb),任一集合为空(如单字符键)时返回 0.0。
312
- def domain_similarity(a: str, b: str) -> float:
313
- """两个归一化域键的相似度(0~1):相同 1.0;包含取长度比;否则二元组 Jaccard。
314
-
315
- 「计算机科学」vs「计算机」→ 0.6(包含);「高中物理」vs「物理」→ 0.5;
316
- 完全无关 → 0.0。用于 fuzzy 路径的「大域亲和」打分。
317
- """
318
- if not a or not b:
319
- return 0.0
320
- if a == b:
321
- return 1.0
322
- if a in b:
323
- return len(a) / len(b)
324
- if b in a:
325
- return len(b) / len(a)
326
- ga = {a[i:i + 2] for i in range(len(a) - 1)}
327
- gb = {b[i:i + 2] for i in range(len(b) - 1)}
328
- if not ga or not gb:
329
- return 0.0
330
- return len(ga & gb) / len(ga | gb)
331
-
332
-
333
- # 生效条件:counts 各值之和为 0(含空 dict 与全 0 计数)时——total_nodes 为假值(缺省 None 或 <=0)返回 {'ok': True, 'reason': 'empty', 'buckets': 0}(与加 total_nodes 参数之前逐位一致),total_nodes > 0 返回 {'ok': False, 'reason': 'empty_buckets', 'buckets': 0, 'nodes': total_nodes, 'problems': [...]};否则在「桶数 >1 且最大桶占比 >30%」、「桶数 >1 且单例桶占比 >50%」、「桶数 ==1(单桶,条件路由不可用)」、桶数 >1 时「期望扫描 >30%」中命中的项写入 problems,返回含 ok(=problems 为空)、buckets、nodes、max_bucket_share、singleton_ratio、expected_scan、problems 的 dict。
334
- def bucket_health(counts: dict, total_nodes: int = None) -> dict:
335
- """分区健康度自检。分桶键一旦退化(巨桶或碎片化),条件路由就是纸面收益,
336
- 必须在写入侧就能发现,而不是等召回变差才回头查。
337
-
338
- counts: {bucket_dir: node_count}
339
- total_nodes: 调用方(`MdCG.health`)持有的**库内节点总数**,唯一用途是把
340
- 「真空库(无节点、无桶)」与「有节点但分桶表为空(分区信息缺失)」分开。
341
- **缺省 None ⇒ 不做该比对**:空 counts 的返回与加本参数之前逐位一致,
342
- 故既有调用方(test_p0 / bench_axis_domain / bench6_arms,只传 counts)
343
- 行为一字不变——M3③ 的向后兼容面。
344
-
345
- 单桶(nb == 1)是「从未分区」而不是「分区退化」:巨桶判据(top/n == 1.0)与
346
- 期望扫描判据(同样恒 1.0)在 nb==1 时必触发且互为同一事实,此前把这类库报成
347
- 「巨桶 / 分区失效」是假话(M3①②)。现只给一条如实读数——条件路由本就不可用;
348
- ok 仍为 False(单桶库的一次查询确实是全量扫描,判据未放宽)。
349
- """
350
- n = sum(counts.values())
351
- nb = len(counts)
352
- if not n:
353
- # 库里有节点却零个桶 ⇒ 分桶表与节点面不一致(分区信息缺失),
354
- # 不能报 ok=True 冒充健康(M3③)。total_nodes 缺省时不作此判断。
355
- if total_nodes and total_nodes > 0:
356
- return {
357
- "ok": False,
358
- "reason": "empty_buckets",
359
- "buckets": 0,
360
- "nodes": int(total_nodes),
361
- "problems": [f"分桶表为空但库内有 {int(total_nodes)} 个节点:"
362
- "分区信息缺失,条件路由不可用(非真空库)"],
363
- }
364
- return {"ok": True, "reason": "empty", "buckets": 0}
365
- top = max(counts.values())
366
- singles = sum(1 for v in counts.values() if v == 1)
367
- # 期望扫描占比:随机取一节点的情境去路由,命中桶的期望大小占全库比例
368
- expected_scan = sum(v * v for v in counts.values()) / n / n
369
- problems = []
370
- if nb > 1 and top / n > 0.30:
371
- problems.append(f"巨桶:最大桶占 {top / n:.1%}(>30% 视为分区失效)")
372
- if nb > 1 and singles / nb > 0.50:
373
- problems.append(f"碎片化:单例桶占 {singles / nb:.1%}(>50% 说明键含实例级字段)")
374
- if nb == 1:
375
- # 巨桶/期望扫描两条在 nb==1 时只是同一事实的两种写法,合并为一条如实读数。
376
- # expected_scan 的**数值**仍在返回 dict 里(下游读的是数:test_p0 :92、
377
- # bench_axis_domain :159),只有文案不再把「未分区」说成「巨桶退化」。
378
- problems.append(f"单桶:仅 1 个分桶({n} 个已分桶节点同桶),"
379
- "条件路由本就不可用(从未分区,非分区退化)")
380
- elif expected_scan > 0.30:
381
- problems.append(f"路由无效:期望扫描 {expected_scan:.1%}(接近全量)")
382
- return {
383
- "ok": not problems,
384
- "buckets": nb,
385
- "nodes": n,
386
- "max_bucket_share": top / n,
387
- "singleton_ratio": singles / nb if nb else 0.0,
388
- "expected_scan": expected_scan,
389
- "problems": problems,
390
- }
391
-
392
-
393
- # ---------------------------------------------------------------------------
394
- # 节点侧大域标签(S1 大域先验收敛的前置元数据)
395
- #
396
- # 为何需要:`big_domain_classify` 一直只作用于 **query 侧**(terms),节点侧没有域字段,
397
- # 于是「14 大域并行打分」算完只能写进 meta(审计偏差 4:先验算出来却当成报告)。
398
- # 要让大域先验真正参与候选收敛,节点必须在写入时固化自己的域。
399
- # 口径:与查询侧同一个分类器(BIG_DOMAINS + big_domain_classify),保证两侧同构。
400
- # ---------------------------------------------------------------------------
401
-
402
- # 域词取词:中文(≥2 字)与拉丁词(≥2 字)。词表命中用「包含关系」判定,
403
- # 故 2 字以上的切口足以覆盖 1~4 字代表词(如「工程」命中「工程师」)。
404
- DOMAIN_TERM_RE = re.compile(r"[\u4e00-\u9fff]{2,}|[A-Za-z][A-Za-z0-9_]{1,}")
405
-
406
-
407
- # 生效条件:text 为假值(None/空串)时返回 [];否则以 DOMAIN_TERM_RE 取词、按出现顺序去重后返回,
408
- # 最多 limit 个(limit 为假值/负数时按空处理,返回 [])。
409
- def domain_terms(text, limit: int = 400) -> list:
410
- """从节点正文/标题抽「域词」(供 big_domain_classify 使用)。
411
-
412
- 只做最小分词:中文按 ≥2 字连续片段、拉丁按 [A-Za-z][A-Za-z0-9_]+ 取词;
413
- 去重保序,最多 limit 个(默认 400,避免长文把分类器拖慢)。
414
- """
415
- if not text or not limit or limit < 1:
416
- return []
417
- out, seen = [], set()
418
- for m in DOMAIN_TERM_RE.finditer(str(text)):
419
- w = m.group(0)
420
- if w in seen:
421
- continue
422
- seen.add(w)
423
- out.append(w)
424
- if len(out) >= limit:
425
- break
426
- return out
427
-
428
-
429
- # 生效条件:bucket 为假值或等于 ORPHAN 时返回空串;否则去掉 "cond_" 前缀、并当末段为 8 位十六进制哈希时剥掉该段,返回剩余的可读键。
430
- def bucket_key_readable(bucket: str) -> str:
431
- """桶目录名 → 可读键(S1b query 侧桶推断用):'cond_感知系统_d94e90d2' → '感知系统'。
432
-
433
- 与 `bucket_dir` 互逆(丢哈希段);`orphan`/空值返回空串(S1b 不把 orphan 当键,orphan 恒作兜底)。
434
- """
435
- if not bucket or bucket == ORPHAN:
436
- return ""
437
- s = str(bucket)
438
- if s.startswith("cond_"):
439
- s = s[len("cond_"):]
440
- head, sep, tail = s.rpartition("_")
441
- if sep and len(tail) == 8 and all(c in "0123456789abcdef" for c in tail):
442
- s = head
443
- return s
444
-
445
-
446
- # 中文词判定:至少含一个汉字
447
- _ZH_RE = re.compile(r"[\u4e00-\u9fff]")
448
-
449
-
450
- # 生效条件:key 缺失或含汉字时返回 [];否则从 tags(保序在前)与 text 域词(domain_terms)中收集含汉字、长度≥2 的词,去重取前 limit 个返回。
451
- def bucket_zh_aliases(key: str, tags, text, limit: int = 6) -> list:
452
- """英文桶键的中文别名(issue #33:S1b 跨语言收敛盲区的修复面)。
453
-
454
- 机理:domain_similarity 的 bigram 兜底跨语言交集恒空——英文桶键 × 中文
455
- query 恒 0.0 → S1b 恒 no_key_match(真实库 91.1% 中文节点恰是设计目标场景)。
456
- 别名**只取节点自身内容**(tags 中文词 ∪ 正文中文域词,tags 优先),零翻译
457
- 依赖——unify_query/en_zh_terms 桥接已被 #33 实测排除(字级直译语义毁)。
458
- 键本身含中文时无跨语言问题,返回 []。
459
- """
460
- if not key or _ZH_RE.search(str(key)):
461
- return []
462
- out, seen = [], set()
463
- src = [str(t) for t in (tags or [])]
464
- src += domain_terms(text or "", limit=200)
465
- for w in src:
466
- if len(w) >= 2 and _ZH_RE.search(w) and w not in seen:
467
- seen.add(w)
468
- out.append(w)
469
- if len(out) >= limit:
470
- break
471
- return out
472
-
473
-
474
- # 生效条件:text 为假值或取不到任何域词时返回 None;否则返回 big_domain_classify(domain_terms(text))
475
- # 的结果(无有效域信号时亦为 None,调用方据此决定是否落域字段)。
476
- def classify_text(text, limit: int = 400):
477
- """正文 → 大域名(节点侧域标签真源)。与查询侧共用 big_domain_classify。
478
-
479
- 返回 None 表示「无有效域信号」——此时**不写** big_domain 字段,
480
- 该节点留在 ORPHAN/兜底池(S1 收敛时必须能被兜底召回,见契约 §3 S1 不变量)。
481
-
482
- issue #53-A:密文(`<!-- mdcg-enc:v1:…`)恒无域信号——无密钥的读面会把
483
- 密文**原样**交到这里,base64 噪声会碰巧命中词表(实测唯一命中形态=「经济」:
484
- 词表里唯一的拉丁词 GDP 被 base64 三连子串撞上),且假标签会被 backfill 的
485
- already 幂等分支永久固化。判据收在此**唯一致敏点**:节点侧全部调用方
486
- (add 写入面、backfill 回填面)自动同覆盖,无需各自设防。
487
- """
488
- from . import crypto # 延迟导入:routing 是底层模块,避免加载序耦合
489
- if crypto.is_encrypted(text):
490
- return None
1
+ # -*- coding: utf-8 -*-
2
+ """md 认知图 · 路由键归一化(风险1)
3
+
4
+ 普查结论(wisdom-book-cloud-new.db, 3048 节点):
5
+ - 原始 condition_space 四元组作分桶键 → 3037 桶 / 3048 节点,99.9% 单例桶。
6
+ 根因:observation_position 实际格式是「<域> 知识点(<实例名>)」,把节点特有的
7
+ 实例名嵌进了条件字段,3033 种取值 ≈ 唯一。按它分桶 = 一节点一桶,查询侧
8
+ 构造不出精确匹配的情境 → 命中率≈0,召回归零(比退化成全量更糟)。
9
+ - observation_tool(93% 集中) / existence_constraint(95% 集中) 去掉 position 后
10
+ 塌缩成单个巨桶。
11
+ - time_window 实测仅 3 种取值,进哈希键是纯噪声。
12
+ - tags 的 domain: 标签 → 95 桶 / 最大桶 5.4% / 期望扫描 1.8%,是唯一健康的键。
13
+
14
+ 因此路由键 = 归一化提取的「域」,而非四元组哈希。写入侧与查询侧共用本模块,
15
+ 保证两侧同构(风险2 的前提:查询构造的键必须与写入键落在同一空间)。
16
+ """
17
+ import math
18
+ import re
19
+ import hashlib
20
+ import unicodedata
21
+
22
+ # observation_position 的实例名尾巴:「知识点(xxx)」「概念(xxx)」等
23
+ _INSTANCE_TAIL = re.compile(
24
+ r"\s*(知识点|概念|条目|卡片|节点|规律|定理|公式)\s*[((].*?[))]\s*$"
25
+ )
26
+ # 骨架填充类后缀:「高中物理知识点内容(按骨架填充)」→「高中物理」
27
+ _SKELETON_TAIL = re.compile(r"(知识点)?内容\s*[((]按骨架填充[))]\s*$")
28
+
29
+ ORPHAN = "orphan"
30
+
31
+
32
+ # 生效条件:text 为任意对象(None 按空串)时返回 str(text) 的 NFKC 归一结果;不 strip、不改大小写——**本仓 NFKC 口径的唯一单点**。
33
+ def nfkc_text(text) -> str:
34
+ """NFKC 归一的**唯一单点**(全角/半角、兼容字形收口,issue #362b/c)。
35
+
36
+ `normalize_domain`(路由键)与 `mdcg.neg_condition_hits` / `mdcg.strip_boundary_terms`
37
+ (负条件判据与边界摘词面)都经此函数取 NFKC。为什么必须抽成函数:本仓的返工教训
38
+ 是「两份实现 + 注释写着同源 = 口径必分叉」(见 `mdcg.py` 里 `_ccg_line` 的副本案)。
39
+ 仓内**不得**再出现第二处 NFKC 归一实现(本模块的单点是唯一入口)——由
40
+ `md_cg/test_issue362_neg_condition.py` 的 E 组做源码面单点断言钉死。
41
+ """
42
+ return unicodedata.normalize("NFKC", "" if text is None else str(text))
43
+
44
+
45
+ #: 繁→简折叠表(#362c:**机制在位、数据待补**)。
46
+ #:
47
+ #: 为什么是空表:仓内**没有**既有的繁简映射表(证据与检索口径见
48
+ #: `md_cg/test_issue362_neg_condition.py` 的 C 组注释)。而「只覆盖本 issue 语料的
49
+ #: 最小表」会在守卫里全绿、在真实流量上静默漏拒——那是**假绿**,比没有表更坏。
50
+ #: 故按 Lead 裁定(2026-10-14):**c 项本轮挂起**,只落机制单点;表默认空 ⇒
51
+ #: 生产行为一字不动。注入点见 `trad_to_simp()` / `set_trad_to_simp()`。
52
+ TRAD_TO_SIMP = {}
53
+
54
+
55
+ # 生效条件:无参时返回当前生效的繁→简折叠表({单字符 str: 单字符 str});默认即模块级 `TRAD_TO_SIMP`(空表)。
56
+ def trad_to_simp() -> dict:
57
+ """繁简折叠表的**读取单点**(#362c 注入点之一)。"""
58
+ return TRAD_TO_SIMP
59
+
60
+
61
+ # 生效条件:table 为 {单字符 str: 单字符 str} 映射时把它设为当前折叠表并返回旧表;table 为假值时复原为空表(返回旧表)。
62
+ def set_trad_to_simp(table) -> dict:
63
+ """繁简折叠表的**写入单点**(#362c):真源一旦确定,只在此处接入。
64
+
65
+ 守卫用它注入 2~3 条**测试用**映射,证明「表一旦有,c 项链路就是通的」——
66
+ 这条非恒真对照要证明的是**机制到位**,而不是「现在没有表」。
67
+ """
68
+ global TRAD_TO_SIMP
69
+ old = TRAD_TO_SIMP
70
+ TRAD_TO_SIMP = dict(table or {})
71
+ return old
72
+
73
+
74
+ # 生效条件:text 为任意对象(None 按空串)时返回「NFKC → casefold → 繁简折叠(表非空时)」的结果;不删空白、不改标点,除这三步外不做任何其它归一。
75
+ def fold_variants(text) -> str:
76
+ """检索/判据面的**字符归一人**(#362b/c):NFKC → casefold → 繁简折叠。
77
+
78
+ NFKC 走与 `normalize_domain` 同一个 `nfkc_text` 单点,故两侧**同口径**;
79
+ casefold 追加大小写折叠(`4G`/`4g`、`PDF`/`pdf`);繁简折叠表**当前为空**
80
+ (见 `TRAD_TO_SIMP`),表非空时逐字符替换。
81
+
82
+ 刻意**不做**超出这三步的任何归一(不删标点、不并同音、不做拼音)——过度归一
83
+ 与归一缺失同样是缺陷:守卫 K 组有 `C++`/`A-B`/`Ⅳ`/`ß` 的非恒真对照把
84
+ 「哪些改写是可接受的既有口径、哪些是越界」逐条钉住。
85
+ """
86
+ s = nfkc_text(text).casefold()
87
+ table = trad_to_simp()
88
+ if table:
89
+ s = "".join(table.get(ch, ch) for ch in s)
90
+ return s
91
+
92
+
93
+ # 生效条件:raw 为真值时按 NFKC 归一化并 strip,最多 3 轮剥离 _INSTANCE_TAIL(无变化即停)、再剥 _SKELETON_TAIL、空白转下划线后返回;raw 为假值(None/空串)或处理后为空串时返回 ORPHAN。
94
+ def normalize_domain(raw: str) -> str:
95
+ """把自由文本的域描述归一化成稳定的短键。
96
+
97
+ 「工程学 知识点(内力与截面法)」 → 工程学
98
+ 「高中物理知识点内容(按骨架填充)」 → 高中物理
99
+ 「数学分析知识点内容(按骨架填充) 知识点(贝塞尔不等式)」 → 数学分析
100
+ """
101
+ if not raw:
102
+ return ORPHAN
103
+ s = nfkc_text(raw).strip()
104
+ # 反复剥离实例名尾巴(可能叠加两层,见上面第三个例子)
105
+ for _ in range(3):
106
+ new = _INSTANCE_TAIL.sub("", s)
107
+ if new == s:
108
+ break
109
+ s = new.strip()
110
+ s = _SKELETON_TAIL.sub("", s).strip()
111
+ s = re.sub(r"\s+", "_", s)
112
+ return s or ORPHAN
113
+
114
+
115
+ # 生效条件:tags 为真值时取其中首个 str(t) 以 "domain:" 开头的项,返回其前缀后内容的 normalize_domain 结果;无此标签且 condition_space 为真值时返回 normalize_domain(condition_space.get("observation_position"))(缺键即 None 归一为 ORPHAN);tags 为假值且 condition_space 为假值时返回 ORPHAN。
116
+ def route_key(condition_space: dict = None, tags=None) -> str:
117
+ """导出条件路由键。优先级:tags 的 domain: > observation_position 归一化 > orphan。
118
+
119
+ domain: 标签是显式声明的域,普查证明它分布最健康(95 桶/最大桶 5.4%),
120
+ 所以优先。没有标签时才回退到从 observation_position 提取。
121
+ """
122
+ for t in tags or []:
123
+ t = str(t)
124
+ if t.startswith("domain:"):
125
+ return normalize_domain(t[len("domain:"):])
126
+ if condition_space:
127
+ return normalize_domain(condition_space.get("observation_position"))
128
+ return ORPHAN
129
+
130
+
131
+ # 生效条件:key 等于 ORPHAN 时原样返回 ORPHAN;否则返回 "cond_" + 把 key 中非[\w中文-]字符替换为下划线并截前 24 字符的串 + "_" + key 的 sha256(utf-8)前 8 位十六进制。
132
+ def bucket_dir(key: str) -> str:
133
+ """路由键 → 目录名。中文键保留可读前缀 + 短哈希,避免文件系统非法字符/超长。"""
134
+ if key == ORPHAN:
135
+ return ORPHAN
136
+ safe = re.sub(r"[^\w\u4e00-\u9fff-]", "_", key)[:24]
137
+ h = hashlib.sha256(key.encode("utf-8")).hexdigest()[:8]
138
+ return f"cond_{safe}_{h}"
139
+
140
+
141
+ # 14 大域代表词表(白箱第 2 篇第 5 章 + 第 3 篇第 4 章:「56 学科卡 → 14 大域
142
+ # → 域内 KCCS」两阶段并行收敛。本表用作阶段 1 的大域并行打分依据——
143
+ # 当 query 没有显式 context 但 query 词能落进某个大域时,先收敛到大域再查。
144
+ #
145
+ # 词的选取原则:覆盖白箱工程文档里出现的高频学科关键词,且不互相吞并。
146
+ # 同一个词可以出现在多个大域(如「公式」在数学与物理都常见),这是合理的:
147
+ # 大域并行打分阶段就是让多域同分,再由阶段 2 的 KCCS 进一步区分。
148
+ BIG_DOMAINS = {
149
+ "数学": {"数学", "算术", "几何", "代数", "微积分", "概率", "统计", "集合", "矩阵",
150
+ "线性", "拓扑", "数论", "公式", "定理", "证明", "函数", "导数", "积分",
151
+ "极限", "方程", "不等式", "贝塞尔", "二分", "素数", "微元"},
152
+ "物理": {"物理", "力学", "电磁", "光学", "热学", "量子", "相对论", "能量", "动量",
153
+ "质量", "速度", "加速度", "电荷", "电压", "电流", "沸点", "海拔",
154
+ "大气压", "压强", "温度", "牛顿", "惯性", "引力"},
155
+ "化学": {"化学", "元素", "分子", "原子", "化合物", "反应", "酸", "碱", "盐",
156
+ "氧化", "还原", "有机", "无机", "离子", "键", "浓度", "溶液"},
157
+ "生物": {"生物", "细胞", "基因", "蛋白质", "酶", "光合", "呼吸", "植物", "动物",
158
+ "进化", "免疫", "神经", "细菌", "病毒", "代谢", "染色", "分裂"},
159
+ "计算机": {"计算机", "算法", "数据结构", "编程", "代码", "软件", "网络", "数据库",
160
+ "系统", "排序", "递归", "图论", "哈希", "索引", "查询", "排序", "锁",
161
+ "事务", "内存", "进程", "线程"},
162
+ "语言": {"语言", "中文", "英文", "语法", "词汇", "语义", "修辞", "文学", "写作",
163
+ "阅读", "拼音", "字", "词", "句"},
164
+ "历史": {"历史", "朝代", "战争", "文明", "政治", "经济史", "文化史", "古代",
165
+ "近代", "现代", "王朝", "革命", "改革"},
166
+ "地理": {"地理", "地形", "气候", "人口", "城市", "国家", "地图", "板块",
167
+ "洋流", "经度", "纬度", "海拔带", "流域"},
168
+ "艺术": {"艺术", "绘画", "音乐", "雕塑", "电影", "设计", "色彩", "构图",
169
+ "旋律", "节奏", "摄影"},
170
+ "经济": {"经济", "市场", "金融", "货币", "投资", "股票", "债券", "GDP",
171
+ "通胀", "财政", "税收", "供需"},
172
+ "心理": {"心理", "认知", "情感", "记忆", "学习", "性格", "行为", "意识",
173
+ "动机", "人格", "焦虑"},
174
+ "医学": {"医学", "疾病", "治疗", "药物", "诊断", "外科", "内科", "儿科",
175
+ "中医", "症状", "病理", "处方"},
176
+ "工程": {"工程", "建筑", "结构", "材料", "机械", "电子", "土木", "桥梁",
177
+ "内力", "截面", "梁", "柱", "应力"},
178
+ "通用": {"常识", "生活", "日常", "通用", "礼仪", "礼貌", "文明", "规则"},
179
+ }
180
+
181
+
182
+ # 生效条件:terms 为真值时对 BIG_DOMAINS 每个大域统计命中词数,最高分为 0 或 terms 为假值(None/空)时返回 None,否则返回最高分大域名(并列取 BIG_DOMAINS 迭代序首个最高分)。
183
+ def big_domain_classify(terms) -> str | None:
184
+ """阶段 1:14 大域并行打分 → 收敛到 top-1。
185
+
186
+ terms 是 expand_query_terms 返回的扩展词集合。
187
+ 大域打分 = query 词命中大域代表词的次数(多词同域累加)。
188
+ 并行在认知结构意义上:即使底层串行计算,14 个大域同时独立评估。
189
+
190
+ 返回最匹配的大域名(多个 0 分 → 返回 None,走原 bucket_dir 路由)。
191
+ """
192
+ if not terms:
193
+ return None
194
+ scores = {}
195
+ for d, vocab in BIG_DOMAINS.items():
196
+ scores[d] = sum(1 for t in terms
197
+ if any(w in t or t in w for w in vocab))
198
+ best = max(scores.items(), key=lambda x: x[1])
199
+ if best[1] == 0:
200
+ return None
201
+ # 多大域并列最高分时,按字典序取第一个稳定结果(避免浮点不确定)
202
+ return best[0]
203
+
204
+
205
+ # 生效条件:terms 为假值(None/空)时返回 {每个 BIG_DOMAINS 域: 0};terms 为真值时返回 {大域: 该域词表命中 terms 中词的个数}。
206
+ def big_domain_score_breakdown(terms) -> dict:
207
+ """暴露打分明细,便于审计与回归测试。"""
208
+ if not terms:
209
+ return {d: 0 for d in BIG_DOMAINS}
210
+ return {d: sum(1 for t in terms if any(w in t or t in w for w in vocab))
211
+ for d, vocab in BIG_DOMAINS.items()}
212
+
213
+
214
+ # ---------------------------------------------------------------------------
215
+ # 分级隶属度(模糊控制「隶属函数」的手写版)
216
+ #
217
+ # 上面的 big_domain_classify 是二值控制:`w in t or t in w` 命中即计 1。
218
+ # 下面是同一套规则库的**分级**版本——命中程度是 0~1 的连续值,并乘 IDF:
219
+ # · 隶属度 membership(t, w):完全相同 1.0;包含关系取长度比(覆盖越全越高)
220
+ # · IDF:一个代表词覆盖的大域越少,区分度越高(「贝塞尔」只在数学出现,
221
+ # 权重高于「公式」这种跨域通用词)
222
+ # 老函数保持不动 → P0/P1 基线可比性不受影响;新函数只供新路径(fuzzy)使用。
223
+ # ---------------------------------------------------------------------------
224
+
225
+ # 生效条件:term 或 word 为假值(None/空串)返回 0.0;相等返回 1.0;word 是 term 子串返回 len(word)/len(term);term 是 word 子串返回 len(term)/len(word);二者无包含关系返回 0.0。
226
+ def membership(term: str, word: str) -> float:
227
+ """词 term 对代表词 word 的隶属度(0.0~1.0,越接近 1 越隶属)。
228
+
229
+ 完全相同 → 1.0
230
+ term 包含 word → len(word)/len(term)(覆盖越全越隶属)
231
+ word 包含 term → len(term)/len(word)
232
+ 无包含关系 → 0.0
233
+ """
234
+ if not term or not word:
235
+ return 0.0
236
+ if term == word:
237
+ return 1.0
238
+ if word in term:
239
+ return len(word) / len(term)
240
+ if term in word:
241
+ return len(term) / len(word)
242
+ return 0.0
243
+
244
+
245
+ # 生效条件:无入参,恒遍历模块级常量 BIG_DOMAINS 的各域代表词表,返回 {代表词: 包含该词的域个数}。
246
+ def _build_domain_df() -> dict:
247
+ """代表词 → 覆盖它的大域数(IDF 的分母)。"""
248
+ df = {}
249
+ for vocab in BIG_DOMAINS.values():
250
+ for w in vocab:
251
+ df[w] = df.get(w, 0) + 1
252
+ return df
253
+
254
+
255
+ _DOMAIN_DF = _build_domain_df()
256
+
257
+
258
+ # 生效条件:恒返回 math.log(1.0 + len(BIG_DOMAINS) / _DOMAIN_DF.get(word, 1)),即 word 在 _DOMAIN_DF 中取其覆盖域数,缺键(含任何未登记值)时按 _DOMAIN_DF.get 的默认 1 代入。
259
+ def domain_idf(word: str) -> float:
260
+ """代表词的区分度权重:log(1 + 大域总数 / 覆盖它的大域数)。
261
+
262
+ 只在一个大域出现的词(如「贝塞尔」)≈ log(15)=2.71;
263
+ 14 个大域都出现的词(如「公式」)≈ log(2)=0.69。
264
+ """
265
+ return math.log(1.0 + len(BIG_DOMAINS) / _DOMAIN_DF.get(word, 1))
266
+
267
+
268
+ # 生效条件:terms 是 dict 时以其条目(键 str(t) 以 "__" 开头者剔除、值为 float)为词权重并忽略 weights,否则以 wmap.get(t, 1.0) 为权重(weights 为假值即 None/空 dict 时 wmap 为空、全部权重取 1.0,terms 为假值则词集为空);逐域累加「词权重 × 该词在域词表内最大(membership × domain_idf)」,权重 <=0 的词跳过,返回 {大域: round(得分, 6)}。
269
+ def big_domain_score_weighted(terms, weights=None) -> dict:
270
+ """阶段 1(分级版):14 大域并行打分,按「隶属度 × IDF」加权。
271
+
272
+ terms: 可迭代的词集合,或 {词: 权重}(expand_query_terms_weighted 的输出,
273
+ 调用方需先剔除 "__source__" 等元数据键)。
274
+ weights: terms 为可迭代时的可选权重表;terms 已是 dict 时忽略。
275
+ 返回 {大域: 得分},得分不再是整数计数,而是连续值。
276
+ """
277
+ if isinstance(terms, dict):
278
+ tw = {str(t): float(w) for t, w in terms.items()
279
+ if not str(t).startswith("__")}
280
+ else:
281
+ wmap = weights or {}
282
+ tw = {str(t): float(wmap.get(t, 1.0)) for t in (terms or [])}
283
+ out = {}
284
+ for d, vocab in BIG_DOMAINS.items():
285
+ s = 0.0
286
+ for t, tw_ in tw.items():
287
+ if tw_ <= 0:
288
+ continue
289
+ best = 0.0
290
+ for w in vocab:
291
+ m = membership(t, w)
292
+ if m > 0.0:
293
+ best = max(best, m * domain_idf(w))
294
+ s += tw_ * best
295
+ out[d] = round(s, 6)
296
+ return out
297
+
298
+
299
+ # 生效条件:以 terms、weights 计算各域加权得分(terms 为假值时各域均为 0.0),得分为空或最高分 <= min_score(默认 0.0)时返回 None,否则返回最高分大域名。
300
+ def big_domain_classify_weighted(terms, weights=None, min_score: float = 0.0):
301
+ """阶段 1(分级版)收敛到 top-1;全部低于 min_score → None。"""
302
+ scores = big_domain_score_weighted(terms, weights)
303
+ if not scores:
304
+ return None
305
+ best = max(scores.items(), key=lambda kv: kv[1])
306
+ if best[1] <= min_score:
307
+ return None
308
+ return best[0]
309
+
310
+
311
+ # 生效条件:a 或 b 为假值(None/空串)返回 0.0;相等返回 1.0;a 是 b 子串返回 len(a)/len(b);b 是 a 子串返回 len(b)/len(a);否则按二者二元组字符集合的 Jaccard 返回 len(ga & gb)/len(ga | gb),任一集合为空(如单字符键)时返回 0.0。
312
+ def domain_similarity(a: str, b: str) -> float:
313
+ """两个归一化域键的相似度(0~1):相同 1.0;包含取长度比;否则二元组 Jaccard。
314
+
315
+ 「计算机科学」vs「计算机」→ 0.6(包含);「高中物理」vs「物理」→ 0.5;
316
+ 完全无关 → 0.0。用于 fuzzy 路径的「大域亲和」打分。
317
+ """
318
+ if not a or not b:
319
+ return 0.0
320
+ if a == b:
321
+ return 1.0
322
+ if a in b:
323
+ return len(a) / len(b)
324
+ if b in a:
325
+ return len(b) / len(a)
326
+ ga = {a[i:i + 2] for i in range(len(a) - 1)}
327
+ gb = {b[i:i + 2] for i in range(len(b) - 1)}
328
+ if not ga or not gb:
329
+ return 0.0
330
+ return len(ga & gb) / len(ga | gb)
331
+
332
+
333
+ # 生效条件:counts 各值之和为 0(含空 dict 与全 0 计数)时——total_nodes 为假值(缺省 None 或 <=0)返回 {'ok': True, 'reason': 'empty', 'buckets': 0}(与加 total_nodes 参数之前逐位一致),total_nodes > 0 返回 {'ok': False, 'reason': 'empty_buckets', 'buckets': 0, 'nodes': total_nodes, 'problems': [...]};否则在「桶数 >1 且最大桶占比 >30%」、「桶数 >1 且单例桶占比 >50%」、「桶数 ==1(单桶,条件路由不可用)」、桶数 >1 时「期望扫描 >30%」中命中的项写入 problems,返回含 ok(=problems 为空)、buckets、nodes、max_bucket_share、singleton_ratio、expected_scan、problems 的 dict。
334
+ def bucket_health(counts: dict, total_nodes: int = None) -> dict:
335
+ """分区健康度自检。分桶键一旦退化(巨桶或碎片化),条件路由就是纸面收益,
336
+ 必须在写入侧就能发现,而不是等召回变差才回头查。
337
+
338
+ counts: {bucket_dir: node_count}
339
+ total_nodes: 调用方(`MdCG.health`)持有的**库内节点总数**,唯一用途是把
340
+ 「真空库(无节点、无桶)」与「有节点但分桶表为空(分区信息缺失)」分开。
341
+ **缺省 None ⇒ 不做该比对**:空 counts 的返回与加本参数之前逐位一致,
342
+ 故既有调用方(test_p0 / bench_axis_domain / bench6_arms,只传 counts)
343
+ 行为一字不变——M3③ 的向后兼容面。
344
+
345
+ 单桶(nb == 1)是「从未分区」而不是「分区退化」:巨桶判据(top/n == 1.0)与
346
+ 期望扫描判据(同样恒 1.0)在 nb==1 时必触发且互为同一事实,此前把这类库报成
347
+ 「巨桶 / 分区失效」是假话(M3①②)。现只给一条如实读数——条件路由本就不可用;
348
+ ok 仍为 False(单桶库的一次查询确实是全量扫描,判据未放宽)。
349
+ """
350
+ n = sum(counts.values())
351
+ nb = len(counts)
352
+ if not n:
353
+ # 库里有节点却零个桶 ⇒ 分桶表与节点面不一致(分区信息缺失),
354
+ # 不能报 ok=True 冒充健康(M3③)。total_nodes 缺省时不作此判断。
355
+ if total_nodes and total_nodes > 0:
356
+ return {
357
+ "ok": False,
358
+ "reason": "empty_buckets",
359
+ "buckets": 0,
360
+ "nodes": int(total_nodes),
361
+ "problems": [f"分桶表为空但库内有 {int(total_nodes)} 个节点:"
362
+ "分区信息缺失,条件路由不可用(非真空库)"],
363
+ }
364
+ return {"ok": True, "reason": "empty", "buckets": 0}
365
+ top = max(counts.values())
366
+ singles = sum(1 for v in counts.values() if v == 1)
367
+ # 期望扫描占比:随机取一节点的情境去路由,命中桶的期望大小占全库比例
368
+ expected_scan = sum(v * v for v in counts.values()) / n / n
369
+ problems = []
370
+ if nb > 1 and top / n > 0.30:
371
+ problems.append(f"巨桶:最大桶占 {top / n:.1%}(>30% 视为分区失效)")
372
+ if nb > 1 and singles / nb > 0.50:
373
+ problems.append(f"碎片化:单例桶占 {singles / nb:.1%}(>50% 说明键含实例级字段)")
374
+ if nb == 1:
375
+ # 巨桶/期望扫描两条在 nb==1 时只是同一事实的两种写法,合并为一条如实读数。
376
+ # expected_scan 的**数值**仍在返回 dict 里(下游读的是数:test_p0 :92、
377
+ # bench_axis_domain :159),只有文案不再把「未分区」说成「巨桶退化」。
378
+ problems.append(f"单桶:仅 1 个分桶({n} 个已分桶节点同桶),"
379
+ "条件路由本就不可用(从未分区,非分区退化)")
380
+ elif expected_scan > 0.30:
381
+ problems.append(f"路由无效:期望扫描 {expected_scan:.1%}(接近全量)")
382
+ return {
383
+ "ok": not problems,
384
+ "buckets": nb,
385
+ "nodes": n,
386
+ "max_bucket_share": top / n,
387
+ "singleton_ratio": singles / nb if nb else 0.0,
388
+ "expected_scan": expected_scan,
389
+ "problems": problems,
390
+ }
391
+
392
+
393
+ # ---------------------------------------------------------------------------
394
+ # 节点侧大域标签(S1 大域先验收敛的前置元数据)
395
+ #
396
+ # 为何需要:`big_domain_classify` 一直只作用于 **query 侧**(terms),节点侧没有域字段,
397
+ # 于是「14 大域并行打分」算完只能写进 meta(审计偏差 4:先验算出来却当成报告)。
398
+ # 要让大域先验真正参与候选收敛,节点必须在写入时固化自己的域。
399
+ # 口径:与查询侧同一个分类器(BIG_DOMAINS + big_domain_classify),保证两侧同构。
400
+ # ---------------------------------------------------------------------------
401
+
402
+ # 域词取词:中文(≥2 字)与拉丁词(≥2 字)。词表命中用「包含关系」判定,
403
+ # 故 2 字以上的切口足以覆盖 1~4 字代表词(如「工程」命中「工程师」)。
404
+ DOMAIN_TERM_RE = re.compile(r"[\u4e00-\u9fff]{2,}|[A-Za-z][A-Za-z0-9_]{1,}")
405
+
406
+
407
+ # 生效条件:text 为假值(None/空串)时返回 [];否则以 DOMAIN_TERM_RE 取词、按出现顺序去重后返回,
408
+ # 最多 limit 个(limit 为假值/负数时按空处理,返回 [])。
409
+ def domain_terms(text, limit: int = 400) -> list:
410
+ """从节点正文/标题抽「域词」(供 big_domain_classify 使用)。
411
+
412
+ 只做最小分词:中文按 ≥2 字连续片段、拉丁按 [A-Za-z][A-Za-z0-9_]+ 取词;
413
+ 去重保序,最多 limit 个(默认 400,避免长文把分类器拖慢)。
414
+ """
415
+ if not text or not limit or limit < 1:
416
+ return []
417
+ out, seen = [], set()
418
+ for m in DOMAIN_TERM_RE.finditer(str(text)):
419
+ w = m.group(0)
420
+ if w in seen:
421
+ continue
422
+ seen.add(w)
423
+ out.append(w)
424
+ if len(out) >= limit:
425
+ break
426
+ return out
427
+
428
+
429
+ # 生效条件:bucket 为假值或等于 ORPHAN 时返回空串;否则去掉 "cond_" 前缀、并当末段为 8 位十六进制哈希时剥掉该段,返回剩余的可读键。
430
+ def bucket_key_readable(bucket: str) -> str:
431
+ """桶目录名 → 可读键(S1b query 侧桶推断用):'cond_感知系统_d94e90d2' → '感知系统'。
432
+
433
+ 与 `bucket_dir` 互逆(丢哈希段);`orphan`/空值返回空串(S1b 不把 orphan 当键,orphan 恒作兜底)。
434
+ """
435
+ if not bucket or bucket == ORPHAN:
436
+ return ""
437
+ s = str(bucket)
438
+ if s.startswith("cond_"):
439
+ s = s[len("cond_"):]
440
+ head, sep, tail = s.rpartition("_")
441
+ if sep and len(tail) == 8 and all(c in "0123456789abcdef" for c in tail):
442
+ s = head
443
+ return s
444
+
445
+
446
+ # 中文词判定:至少含一个汉字
447
+ _ZH_RE = re.compile(r"[\u4e00-\u9fff]")
448
+
449
+
450
+ # 生效条件:key 缺失或含汉字时返回 [];否则从 tags(保序在前)与 text 域词(domain_terms)中收集含汉字、长度≥2 的词,去重取前 limit 个返回。
451
+ def bucket_zh_aliases(key: str, tags, text, limit: int = 6) -> list:
452
+ """英文桶键的中文别名(issue #33:S1b 跨语言收敛盲区的修复面)。
453
+
454
+ 机理:domain_similarity 的 bigram 兜底跨语言交集恒空——英文桶键 × 中文
455
+ query 恒 0.0 → S1b 恒 no_key_match(真实库 91.1% 中文节点恰是设计目标场景)。
456
+ 别名**只取节点自身内容**(tags 中文词 ∪ 正文中文域词,tags 优先),零翻译
457
+ 依赖——unify_query/en_zh_terms 桥接已被 #33 实测排除(字级直译语义毁)。
458
+ 键本身含中文时无跨语言问题,返回 []。
459
+ """
460
+ if not key or _ZH_RE.search(str(key)):
461
+ return []
462
+ out, seen = [], set()
463
+ src = [str(t) for t in (tags or [])]
464
+ src += domain_terms(text or "", limit=200)
465
+ for w in src:
466
+ if len(w) >= 2 and _ZH_RE.search(w) and w not in seen:
467
+ seen.add(w)
468
+ out.append(w)
469
+ if len(out) >= limit:
470
+ break
471
+ return out
472
+
473
+
474
+ # 生效条件:text 为假值或取不到任何域词时返回 None;否则返回 big_domain_classify(domain_terms(text))
475
+ # 的结果(无有效域信号时亦为 None,调用方据此决定是否落域字段)。
476
+ def classify_text(text, limit: int = 400):
477
+ """正文 → 大域名(节点侧域标签真源)。与查询侧共用 big_domain_classify。
478
+
479
+ 返回 None 表示「无有效域信号」——此时**不写** big_domain 字段,
480
+ 该节点留在 ORPHAN/兜底池(S1 收敛时必须能被兜底召回,见契约 §3 S1 不变量)。
481
+
482
+ issue #53-A:密文(`<!-- mdcg-enc:v1:…`)恒无域信号——无密钥的读面会把
483
+ 密文**原样**交到这里,base64 噪声会碰巧命中词表(实测唯一命中形态=「经济」:
484
+ 词表里唯一的拉丁词 GDP 被 base64 三连子串撞上),且假标签会被 backfill 的
485
+ already 幂等分支永久固化。判据收在此**唯一致敏点**:节点侧全部调用方
486
+ (add 写入面、backfill 回填面)自动同覆盖,无需各自设防。
487
+ """
488
+ from . import crypto # 延迟导入:routing 是底层模块,避免加载序耦合
489
+ if crypto.is_encrypted(text):
490
+ return None
491
491
  return big_domain_classify(domain_terms(text, limit))