argo-search 2.14.1 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +54 -832
  3. package/README.ja.md +53 -833
  4. package/README.ko.md +53 -831
  5. package/README.md +126 -769
  6. package/README.zh.md +124 -893
  7. package/SKILL.md +17 -18
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +23 -23
  10. package/backends/concept_vectors.bin +0 -0
  11. package/backends/domain_profiles.json +42 -0
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +124 -28
  14. package/backends/quota_profiles.json +70 -0
  15. package/bin/argo +30 -17
  16. package/config.yaml +173 -33
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +23 -0
  20. package/docs/ENGINE_CATALOG.md +97 -85
  21. package/docs/MCP_SETUP.md +1 -1
  22. package/docs/RELEASE_NOTES_v2.14.1.md +4 -4
  23. package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
  24. package/docs/RELEASING.md +1 -1
  25. package/engines/specs/ai_labs.yaml +89 -0
  26. package/engines/specs/bilibili_hot.yaml +11 -1
  27. package/engines/specs/brave.yaml +3 -3
  28. package/engines/specs/cisa_alerts.yaml +40 -0
  29. package/engines/specs/cn_ai_news.yaml +10 -8
  30. package/engines/specs/digup.yaml +11 -6
  31. package/engines/specs/douyin_hot.yaml +11 -1
  32. package/engines/specs/dw_news.yaml +4 -2
  33. package/engines/specs/eng_blogs.yaml +63 -0
  34. package/engines/specs/europeana.yaml +3 -4
  35. package/engines/specs/felo.yaml +3 -3
  36. package/engines/specs/firecrawl.yaml +3 -0
  37. package/engines/specs/fourget.yaml +5 -2
  38. package/engines/specs/france24.yaml +6 -4
  39. package/engines/specs/fxtwitter.yaml +29 -6
  40. package/engines/specs/grepapp_mcp.yaml +62 -0
  41. package/engines/specs/guardian_rss.yaml +6 -4
  42. package/engines/specs/itotii.yaml +13 -1
  43. package/engines/specs/lobsters.yaml +41 -0
  44. package/engines/specs/local_seek.yaml +6 -0
  45. package/engines/specs/open_meteo.yaml +1 -1
  46. package/engines/specs/redskill.yaml +2 -0
  47. package/engines/specs/searxng.yaml +4 -2
  48. package/engines/specs/sec_edgar.yaml +8 -3
  49. package/engines/specs/tinyfish.yaml +2 -0
  50. package/engines/specs/tinyfish_news.yaml +2 -0
  51. package/engines/specs/tinyfish_paper.yaml +2 -0
  52. package/engines/specs/toutiao_hot.yaml +11 -1
  53. package/engines/specs/train.yaml +3 -0
  54. package/engines/specs/twitter.yaml +4 -0
  55. package/engines/specs/unpaywall.yaml +6 -0
  56. package/engines/specs/vam.yaml +17 -3
  57. package/engines/specs/weibo_hot.yaml +11 -1
  58. package/engines/specs/wolframalpha.yaml +3 -3
  59. package/engines/specs/xiaohongshu.yaml +2 -0
  60. package/engines/specs/zhihu.yaml +3 -18
  61. package/engines/specs/zhihu_kb.yaml +18 -0
  62. package/engines/specs/zhihu_questions.yaml +19 -0
  63. package/package.json +3 -2
  64. package/packages/dsh-plugin/README.md +9 -14
  65. package/packages/dsh-plugin/dsh/client.js +467 -1024
  66. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  67. package/packages/dsh-plugin/dsh/runner.js +2 -0
  68. package/packages/dsh-plugin/package.json +8 -3
  69. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  70. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  71. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  72. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  73. package/scripts/adaptive.py +7 -1
  74. package/scripts/archive_run.py +112 -53
  75. package/scripts/argo_paths.py +40 -3
  76. package/scripts/badcase_ledger.py +108 -9
  77. package/scripts/build_concept_table.py +112 -55
  78. package/scripts/cache.py +5 -1
  79. package/scripts/caliber_isolation.py +60 -23
  80. package/scripts/circuit_breaker.py +56 -8
  81. package/scripts/cli_io.py +20 -2
  82. package/scripts/config_cache.py +31 -0
  83. package/scripts/daemon.py +146 -51
  84. package/scripts/dormant_ledger.py +23 -9
  85. package/scripts/engine_dispatch.py +3 -3
  86. package/scripts/engine_env.py +182 -1
  87. package/scripts/engine_families.py +50 -7
  88. package/scripts/engine_states.py +3 -50
  89. package/scripts/engine_validate.py +13 -45
  90. package/scripts/engines.py +15 -31
  91. package/scripts/engines_base.py +42 -58
  92. package/scripts/engines_builders.py +0 -15
  93. package/scripts/engines_builders_batch10.py +346 -100
  94. package/scripts/engines_builders_batch11.py +2 -75
  95. package/scripts/engines_builders_batch9.py +15 -24
  96. package/scripts/engines_builders_cn.py +0 -194
  97. package/scripts/engines_builders_feeds.py +55 -5
  98. package/scripts/engines_builders_intl.py +15 -115
  99. package/scripts/engines_builders_pixiv.py +2 -16
  100. package/scripts/engines_builders_search.py +7 -14
  101. package/scripts/engines_builders_tech.py +5 -14
  102. package/scripts/engines_builders_weather.py +236 -0
  103. package/scripts/engines_fields.py +91 -0
  104. package/scripts/engines_http.py +135 -0
  105. package/scripts/engines_mcp.py +383 -0
  106. package/scripts/engines_parsers.py +13 -369
  107. package/scripts/engines_schema_drift.py +260 -0
  108. package/scripts/evidence.py +13 -0
  109. package/scripts/evidence_loop.py +4 -3
  110. package/scripts/fetch_jsrun.py +15 -11
  111. package/scripts/fetch_v3.py +28 -28
  112. package/scripts/fulltext_store.py +42 -1
  113. package/scripts/fxtwitter_api.py +8 -7
  114. package/scripts/gen_engine_catalog.py +2 -2
  115. package/scripts/general_pool.py +15 -4
  116. package/scripts/health_check.py +1 -1
  117. package/scripts/link_source.py +65 -24
  118. package/scripts/local_seek_adapter.py +57 -17
  119. package/scripts/mcp_handlers.py +53 -31
  120. package/scripts/mcp_handlers_surface.py +6 -18
  121. package/scripts/mcp_transport.py +1 -1
  122. package/scripts/min_version_scan.py +7 -3
  123. package/scripts/network_aware.py +7 -13
  124. package/scripts/pre-commit +45 -43
  125. package/scripts/query_understanding.py +30 -6
  126. package/scripts/quota.py +6 -1
  127. package/scripts/rank_signals.py +9 -0
  128. package/scripts/recompute.py +15 -5
  129. package/scripts/recovery.py +21 -15
  130. package/scripts/release.py +14 -26
  131. package/scripts/release_check.py +5 -25
  132. package/scripts/replay_eval.py +2 -2
  133. package/scripts/research_cli.py +40 -0
  134. package/scripts/research_notes.py +368 -0
  135. package/scripts/route.py +32 -70
  136. package/scripts/route_audit.py +259 -0
  137. package/scripts/route_combo.py +10 -4
  138. package/scripts/route_domains.py +150 -23
  139. package/scripts/route_lang.py +20 -7
  140. package/scripts/route_log.py +26 -9
  141. package/scripts/route_policy.py +85 -6
  142. package/scripts/route_telemetry_export.py +199 -0
  143. package/scripts/rrf_classic.py +5 -22
  144. package/scripts/search.py +2 -1
  145. package/scripts/search_attribution.py +33 -10
  146. package/scripts/search_entry.py +5 -1
  147. package/scripts/search_output.py +5 -4
  148. package/scripts/search_pipeline.py +12 -0
  149. package/scripts/search_rank.py +21 -11
  150. package/scripts/semantic_evidence.py +375 -168
  151. package/scripts/settings_page.py +3 -3
  152. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  153. package/scripts/social_engines/zhihu_engine.py +251 -43
  154. package/scripts/sogou_weixin_browser.py +5 -6
  155. package/scripts/source_audit.py +2 -2
  156. package/scripts/source_ledger.py +2 -15
  157. package/scripts/source_selection.py +45 -20
  158. package/scripts/straggler_policy.py +1 -2
  159. package/scripts/sync_backends.py +17 -0
  160. package/scripts/tfidf_router.py +23 -11
  161. package/scripts/time_utils.py +54 -1
  162. package/scripts/train.py +68 -2
  163. package/scripts/usage_log.py +26 -1
  164. package/sub-skills/argo-wide-research/SKILL.md +68 -0
  165. package/sub-skills/ego-search/SKILL.md +1 -1
  166. package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
  167. package/scripts/caliber_dedupe.py +0 -66
  168. package/scripts/engines_builders_batch16.py +0 -13
  169. package/scripts/health_probe.py +0 -253
  170. package/scripts/social_engines/twitter_engine.py +0 -514
  171. package/scripts/sync_installs.py +0 -29
