argo-search 2.10.0 → 2.10.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 (85) hide show
  1. package/README.en.md +50 -10
  2. package/README.es.md +49 -9
  3. package/README.ja.md +50 -10
  4. package/README.ko.md +50 -10
  5. package/README.md +50 -30
  6. package/SKILL.md +11 -10
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/engine_concept_vectors.json +3104 -0
  9. package/backends/engine_registry.yaml +2 -2
  10. package/backends/source_types_cn.json +9 -0
  11. package/config.yaml +105 -24
  12. package/docs/ENGINE_CATALOG.md +8 -8
  13. package/docs/RELEASE_NOTES_v2.10.1.md +57 -0
  14. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  15. package/engines/_template_http.yaml +2 -0
  16. package/engines/specs/ncpssd.yaml +3 -0
  17. package/engines/specs/sciverse.yaml +1 -0
  18. package/package.json +4 -2
  19. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  20. package/packages/dsh-plugin/dsh/index.js +7 -7
  21. package/packages/dsh-plugin/dsh/runner.js +72 -46
  22. package/packages/dsh-plugin/package.json +1 -1
  23. package/packages/dsh-plugin/test/index.test.js +43 -0
  24. package/scripts/argo_engine_registry.py +30 -4
  25. package/scripts/argo_paths.py +7 -1
  26. package/scripts/build_concept_table.py +612 -0
  27. package/scripts/build_route_labels.py +285 -0
  28. package/scripts/caliber_dedupe.py +66 -0
  29. package/scripts/caliber_isolation.py +4 -2
  30. package/scripts/ci_drift_gate.py +47 -24
  31. package/scripts/circuit_breaker.py +25 -3
  32. package/scripts/concept_lookup.py +212 -0
  33. package/scripts/engine_dispatch.py +6 -8
  34. package/scripts/engine_status.py +12 -5
  35. package/scripts/engines.py +29 -7
  36. package/scripts/engines_base.py +48 -17
  37. package/scripts/engines_builders_data.py +10 -3
  38. package/scripts/engines_builders_skill.py +87 -10
  39. package/scripts/evidence.py +26 -5
  40. package/scripts/extend_route_labels.py +239 -0
  41. package/scripts/extend_route_labels_by_capability.py +344 -0
  42. package/scripts/gen_routing_snapshot.py +22 -3
  43. package/scripts/lang_detect.py +12 -3
  44. package/scripts/local_seek.py +66 -14
  45. package/scripts/mcp_transport.py +1 -1
  46. package/scripts/numeric_verify.py +330 -0
  47. package/scripts/plan.py +25 -4
  48. package/scripts/pre-commit +2 -2
  49. package/scripts/rank_signals.py +48 -4
  50. package/scripts/ranking_eval.py +23 -1
  51. package/scripts/regression_p0p1.py +7 -2
  52. package/scripts/release.py +398 -0
  53. package/scripts/route.py +24 -3
  54. package/scripts/route_accuracy_eval.py +191 -0
  55. package/scripts/route_combo.py +32 -1
  56. package/scripts/route_domains.py +258 -5
  57. package/scripts/route_primary.py +101 -0
  58. package/scripts/search.py +5 -2
  59. package/scripts/search_cli.py +111 -7
  60. package/scripts/search_output.py +73 -1
  61. package/scripts/search_pipeline.py +9 -2
  62. package/scripts/search_rank.py +3 -1
  63. package/scripts/serp_guard.py +11 -0
  64. package/scripts/snippet_clean.py +60 -0
  65. package/scripts/social_engines/twitter_engine.py +127 -43
  66. package/scripts/social_engines/xiaohongshu_engine.py +11 -1
  67. package/scripts/tfidf_router.py +52 -2
  68. package/scripts/train.py +15 -0
  69. package/scripts/url_canon.py +2 -1
  70. package/scripts/verify_with.py +124 -0
  71. package/scripts/video_route.py +3 -3
  72. package/sub-skills/local-search/SKILL.md +3 -2
  73. package/sub-skills/local-search/bm25.py +89 -8
  74. package/sub-skills/local-search/config.yaml +12 -0
  75. package/sub-skills/local-search/parse_maps.yaml +8 -0
  76. package/sub-skills/local-search/parsers.py +5 -2
  77. package/sub-skills/local-search/search_v3.py +87 -1
  78. package/sub-skills/local-search/smart_router.py +1 -1
  79. package/sub-skills/local-seek/SKILL.md +6 -5
  80. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  81. package/sub-skills/local-seek/scripts/seek.py +171 -40
  82. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
  83. package/engines/specs/_cisa_kev.yaml +0 -54
  84. package/engines/specs/_osv.yaml +0 -63
  85. package/scripts/image_vision/vision_probe +0 -0
@@ -15,12 +15,84 @@ Argo 已有的 skillsmp(仓库星数)、clawhub(生态下载量)是另
15
15
  from __future__ import annotations
16
16
 
17
17
  import json
18
+ import math
19
+ import re
18
20
  import urllib.parse
19
21
  import urllib.request
20
22
  from typing import Any
21
23
 
22
24
  from engines_base import safe_search, http_open, rank_score
23
25
 
26
+ # ── 面向英文技能目录(explainx/skills.sh/skillsmp/clawhub)的轻量中英概念映射 ──
27
+ _ZH_TO_EN_SKILL_TERMS: tuple[tuple[str, str], ...] = (
28
+ ("架构图", "architecture diagram"),
29
+ ("流程图", "flowchart diagram"),
30
+ ("思维导图", "mindmap"),
31
+ ("时序图", "sequence diagram"),
32
+ ("画图", "diagram"),
33
+ ("可视化", "visualization chart"),
34
+ ("图表", "chart"),
35
+ ("海报", "poster"),
36
+ ("浏览器", "browser"),
37
+ ("自动化", "automation"),
38
+ ("记忆", "memory"),
39
+ ("爬虫", "scraper crawl"),
40
+ ("抓取", "fetch scrape"),
41
+ ("网页", "web"),
42
+ ("公众号", "wechat"),
43
+ ("微信", "wechat"),
44
+ ("视频", "video"),
45
+ ("字幕", "caption subtitle"),
46
+ ("论文", "academic paper"),
47
+ ("学术", "academic"),
48
+ ("文献", "literature citation"),
49
+ ("金融", "finance stock"),
50
+ ("股票", "stock"),
51
+ ("审查", "code review"),
52
+ ("体检", "audit health"),
53
+ ("调试", "debug"),
54
+ ("测试", "testing"),
55
+ ("表格", "spreadsheet excel csv"),
56
+ ("文档", "document"),
57
+ ("技能", "skill"),
58
+ # 通用高频补充(2026-10-31:实测「渲染」查询归一后只剩 remotion,映射盲区)
59
+ ("渲染", "render"),
60
+ ("翻译", "translation translate"),
61
+ ("邮件", "email mail"),
62
+ ("摘要", "summary summarize"),
63
+ ("投资", "invest investing"),
64
+ ("图片", "image"),
65
+ ("下载", "download"),
66
+ ("剪辑", "video editing"),
67
+ )
68
+
69
+
70
+ def _normalize_en_catalog_query(query: str) -> str:
71
+ """将含中文的技能检索词对齐为英文目录可命中的英文查询词(纯英文原样返回)。"""
72
+ q = (query or "").strip()
73
+ if not q or q.isascii():
74
+ return q
75
+ en_bits: list[str] = re.findall(r"[A-Za-z0-9_+-]{2,}", q)
76
+ remaining = q
77
+ for zh, en in _ZH_TO_EN_SKILL_TERMS:
78
+ if zh in remaining:
79
+ if en not in en_bits:
80
+ en_bits.append(en)
81
+ remaining = remaining.replace(zh, " ")
82
+ return " ".join(en_bits) if en_bits else q
83
+
84
+
85
+ def _skill_rank_score(rank: int, popularity: Any = 0, is_official: bool = False) -> float:
86
+ """结合上游位次、对数饱和流行度先验 (log10(1+pop)) 与官方标记计算初始分。"""
87
+ try:
88
+ pop = max(0, int(popularity or 0))
89
+ except (TypeError, ValueError):
90
+ pop = 0
91
+ pop_bonus = min(0.14, 0.026 * math.log10(1 + pop)) if pop > 0 else 0.0
92
+ off_bonus = 0.04 if is_official else 0.0
93
+ base = min(0.92, 0.72 + pop_bonus + off_bonus)
94
+ return rank_score(base, rank)
95
+
24
96
  # ── explainx.ai(12075 条,安装量 + 分类 + 官方标记)────────────────────────
25
97
  _EXPLAINX_URL = "https://explainx.ai/api/skills"
26
98
 
@@ -79,7 +151,7 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
79
151
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
80
152
  ) -> list[dict[str, Any]]:
81
153
  to = _timeout or timeout
82
- q = (query or "").strip()
154
+ q = _normalize_en_catalog_query(query)
83
155
  if not q:
84
156
  return []
85
157
  url = f"{_EXPLAINX_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -99,11 +171,12 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
99
171
  installs = s.get("totalInstalls") or 0
100
172
  weekly = s.get("weeklyInstalls")
101
173
  category = s.get("category") or ""
174
+ is_official = bool(s.get("isOfficial"))
102
175
  # 安装量是这一源的核心价值,必须出现在摘要里(L1 做不到)
103
176
  bits = [f"安装 {installs}"]
104
177
  if weekly is not None and weekly != installs:
105
178
  bits.append(f"本周 +{weekly}")
106
- if s.get("isOfficial"):
179
+ if is_official:
107
180
  bits.append("官方")
108
181
  summary = " · ".join(bits)
109
182
  if category:
@@ -114,17 +187,18 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
114
187
  "url": f"https://github.com/{owner}/{repo}",
115
188
  "snippet": summary,
116
189
  "source": "explainx",
117
- "score": rank_score(0.75, rank),
190
+ "score": _skill_rank_score(rank, installs, is_official),
118
191
  # 可验证出处:owner/repo 是「装什么」的权威答案
119
192
  "upstream": f"{owner}/{repo}",
120
193
  "metadata": {
121
194
  "category": category,
122
195
  "totalInstalls": installs,
123
196
  "weeklyInstalls": weekly,
124
- "isOfficial": bool(s.get("isOfficial")),
197
+ "isOfficial": is_official,
125
198
  },
126
199
  }
127
200
  )
201
+ results.sort(key=lambda r: -r["score"])
128
202
  return results
129
203
 
130
204
  return _engine
@@ -148,7 +222,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
148
222
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
149
223
  ) -> list[dict[str, Any]]:
150
224
  to = _timeout or timeout
151
- q = (query or "").strip()
225
+ q = _normalize_en_catalog_query(query)
152
226
  if not q:
153
227
  return []
154
228
  url = (
@@ -180,7 +254,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
180
254
  "url": url_final,
181
255
  "snippet": summary[:400],
182
256
  "source": "skillsmp",
183
- "score": rank_score(0.75, rank),
257
+ "score": _skill_rank_score(rank, stars, False),
184
258
  "published_at": _normalize_epoch(s.get("updatedAt")),
185
259
  "upstream": github or market,
186
260
  "metadata": {
@@ -190,6 +264,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
190
264
  },
191
265
  }
192
266
  )
267
+ results.sort(key=lambda r: -r["score"])
193
268
  return results
194
269
 
195
270
  return _engine
@@ -211,7 +286,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
211
286
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
212
287
  ) -> list[dict[str, Any]]:
213
288
  to = _timeout or timeout
214
- q = (query or "").strip()
289
+ q = _normalize_en_catalog_query(query)
215
290
  if not q:
216
291
  return []
217
292
  url = f"{_CLAWHUB_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -240,7 +315,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
240
315
  "url": f"https://clawhub.ai{canonical}",
241
316
  "snippet": summary[:400],
242
317
  "source": "clawhub",
243
- "score": rank_score(0.75, rank),
318
+ "score": _skill_rank_score(rank, downloads, official),
244
319
  "published_at": _normalize_epoch(s.get("updatedAt")),
245
320
  # install.reference 是 owner/slug 形式的安装引用
246
321
  "upstream": ((s.get("install") or {}).get("reference")) or "",
@@ -253,6 +328,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
253
328
  },
254
329
  }
255
330
  )
331
+ results.sort(key=lambda r: -r["score"])
256
332
  return results
257
333
 
258
334
  return _engine
@@ -275,7 +351,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
275
351
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
276
352
  ) -> list[dict[str, Any]]:
277
353
  to = _timeout or timeout
278
- q = (query or "").strip()
354
+ q = _normalize_en_catalog_query(query)
279
355
  if not q:
280
356
  return []
281
357
  url = f"{_SKILLS_SH_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -300,7 +376,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
300
376
  "url": f"{_SKILLS_SH_PAGE}{sid}",
301
377
  "snippet": f"安装 {installs} · {source}",
302
378
  "source": "skills_sh",
303
- "score": rank_score(0.75, rank),
379
+ "score": _skill_rank_score(rank, installs, False),
304
380
  # 可验证出处:三段式 id 指向技能本身(比市场页更精确)
305
381
  "upstream": sid,
306
382
  "metadata": {
@@ -309,6 +385,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
309
385
  },
310
386
  }
311
387
  )
388
+ results.sort(key=lambda r: -r["score"])
312
389
  return results
313
390
 
314
391
  return _engine
@@ -152,7 +152,7 @@ from serp_guard import ( # noqa: E402
152
152
 
153
153
 
154
154
  @functools.lru_cache(maxsize=512)
155
- def _score_authority_cached(url: str, source: str = "") -> tuple:
155
+ def _score_authority_cached(url: str, source: str = "", query: str = "") -> tuple:
156
156
  """score_authority 的缓存版本,返回 tuple(lru_cache 要求可哈希返回值)。"""
157
157
  if not url:
158
158
  return (0.3, "无 URL", "unknown", "", True)
@@ -228,6 +228,24 @@ def _score_authority_cached(url: str, source: str = "") -> tuple:
228
228
  else:
229
229
  best_reason += f"(引擎={source})"
230
230
 
231
+ # 有条件降权(2026-10-29,issue #34):同一域名在不同查询语境下可信度
232
+ # 不同——裁判文书站对「集采政策」是答非所问,对「判决书检索」是一手源。
233
+ # 放在引擎保底分之后做**最终裁决**:否则 anysearch 这类引擎的 0.75 保底
234
+ # 会把降权分拉回来(实测 0.15 → 0.75,降权形同虚设)。
235
+ # 只在调用方给了 query 时生效:无 query 的评分路径(状态展示、研究摘要)
236
+ # 保持原表行为,避免把「没传上下文」误判成「非法律查询」。
237
+ if query:
238
+ cond = _load_cn_source_types().get("demote_domains_unless") or {}
239
+ for d, meta in cond.items():
240
+ if d.startswith("_"):
241
+ continue
242
+ if domain == d or domain.endswith("." + d):
243
+ unless = meta.get("unless") or ""
244
+ if not (unless and re.search(unless, query, re.I)):
245
+ best_score = float(meta.get("score", 0.3))
246
+ best_reason = f"降权:{meta.get('reason', d)}"
247
+ break
248
+
231
249
  tier = (
232
250
  "high" if best_score >= 0.8
233
251
  else "medium" if best_score >= 0.6
@@ -238,14 +256,17 @@ def _score_authority_cached(url: str, source: str = "") -> tuple:
238
256
  return (best_score, best_reason, tier, domain, bool(is_serp))
239
257
 
240
258
 
241
- def score_authority(url: str, source: str = "") -> dict[str, Any]:
259
+ def score_authority(url: str, source: str = "", query: str = "") -> dict[str, Any]:
242
260
  """评估 URL 的权威性(Selection 门槛)。
243
261
 
244
- 结果按 (url, source) 做进程内 lru_cache:同一 URL + source 组合在多次
262
+ 结果按 (url, source, query) 做进程内 lru_cache:同一 URL + source 组合在多次
245
263
  rerank/selection 中只算一次,避免 search.py 的 local_five_dim_rerank 与
246
264
  _attach_selection_signals 对同一 URL 重复评分。
265
+
266
+ query 可选:只在有条件降权(demote_domains_unless,如裁判文书站)时需要,
267
+ 无 query 的调用方保持原表行为,缓存也按空 query 各自命中。
247
268
  """
248
- score, reason, tier, domain, is_serp = _score_authority_cached(url, source)
269
+ score, reason, tier, domain, is_serp = _score_authority_cached(url, source, query)
249
270
  return {
250
271
  "score": round(score, 2),
251
272
  "reason": reason,
@@ -674,7 +695,7 @@ def compute_credibility(
674
695
  title = r.get("title", "") or ""
675
696
  snippet = r.get("snippet", "") or ""
676
697
 
677
- auth = score_authority(url, source)
698
+ auth = score_authority(url, source, query)
678
699
  fresh = score_freshness(r, query_time)
679
700
  density = score_evidence_density(snippet, title)
680
701
 
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env python3
2
+ """extend_route_labels.py — 给路由语料加意图类型标签(外部反馈驱动扩展)。
3
+
4
+ ## 为什么需要它
5
+
6
+ `build_route_labels.py` 从本机数据构建的语料只有 `expect_domain`(历史路由
7
+ 输出)。但外部反馈(GitHub Issue #34.1)暴露的是一类**意图撞车**问题:
8
+ 同一个词在不同意图下属于不同域(`PD-1` 在「市场规模」下是商业分析,在
9
+ 「蛋白结构域」下是生信)。只看 domain 标签无法覆盖这类场景——需要一层
10
+ **意图类型**标签。
11
+
12
+ ## MECE 拆解:意图类型六分类
13
+
14
+ 按「用户想要什么」正交拆分,六类互不重叠、合起来穷尽:
15
+
16
+ | 类型 | 定义 | 典型域 | 撞车场景 |
17
+ |---|---|---|---|
18
+ | `factual` | 查事实/定义/数据 | cn_encyclopedia, stock_query, macro_data | 药靶点名 vs 商业名词 |
19
+ | `content` | 找内容/攻略/教程 | chinese_general, chinese_tech_deep, english_tech | 「原理」要讲解 vs 要论文 |
20
+ | `academic` | 找文献/论文/数据集 | academic, scholar_search, dataset_search | 「论文」要文献 vs 要讲解 |
21
+ | `sentiment` | 看舆情/评论/讨论 | social | 「攻略」要内容 vs 「舆情」要监听 |
22
+ | `entity` | 查机构/公司/人物 | org_entity, company_search | 公司名 vs 产品名 |
23
+ | `navigational` | 找入口/工具/站点 | dsh_plugin_search, skill_search | 找工具 vs 找资料 |
24
+
25
+ **穷尽性检查**:六类覆盖了「事实/内容/学术/舆情/实体/导航」六个正交维度。
26
+ 不在这六类里的查询(如「天气」「股价」)归入 `factual`(它们是查事实)。
27
+
28
+ ## 与外部反馈的对应
29
+
30
+ | 外部反馈 | 撞车场景 | 标签解法 |
31
+ |---|---|---|
32
+ | Issue #34.1 | PD-1 市场规模 vs 蛋白结构域 | `factual`(商业)vs `factual`(生信)——**同类不同域**,靠域标签区分 |
33
+ | v2.10.2 路由收口 | Transformer 原理 vs 论文 | `content` vs `academic`——**跨类**,靠意图标签区分 |
34
+ | v2.10.2 路由收口 | 小红书攻略 vs 舆情 | `content` vs `sentiment`——**跨类**,靠意图标签区分 |
35
+
36
+ ## 用法
37
+
38
+ python3 scripts/extend_route_labels.py # 加标签并写回
39
+ python3 scripts/extend_route_labels.py --dry-run # 只统计不写
40
+ python3 scripts/extend_route_labels.py --report # 打印撞车场景覆盖
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import json
47
+ import re
48
+ import sys
49
+ from collections import Counter
50
+ from pathlib import Path
51
+ from typing import Any
52
+
53
+ ROOT = Path(__file__).resolve().parent.parent
54
+ SCRIPTS = ROOT / "scripts"
55
+ sys.path.insert(0, str(SCRIPTS))
56
+
57
+ LABELS = ROOT / "tests" / "golden" / "route_labeled.jsonl"
58
+
59
+ # ── 意图类型判定(规则优先,域兜底)──────────────────────────────────────────
60
+ # 判据是「查询里出现了什么意图词」,不是「路由到了哪个域」——后者是输出,
61
+ # 用它当标签等于把答案抄进题目。
62
+
63
+ _INTENT_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
64
+ # academic:明确的文献意图词
65
+ ("academic", re.compile(
66
+ r"(论文|文献|综述|survey|review|arxiv|期刊|journal|doi|引用|reference|"
67
+ r"scholar|学术|科研|研究|实验|数据集|dataset|benchmark|评测)", re.I)),
68
+ # sentiment:舆情/讨论意图词
69
+ ("sentiment", re.compile(
70
+ r"(舆情|评论|讨论|网友|吐槽|口碑|评价|反馈|热议|争议|态度|"
71
+ r"sentiment|opinion|review|discussion|complaint)", re.I)),
72
+ # content:内容/教程意图词
73
+ ("content", re.compile(
74
+ r"(教程|攻略|指南|详解|原理|是什么|怎么用|如何|最佳实践|best practice|"
75
+ r"tutorial|guide|how to|example|案例|方案|步骤|方法)", re.I)),
76
+ # entity:机构/公司/人物意图词
77
+ ("entity", re.compile(
78
+ r"(公司|企业|集团|机构|组织|官网|总部|创始人|CEO|董事长|"
79
+ r"company|inc\.|corp\.|ltd\.|gmbh|organization)", re.I)),
80
+ # navigational:找入口/工具意图词
81
+ ("navigational", re.compile(
82
+ r"(插件|技能|工具|安装|下载|marketplace|plugin|skill|tool|install|"
83
+ r"下载|仓库|repo|github|npm|pypi)", re.I)),
84
+ ]
85
+
86
+
87
+ def classify_intent(query: str, domain: str | None = None) -> str:
88
+ """判定查询的意图类型。规则优先,域兜底。
89
+
90
+ 域兜底只用于规则没命中时——它是**弱信号**(域是路由输出),但比
91
+ 无标签好。兜底映射按域的语义归属,不是按域名字面。
92
+ """
93
+ for name, pat in _INTENT_PATTERNS:
94
+ if pat.search(query):
95
+ return name
96
+ # 域兜底
97
+ _DOMAIN_INTENT = {
98
+ "academic": "academic", "scholar_search": "academic",
99
+ "dataset_search": "academic",
100
+ "social": "sentiment",
101
+ "org_entity": "entity", "company_search": "entity",
102
+ "dsh_plugin_search": "navigational", "skill_search": "navigational",
103
+ "chinese_tech_deep": "content", "english_tech": "content",
104
+ "tech_deep": "content", "code_search": "content",
105
+ "cn_encyclopedia": "factual", "dictionary_search": "factual",
106
+ "stock_query": "factual", "fund_query": "factual",
107
+ "us_stock": "factual", "macro_data": "factual",
108
+ "financial_news": "factual", "weather_query": "factual",
109
+ }
110
+ if domain and domain in _DOMAIN_INTENT:
111
+ return _DOMAIN_INTENT[domain]
112
+ return "factual" # 默认:查事实
113
+
114
+
115
+ # ── 外部反馈的撞车场景(回归锚)────────────────────────────────────────────
116
+
117
+ # 来自 GitHub Issue #34.1 与 v2.10.2 路由准确率收口的实测场景。
118
+ # 每条:(查询, 期望域, 期望意图类型, 反馈来源)
119
+ COLLISION_ANCHORS: list[tuple[str, str, str, str]] = [
120
+ # Issue #34.1:药靶点撞基因名
121
+ ("PD-1 抑制剂 2026 市场规模", "chinese_general", "factual", "Issue#34.1"),
122
+ ("重组胶原蛋白 医美 市场规模", "chinese_general", "factual", "Issue#34.1"),
123
+ ("PD-1 蛋白 结构域 序列", "protein_search", "factual", "Issue#34.1"),
124
+ # v2.10.2:原理 vs 论文
125
+ ("Transformer 模型 原理", "chinese_tech_deep", "content", "v2.10.2"),
126
+ ("Transformer 原理 论文", "academic", "academic", "v2.10.2"),
127
+ ("深度学习 原理", "chinese_tech_deep", "content", "v2.10.2"),
128
+ ("Attention 机制 详解", "chinese_general", "content", "v2.10.2"),
129
+ # v2.10.2:攻略 vs 舆情
130
+ ("小红书 露营 攻略", "chinese_general", "content", "v2.10.2"),
131
+ ("小红书 露营 舆情", "social", "sentiment", "v2.10.2"),
132
+ ("小红书 露营 评论", "social", "sentiment", "v2.10.2"),
133
+ # v2.10.2:技能目录
134
+ ("小红书 技能 排行榜", "redskill_search", "navigational", "v2.10.2"),
135
+ # v2.10.2:行情 vs 财报
136
+ ("贵州茅台股价", "stock_query", "factual", "v2.10.2"),
137
+ ("宁德时代 股价", "stock_query", "factual", "v2.10.2"),
138
+ # v2.10.2:学术检索正例
139
+ ("科研数据集 开放数据 下载", "dataset_search", "academic", "v2.10.2"),
140
+ ("google scholar 学术论文 期刊", "scholar_search", "academic", "v2.10.2"),
141
+ ]
142
+
143
+
144
+ def extend(entries: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
145
+ """给每条语料加 `intent` 字段,并追加撞车锚。"""
146
+ out: dict[str, dict[str, Any]] = {}
147
+ for e in entries:
148
+ q = e["query"]
149
+ e2 = dict(e)
150
+ e2["intent"] = classify_intent(q, e.get("expect_domain"))
151
+ out[q] = e2
152
+
153
+ # 追加撞车锚(不在语料里的才加,避免重复)
154
+ added = 0
155
+ for q, dom, intent, src in COLLISION_ANCHORS:
156
+ if q in out:
157
+ # 已存在:核对意图标签是否一致
158
+ if out[q].get("intent") != intent:
159
+ out[q]["intent"] = intent
160
+ out[q]["intent_source"] = src
161
+ continue
162
+ out[q] = {
163
+ "query": q,
164
+ "expect_domain": dom,
165
+ "expect_family": None,
166
+ "evidence": "feedback",
167
+ "quality": {"errors": False, "recovered": False,
168
+ "count": 0, "occurrences": 1},
169
+ "source": src,
170
+ "intent": intent,
171
+ "intent_source": src,
172
+ }
173
+ added += 1
174
+
175
+ result = [out[k] for k in sorted(out)]
176
+ stats = {
177
+ "total": len(result),
178
+ "added_anchors": added,
179
+ "by_intent": dict(Counter(e.get("intent") for e in result)),
180
+ "by_evidence": dict(Counter(e.get("evidence") for e in result)),
181
+ }
182
+ return result, stats
183
+
184
+
185
+ def _report(entries: list[dict[str, Any]]) -> None:
186
+ """打印撞车场景覆盖情况。"""
187
+ from route import route_query
188
+ from config import get_domains
189
+
190
+ live = {d.get("name") for d in get_domains()}
191
+ anchors = [e for e in entries if e.get("evidence") == "feedback"]
192
+ print(f"[extend_route_labels] 撞车锚 {len(anchors)} 条,逐条核验:")
193
+ ok = 0
194
+ for e in anchors:
195
+ try:
196
+ r = route_query(e["query"], mode="auto", depth="fast")
197
+ except Exception:
198
+ continue
199
+ got = r.get("domain")
200
+ want = e["expect_domain"]
201
+ hit = got == want and want in live
202
+ ok += hit
203
+ print(f" {'OK ' if hit else 'BAD'} {e['query'][:30]!r:34} "
204
+ f"want={want:20} got={got:20} intent={e.get('intent')}")
205
+ print(f"[extend_route_labels] 撞车锚命中 {ok}/{len(anchors)}")
206
+
207
+
208
+ def main() -> int:
209
+ ap = argparse.ArgumentParser(description="给路由语料加意图类型标签")
210
+ ap.add_argument("--dry-run", action="store_true")
211
+ ap.add_argument("--report", action="store_true", help="打印撞车锚覆盖")
212
+ args = ap.parse_args()
213
+
214
+ if not LABELS.is_file():
215
+ print(f"[extend_route_labels] 语料不存在:{LABELS}", file=sys.stderr)
216
+ return 1
217
+ entries = [json.loads(l) for l in
218
+ LABELS.read_text(encoding="utf-8").splitlines() if l.strip()]
219
+
220
+ extended, stats = extend(entries)
221
+ print(f"[extend_route_labels] 语料 {len(entries)} -> {stats['total']} 条"
222
+ f"(新增撞车锚 {stats['added_anchors']})")
223
+ print(f"[extend_route_labels] 意图分布: {stats['by_intent']}")
224
+ print(f"[extend_route_labels] 证据分档: {stats['by_evidence']}")
225
+
226
+ if args.report:
227
+ _report(extended)
228
+ if args.dry_run:
229
+ return 0
230
+
231
+ with LABELS.open("w", encoding="utf-8") as f:
232
+ for e in extended:
233
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
234
+ print(f"[extend_route_labels] 已写回 {LABELS}")
235
+ return 0
236
+
237
+
238
+ if __name__ == "__main__":
239
+ raise SystemExit(main())