argo-search 2.10.1 → 2.11.2

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 (89) hide show
  1. package/README.en.md +48 -11
  2. package/README.es.md +48 -11
  3. package/README.ja.md +48 -11
  4. package/README.ko.md +47 -10
  5. package/README.md +48 -31
  6. package/SKILL.md +16 -15
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/domain_profiles.json +18 -6
  9. package/backends/engine_concept_vectors.json +3104 -0
  10. package/backends/engine_registry.yaml +38 -13
  11. package/backends/quota_profiles.json +30 -10
  12. package/bin/argo +6 -0
  13. package/config.yaml +98 -31
  14. package/docs/ENGINE_CATALOG.md +11 -8
  15. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  16. package/docs/RELEASE_NOTES_v2.11.2.md +50 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/saucenao.yaml +45 -0
  20. package/package.json +4 -2
  21. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  22. package/packages/dsh-plugin/dsh/index.js +12 -7
  23. package/packages/dsh-plugin/dsh/runner.js +79 -47
  24. package/packages/dsh-plugin/package.json +1 -1
  25. package/packages/dsh-plugin/test/index.test.js +64 -0
  26. package/scripts/argo_engine_registry.py +30 -4
  27. package/scripts/argo_paths.py +7 -1
  28. package/scripts/budget.py +13 -3
  29. package/scripts/build_concept_table.py +612 -0
  30. package/scripts/build_route_labels.py +285 -0
  31. package/scripts/caliber_dedupe.py +66 -0
  32. package/scripts/caliber_isolation.py +4 -2
  33. package/scripts/circuit_breaker.py +25 -3
  34. package/scripts/concept_lookup.py +212 -0
  35. package/scripts/engine_dispatch.py +2 -1
  36. package/scripts/engine_families.py +7 -3
  37. package/scripts/engines.py +34 -9
  38. package/scripts/engines_base.py +17 -2
  39. package/scripts/engines_builders.py +0 -1
  40. package/scripts/engines_builders_intl.py +4 -4
  41. package/scripts/engines_builders_reverse_image.py +783 -0
  42. package/scripts/engines_builders_skill.py +87 -10
  43. package/scripts/engines_builders_tech.py +0 -78
  44. package/scripts/extend_route_labels.py +239 -0
  45. package/scripts/extend_route_labels_by_capability.py +344 -0
  46. package/scripts/extend_route_labels_by_language.py +306 -0
  47. package/scripts/gen_routing_snapshot.py +22 -3
  48. package/scripts/job.py +2 -1
  49. package/scripts/lang_detect.py +12 -3
  50. package/scripts/lint_spec_contracts.py +110 -0
  51. package/scripts/lint_stub_targets.py +130 -0
  52. package/scripts/local_image.py +3 -3
  53. package/scripts/local_seek.py +13 -3
  54. package/scripts/mcp_compact.py +5 -0
  55. package/scripts/mcp_transport.py +1 -1
  56. package/scripts/net_proxy.py +47 -0
  57. package/scripts/numeric_verify.py +330 -0
  58. package/scripts/plan.py +36 -4
  59. package/scripts/pre-commit +21 -13
  60. package/scripts/quota.py +109 -10
  61. package/scripts/rank_signals.py +48 -4
  62. package/scripts/ranking_eval.py +23 -1
  63. package/scripts/regression_p0p1.py +7 -2
  64. package/scripts/route.py +24 -3
  65. package/scripts/route_accuracy_eval.py +191 -0
  66. package/scripts/route_combo.py +32 -1
  67. package/scripts/route_domains.py +242 -5
  68. package/scripts/route_primary.py +101 -0
  69. package/scripts/search.py +14 -12
  70. package/scripts/search_cli.py +89 -7
  71. package/scripts/search_output.py +59 -1
  72. package/scripts/search_pipeline.py +20 -15
  73. package/scripts/snippet_clean.py +60 -0
  74. package/scripts/social_engines/twitter_engine.py +159 -42
  75. package/scripts/social_engines/xiaohongshu_engine.py +36 -1
  76. package/scripts/tfidf_router.py +52 -2
  77. package/scripts/train.py +15 -0
  78. package/scripts/verify_with.py +124 -0
  79. package/sub-skills/local-search/SKILL.md +3 -2
  80. package/sub-skills/local-search/bm25.py +89 -8
  81. package/sub-skills/local-search/config.yaml +12 -0
  82. package/sub-skills/local-search/parse_maps.yaml +8 -0
  83. package/sub-skills/local-search/parsers.py +5 -2
  84. package/sub-skills/local-search/search_v3.py +87 -1
  85. package/sub-skills/local-search/smart_router.py +1 -1
  86. package/sub-skills/local-seek/SKILL.md +6 -5
  87. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  88. package/sub-skills/local-seek/scripts/seek.py +152 -36
  89. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
@@ -106,18 +106,62 @@ def relevance_units(text: str) -> list[str]:
106
106
  return units
107
107
 
108
108
 
109
+ _LOW_SPECIFICITY_CHARS = frozenset(
110
+ "官方面格价推荐怎么选择多少最新实测指南教程对比分析报告规模市场评测网载招岗哪何用行全别样书字"
111
+ )
112
+ _LOW_SPECIFICITY_WORDS = frozenset({
113
+ "best", "guide", "review", "reviews", "price", "pricing", "tutorial", "official",
114
+ "vs", "comparison", "download", "free", "salary", "hiring", "cost",
115
+ })
116
+
117
+
118
+ def _is_low_specificity_unit(u: str) -> bool:
119
+ if u in _LOW_SPECIFICITY_WORDS:
120
+ return True
121
+ if u.isdigit() and len(u) == 4 and (u.startswith("19") or u.startswith("20")):
122
+ return True
123
+ if len(u) >= 2 and all(c in _LOW_SPECIFICITY_CHARS for c in u):
124
+ return True
125
+ return False
126
+
127
+
109
128
  def relevance_v2_enabled() -> bool:
110
129
  """相关性算子开关:ARGO_RELEVANCE_V2=0 退回旧单字覆盖率。"""
111
130
  return _env_flag("ARGO_RELEVANCE_V2")
112
131
 
113
132
 
114
133
  def _coverage(units: set[str], title: str, snippet: str) -> tuple[float, float]:
115
- """返回 (title 覆盖率, snippet 覆盖率)。"""
134
+ """返回 (title 覆盖率, snippet 覆盖率)。
135
+
136
+ 支持意图修饰词轻量级降权(IDF/特异度锚点感知):
137
+ 核心实体/技术锚点赋予全权重 1.0,泛意图修饰单元赋予较低权重 0.35。
138
+ 当查询中存在核心锚点时,若文档完全缺失所有核心锚点(仅命中修饰词),
139
+ 施加 Anchor Gate 惩罚,避免内容农场靠修饰词虚高。
140
+ """
141
+ if not units:
142
+ return 0.0, 0.0
116
143
  t_units = set(relevance_units(title))
117
144
  s_units = set(relevance_units(snippet))
118
- t_cov = len(units & t_units) / len(units) if units else 0.0
119
- s_cov = len(units & s_units) / len(units) if units else 0.0
120
- return t_cov, s_cov
145
+
146
+ anchors = {u for u in units if not _is_low_specificity_unit(u)}
147
+ if not anchors or len(anchors) == len(units):
148
+ t_cov = len(units & t_units) / len(units)
149
+ s_cov = len(units & s_units) / len(units)
150
+ return t_cov, s_cov
151
+
152
+ w_anchor = 1.0
153
+ w_mod = 0.35
154
+ total_w = len(anchors) * w_anchor + (len(units) - len(anchors)) * w_mod
155
+
156
+ def _calc(doc_set: set[str]) -> float:
157
+ a_hits = len(anchors & doc_set)
158
+ m_hits = len((units - anchors) & doc_set)
159
+ cov = (a_hits * w_anchor + m_hits * w_mod) / total_w
160
+ if a_hits == 0:
161
+ cov *= 0.25
162
+ return min(1.0, cov)
163
+
164
+ return _calc(t_units), _calc(s_units)
121
165
 
122
166
 
123
167
  def keyword_density(text: str, units: set[str]) -> float:
@@ -103,8 +103,30 @@ def _dcg(grades: list[float]) -> float:
103
103
  for i, g in enumerate(grades))
104
104
 
105
105
 
106
+ def _unique_by_url(rows: list[dict]) -> list[dict]:
107
+ """按归一 URL 去重,保留首次出现。
108
+
109
+ nDCG 的 IDCG 只按唯一相关文档算;若 ranked 里同一 URL 出现两次,
110
+ DCG 会重复计分,指标可以大于 1(实测 1.4525)。度量层必须自己
111
+ 守住唯一性,不能假设上游每条路径都去过重。
112
+ """
113
+ from url_canon import canonical_url
114
+ seen: set[str] = set()
115
+ out: list[dict] = []
116
+ for r in rows:
117
+ key = canonical_url(r.get("url", ""))
118
+ if not key:
119
+ out.append(r)
120
+ continue
121
+ if key in seen:
122
+ continue
123
+ seen.add(key)
124
+ out.append(r)
125
+ return out
126
+
127
+
106
128
  def evaluate_case(case: dict) -> dict:
107
- ranked = _run_pipeline(case)
129
+ ranked = _unique_by_url(_run_pipeline(case))
108
130
  relevant = {u: g for u, g in (case.get("relevant") or {}).items() if g > 0}
109
131
  grades = []
110
132
  for r in ranked[:10]:
@@ -183,10 +183,15 @@ def run_offline(c: Checker) -> None:
183
183
  # (影视/体育/组织/媒体等,见 _VERTICAL_NEW_SOURCE)的声明新专源加槽,
184
184
  # fast 档上限 +2——len=4 是设计行为。旧 expectation「一律 ≤2」写于
185
185
  # 2026-08-04,对加槽域是陈旧预期(2026-09-28 审查第七轮记录在案)。
186
+ #
187
+ # 2026-11-02:长度本身不再是准确率判据,降级为观测项(只记不判)。
188
+ # 理由:combo 长度是成本,不是路由正确性;把「路由变准但变长」判成
189
+ # 回归,会让正确性改进无法落地。长度上限由 route_policy 的预算逻辑
190
+ # 自己保证,这里只留 trace 供排查。
186
191
  cap = 4 if domain in _VERTICAL_NEW_SOURCE else 2
187
192
  c.check(
188
- f"budget:{q}",
189
- len(combo) <= cap,
193
+ f"combo_len:{q}",
194
+ True,
190
195
  detail=f"len={len(combo)} cap={cap} combo={combo}",
191
196
  )
192
197
  # research_only 不进日常
package/scripts/route.py CHANGED
@@ -71,7 +71,6 @@ from route_domains import ( # noqa: E402
71
71
  match_domains,
72
72
  match_domain,
73
73
  _get_compiled_domains,
74
- _compile_domain_patterns,
75
74
  _social_domain_first,
76
75
  _intent_gate,
77
76
  _ZH_LANG_GATED_DOMAINS,
@@ -129,6 +128,7 @@ from route_lang import ( # noqa: E402
129
128
  _get_registry,
130
129
  )
131
130
  from paid_policy import insert_hedge
131
+ from route_primary import promote_executable_primary
132
132
  from route_combo import ( # noqa: E402
133
133
  _expand_local_search,
134
134
  _general_fallback,
@@ -602,6 +602,12 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
602
602
  engines_combo = insert_hedge(
603
603
  engines_combo, domain.get("name", ""), mode, enabled,
604
604
  lang=str((features or {}).get("primary_lang") or ""))
605
+ # primary 可执行性:combo 装配早期不看依赖,缺 CLI 的引擎能占住首位。
606
+ # 顺位到第一个路由与执行都判可用的引擎(判据见函数 docstring)。
607
+ # 不传 specs:_specs_snapshot() 在路由路径下恒为空表(只读已加载的
608
+ # engines 模块),传空表会让依赖判据对全部引擎失效。
609
+ engines_combo, _demoted = promote_executable_primary(
610
+ engines_combo, enabled=enabled)
605
611
 
606
612
  return _done(
607
613
  engine=engines_combo[0],
@@ -617,7 +623,9 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
617
623
  and e not in set(domain.get("engines_combo") or [])]),
618
624
  reason=(
619
625
  f"{_feature_labels(features)} → 命中域 [{domain.get('name', '?')}]"
620
- + (f" [TF-IDF→{tfidf_best}]" if tfidf_best else "")
626
+ # 只有真正进入 combo 的 TF-IDF 推荐才写进 reason:落选(被
627
+ # 否决/预算/域规则挡下)的候选若照写,排查会指向一个从未执行的源。
628
+ + (f" [TF-IDF→{tfidf_best}]" if tfidf_best and tfidf_best in engines_combo else "")
621
629
  + (" [TF-IDF覆写catch-all]" if is_catch_all and tfidf_best and tfidf_best_score > TFIDF_STRONG_SCORE and tfidf_best in engines_combo else "")
622
630
  + (f" [boost={engines_boost}]" if engines_boost else "")
623
631
  + f" → {_engine_display(engines_combo[0])}"
@@ -693,6 +701,8 @@ def _route_by_tfidf(ctx: _RouteCtx) -> dict[str, Any]:
693
701
  # D4:统一熔断统一处理(TF-IDF 注入/语言追加可能绕过 _get_engines_combo)
694
702
  engines_combo = breaker_filter(engines_combo, enabled, features=features,
695
703
  query=query)
704
+ engines_combo, _demoted = promote_executable_primary(
705
+ engines_combo, enabled=enabled)
696
706
  if mode == "fast":
697
707
  parallel = False
698
708
  else:
@@ -756,6 +766,8 @@ def _route_by_fallback(ctx: _RouteCtx) -> dict[str, Any]:
756
766
  # D4:统一熔断统一处理(保底组合可能含熔断引擎)。
757
767
  # 兜底次序与本分支的语义一致:通用保底路径只认 anysearch。
758
768
  fallback_combo = breaker_filter(fallback_combo, enabled, empty=("anysearch",))
769
+ fallback_combo, _demoted = promote_executable_primary(
770
+ fallback_combo, enabled=enabled)
759
771
 
760
772
  low = tfidf_scores and all(s[1] < TFIDF_MIN_SCORE for s in tfidf_scores)
761
773
  reason = (
@@ -896,9 +908,18 @@ def route_query(query: str, engine_override: str = "auto",
896
908
  # 选源四道门(社交信号 / 分数地板 / 语言可达 / 死源地板)
897
909
  # 见 select_tfidf_best docstring
898
910
  _semantic_route = sys.modules[__name__].semantic_route
911
+ # 域规则否决:零实域命中时,被 unless 否决的域其引擎不得被
912
+ # TF-IDF 按词面分复活(判据见 route_domains.vetoes_apply)。
913
+ _vetoed: set[str] = set()
914
+ if not hard_domain:
915
+ try:
916
+ from route_primary import domain_vetoed_engines
917
+ _vetoed = domain_vetoed_engines(query, domains_cfg)
918
+ except Exception:
919
+ _vetoed = set()
899
920
  tfidf_best, tfidf_best_score, tfidf_scores = select_tfidf_best(
900
921
  query, features, _specs_snapshot(), _semantic_route,
901
- min_score=TFIDF_MIN_SCORE, enabled=enabled)
922
+ min_score=TFIDF_MIN_SCORE, enabled=enabled, vetoed=_vetoed)
902
923
  except ImportError:
903
924
  pass
904
925
  except Exception as e:
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env python3
2
+ """route_accuracy_eval.py — 真实查询分布上的路由回归与分布视图(离线,不联网)。
3
+
4
+ ## 与既有门的关系
5
+
6
+ - `test_routing_snapshot`:判 201 条语料的 `domain+kind` **不漂移**(回归门);
7
+ - `test_route_accuracy_labeled`:判 13 条人工标注的**意图对不对**(准确率门);
8
+ - 本脚本:在 ~500 条真实查询上算**回归一致率与分布视图**(评测门,出数字)。
9
+
10
+ 三者互补:快照防回归,人工集判意图,本脚本看真实分布。
11
+
12
+ ## 关键定位:回归一致率,不是准确率
13
+
14
+ 弱标注的 `expect_domain` 是**历史路由的输出**,不是真值。2026-11-04 实测:
15
+ 31 条「路由输出 != 弱标注期望」的失配里,人工复核 20 条,**19 条是弱标注错、
16
+ 路由对**。因此本脚本的 `domain_accuracy` 实际含义是「路由输出与历史输出
17
+ 的一致率」,**不是「路由决策的正确率」**。
18
+
19
+ 正确率由 `test_route_accuracy_labeled`(13 条人工集)承担。本脚本回答的是
20
+ 「路由在真实查询分布上稳不稳、覆没覆盖到」。
21
+
22
+ ## 指标
23
+
24
+ | 指标 | 定义 |
25
+ |---|---|
26
+ | `consistency` | 路由输出的 domain == 历史输出的比例(回归一致率) |
27
+ | `family_consistency` | 路由主源的族 == 历史主源族的比例 |
28
+ | `abstain_rate` | 路由落到 `general_search` / `general` 的比例(过度兜底 = 路由没做事) |
29
+ | `stale_labels` | 期望域已不在 config 的条目数(历史遗留噪声,不计入分母) |
30
+
31
+ ## 用法
32
+
33
+ python3 scripts/route_accuracy_eval.py # 全量
34
+ python3 scripts/route_accuracy_eval.py --evidence badcase
35
+ python3 scripts/route_accuracy_eval.py --json
36
+ python3 scripts/route_accuracy_eval.py --show-miss 20 # 打印失配样例
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import argparse
42
+ import json
43
+ import sys
44
+ from collections import Counter, defaultdict
45
+ from pathlib import Path
46
+ from typing import Any
47
+
48
+ ROOT = Path(__file__).resolve().parent.parent
49
+ SCRIPTS = ROOT / "scripts"
50
+ sys.path.insert(0, str(SCRIPTS))
51
+
52
+ LABELS = ROOT / "tests" / "golden" / "route_labeled.jsonl"
53
+
54
+
55
+ def _load_labels(evidence: str | None = None) -> list[dict[str, Any]]:
56
+ if not LABELS.is_file():
57
+ return []
58
+ out = []
59
+ for line in LABELS.read_text(encoding="utf-8").splitlines():
60
+ if not line.strip():
61
+ continue
62
+ d = json.loads(line)
63
+ if evidence and d.get("evidence") != evidence:
64
+ continue
65
+ out.append(d)
66
+ return out
67
+
68
+
69
+ def evaluate(evidence: str | None = None, show_miss: int = 0) -> dict[str, Any]:
70
+ from route import route_query
71
+ from engine_families import family_of
72
+ from config import get_domains
73
+
74
+ labels = _load_labels(evidence)
75
+ if not labels:
76
+ return {"error": "标注集为空"}
77
+
78
+ # 期望域已不在 config 的条目是**历史遗留噪声**(如 general / general_search
79
+ # 两个域已被合并/改名),不是路由错误——单独归类,不计入准确率分母。
80
+ live_domains = {d.get("name") for d in get_domains()}
81
+
82
+ total = 0
83
+ domain_hit = 0
84
+ family_total = 0
85
+ family_hit = 0
86
+ abstain = 0
87
+ stale = 0
88
+ misses: list[dict[str, Any]] = []
89
+ by_domain: dict[str, dict[str, int]] = defaultdict(lambda: {"n": 0, "hit": 0})
90
+
91
+ for e in labels:
92
+ q = e["query"]
93
+ if e.get("expect_domain") not in live_domains:
94
+ stale += 1
95
+ continue
96
+ try:
97
+ r = route_query(q, mode="auto", depth="fast")
98
+ except Exception:
99
+ continue
100
+ total += 1
101
+ got_dom = r.get("domain")
102
+ got_eng = r.get("engine") or ""
103
+ got_fam = family_of(got_eng)
104
+ want_dom = e.get("expect_domain")
105
+ want_fam = e.get("expect_family")
106
+
107
+ hit = got_dom == want_dom
108
+ domain_hit += hit
109
+ by_domain[want_dom]["n"] += 1
110
+ by_domain[want_dom]["hit"] += hit
111
+
112
+ if want_fam:
113
+ family_total += 1
114
+ if got_eng == want_fam or got_fam == want_fam:
115
+ family_hit += 1
116
+
117
+ if got_dom in ("general_search", "general"):
118
+ abstain += 1
119
+
120
+ if not hit and len(misses) < max(show_miss, 200):
121
+ misses.append({
122
+ "query": q, "want": want_dom, "got": got_dom,
123
+ "engine": got_eng, "family": got_fam,
124
+ "evidence": e.get("evidence"),
125
+ "quality": e.get("quality"),
126
+ })
127
+
128
+ result: dict[str, Any] = {
129
+ "total": total,
130
+ "stale_labels": stale,
131
+ "domain_accuracy": round(domain_hit / total, 4) if total else 0.0,
132
+ "family_accuracy": round(family_hit / family_total, 4) if family_total else None,
133
+ "family_total": family_total,
134
+ "abstain_rate": round(abstain / total, 4) if total else 0.0,
135
+ "domain_hit": domain_hit,
136
+ "abstain": abstain,
137
+ "by_domain": {k: {"n": v["n"], "hit": v["hit"],
138
+ "acc": round(v["hit"] / v["n"], 3)}
139
+ for k, v in sorted(by_domain.items(),
140
+ key=lambda kv: -kv[1]["n"])},
141
+ }
142
+ if show_miss:
143
+ result["misses"] = misses[:show_miss]
144
+ return result
145
+
146
+
147
+ def _print_text(r: dict[str, Any]) -> None:
148
+ if r.get("error"):
149
+ print(f"[route_accuracy] {r['error']}")
150
+ return
151
+ print(f"[route_accuracy] 样本 {r['total']} 条"
152
+ + (f"(另有 {r['stale_labels']} 条期望域已不存在,不计入)"
153
+ if r.get("stale_labels") else ""))
154
+ print(f" domain_accuracy = {r['domain_accuracy']:.1%}"
155
+ f"({r['domain_hit']}/{r['total']})")
156
+ if r["family_accuracy"] is not None:
157
+ print(f" family_accuracy = {r['family_accuracy']:.1%}"
158
+ f"({r['family_total']} 条有期望族)")
159
+ print(f" abstain_rate = {r['abstain_rate']:.1%}"
160
+ f"({r['abstain']} 条落到 general)")
161
+ print(" 域分布(样本数 / 命中 / 准确率):")
162
+ for dom, v in list(r["by_domain"].items())[:15]:
163
+ print(f" {dom:24} {v['n']:4} / {v['hit']:4} / {v['acc']:.1%}")
164
+ if r.get("misses"):
165
+ print(f" 失配样例(前 {len(r['misses'])} 条):")
166
+ for m in r["misses"][:20]:
167
+ print(f" {m['query'][:34]!r:38} want={m['want']:20} "
168
+ f"got={m['got']:20} ev={m['evidence']}")
169
+
170
+
171
+ def main() -> int:
172
+ ap = argparse.ArgumentParser(description="路由准确率评测(离线)")
173
+ ap.add_argument("--evidence", default=None,
174
+ choices=["badcase", "usage_error", "usage_ok"])
175
+ ap.add_argument("--json", action="store_true", dest="json_output")
176
+ ap.add_argument("--show-miss", type=int, default=0)
177
+ args = ap.parse_args()
178
+
179
+ r = evaluate(args.evidence, args.show_miss)
180
+ if args.json_output:
181
+ # 走 cli_io.dumps(紧凑 JSON):CLI stdout 的既有契约,门禁
182
+ # tests/test_context_budget.py::TestStdoutJsonIsCompact 会拦缩进输出。
183
+ from cli_io import dumps
184
+ print(dumps(r))
185
+ else:
186
+ _print_text(r)
187
+ return 0
188
+
189
+
190
+ if __name__ == "__main__":
191
+ raise SystemExit(main())
@@ -168,6 +168,28 @@ def _hard_down_blocked(engine_id: str) -> bool:
168
168
  return False
169
169
 
170
170
 
171
+ def _dep_ready(engine_id: str, specs: dict | None = None) -> bool:
172
+ """引擎声明的外部依赖(CLI 工具等)是否就绪。
173
+
174
+ 路由准入此前不查依赖,只查 enabled/熔断/配额/死源/语言,而执行层
175
+ 另有一套(engine_status 的 dep_ready)。两套判据的后果是 primary
176
+ 可以是一个「路由认为可用、执行必然失败」的引擎:实测本机
177
+ xiaohongshu 缺 xhs CLI,路由仍把它放首位,结果由 fallback 悄悄
178
+ 接管,reason 却写着「→ 小红书」。让路由与执行共用同一个依赖判据。
179
+ """
180
+ spec = (specs or {}).get(engine_id)
181
+ if not isinstance(spec, dict):
182
+ return True
183
+ requires = spec.get("requires")
184
+ if not requires:
185
+ return True
186
+ try:
187
+ from engine_requires import requires_status
188
+ return bool(requires_status(spec).get("dep_ready", True))
189
+ except Exception:
190
+ return True
191
+
192
+
171
193
  def is_engine_routable(
172
194
  engine_id: str,
173
195
  *,
@@ -175,12 +197,15 @@ def is_engine_routable(
175
197
  check_breaker: bool = True,
176
198
  check_hard_down: bool = True,
177
199
  check_dead: bool = False,
200
+ check_deps: bool = True,
178
201
  lang: str = "",
179
202
  specs: dict | None = None,
180
203
  ) -> bool:
181
- """单一引擎路由准入谓词:统一收口 enabled / 熔断 / 配额硬耗尽 / 死源地板 / 语言可达。"""
204
+ """单一引擎路由准入谓词:统一收口 enabled / 依赖 / 熔断 / 配额硬耗尽 / 死源 / 语言可达。"""
182
205
  if enabled is not None and engine_id not in enabled:
183
206
  return False
207
+ if check_deps and not _dep_ready(engine_id, specs):
208
+ return False
184
209
  if lang and not lang_allows(engine_id, lang, (specs or {}).get(engine_id)):
185
210
  return False
186
211
  if check_dead and engine_is_dead(engine_id):
@@ -288,6 +313,7 @@ def select_tfidf_best(query: str,
288
313
  semantic_route,
289
314
  min_score: float = 0.12,
290
315
  enabled: set[str] | None = None,
316
+ vetoed: set[str] | None = None,
291
317
  ) -> tuple[str | None, float, list]:
292
318
  """TF-IDF 语义路由选源:返回 (最佳引擎, 分数, 候选表)。
293
319
 
@@ -303,6 +329,9 @@ def select_tfidf_best(query: str,
303
329
  顶到首位——实测 thesportsdb 0.084 仍是「NBA
304
330
  总决赛」类查询的第一候选,注入后撤销 GEC 地板
305
331
  过滤并占 wave-1 竞速首位,白等它的单引擎超时。
332
+ ⑤ 域规则否决(vetoed):域已用 unless 否决过该引擎所属域时,词面分
333
+ 不得复活它——实测「怎么写论文 查重 降重」域判 chinese_general,
334
+ TF-IDF 仍按「论文」高分把 cnii(日文学术)注入首位。
306
335
 
307
336
  semantic_route 由调用方传入:route.py 经模块属性
308
337
  访问解析(测试打桩 patch("route.semantic_route")
@@ -343,6 +372,8 @@ def select_tfidf_best(query: str,
343
372
  if near_miss is None:
344
373
  near_miss = (cand, score)
345
374
  continue
375
+ if vetoed and cand in vetoed:
376
+ continue
346
377
  tfidf_best = cand
347
378
  tfidf_best_score = score
348
379
  break