package/scripts/route.py CHANGED
@@ -76,6 +76,7 @@ from route_domains import ( # noqa: E402
76
76
  _ZH_LANG_GATED_DOMAINS,
77
77
  _DIFFUSE_SIGNAL_RE,
78
78
  _INTENT_MIN_TOKENS,
79
+ platform_native_engine,
79
80
  )
80
81
 
81
82
  # 路由决策缓存(存储层)住在 route_cache;route_query_cached 是本模块的编排
@@ -157,6 +158,10 @@ from route_policy import ( # noqa: E402
157
158
  _new_source_budget_extra,
158
159
  _apply_engine_policy,
159
160
  _apply_policy_with_new_source_slots,
161
+ is_pure_combo_domain,
162
+ apply_domain_combo_rules,
163
+ resolve_pure_combo_fallback,
164
+ build_domain_must_keep,
160
165
  )
161
166
 
162
167
  # ── 特征提取 ──────────────────────────────────────────────────────────────────
@@ -365,49 +370,16 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
365
370
  _specs_snapshot()))
366
371
  _filtered = [e for e in engines_combo if e not in _drop]
367
372
  engines_combo = _filtered or [e for e in ["anysearch"] if e in enabled] or engines_combo
368
- # 🔑 中文查询 + 学术类域 → 剔除纯英文论文源(ENGINE_LANGS 声明 langs=["en"])
369
- if (domain.get("name") in ("tech_deep", "academic")
370
- and any("\u4e00" <= ch <= "\u9fff" for ch in query)):
371
- engines_combo = [e for e in engines_combo
372
- if engine_langs(e, _specs_snapshot().get(e)) != {"en"}]
373
- if not engines_combo:
374
- engines_combo = [e for e in ["arxiv", "anysearch", "local_search"]
375
- if e in enabled]
376
- # 🔑 macro_data 域 + 非美国国家词 → worldbank 前置(FRED 无该国数据,
377
- # 且错误结果会触发 early-stop 短路,导致「中国GDP」只回美国数据)
378
- if (domain.get("name") == "macro_data"
379
- and is_foreign_macro_query(query)
380
- and "worldbank" in engines_combo):
381
- engines_combo = ["worldbank"] + [e for e in engines_combo if e != "worldbank"]
382
- # 🔑 macro_data 域 + 中国宏观词 → nbs_stats(国家统计局)前置:
383
- # 本国宏观数据权威源,最新年份比 worldbank 全(worldbank 有 1-2 年
384
- # 数据滞后,「2025 年 GDP」类查询会空手)。与上方 worldbank 前置
385
- # 配合,中国查询最终位次 [nbs_stats, worldbank, ...]
386
- if (domain.get("name") == "macro_data"
387
- and "nbs_stats" in engines_combo
388
- and ("中国" in query or "china" in query.lower())):
389
- engines_combo = ["nbs_stats"] + [e for e in engines_combo if e != "nbs_stats"]
390
- # 🔑 为中文/学术查询追加本地引擎
391
- # modal_card 保持纯结构化路径:只走 bocha_ai → bocha,不混 web/geo 补充源
392
- _pure_combo = domain.get("name") == "modal_card"
373
+ engines_combo = apply_domain_combo_rules(
374
+ domain, engines_combo, query, enabled, _specs_snapshot())
375
+ _pure_combo = is_pure_combo_domain(domain)
393
376
  if not _pure_combo:
394
377
  engines_combo = _merge_language_engines(engines_combo, features, lang_engines)
395
378
  engines_combo = _lang_aware_combo_order(
396
379
  engines_combo, features, domain.get("name"), enabled, query)
397
380
  if not engines_combo:
398
381
  if _pure_combo:
399
- # 密钥缺失时 env_ready 会踢 combo;仍保留域声明引擎,
400
- # 执行层返回 error item,避免静默改走 anysearch 污染结构化语义
401
- declared = list(domain.get("engines_combo") or [])
402
- if not declared and domain.get("primary"):
403
- declared = [domain["primary"]]
404
- try:
405
- from engine_env import is_engine_allowed_by_env
406
- engines_combo = [
407
- e for e in declared if is_engine_allowed_by_env(e)
408
- ] or declared
409
- except ImportError:
410
- engines_combo = declared
382
+ engines_combo = resolve_pure_combo_fallback(domain)
411
383
  if not engines_combo:
412
384
  # 域内引擎全被过滤,回退(本地优先 + 通用免费源唯一来源)
413
385
  engines_combo = _general_fallback(
@@ -482,32 +454,8 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
482
454
  # 注意:本分支的 must_keep 组装**不能**并成一次调用——geo 项与 lang 项
483
455
  # 之间夹着垂直域主源保护,而 policy 是按 must_keep 的**顺序**补位的
484
456
  # (见 _apply_engine_policy 的 `for e in must_keep`),合并会改变 combo 次序。
485
- must_keep = []
486
- if features.get("has_geo") and "local_openstreetmap" in enabled and not _pure_combo:
487
- must_keep.append("local_openstreetmap")
488
- # 垂直域主源保护(名单见模块级 _VERTICAL_KEEP):这些域的专属源在
489
- # combo 里不是「通用源」,被 budget 截断后该域等于没源可用(实测
490
- # medical 的 who_don、japan_law 的 egov_law 均因 budget=2 被裁掉
491
- # → 路由命中但零结果)。
492
- if domain.get("name") in _VERTICAL_KEEP:
493
- p = domain.get("primary")
494
- # modal_card 可在缺 key(不在 enabled)时仍 must_keep,避免 budget 再裁
495
- # primary 受死源地板约束(engine_is_dead,与 GEC 同口径):
496
- # 死源进 must_keep 会被策略层强制补回 combo,撤销 GEC 地板过滤
497
- if p and p not in must_keep and (p in enabled or _pure_combo) \
498
- and not engine_is_dead(p):
499
- must_keep.append(p)
500
- # modal_card 整 combo 保底(bocha_ai 无配额时 bocha 必须在位)
501
- if domain.get("name") == "modal_card":
502
- for e in domain.get("engines_combo") or []:
503
- if e not in must_keep and (e in enabled or _pure_combo):
504
- must_keep.append(e)
505
- elif (p and p in enabled and p not in must_keep
506
- and not engine_is_dead(p)):
507
- must_keep.append(p)
508
- if domain.get("name") == "geo_places" and "local_openstreetmap" in enabled:
509
- if "local_openstreetmap" not in must_keep:
510
- must_keep.append("local_openstreetmap")
457
+ must_keep = build_domain_must_keep(
458
+ domain, features, enabled, _pure_combo, engine_is_dead)
511
459
 
512
460
  if not _pure_combo:
513
461
  must_keep.extend(_lang_must_keep(features, enabled, engines_combo, query))
@@ -554,7 +502,7 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
554
502
  try:
555
503
  from circuit_breaker import get_breaker
556
504
  st = get_breaker().status(p)
557
- if (st.get("state") == engine_states.BREAKER_OPEN and int(st.get("cooldown_remain") or 0) > 0):
505
+ if st.get("state") == engine_states.BREAKER_DISABLED or int(st.get("cooldown_remain") or 0) > 0:
558
506
  p = None
559
507
  except Exception as _exc: # 侧信道:熔断状态只影响 primary 扶正提示(规则见 except_sets)
560
508
  import logging
@@ -563,6 +511,18 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
563
511
  if p and p in engines_combo:
564
512
  engines_combo = [p] + [e for e in engines_combo if e != p]
565
513
 
514
+ # 平台原生主源(2026-11-15):X/推特/reddit 语境查询的主位应是平台原生
515
+ # 通道而非同域通用社区源——「推特上大家对 GPT 的评价」主位给 zhihu 等于
516
+ # 没接平台(实测公开版还把这类查询劫持到 academic/arXiv,@social_context
517
+ # 守卫已救回 social,这里是最后一步:原生源扶正/注入主位)。原生源未
518
+ # 启用或熔断时保持原序;注入时顶掉末位成员,预算窗口内保住原生主位。
519
+ _native = platform_native_engine(query) if domain.get("name") == "social" else None
520
+ if _native and _native in enabled and engines_combo \
521
+ and _native != engines_combo[0]:
522
+ _pre_len = len(engines_combo)
523
+ engines_combo = [_native] + [e for e in engines_combo if e != _native]
524
+ engines_combo = engines_combo[:max(_pre_len, 1)]
525
+
566
526
  # 强语义注入(v2.7.10):判据与「为什么放在 primary 扶正之后」见
567
527
  # route_combo.inject_strong_semantic 的 docstring。
568
528
  engines_combo, _strong = inject_strong_semantic(
@@ -830,15 +790,16 @@ def route_query(query: str, engine_override: str = "auto",
830
790
  # → 熔断器空键 ''),MCP/外部调用可能传入空 engine 参数
831
791
  # 显式引擎也补 domain 判定:让缓存 TTL 按真实域分域(财经 5min /
832
792
  # 新闻 10min / 学术 2h),usage_log 统计不再全糊成 general。
833
- _domain = None
834
- _hits = match_domains(query, max_n=1)
835
- if _hits:
836
- _domain = _hits[0].get("name")
793
+ _feats = extract_features(query)
794
+ if lang_override:
795
+ _feats = apply_lang_override(_feats, lang_override)
796
+ _hits = match_domains(query, max_n=1, intents=_feats.get("intents"))
797
+ _domain = _hits[0].get("name") if _hits else None
837
798
  return _done(
838
799
  engine=engines[0], engines=engines,
839
800
  engines_combo=engines,
840
801
  reason=f"用户指定: {', '.join(engines)}", confidence=1.0,
841
- features={}, domain=_domain, parallel=False, mode=mode,
802
+ features=_feats, domain=_domain, parallel=False, mode=mode,
842
803
  depth=depth, context=context,
843
804
  login_hint=_detect_login_intent(query, None),
844
805
  )
@@ -871,7 +832,8 @@ def route_query(query: str, engine_override: str = "auto",
871
832
  # (见 route_domains 模块 docstring):域精度的全部规则只有那一个实现,
872
833
  # 这里不再各调一次,避免「某个守卫忘了在另一条路径上施加」。
873
834
  _domain_hits = match_domains(query, domains_cfg,
874
- primary_lang=features.get("primary_lang"))
835
+ primary_lang=features.get("primary_lang"),
836
+ intents=features.get("intents"))
875
837
  domain = _domain_hits[0] if _domain_hits else None
876
838
  secondary = _domain_hits[1:] if len(_domain_hits) > 1 else []
877
839
  hard_domain = bool(domain and domain.get("patterns"))
@@ -0,0 +1,259 @@
1
+ #!/usr/bin/env python3
2
+ """route_audit.py — 路由误判度量(方案三:先量化,再决定修机制还是修个案)
3
+
4
+ ## 为什么需要它
5
+
6
+ `SUBSTRING_ACCIDENTS`(26 条)+ `LEGITIMATE_ROUTES`(41 条)是**手工**语料,
7
+ 误判靠人一个个撞见——2026-11-15 的 4 例(X/小红书/reddit 语境被 academic 与
8
+ tech_deep 劫持)就是这么发现的。本脚本补上「度量」这一格:
9
+
10
+ 1. 真实查询面:从 usage_log 取全部去重查询,跑当前路由,得到「域 × 查询」
11
+ 的实际分布,暴露「某个域吃掉了大量不该它的查询」这类结构性偏移。
12
+ 2. 语境交叉面:对每个域构造**触发词 × 语境词**的正反对照(语境词取自
13
+ `_CONTEXT_WORDS`:平台/产品/内容/论文/商业…),判定「命中域是否与该
14
+ 语境语义一致」,输出可疑清单。
15
+ 3. 基线数:`--json` 落盘为可复跑的基线(方案二改打分后重跑对比)。
16
+
17
+ ## 判据(保守,宁可少报)
18
+
19
+ 可疑 = 命中域 != 期望域,且**查询里出现了另一域的强语境词**。不做「域对不对」
20
+ 的主观判断——只报「语境词与命中域语义冲突」这一可机械验证的形态,人工复核后
21
+ 才进 SUBSTRING_ACCIDENTS。
22
+
23
+ 用法:
24
+ python3 scripts/route_audit.py # 打印摘要
25
+ python3 scripts/route_audit.py --all # 打印全部可疑
26
+ python3 scripts/route_audit.py --json BASELINE # 落盘基线
27
+ python3 scripts/route_audit.py --compare BASE # 与基线对比(方案二验收)
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import collections
34
+ import glob
35
+ import json
36
+ import sys
37
+ from pathlib import Path
38
+ from typing import Any
39
+
40
+ SCRIPTS = Path(__file__).resolve().parent
41
+ if str(SCRIPTS) not in sys.path:
42
+ sys.path.insert(0, str(SCRIPTS))
43
+
44
+ # 语境词表:每类是一组「强语境信号」。域与语境冲突时才是可疑。
45
+ # 词表刻意保守——只收语义指向明确的词,收宽了会淹没真误判。
46
+ #
47
+ # 2026-11-15 首轮实测教训:把「平台名」(抖音/小红书/微博…)直接当社交语境,
48
+ # 在 500 条真实查询上报出 8 条可疑,人工复核后**全是误报**——它们查的是
49
+ # 「平台官方公告 / 推荐算法说明 / 运营规范」,命中 chinese_tech_deep 或
50
+ # financial_news 恰恰能抓到官方文档,不是误判。
51
+ # 故平台词拆成两类:只有带**讨论/舆情**语义的写法才算社交语境。
52
+ _CONTEXT_WORDS: dict[str, list[str]] = {
53
+ # 强社交语境:明确要社区讨论/舆情,不是要官方说明
54
+ "social_platform": [
55
+ "X 上", "X 平台", "twitter 上", "网友", "热议", "舆论", "舆情",
56
+ "怎么看", "评价", "测评", "讨论", "吐槽", "口碑",
57
+ ],
58
+ "product_daily": [
59
+ "使用技巧", "怎么用", "教程", "指南", "官网", "价格", "多少钱",
60
+ "下载", "安装", "注册", "账号", "对比", "哪个好",
61
+ ],
62
+ "academic": [
63
+ "论文", "paper", "综述", "文献", "期刊", "arXiv", "DOI", "预印本",
64
+ "研究进展", "同行评议", "引用",
65
+ ],
66
+ "commercial_market": [
67
+ "市场规模", "市场份额", "销售额", "营收", "市值", "融资", "财报",
68
+ "集采", "医保", "报销", "竞争格局", "龙头",
69
+ ],
70
+ "tech_engineering": [
71
+ "源码分析", "实现原理", "架构设计", "性能优化", "内存安全", "深入研究",
72
+ "底层", "源码", "debug", "报错",
73
+ ],
74
+ }
75
+
76
+ # 域 → 它**应该**匹配的语境(语义一致面)。命中域不含该语境的域即为可疑。
77
+ # 只登记有明确语义的域,其余不参与语境检查(避免误报)。
78
+ _DOMAIN_CONTEXT: dict[str, tuple[str, ...]] = {
79
+ "academic": ("academic",),
80
+ "social": ("social_platform",),
81
+ "chinese_tech_deep": ("tech_engineering",),
82
+ "english_tech": ("tech_engineering",),
83
+ "ai_model": ("product_daily",),
84
+ "financial_news": ("commercial_market",),
85
+ "stock_query": ("commercial_market",),
86
+ "fund_query": ("commercial_market",),
87
+ "medical": ("commercial_market",),
88
+ "chem_search": ("commercial_market",),
89
+ "protein_search": ("commercial_market",),
90
+ "company_search": ("commercial_market",),
91
+ }
92
+
93
+ # 语境 → 若查询只含该语境词而命中了语义冲突的域,可疑度更高
94
+ _STRONG_CONFLICT: dict[str, tuple[str, ...]] = {
95
+ "social_platform": ("academic", "chinese_tech_deep", "english_tech"),
96
+ "academic": ("social",),
97
+ }
98
+
99
+
100
+ def _route(query: str) -> dict[str, Any]:
101
+ """跑一次路由,返回 {domain, primary, intents, lang}。
102
+
103
+ 用 `match_domains(max_n=1, primary_lang=...)`——`route.match_domain` 兼容
104
+ 接口不吃 primary_lang,会跳过中文域语言门控,度量结果会与生产不一致。
105
+ """
106
+ from route import extract_features
107
+ from route_domains import match_domains
108
+ feat = extract_features(query)
109
+ lang = feat.get("primary_lang")
110
+ # max_n=3 与生产主路径一致(route.py 的 _domain_hits):max_n=1 时
111
+ # intent 让位拿不到次域,度量会看不见修复效果。
112
+ hits = match_domains(query, max_n=3, primary_lang=lang,
113
+ intents=feat.get("intents"))
114
+ dom = hits[0] if hits else None
115
+ return {
116
+ "domain": dom.get("name") if dom else None,
117
+ "primary": dom.get("primary") if dom else None,
118
+ "lang": lang,
119
+ "intents": feat.get("intents") or [],
120
+ }
121
+
122
+
123
+ def _contexts_in(query: str) -> list[str]:
124
+ """查询里出现了哪些语境(小写匹配)。"""
125
+ q = query.lower()
126
+ return [name for name, words in _CONTEXT_WORDS.items()
127
+ if any(w.lower() in q for w in words)]
128
+
129
+
130
+ def _real_queries(limit: int = 0) -> list[str]:
131
+ """从 usage_log 取去重真实查询(带出现次数)。"""
132
+ counts: collections.Counter = collections.Counter()
133
+ pattern = str(Path.home() / ".cache" / "unified-search" / "usage_log" / "*.jsonl")
134
+ for f in glob.glob(pattern):
135
+ try:
136
+ for line in open(f, encoding="utf-8"):
137
+ try:
138
+ d = json.loads(line)
139
+ except Exception:
140
+ continue
141
+ if d.get("stream") == "query" and d.get("query"):
142
+ counts[d["query"].strip()] += 1
143
+ except OSError:
144
+ continue
145
+ top = counts.most_common(limit or None)
146
+ return [q for q, _ in top]
147
+
148
+
149
+ def audit(queries: list[str]) -> dict[str, Any]:
150
+ """对一批查询做语境一致性度量。"""
151
+ suspicious: list[dict[str, Any]] = []
152
+ domain_dist: collections.Counter = collections.Counter()
153
+ for q in queries:
154
+ r = _route(q)
155
+ dom = r["domain"]
156
+ domain_dist[dom or "(none)"] += 1
157
+ ctxs = _contexts_in(q)
158
+ if not dom or not ctxs:
159
+ continue
160
+ want_ctxs = _DOMAIN_CONTEXT.get(dom)
161
+ if not want_ctxs:
162
+ continue
163
+ # 语境一致性:命中的域应当至少匹配一个查询语境
164
+ if any(c in want_ctxs for c in ctxs):
165
+ continue
166
+ # 强冲突:查询含 A 语境,却命中了语义冲突的域
167
+ strong = any(
168
+ dom in _STRONG_CONFLICT.get(c, ())
169
+ for c in ctxs
170
+ )
171
+ suspicious.append({
172
+ "query": q, "domain": dom, "contexts": ctxs,
173
+ "strong": strong, "intents": r["intents"],
174
+ })
175
+ return {
176
+ "total": len(queries),
177
+ "domain_distribution": dict(domain_dist.most_common()),
178
+ "suspicious": suspicious,
179
+ "suspicious_count": len(suspicious),
180
+ "strong_count": sum(1 for s in suspicious if s["strong"]),
181
+ }
182
+
183
+
184
+ def check_order_invariance(queries: list[str]) -> dict[str, Any]:
185
+ """验证 match_domains 在 config.domains 正序与倒序下主域及前 3 域完全一致。"""
186
+ from config import load_config
187
+ from route import extract_features
188
+ from route_domains import match_domains
189
+
190
+ domains = load_config().get("domains") or []
191
+ reversed_domains = list(reversed(domains))
192
+ samples = queries or [
193
+ "AAPL stock price", "华为 总部在哪", "Twitter X 上 热议 LLM",
194
+ "Python asyncio tutorial", "東京 天気 予報",
195
+ ]
196
+ mismatches = []
197
+ for q in samples:
198
+ feat = extract_features(q)
199
+ lang = feat.get("primary_lang")
200
+ intents = feat.get("intents")
201
+ fwd = [d.get("name") for d in match_domains(
202
+ q, domains=domains, max_n=3, primary_lang=lang, intents=intents)]
203
+ rev = [d.get("name") for d in match_domains(
204
+ q, domains=reversed_domains, max_n=3, primary_lang=lang, intents=intents)]
205
+ if fwd != rev:
206
+ mismatches.append({"forward": fwd, "reversed": rev})
207
+ return {"checked": len(samples), "mismatch_count": len(mismatches), "mismatches": mismatches[:10]}
208
+
209
+
210
+ def main() -> int:
211
+ ap = argparse.ArgumentParser(description="路由误判度量")
212
+ ap.add_argument("--all", action="store_true", help="打印全部可疑条目")
213
+ ap.add_argument("--limit", type=int, default=500,
214
+ help="真实查询抽样上限(0=全部)")
215
+ ap.add_argument("--json", metavar="BASELINE", help="把结果落盘为基线")
216
+ ap.add_argument("--compare", metavar="BASELINE", help="与基线对比")
217
+ ap.add_argument("--check-order-invariance", action="store_true",
218
+ help="验证 domains 列表倒序时命中结果是否顺序无关")
219
+ args = ap.parse_args()
220
+
221
+ queries = _real_queries(args.limit)
222
+ if args.check_order_invariance:
223
+ inv = check_order_invariance(queries)
224
+ print(f"顺序无关性检查:{inv['checked']} 条,差异 {inv['mismatch_count']} 条")
225
+ if inv["mismatch_count"]:
226
+ print(f" 前 10 例:{inv['mismatches']}")
227
+ return 1
228
+ return 0
229
+ result = audit(queries)
230
+
231
+ print(f"真实查询 {result['total']} 条;命中域分布 Top10:")
232
+ for dom, n in list(result["domain_distribution"].items())[:10]:
233
+ print(f" {dom:22} {n}")
234
+ print(f"\n语境可疑 {result['suspicious_count']} 条"
235
+ f"(强冲突 {result['strong_count']} 条)")
236
+ for s in result["suspicious"][:(None if args.all else 20)]:
237
+ flag = "强" if s["strong"] else " "
238
+ print(f" [{flag}] {s['domain']:20} {s['contexts']} {s['query'][:44]!r}")
239
+
240
+ if args.json:
241
+ Path(args.json).parent.mkdir(parents=True, exist_ok=True)
242
+ Path(args.json).write_text(
243
+ json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
244
+ print(f"\n基线已写入 {args.json}")
245
+
246
+ if args.compare:
247
+ base = json.loads(Path(args.compare).read_text(encoding="utf-8"))
248
+ b = {s["query"]: s["domain"] for s in base["suspicious"]}
249
+ n = {s["query"]: s["domain"] for s in result["suspicious"]}
250
+ fixed = sorted(set(b) - set(n))
251
+ new = sorted(set(n) - set(b))
252
+ print(f"\n与基线 {args.compare} 对比:")
253
+ print(f" 修复 {len(fixed)} 条:{fixed[:10]}")
254
+ print(f" 新增 {len(new)} 条:{new[:10]}")
255
+ return 0
256
+
257
+
258
+ if __name__ == "__main__":
259
+ raise SystemExit(main())
@@ -108,8 +108,7 @@ def _breaker_blocked(engine_id: str) -> bool:
108
108
  state = st.get("state")
109
109
  if state == engine_states.BREAKER_DISABLED:
110
110
  return True
111
- return (state == engine_states.BREAKER_OPEN
112
- and int(st.get("cooldown_remain") or 0) > 0)
111
+ return int(st.get("cooldown_remain") or 0) > 0
113
112
 
114
113
 
115
114
  def _filter_breaker_blocked(engine_list: list[str]) -> list[str]:
@@ -265,6 +264,7 @@ def tfidf_lead_combo(tfidf_best: str | None, tfidf_best_score: float,
265
264
  enabled: set[str], *, mode: str = "auto",
266
265
  depth: str = "fast", context: str = "search",
267
266
  lang: str = "",
267
+ intents: tuple[str, ...] | list[str] | None = None,
268
268
  score_fn: Callable[[str, str, str, str],
269
269
  tuple[float, int]] | None = None
270
270
  ) -> list[str]:
@@ -282,7 +282,7 @@ def tfidf_lead_combo(tfidf_best: str | None, tfidf_best_score: float,
282
282
  strong = bool(tfidf_best and tfidf_best_score > TFIDF_STRONG_SCORE)
283
283
  generals = _ranked_general(
284
284
  enabled, mode=mode, depth=depth, context=context, lang=lang,
285
- score_fn=score_fn)
285
+ intents=intents, score_fn=score_fn)
286
286
  lead: list[str] = []
287
287
  if strong:
288
288
  lead = [tfidf_best]
@@ -518,7 +518,13 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
518
518
  # 桶无样本时 adaptive.get_score 自动回退全局分。判据与旧口径一致,
519
519
  # 只是多了一个维度——「引擎在 A 域强、B 域弱」现在可被路由区分。
520
520
  _dom_name = str(domain.get("name") or "")
521
- _q_lang = str((features or {}).get("primary_lang") or "")
521
+ _feats = features or {}
522
+ _q_lang = str(
523
+ _feats.get("lang_override")
524
+ or _feats.get("effective_lang")
525
+ or _feats.get("primary_lang")
526
+ or ""
527
+ )
522
528
  _score_memo: dict[str, float] = {}
523
529
 
524
530
  def _score_of(e: str) -> float: