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
@@ -37,6 +37,14 @@ DOMAIN_PROFILES_PATH = BACKENDS_DIR / "domain_profiles.json"
37
37
 
38
38
  _TOKEN_PATTERN = re.compile(r"[一-鿿\u3040-\u30ff\uac00-\ud7af]|[a-zA-Z0-9]+")
39
39
 
40
+ # 通用搜索泛域(与 route_combo._GENERAL_ENGINES 的 catch-all 部分对齐,但不含
41
+ # arxiv/wikipedia 这类有明确用途的宽域源):这些引擎的 domain_profiles 文档
42
+ # 覆盖大量通用词,概念向量对它们几乎恒为高值,会挤掉垂直引擎。
43
+ _CATCH_ALL_CONCEPT = frozenset({
44
+ "anysearch", "byted", "bocha", "octen", "local_search", "zhihu",
45
+ "wechat_sogou", "uapi", "tavily", "brave", "bocha_ai", "seltz",
46
+ })
47
+
40
48
 
41
49
  def tokenize(text: str) -> list[str]:
42
50
  """简单分词:中文/日文/韩文单字 + 英文单词,统一小写。
@@ -262,6 +270,23 @@ class SemanticRouter:
262
270
  return [("anysearch", 0.0, "无领域文档,回退 AnySearch")]
263
271
 
264
272
  query_vec = self.vectorizer.transform(query)
273
+ # P2: 静态概念语义向量 (Model2Vec 思想,零依赖快速查表)
274
+ concept_vec = None
275
+ cl = None
276
+ try:
277
+ from concept_lookup import (
278
+ get_concept_lookup,
279
+ concept_router_enabled,
280
+ strip_context_dims,
281
+ )
282
+ if concept_router_enabled():
283
+ cl = get_concept_lookup()
284
+ if cl.is_available:
285
+ # 地名维清零:避免含地名的查询被航空/测绘类引擎凭地名重叠拉高
286
+ concept_vec = strip_context_dims(cl.text_vector(query))
287
+ except Exception:
288
+ concept_vec = None
289
+
265
290
  scores = []
266
291
  quota_state = _load_quota_state() if quota_aware else {}
267
292
  cost_profiles = _load_cost_profiles()
@@ -269,7 +294,32 @@ class SemanticRouter:
269
294
 
270
295
  for name in self.engine_names:
271
296
  sim = cosine_similarity(query_vec, self.engine_vectors[name])
297
+ eff_sim = sim
298
+ c_sim = 0.0
299
+ if concept_vec is not None and cl is not None:
300
+ eng_cvec = strip_context_dims(cl.get_engine_vector(name))
301
+ if eng_cvec is not None:
302
+ c_sim = cl.vector_cosine(concept_vec, eng_cvec)
303
+ catch_all = name in _CATCH_ALL_CONCEPT
304
+ if c_sim >= 0.75:
305
+ if catch_all:
306
+ # 泛域引擎词表覆盖面广,概念相似度易虚高,只作弱辅助;
307
+ # 无词面交集时不允许概念单独把它拉上第一
308
+ eff_sim = (max(sim, 0.90 * sim + 0.10 * c_sim)
309
+ if sim > 0 else sim)
310
+ elif sim > 0:
311
+ eff_sim = max(sim, 0.70 * sim + 0.30 * c_sim)
312
+ else:
313
+ eff_sim = c_sim * 0.50
314
+ elif sim > 0 and c_sim > 0.40:
315
+ if catch_all:
316
+ eff_sim = max(sim, 0.95 * sim + 0.05 * c_sim)
317
+ else:
318
+ eff_sim = max(sim, 0.80 * sim + 0.20 * c_sim)
319
+
272
320
  parts = []
321
+ if c_sim >= 0.75 and sim <= 0:
322
+ parts.append(f"concept={c_sim:.2f}")
273
323
 
274
324
  # boost 加权
275
325
  boost = 1.0
@@ -290,7 +340,7 @@ class SemanticRouter:
290
340
  if hit_combos:
291
341
  parts.append(f"combo:{','.join(hit_combos)}")
292
342
 
293
- final_score = sim * boost
343
+ final_score = eff_sim * boost
294
344
 
295
345
  # 成本感知(profiles 已缓存,不再每引擎读盘)
296
346
  cf = _cost_factor(name, cost_profiles)
@@ -308,7 +358,7 @@ class SemanticRouter:
308
358
  final_score *= 0.5 + qr
309
359
  parts.append(f"配额偏低({qr:.0%})")
310
360
 
311
- reason = f"sim={sim:.3f}" + (f", {', '.join(parts)}" if parts else "")
361
+ reason = f"sim={eff_sim:.3f}" + (f", {', '.join(parts)}" if parts else "")
312
362
  scores.append((name, round(final_score, 4), reason))
313
363
 
314
364
  scores.sort(key=lambda x: -x[1])
package/scripts/train.py CHANGED
@@ -131,6 +131,16 @@ def _parse_travel_date(text: str) -> tuple[date | None, str]:
131
131
  return None, text
132
132
 
133
133
 
134
+ # 口语填充词(2026-10-31 评测 fz07 实测):「杭州到黄山坐高铁最快需要多久?」
135
+ # 拆分后到站段是「黄山坐高铁最快需要多久」,站名匹配必败、整条静默返回空。
136
+ # 只剥多字交通/时长词,不做单字剥离——站名剥字教训(「张家口」→「家口」)
137
+ # 在此同样适用;剥完仍以站名表为准解析,表里没有的站照旧失败。
138
+ _QUERY_FILLER_RE = re.compile(
139
+ r"坐高铁|坐火车|高铁|火车|列车|动车|最快需要多久|需要多久|最快多久|多久"
140
+ r"|多长时间|几个小时|几小时|怎么走|时刻表|车次表"
141
+ )
142
+
143
+
134
144
  def _parse_query(q: str) -> dict | None:
135
145
  """从自然语言查询词解析 出发站/到达站/日期/车次类型。
136
146
 
@@ -165,6 +175,11 @@ def _parse_query(q: str) -> dict | None:
165
175
  # 「高碑店」→「碑店」、「次渠」→「渠」。站名后缀(北京站/上海市)由
166
176
  # _resolve_station 统一剥离(它已有 `[市站]$`),这里不必也不该再剥一遍。
167
177
  parts = [p.strip(" \t,。!?、") for p in parts if p.strip()]
178
+ parts = [_QUERY_FILLER_RE.sub(" ", p).strip(" \t,。!?、") for p in parts]
179
+ # 悬挂字:填充词被车次类型/本剥离先后摘掉后,「坐/的」可能残在段尾
180
+ # (实测「黄山坐」「黄山北的」);行尾锚只动段尾,不碰站名内部。
181
+ parts = [re.sub(r"[坐的]\s*$", "", p).strip() for p in parts]
182
+ parts = [p for p in parts if p]
168
183
  if len(parts) < 2:
169
184
  return None
170
185
  from_name, to_name = parts[0], parts[1]
@@ -47,11 +47,12 @@ TRACKING_PARAMS: frozenset[str] = frozenset({
47
47
  "from_source", "from_spmid", "from_spmid2", "vd_source", "unique_k",
48
48
  "buvid", "buvid3", "buvid4", "up_id", "seid", "spmid", "timestamp",
49
49
  "wxshare", "weibo_id", "share_referer", "share_object_id",
50
- # 通用归因
50
+ # 通用归因与平台语言/分享变体(YouTube vl/si 会把同一视频拆成多条重复 URL)
51
51
  "ref", "ref_src", "ref_url", "refer", "referer", "referrer",
52
52
  "source", "from", "src", "cmp", "camp", "srsltid",
53
53
  "clickid", "click_id", "clicktime", "scid", "scene", "sessionid",
54
54
  "trace", "trace_id", "track", "tracking_id", "trk", "trkcampaign",
55
+ "si", "vl",
55
56
  })
56
57
 
57
58
  # 移动站/AMP 子域前缀(fold_mobile)与 www 前缀(fold_www)分开——
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env python3
2
+ """verify_with.py — 主查+核对配对:一个查询类型配一个核对引擎。
3
+
4
+ 问题重定义(第一性,2026-11-01 实测):
5
+ 同一 query 的主查聚合池(中文多源)混着转述、旧闻与 SEO 毒内容;而
6
+ 「核对」要的是一张干净的**独立官方簇**。实测「iPhone 17 Pro Max 官方
7
+ 价格」:主查 top-8 无一条干净官方直链,`--engine exa` 3 秒返回的 top-5
8
+ 全部是 apple.com 官方域(大陆/英/日/港/泰)。主查与核对是两种不同的
9
+ 检索意图,不该靠一个融合排序硬捏。
10
+
11
+ 外部佐证:X 帖(@qi9098,2026-10-31)的路由表把「先用什么查、再用什么
12
+ 核对」写成两列——「一般网页、新闻、价格:WebSearch,再用 Exa 核对」。
13
+
14
+ 设计取舍:
15
+ ① 配对规则是「查询类型 → 核对引擎」,不是引擎属性——所以放本模块的
16
+ 规则表,不进 engine_registry.yaml(引擎条目描述的是引擎自己)。
17
+ ② 核对结果**独立交付**(verify_with 段),不并入主排序:官方簇的价值
18
+ 在「给 Agent 一眼可对的第二意见」,混排反而稀释。
19
+ ③ 默认关(显式 --verify-with 才跑)。auto 档按规则表选引擎,无规则
20
+ 命中就明确报 skipped,不静默空转。
21
+ ④ 核对调用走 super_search 的单引擎路径(与 --engine exa 完全同款),
22
+ 复用其缓存与告警纪律;失败 fail-open,绝不拖垮主搜索。
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import re
28
+ import time
29
+ from typing import Any, Callable
30
+ from urllib.parse import urlparse
31
+
32
+ # 规则表:查询特征 → 核对引擎。顺序即优先级,首条命中即返回。
33
+ # why exa:语义检索强于词面,官方/一手站点召回稳定(10-31 实测 5/5 官方簇),
34
+ # 且在本机免密钥可路由;deepseek_search 计费不作默认核对档。
35
+ _VERIFY_RULES: tuple[tuple[re.Pattern[str], str], ...] = (
36
+ # 价格/购买意图:价格、售价、报价、多少钱、行情价、price
37
+ (re.compile(r"价格|售价|报价|多少钱|卖多少|费用|收费|price|pricing|cost",
38
+ re.IGNORECASE), "exa"),
39
+ # 官方规格/参数核对:参数、配置、规格、对比
40
+ (re.compile(r"参数|配置|规格|spec|specification|对比",
41
+ re.IGNORECASE), "exa"),
42
+ )
43
+
44
+
45
+ def pick_verify_engine(query: str, domain: str | None = None) -> str | None:
46
+ """按查询特征选核对引擎;无规则命中返回 None(调用方明确 skipped)。"""
47
+ if not query:
48
+ return None
49
+ for pat, engine in _VERIFY_RULES:
50
+ if pat.search(query):
51
+ return engine
52
+ return None
53
+
54
+
55
+ def _domain_of(url: str) -> str:
56
+ try:
57
+ return urlparse(url).netloc.lower()
58
+ except Exception: # pragma: no cover
59
+ return ""
60
+
61
+
62
+ def run_verify_search(query: str, engine: str, n: int = 5,
63
+ timeout: int = 10) -> dict[str, Any]:
64
+ """单引擎核对检索(与 `--engine <名>` 同一条路径)。失败抛给调用方。"""
65
+ from search import super_search # 懒加载:search 模块重(~百 ms),仅开启时付
66
+ # include_local 显式关:fast 模式默认并入本机文件命中(file://),而核对
67
+ # 簇要的是「独立 web 官方簇」——实测 file:// 命中混进 exa 结果污染核对段
68
+ # (2026-11-01 端到端实测抓到)。
69
+ out = super_search(query, engine=engine, n=n, mode="fast", quiet=True,
70
+ timeout=timeout, include_local=False)
71
+ return out.get("results") or []
72
+
73
+
74
+ def attach_verify_with(results: dict[str, Any],
75
+ query: str,
76
+ engine: str = "auto",
77
+ n: int = 5,
78
+ timeout: int = 10,
79
+ runner: Callable[..., list[dict]] | None = None,
80
+ ) -> dict[str, Any]:
81
+ """执行核对并写 results["verify_with"] 段。
82
+
83
+ engine="auto":按规则表选;无命中 → {"engine": None, "skipped": "no_rule"}。
84
+ engine 显式点名:照跑(含未知引擎——错误由执行层 errors 报告,这里不拦)。
85
+
86
+ 段结构(独立交付,不动主排序):
87
+ engine 实际使用的核对引擎
88
+ skipped 未执行原因(no_rule / error:…),无则无此键
89
+ elapsed_ms 核对调用墙钟
90
+ results 核对结果(每条附 verify_provenance=True,n 条)
91
+ overlap 与主查的域级重叠 {domains, count}——重叠是「两路独立
92
+ 检索都看到同一域」,是比 URL 级更稳的核对信号
93
+ """
94
+ chosen = engine
95
+ if engine in ("auto", ""):
96
+ chosen = pick_verify_engine(query, results.get("domain"))
97
+ if not chosen:
98
+ return {"engine": None, "skipped": "no_rule"}
99
+
100
+ run = runner or run_verify_search
101
+ t0 = time.perf_counter()
102
+ try:
103
+ vres = run(query, chosen, n=n, timeout=timeout)
104
+ except Exception as e: # fail-open:核对失败不影响主搜索交付
105
+ return {"engine": chosen, "skipped": f"error:{type(e).__name__}",
106
+ "elapsed_ms": round((time.perf_counter() - t0) * 1000, 1)}
107
+
108
+ elapsed = round((time.perf_counter() - t0) * 1000, 1)
109
+ for r in vres or []:
110
+ if isinstance(r, dict):
111
+ r["verify_provenance"] = True
112
+
113
+ main_domains = {_domain_of(r.get("url") or "")
114
+ for r in (results.get("results") or []) if isinstance(r, dict)}
115
+ verify_domains = {_domain_of(r.get("url") or "") for r in (vres or [])
116
+ if isinstance(r, dict)} - {""}
117
+ overlap = sorted(d for d in verify_domains if d in main_domains)
118
+
119
+ return {
120
+ "engine": chosen,
121
+ "elapsed_ms": elapsed,
122
+ "results": vres or [],
123
+ "overlap": {"domains": overlap, "count": len(overlap)},
124
+ }
@@ -17,9 +17,9 @@ from __future__ import annotations
17
17
 
18
18
  from typing import Any
19
19
 
20
- # config 缺 video 域时的兜底:B 站是当前唯一稳定免费的视频搜索源,
21
- # anysearch 负责带出 YouTube 等海外视频(无独立 YouTube 引擎时)。
22
- _FALLBACK = ("bilibili", "anysearch")
20
+ # config 缺 video 域时的兜底:B 站负责中文视频,parallel_free 负责海外/YouTube
21
+ # 视频(免 Key 直连),anysearch 补充国内综合索引。
22
+ _FALLBACK = ("bilibili", "parallel_free", "anysearch")
23
23
 
24
24
 
25
25
  def _video_domain() -> dict[str, Any]:
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: local-search
3
3
  parent: argo
4
- description: argo 的本地/零成本兜底子技能。封装基于公开页面/HTML/RSS/JSON/CLI 的 29 个本地搜索引擎,不单独响应触发词,仅由 argo 通过 --local-first 调用。
4
+ description: argo 的本地/零成本兜底子技能。封装基于公开页面/HTML/RSS/JSON/CLI 的 30 个本地搜索引擎,不单独响应触发词,仅由 argo 通过 --local-first 调用。
5
5
  version: 1.1.0
6
6
  ---
7
7
 
@@ -19,7 +19,7 @@ Local Search 是 argo 的「零成本兜底适配器」,用于:
19
19
  - **输出与主 skill 同 schema**:`results[]` / `engines_used` / `errors` / `elapsed_ms`,可直接进 evidence 与 RRF。
20
20
  - **`local_X` 与主清单的 `X` 是别名,不是备份**:`local_arxiv`/`local_crossref`/`local_semantic_scholar`/`local_github`/`local_npm`/`local_wikipedia`/`local_stackoverflow`/`local_google_news` 与主清单同名项**打同一个上游端点**(主清单走官方 API、这里走免密钥直取),不存在「API 挂了抓取版兜底」。同上游同格式由 `tests/test_local_search_registry.py` 锁定。
21
21
 
22
- ### 本地引擎列表(29 个,27 个默认启用)
22
+ ### 本地引擎列表(30 个,28 个默认启用)
23
23
 
24
24
  | unified 名称 | 类型 | 默认启用 | 类别 | 说明 |
25
25
  |--------------|------|----------|------|------|
@@ -46,6 +46,7 @@ Local Search 是 argo 的「零成本兜底适配器」,用于:
46
46
  | local_stackoverflow | json | ✅ | code | StackOverflow 问题 |
47
47
  | local_gitlab | json | ✅ | code | GitLab API |
48
48
  | local_npm | json | ✅ | code | NPM Registry |
49
+ | local_hackernews | json | ✅ | code/web_general | Hacker News / Algolia API |
49
50
  | local_wikipedia | json | ✅ | reference | MediaWiki API(ddgs wikipedia backend 结果过少) |
50
51
  | local_wiktionary | json | ✅ | reference | Wiktionary API |
51
52
  | local_wikiquote | json | ✅ | reference | Wikiquote API |
@@ -121,30 +121,101 @@ class BM25:
121
121
  return total
122
122
 
123
123
 
124
+ # 权威站点与官方开发者/百科/学术域(白名单适度加成)
125
+ _AUTHORITATIVE_DOMAINS: frozenset[str] = frozenset({
126
+ "github.com", "gitlab.com", "stackoverflow.com", "wikipedia.org",
127
+ "arxiv.org", "developer.mozilla.org", "docs.python.org", "python.org",
128
+ "golang.org", "go.dev", "rust-lang.org", "kernel.org", "w3.org",
129
+ "learn.microsoft.com", "pypi.org", "npmjs.com", "baike.baidu.com",
130
+ "zhihu.com", "segmentfault.com", "juejin.cn", "v2ex.com",
131
+ "nature.com", "science.org", "acm.org", "ieee.org",
132
+ })
133
+
134
+ # 常见低质采集站/垃圾农场特征(微幅降权)
135
+ _NOISE_DOMAIN_PATTERNS: tuple[str, ...] = (
136
+ "csdn.net", "jb51.net", "iteye.com",
137
+ )
138
+
139
+
140
+ def _domain_quality_prior(url: str) -> float:
141
+ """基于 URL 域名的先验质量分(-0.3 ~ +0.5)。
142
+
143
+ 零依赖纯规则:高信噪比技术、百科、学术域给予正向增益,低信噪比/采集站特征适度降权。
144
+ 仅用于在词面相关(BM25 > 0)的前提下微调,不破坏 fail-soft 契约。
145
+ """
146
+ if not url or "://" not in url:
147
+ return 0.0
148
+ try:
149
+ domain = url.split("://", 1)[1].split("/", 1)[0].split(":", 1)[0].lower()
150
+ except Exception:
151
+ return 0.0
152
+ for auth in _AUTHORITATIVE_DOMAINS:
153
+ if domain == auth or domain.endswith("." + auth):
154
+ return 0.5
155
+ for noise in _NOISE_DOMAIN_PATTERNS:
156
+ if noise in domain:
157
+ return -0.3
158
+ return 0.0
159
+
160
+
161
+ def _url_tokens_text(url: str) -> str:
162
+ """提取 URL path 中的 slug 词元作为弱辅助匹配信号。"""
163
+ if not url or "://" not in url:
164
+ return ""
165
+ try:
166
+ path = url.split("://", 1)[1].split("?", 1)[0].split("#", 1)[0]
167
+ slugs = re.findall(r"[A-Za-z0-9_-]{2,}", path)
168
+ return " ".join(slugs)
169
+ except Exception:
170
+ return ""
171
+
172
+
124
173
  def _phrase_proximity_bonus(query: str, title: str, snippet: str) -> float:
125
174
  """词邻近度与短语连续匹配加成(归一化为 0.0~1.0)。
126
175
 
127
- 当完整查询短语在标题或摘要逐字紧密出现时给予增益,提升复合词精准命中率。
176
+ 当完整查询短语或紧邻词元在标题或摘要逐字紧密出现时给予增益,提升复合词精准命中率。
128
177
  """
129
178
  q_low = (query or "").lower().strip()
130
179
  if not q_low or len(q_low) < 2:
131
180
  return 0.0
132
181
  t_low = (title or "").lower()
133
182
  s_low = (snippet or "").lower()
183
+
184
+ # 1. 完整短语匹配优先
134
185
  if q_low in t_low:
135
186
  return 1.0 # 标题完整覆盖查询短语
136
187
  if q_low in s_low:
137
- return 0.5 # 摘要完整覆盖查询短语
138
- return 0.0
188
+ return 0.6 # 摘要完整覆盖查询短语
189
+
190
+ # 2. 多词紧邻跨度匹配
191
+ sub_terms = [t for t in re.split(r"[\s\-_,.:;!?,。!?]+", q_low) if len(t) >= 2]
192
+ if len(sub_terms) >= 2:
193
+ if all(st in t_low for st in sub_terms):
194
+ positions = [t_low.find(st) for st in sub_terms]
195
+ if max(positions) - min(positions) <= 50:
196
+ return 0.85
197
+ if all(st in s_low for st in sub_terms):
198
+ positions = [s_low.find(st) for st in sub_terms]
199
+ if max(positions) - min(positions) <= 100:
200
+ return 0.4
139
201
 
202
+ return 0.0
140
203
 
141
204
 
142
205
  def _doc_text(r: dict[str, Any]) -> str:
143
- """参与相关度计算的文档文本:title 权重高于 snippet——做法是标题
144
- 拼两遍(TF 加成),不引入第二套字段权重机制。"""
206
+ """参与相关度计算的文档文本:title 权重高于 snippet。
207
+ BM25F 近似加权:标题 3 遍,正文 1 遍,URL slug 辅助字段 1 遍。"""
145
208
  title = (r.get("title") or "").strip()
146
209
  snippet = (r.get("snippet") or "").strip()
147
- return f"{title} {title} {snippet}" if title else snippet
210
+ url_slug = _url_tokens_text(r.get("url") or "")
211
+ parts = []
212
+ if title:
213
+ parts.extend([title, title, title])
214
+ if snippet:
215
+ parts.append(snippet)
216
+ if url_slug:
217
+ parts.append(url_slug)
218
+ return " ".join(parts) if parts else ""
148
219
 
149
220
 
150
221
  def rerank(by_engine: dict[str, list[dict[str, Any]]], query: str,
@@ -171,12 +242,22 @@ def rerank(by_engine: dict[str, list[dict[str, Any]]], query: str,
171
242
  scorer = BM25(docs)
172
243
  raw = [scorer.score(q_terms, i) for i in range(len(flat))]
173
244
  max_raw = max(raw) if raw else 0.0
245
+ pos_raw = sorted(x for x in raw if x > 0)
246
+ pivot = pos_raw[len(pos_raw) // 2] if pos_raw else 1.0
247
+ max_sat = (max_raw / (max_raw + pivot)) if max_raw > 0 else 1.0
174
248
 
175
249
  for (eng, idx, r), bm in zip(flat, raw):
176
- bm25_norm = (bm / max_raw) if max_raw > 0 else 0.0
250
+ if bm > 0 and max_raw > 0:
251
+ # 融合线性比值与连续归一化的 Robertson-Zaragoza 饱和项,抗离群长标题且无断点
252
+ rel_max = bm / max_raw
253
+ sat_norm = (bm / (bm + pivot)) / max_sat
254
+ bm25_norm = 0.65 * rel_max + 0.35 * sat_norm
255
+ else:
256
+ bm25_norm = 0.0
177
257
  prior_norm = _position_prior(idx) / _PRIOR_BASE
178
258
  prox_val = _phrase_proximity_bonus(query, r.get("title", ""), r.get("snippet", ""))
179
- rel_score = min(bm25_norm * 0.80 + prox_val * 0.20, 1.0) if bm25_norm > 0 else 0.0
259
+ domain_val = _domain_quality_prior(r.get("url", ""))
260
+ rel_score = min(max(bm25_norm * 0.72 + prox_val * 0.18 + domain_val * 0.16, 0.0), 1.0) if bm25_norm > 0 else 0.0
180
261
  r["score"] = round(w_bm25 * rel_score + (1.0 - w_bm25) * prior_norm, 3)
181
262
 
182
263
  for eng in by_engine:
@@ -423,3 +423,15 @@ engines:
423
423
  addressdetails: 1
424
424
  headers:
425
425
  User-Agent: unified-search-local/1.0.1
426
+
427
+ local_hackernews:
428
+ type: json
429
+ enabled: true
430
+ categories: [code, web_general]
431
+ url: "https://hn.algolia.com/api/v1/search"
432
+ query_param: query
433
+ method: GET
434
+ timeout: 8
435
+ format: json
436
+ extra_params:
437
+ hitsPerPage: "{n}"
@@ -180,3 +180,11 @@ json:
180
180
  url: null
181
181
  snippet: "type"
182
182
  url_template: "https://www.openstreetmap.org/{osm_type}/{osm_id}"
183
+
184
+ local_hackernews:
185
+ items: "hits"
186
+ title: "title"
187
+ url: "url"
188
+ snippet: "story_text"
189
+ url_template: "https://news.ycombinator.com/item?id={objectID}"
190
+ published_at: "created_at"
@@ -303,8 +303,11 @@ def _parse_json(engine_name: str, text: str, maps: dict[str, Any],
303
303
  if url_key:
304
304
  raw = _get_path(item, url_key)
305
305
  url = str(raw or "")[:500]
306
- elif url_template:
307
- url = _format_url(url_template, item)
306
+ # url 字段存在但为空(如 HN Algolia 的 comment/Ask HN hit)时回落
307
+ # 模板——此前 if/elif 互斥,url_key 一旦配置模板兜底即成死代码
308
+ # (2026-10-30 实测 local_hackernews 全部条目 url 为空)。
309
+ if not url and url_template:
310
+ url = _format_url(url_template, item)[:500]
308
311
  if snippet_key:
309
312
  raw = _get_path(item, snippet_key)
310
313
  snippet = str(raw or "")[:300]
@@ -69,6 +69,23 @@ from engine_registry import EngineRegistry, get_registry
69
69
  from local_health_check import get_available_engines
70
70
  from smart_router import route_query
71
71
 
72
+ def _get_circuit_breaker():
73
+ """**调用期**从 sys.modules 解析熔断器工厂,不在导入期绑死函数对象。
74
+
75
+ 为什么:本模块在导入期 `from circuit_breaker import get_breaker` 绑定的是
76
+ 那一刻的模块对象;`circuit_breaker.STATE_PATH` 由 ARGO_STATE_DIR 在导入期
77
+ 派生,而测试会用 `sys.modules.pop` 把它重导入(test_argo_paths 的
78
+ `test_module_paths_under_state_root`)。重导入后 `import circuit_breaker`
79
+ 拿到新模块对象,本模块绑的仍是旧模块的函数——「记录熔断」写新路径、
80
+ 「读取熔断」读旧路径,同一个类对默认路径给出两个答案,表现为全套件红、
81
+ 单跑全绿。运行期解析让两侧永远指向同一个模块对象。
82
+ """
83
+ try:
84
+ import circuit_breaker
85
+ return circuit_breaker.get_breaker()
86
+ except Exception:
87
+ return None
88
+
72
89
  logger = logging.getLogger("local_search.search_v3")
73
90
  if not logger.handlers:
74
91
  logger.setLevel(logging.WARNING)
@@ -325,6 +342,48 @@ def _sort_results(results: list[dict[str, Any]], sort: str) -> list[dict[str, An
325
342
  return sorted(results, key=_key)
326
343
 
327
344
 
345
+ def _dedup_near_duplicates(results: list[dict[str, Any]]) -> list[dict[str, Any]]:
346
+ """结果级去重:URL 相同直接合并;同引擎 title+snippet 近同归并。
347
+
348
+ rrf_merge 只按 canonical URL 去重且仅在多引擎路径生效,单引擎路径
349
+ 完全没人管(2026-10-30 实测 local_hackernews:同一 Ask HN 被上游各收
350
+ 一份,objectID 不同 URL 必不同,按 URL 永远合并不了)。归并只看同
351
+ 引擎——跨引擎同标题是共识信号,留给 rrf_merge 的 consensus 标注。
352
+ """
353
+ def _norm(s: Any) -> str:
354
+ return re.sub(r"\s+", " ", str(s or "")).strip().lower()
355
+
356
+ kept: list[dict[str, Any]] = []
357
+ seen_url: dict[str, int] = {}
358
+ seen_text: dict[tuple[str, str, str], int] = {}
359
+ for r in results:
360
+ if not isinstance(r, dict):
361
+ continue
362
+ url = str(r.get("url") or "").strip()
363
+ if url:
364
+ key = url.rstrip("/")
365
+ if key in seen_url:
366
+ idx = seen_url[key]
367
+ if float(r.get("score") or 0) > float(kept[idx].get("score") or 0):
368
+ kept[idx] = r
369
+ continue
370
+ seen_url[key] = len(kept)
371
+ title = _norm(r.get("title"))[:200]
372
+ snippet = _norm(r.get("snippet"))[:80]
373
+ eng = str(r.get("_engine") or r.get("source") or "")
374
+ if title and snippet:
375
+ tkey = (eng, title, snippet)
376
+ if tkey in seen_text:
377
+ idx = seen_text[tkey]
378
+ if url and not str(kept[idx].get("url") or "").strip():
379
+ kept[idx] = r # 同文异链:保留有链接的那条
380
+ seen_url[url.rstrip("/")] = idx
381
+ continue
382
+ seen_text[tkey] = len(kept)
383
+ kept.append(r)
384
+ return kept
385
+
386
+
328
387
  def _fetch(url: str, method: str = "GET", data: bytes | None = None,
329
388
  headers: dict[str, str] | None = None, timeout: float = 8,
330
389
  user_agent: str = "") -> str:
@@ -679,6 +738,7 @@ def search_engines(
679
738
  settings = cfg.get("settings", {})
680
739
  max_parallel = max_parallel or settings.get("max_parallel_engines", 5)
681
740
 
741
+ is_auto_routed = engines is None
682
742
  # 自动路由
683
743
  if not engines:
684
744
  decision = route_query(query, registry=reg, max_engines=3, require_available=False)
@@ -693,10 +753,26 @@ def search_engines(
693
753
  # 被过滤掉的引擎必须上报(engines_dropped)——静默替换会让「我要的三
694
754
  # 个引擎」变成「你给的一个引擎」而无人知晓(2026-09-13 审查假设#7)。
695
755
  engines_dropped: list[str] = []
756
+ # 熔断器过滤:自动路由模式下跳过正处于熔断冷却期的引擎
757
+ if is_auto_routed and _get_circuit_breaker is not None:
758
+ try:
759
+ _breaker = _get_circuit_breaker()
760
+ active_engines: list[str] = []
761
+ for e in engines:
762
+ allowed, reason = _breaker.allow(e)
763
+ if allowed:
764
+ active_engines.append(e)
765
+ else:
766
+ engines_dropped.append(f"{e}({reason})")
767
+ if active_engines:
768
+ engines = active_engines
769
+ except Exception as e:
770
+ logger.debug(f"熔断器过滤跳过: {e}")
771
+
696
772
  if mode in ("fast", "budget"):
697
773
  try:
698
774
  available = set(get_available_engines(registry=reg, engine_names=engines))
699
- engines_dropped = [e for e in engines if e not in available]
775
+ engines_dropped.extend(e for e in engines if e not in available)
700
776
  engines = [e for e in engines if e in available]
701
777
  except Exception as e:
702
778
  logger.warning(f"可用性检查失败: {e}")
@@ -817,8 +893,16 @@ def search_engines(
817
893
  _t, name, holder = entry
818
894
  _n, res, err = holder.get("r", (name, [], f"{name}: 线程结束但没有返回值"))
819
895
  _collect(_n, res)
896
+ _cb = _get_circuit_breaker() if _get_circuit_breaker is not None else None
820
897
  if err:
821
898
  errors.append(err)
899
+ if _cb is not None:
900
+ err_low = err.lower()
901
+ kind = "timeout" if "timeout" in err_low else ("blocked" if ("captcha" in err_low or "429" in err_low) else "error")
902
+ _cb.record_failure(_n, kind=kind)
903
+ elif res:
904
+ if _cb is not None:
905
+ _cb.record_success(_n)
822
906
 
823
907
  try:
824
908
  enough_at: float | None = None
@@ -935,6 +1019,8 @@ def search_engines(
935
1019
  else:
936
1020
  all_results.sort(key=lambda x: x.get("score", 0), reverse=True)
937
1021
  elapsed = int((time.time() - t0_all) * 1000)
1022
+ # 截断前去重:重复条目挤占 n*len(engines) 配额时,有效结果会被顶掉
1023
+ all_results = _dedup_near_duplicates(all_results)
938
1024
  final_results = all_results[: n * len(engines)] if engines else all_results[:n]
939
1025
 
940
1026
  payload = {
@@ -60,7 +60,7 @@ _RE_LOCATION = re.compile(
60
60
  # 分类 → 默认引擎优先级映射
61
61
  CATEGORY_PRIORITY = {
62
62
  "academic": ["local_arxiv", "local_semantic_scholar", "local_crossref", "local_pubmed"],
63
- "code": ["local_github", "local_stackoverflow", "local_gitlab", "local_npm"],
63
+ "code": ["local_github", "local_stackoverflow", "local_gitlab", "local_npm", "local_hackernews"],
64
64
  "news": ["local_bing_news", "local_google_news", "local_duckduckgo_news"],
65
65
  # chinese 与主路径 route_combo._select_sub_engines 中文支对齐(2026-10-06 实测):
66
66
  # baidu 直连 0 结果移出;sogou(~1s 相关)/360(~1s)实测可用;yandex 殿后。
@@ -30,14 +30,15 @@ description: 本机文件与代码内容搜索(rg/fd/mdfind/grep 统一入口
30
30
  # 以下以 argo 安装根为 cwd;或写死 $ARGO_HOME/sub-skills/local-seek/scripts/seek.py
31
31
  python3 sub-skills/local-seek/scripts/seek.py "查询词" # 默认:当前目录全文
32
32
  python3 sub-skills/local-seek/scripts/seek.py "查询词" --path ~/notes # 指定目录
33
- python3 sub-skills/local-seek/scripts/seek.py "词" --path ~/.agents --dot # 连 . 开头目录与软链一起搜;搜 ~/.agents、~/.zcode 要加(Spotlight 收不到)
34
- python3 sub-skills/local-seek/scripts/seek.py "词" --path . --include-noise # repos/、tests/ 等与真源平权(默认排真源之后,仍搜得到)
35
- python3 sub-skills/local-seek/scripts/seek.py "查询词" --count # 先数命中,再决定是否深入
33
+ python3 sub-skills/local-seek/scripts/seek.py "词" --path ~/.agents --dot # 连 . 开头目录与软链一起搜
34
+ python3 sub-skills/local-seek/scripts/seek.py "词" --path . --include-noise # 噪声目录与真源平权
35
+ python3 sub-skills/local-seek/scripts/seek.py "查询词" --count # 先数命中数
36
36
  python3 sub-skills/local-seek/scripts/seek.py "查询词" --filename # 按文件名
37
- python3 sub-skills/local-seek/scripts/seek.py "查询词" --spotlight # 全盘兜底(PDF/邮件/笔记)
37
+ python3 sub-skills/local-seek/scripts/seek.py "查询词" --spotlight # 全盘兜底
38
38
  python3 sub-skills/local-seek/scripts/seek.py "查询词" --type py,ts
39
39
  python3 sub-skills/local-seek/scripts/seek.py "查询词" --json # 结构化输出
40
- python3 sub-skills/local-seek/scripts/seek.py "查询词" --exact # 关闭中文扩展,精确匹配
40
+ python3 sub-skills/local-seek/scripts/seek.py "查询词" --exact # 精确匹配(关扩展)
41
+ python3 sub-skills/local-seek/scripts/seek.py "符号名" --symbol # 精确符号/词边界匹配
41
42
  python3 sub-skills/local-seek/scripts/seek.py "查询词" --exclude 某文件 # 额外排除(可重复)
42
43
  python3 sub-skills/local-seek/scripts/seek.py --outline 文件路径 # 文件结构(def/class/标题/顶层key)
43
44
  python3 sub-skills/local-seek/scripts/seek.py --lines 10-50 文件路径 # 按行读取,替代 read_file 全文
@@ -55,7 +55,7 @@ CASES = [
55
55
  {"name": "文件级-cache键域隔离", "argv": ["cache_key_vdom", "--path", ARGO_ROOT],
56
56
  "expect": ["scripts/cache_key_vdom.py"], "topk": 5},
57
57
  {"name": "文件级-hash_token实现", "argv": ["def _hash_token", "--path", ARGO_ROOT],
58
- "expect": ["scripts/cache.py"], "topk": 5},
58
+ "expect": ["scripts/cache.py", "scripts/cache_similarity.py"], "topk": 5},
59
59
  # 守卫用例(topk=8):行级语义下文档密集行同样合法,只守「实现文件仍在
60
60
  # top-8 内可被看见」,防实现被彻底挤出视野的回归
61
61
  {"name": "守卫-语义缓存minhash", "argv": ["语义缓存 minhash 软命中", "--path", ARGO_ROOT],