argo-search 2.14.1 → 2.16.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 (245) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +57 -813
  3. package/README.ja.md +56 -814
  4. package/README.ko.md +56 -812
  5. package/README.md +160 -754
  6. package/README.zh.md +152 -872
  7. package/SKILL.md +22 -23
  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 +149 -6
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +139 -30
  14. package/backends/quota_profiles.json +83 -3
  15. package/bin/argo +33 -17
  16. package/config.yaml +189 -33
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +38 -0
  20. package/docs/ENGINE_CATALOG.md +102 -89
  21. package/docs/MCP_SETUP.md +10 -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/RELEASE_NOTES_v2.16.0.md +58 -0
  25. package/docs/RELEASING.md +1 -1
  26. package/engines/specs/ai_labs.yaml +89 -0
  27. package/engines/specs/archive_org.yaml +1 -1
  28. package/engines/specs/bilibili_hot.yaml +11 -1
  29. package/engines/specs/brave.yaml +3 -3
  30. package/engines/specs/carbon_intensity.yaml +1 -1
  31. package/engines/specs/cisa_alerts.yaml +40 -0
  32. package/engines/specs/cn_ai_news.yaml +10 -8
  33. package/engines/specs/crates.yaml +1 -1
  34. package/engines/specs/crossref.yaml +4 -2
  35. package/engines/specs/crt_sh.yaml +1 -1
  36. package/engines/specs/dblp.yaml +1 -1
  37. package/engines/specs/devto.yaml +1 -1
  38. package/engines/specs/digup.yaml +11 -6
  39. package/engines/specs/docker_hub.yaml +1 -1
  40. package/engines/specs/douyin_hot.yaml +11 -1
  41. package/engines/specs/dw_news.yaml +4 -2
  42. package/engines/specs/eng_blogs.yaml +63 -0
  43. package/engines/specs/europeana.yaml +3 -4
  44. package/engines/specs/europepmc.yaml +1 -1
  45. package/engines/specs/felo.yaml +3 -3
  46. package/engines/specs/firecrawl.yaml +3 -0
  47. package/engines/specs/fourget.yaml +5 -2
  48. package/engines/specs/france24.yaml +6 -4
  49. package/engines/specs/fxtwitter.yaml +30 -7
  50. package/engines/specs/gbfs_nyc.yaml +1 -1
  51. package/engines/specs/gleif.yaml +1 -1
  52. package/engines/specs/gov_regulations.yaml +1 -1
  53. package/engines/specs/grepapp_mcp.yaml +62 -0
  54. package/engines/specs/guardian_rss.yaml +6 -4
  55. package/engines/specs/hf_datasets.yaml +1 -1
  56. package/engines/specs/huggingface.yaml +1 -1
  57. package/engines/specs/itotii.yaml +13 -1
  58. package/engines/specs/keenable.yaml +7 -1
  59. package/engines/specs/linux_do.yaml +63 -0
  60. package/engines/specs/lobsters.yaml +41 -0
  61. package/engines/specs/local_crossref.yaml +3 -1
  62. package/engines/specs/local_github.yaml +1 -1
  63. package/engines/specs/local_npm.yaml +6 -0
  64. package/engines/specs/local_openstreetmap.yaml +1 -1
  65. package/engines/specs/local_seek.yaml +6 -0
  66. package/engines/specs/maven.yaml +1 -1
  67. package/engines/specs/mdn.yaml +1 -1
  68. package/engines/specs/musicbrainz.yaml +1 -1
  69. package/engines/specs/nasa_images.yaml +1 -1
  70. package/engines/specs/nhtsa_vpic.yaml +6 -3
  71. package/engines/specs/npm.yaml +1 -1
  72. package/engines/specs/nuget.yaml +1 -1
  73. package/engines/specs/nvd.yaml +1 -1
  74. package/engines/specs/open_meteo.yaml +1 -1
  75. package/engines/specs/openalex.yaml +4 -2
  76. package/engines/specs/openreview.yaml +1 -1
  77. package/engines/specs/polymarket.yaml +1 -1
  78. package/engines/specs/redskill.yaml +2 -0
  79. package/engines/specs/searxng.yaml +4 -2
  80. package/engines/specs/sec_edgar.yaml +9 -4
  81. package/engines/specs/steam.yaml +1 -1
  82. package/engines/specs/tinyfish.yaml +2 -0
  83. package/engines/specs/tinyfish_news.yaml +2 -0
  84. package/engines/specs/tinyfish_paper.yaml +2 -0
  85. package/engines/specs/toutiao_hot.yaml +11 -1
  86. package/engines/specs/train.yaml +3 -0
  87. package/engines/specs/twitter.yaml +4 -0
  88. package/engines/specs/unpaywall.yaml +6 -0
  89. package/engines/specs/vam.yaml +17 -3
  90. package/engines/specs/weibo_hot.yaml +11 -1
  91. package/engines/specs/wikidata.yaml +1 -1
  92. package/engines/specs/wikipedia.yaml +1 -1
  93. package/engines/specs/wolframalpha.yaml +3 -3
  94. package/engines/specs/xiaohongshu.yaml +2 -0
  95. package/engines/specs/zhihu.yaml +3 -18
  96. package/engines/specs/zhihu_hot_app.yaml +1 -1
  97. package/engines/specs/zhihu_kb.yaml +18 -0
  98. package/engines/specs/zhihu_questions.yaml +19 -0
  99. package/package.json +4 -2
  100. package/packages/dsh-plugin/README.md +9 -14
  101. package/packages/dsh-plugin/dsh/client.js +481 -1037
  102. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  103. package/packages/dsh-plugin/dsh/index.js +6 -0
  104. package/packages/dsh-plugin/dsh/runner.js +3 -1
  105. package/packages/dsh-plugin/dsh/workbench-client.js +796 -0
  106. package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
  107. package/packages/dsh-plugin/dsh/workbench-suggestions.js +148 -0
  108. package/packages/dsh-plugin/dsh/workbench.js +966 -0
  109. package/packages/dsh-plugin/icon.svg +23 -0
  110. package/packages/dsh-plugin/package.json +10 -3
  111. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  112. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  113. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  114. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  115. package/packages/dsh-plugin/test/workbench.test.js +92 -0
  116. package/scripts/adaptive.py +7 -1
  117. package/scripts/archive_run.py +112 -53
  118. package/scripts/argo_paths.py +42 -5
  119. package/scripts/badcase_ledger.py +117 -9
  120. package/scripts/build_concept_table.py +112 -55
  121. package/scripts/cache.py +6 -2
  122. package/scripts/caliber_isolation.py +60 -23
  123. package/scripts/circuit_breaker.py +72 -11
  124. package/scripts/cli_io.py +20 -2
  125. package/scripts/config_cache.py +44 -1
  126. package/scripts/daemon.py +151 -51
  127. package/scripts/dormant_ledger.py +23 -9
  128. package/scripts/engine_dispatch.py +8 -5
  129. package/scripts/engine_env.py +191 -1
  130. package/scripts/engine_families.py +50 -7
  131. package/scripts/engine_states.py +3 -50
  132. package/scripts/engine_validate.py +13 -45
  133. package/scripts/engines.py +15 -31
  134. package/scripts/engines_base.py +66 -61
  135. package/scripts/engines_builders.py +0 -15
  136. package/scripts/engines_builders_archive.py +4 -3
  137. package/scripts/engines_builders_batch10.py +346 -100
  138. package/scripts/engines_builders_batch11.py +4 -76
  139. package/scripts/engines_builders_batch13.py +4 -3
  140. package/scripts/engines_builders_batch14.py +2 -1
  141. package/scripts/engines_builders_batch15.py +2 -1
  142. package/scripts/engines_builders_batch9.py +16 -25
  143. package/scripts/engines_builders_cn.py +7 -201
  144. package/scripts/engines_builders_data.py +12 -11
  145. package/scripts/engines_builders_data_macro.py +5 -4
  146. package/scripts/engines_builders_dsh.py +2 -1
  147. package/scripts/engines_builders_feeds.py +76 -11
  148. package/scripts/engines_builders_finance.py +2 -1
  149. package/scripts/engines_builders_intl.py +18 -117
  150. package/scripts/engines_builders_media.py +59 -12
  151. package/scripts/engines_builders_pixiv.py +2 -16
  152. package/scripts/engines_builders_science.py +8 -7
  153. package/scripts/engines_builders_search.py +7 -14
  154. package/scripts/engines_builders_skill.py +2 -1
  155. package/scripts/engines_builders_tech.py +8 -17
  156. package/scripts/engines_builders_weather.py +241 -0
  157. package/scripts/engines_fields.py +91 -0
  158. package/scripts/engines_http.py +184 -0
  159. package/scripts/engines_mcp.py +405 -0
  160. package/scripts/engines_parsers.py +13 -369
  161. package/scripts/engines_schema_drift.py +260 -0
  162. package/scripts/evidence.py +13 -0
  163. package/scripts/evidence_loop.py +19 -4
  164. package/scripts/extend_route_labels.py +6 -0
  165. package/scripts/fetch_jina.py +98 -0
  166. package/scripts/fetch_jsrun.py +15 -11
  167. package/scripts/fetch_v3.py +79 -120
  168. package/scripts/fulltext_store.py +42 -1
  169. package/scripts/fxtwitter_api.py +8 -7
  170. package/scripts/gen_engine_catalog.py +2 -2
  171. package/scripts/general_pool.py +15 -4
  172. package/scripts/health_check.py +1 -1
  173. package/scripts/image_vision/vision_probe +0 -0
  174. package/scripts/install.sh +2 -0
  175. package/scripts/link_source.py +65 -24
  176. package/scripts/local_seek_adapter.py +57 -17
  177. package/scripts/matrix_search_eval.py +8 -10
  178. package/scripts/mcp_handlers.py +53 -31
  179. package/scripts/mcp_handlers_surface.py +6 -18
  180. package/scripts/mcp_transport.py +10 -5
  181. package/scripts/min_version_scan.py +7 -3
  182. package/scripts/network_aware.py +7 -13
  183. package/scripts/numeric_verify.py +3 -2
  184. package/scripts/output_transparency.py +3 -0
  185. package/scripts/pre-commit +45 -43
  186. package/scripts/query_understanding.py +30 -6
  187. package/scripts/quota.py +36 -30
  188. package/scripts/rank_signals.py +9 -0
  189. package/scripts/recompute.py +15 -5
  190. package/scripts/recovery.py +38 -29
  191. package/scripts/recovery_runner.py +29 -10
  192. package/scripts/redskill/redskill_engine.py +2 -1
  193. package/scripts/release.py +14 -26
  194. package/scripts/release_check.py +5 -25
  195. package/scripts/replay_eval.py +2 -2
  196. package/scripts/research_cli.py +40 -0
  197. package/scripts/research_notes.py +368 -0
  198. package/scripts/route.py +40 -70
  199. package/scripts/route_audit.py +259 -0
  200. package/scripts/route_combo.py +21 -6
  201. package/scripts/route_domains.py +150 -23
  202. package/scripts/route_lang.py +20 -7
  203. package/scripts/route_log.py +26 -9
  204. package/scripts/route_policy.py +85 -6
  205. package/scripts/route_telemetry_export.py +199 -0
  206. package/scripts/rrf_classic.py +5 -22
  207. package/scripts/search.py +2 -1
  208. package/scripts/search_attribution.py +53 -10
  209. package/scripts/search_entry.py +32 -1
  210. package/scripts/search_output.py +23 -11
  211. package/scripts/search_pipeline.py +15 -3
  212. package/scripts/search_rank.py +21 -11
  213. package/scripts/semantic_evidence.py +394 -178
  214. package/scripts/serp_guard.py +13 -1
  215. package/scripts/settings_page.py +4 -3
  216. package/scripts/single_flight.py +1 -1
  217. package/scripts/social_engines/hackernews_engine.py +2 -1
  218. package/scripts/social_engines/reddit_engine.py +2 -1
  219. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  220. package/scripts/social_engines/zhihu_engine.py +252 -43
  221. package/scripts/sogou_weixin_browser.py +5 -6
  222. package/scripts/source_audit.py +44 -9
  223. package/scripts/source_ledger.py +2 -15
  224. package/scripts/source_selection.py +45 -20
  225. package/scripts/straggler_policy.py +1 -2
  226. package/scripts/sync_backends.py +17 -0
  227. package/scripts/tfidf_router.py +23 -11
  228. package/scripts/time_utils.py +54 -1
  229. package/scripts/train.py +68 -2
  230. package/scripts/usage_log.py +50 -10
  231. package/scripts/watch.py +3 -3
  232. package/scripts/zhihu_quota.py +2 -1
  233. package/sub-skills/argo-wide-research/SKILL.md +70 -0
  234. package/sub-skills/ego-search/{SKILL.md → README.md} +15 -47
  235. package/sub-skills/ego-search/scripts/ego_search.py +13 -4
  236. package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
  237. package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
  238. package/sub-skills/local-search/engine_registry.py +32 -7
  239. package/sub-skills/local-seek/SKILL.md +20 -22
  240. package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
  241. package/scripts/caliber_dedupe.py +0 -66
  242. package/scripts/engines_builders_batch16.py +0 -13
  243. package/scripts/health_probe.py +0 -253
  244. package/scripts/social_engines/twitter_engine.py +0 -514
  245. package/scripts/sync_installs.py +0 -29
@@ -11,18 +11,15 @@
11
11
  from __future__ import annotations
12
12
 
13
13
  import os
14
+ import random
14
15
  from typing import Any
15
16
 
16
17
 
17
18
  def _env_int(name: str, default: int, minimum: int = 1) -> int:
18
19
  """读整型环境变量,任何异常都退回 default。
19
20
 
20
- 为什么必须有:这一行原本裸写 `int(os.environ.get(...))`,于是
21
- `ARGO_ROUTE_SAMPLE_RATE=abc` 在**模块导入期**抛 ValueError,经
22
- route.py 的导入链直接把整个 `argo search` 打挂——与本模块 docstring
23
- 写的「必须永远 fail-open,使用日志写失败绝不能让一次搜索失败」正好相反,
24
- 而且触发它的只是一个拼错的采样率。mcp_handlers 早有同名 _env_int,
25
- 两处各写各的才是这个 bug 的成因。
21
+ 调用期按需解析(不在模块导入期读 os.environ),避免导入链失败或测试改写
22
+ 环境变量后仍沿用旧采样率。
26
23
  """
27
24
  try:
28
25
  return max(minimum, int(str(os.environ.get(name, "")).strip() or default))
@@ -30,18 +27,37 @@ def _env_int(name: str, default: int, minimum: int = 1) -> int:
30
27
  return default
31
28
 
32
29
 
33
- _ROUTE_SAMPLE_RATE = _env_int("ARGO_ROUTE_SAMPLE_RATE", 20)
30
+ _DEFAULT_ROUTE_SAMPLE_RATE = 20
31
+ # 模块级覆盖槽:仅测试用 monkeypatch 注入确定采样率(=1 时每调必落)。
32
+ # 运行期**不做 env→本值的缓存**:一旦缓存,「先设 env 再删」的进程会在后续调用
33
+ # 静默退回缓存值(实测 1 → 20),与「运行期生效」的意图相反。
34
+ _ROUTE_SAMPLE_RATE = _DEFAULT_ROUTE_SAMPLE_RATE
34
35
  _route_sample_counter = 0
35
36
 
36
37
 
38
+ def _resolve_rate() -> int:
39
+ """采样率:显式覆盖槽优先(测试注入),否则每次调用现读 env。"""
40
+ if _ROUTE_SAMPLE_RATE != _DEFAULT_ROUTE_SAMPLE_RATE:
41
+ return _ROUTE_SAMPLE_RATE
42
+ return _env_int("ARGO_ROUTE_SAMPLE_RATE", _DEFAULT_ROUTE_SAMPLE_RATE)
43
+
44
+
37
45
  def sample_route(done: dict[str, Any], kw: dict[str, Any]) -> None:
38
46
  """按采样率把路由决策落一条使用日志记录。"""
39
47
  global _route_sample_counter
40
48
  if "features" not in kw or not kw.get("features"):
41
49
  return # engine_override 直通等无语义分支不采样
50
+ rate = max(1, int(_resolve_rate()))
42
51
  _route_sample_counter += 1
43
- if _route_sample_counter % _ROUTE_SAMPLE_RATE != 0:
44
- return
52
+ if rate > 1:
53
+ # 单次 CLI 进程只有第 1 次调用:若只看 `_route_sample_counter % rate == 0`,
54
+ # 每次退出后计数器归零导致 CLI 路径零采样;首次调用用无状态随机采样,
55
+ # 长驻进程(daemon/MCP)第 2 次起继续按固定步长采样。
56
+ should_emit = (random.randrange(rate) == 0
57
+ if _route_sample_counter == 1
58
+ else (_route_sample_counter % rate == 0))
59
+ if not should_emit:
60
+ return
45
61
  f = kw.get("features") or {}
46
62
  try:
47
63
  from usage_log import emit
@@ -53,6 +69,7 @@ def sample_route(done: dict[str, Any], kw: dict[str, Any]) -> None:
53
69
  "mode": kw.get("mode"),
54
70
  "lang_override": f.get("lang_override"),
55
71
  "primary_lang": f.get("primary_lang"),
72
+ "effective_lang": f.get("effective_lang"),
56
73
  "script": f.get("script"),
57
74
  "has_compare": f.get("has_compare"),
58
75
  "has_technical": f.get("has_technical"),
@@ -69,6 +69,10 @@ _VERTICAL_NEW_SOURCE: dict[str, tuple[str, ...]] = {
69
69
  # 2026-11-11:maven/nuget 补 Java/JVM 与 .NET 两个生态的关键词发现,
70
70
  # 声明在 crates 之后(位次 4/5)。本域基础预算 3,两源需加槽通电。
71
71
  "package_search": ("maven", "nuget"),
72
+ # 2026-11-11:cisa_alerts 声明在 crt_sh 之后(位次 4),加槽扩容,不挤掉 crt_sh
73
+ "security_search": ("cisa_alerts",),
74
+ # 2026-11-11:eng_blogs 顶尖架构博客聚合加槽
75
+ "english_tech": ("eng_blogs",),
72
76
  }
73
77
 
74
78
 
@@ -252,9 +256,10 @@ def _apply_policy_with_new_source_slots(
252
256
  live = [e for e in _VERTICAL_NEW_SOURCE.get((domain or {}).get("name"), ())
253
257
  if e in declared and (enabled is None or e in enabled)]
254
258
  keep = list(must_keep or [])
255
- for e in live:
256
- if e not in engines_combo and e not in keep:
257
- keep.append(e)
259
+ if (mode or "auto") not in ("fast", "budget"):
260
+ for e in live:
261
+ if e not in keep:
262
+ keep.append(e)
258
263
  return _apply_engine_policy(
259
264
  engines_combo, mode=mode, depth=depth, context=context,
260
265
  engines_boost=engines_boost, enabled=enabled,
@@ -262,7 +267,81 @@ def _apply_policy_with_new_source_slots(
262
267
  budget_extra=_new_source_budget_extra(
263
268
  domain, declared or engines_combo, enabled or set(),
264
269
  mode=mode, depth=depth, context=context,
265
- # 传当前 combo:新源还在里面但被重排推出窗口时,额度要按它在
266
- # 当前 combo 的位次算(只在声明位次上算会得到 0,见该函数说明)
267
- live_combo=engines_combo),
270
+ # 传当前 combo:新源还在里面但被重排推出窗口时,额度要按它在
271
+ # 当前 combo 的位次算(只在声明位次上算会得到 0,见该函数说明)
272
+ live_combo=engines_combo),
268
273
  )
274
+
275
+
276
+ def is_pure_combo_domain(domain: dict[str, Any] | None) -> bool:
277
+ """域是否声明 pure_combo(保持纯结构化路径,不混入通用/地理/次域源)。"""
278
+ d = domain or {}
279
+ return bool(d.get("pure_combo")) or d.get("name") == "modal_card"
280
+
281
+
282
+ def apply_domain_combo_rules(
283
+ domain: dict[str, Any],
284
+ engines_combo: list[str],
285
+ query: str,
286
+ enabled: set[str],
287
+ specs: dict[str, Any],
288
+ ) -> list[str]:
289
+ """应用声明式域策略(zh_filter_en_only / 宏观区域前置),减轻 route.py 负担。"""
290
+ zh_filter = bool(domain.get("zh_filter_en_only")) or (
291
+ domain.get("name") in ("tech_deep", "academic")
292
+ )
293
+ if zh_filter and any("\u4e00" <= ch <= "\u9fff" for ch in query):
294
+ from engine_families import engine_langs
295
+ engines_combo = [
296
+ e for e in engines_combo
297
+ if engine_langs(e, specs.get(e)) != {"en"}
298
+ ]
299
+ if not engines_combo:
300
+ engines_combo = [e for e in ["arxiv", "anysearch", "local_search"] if e in enabled]
301
+
302
+ if domain.get("name") == "macro_data":
303
+ from macro_countries import is_foreign_macro_query
304
+ if is_foreign_macro_query(query) and "worldbank" in engines_combo:
305
+ engines_combo = ["worldbank"] + [e for e in engines_combo if e != "worldbank"]
306
+ if "nbs_stats" in engines_combo and ("中国" in query or "china" in query.lower()):
307
+ engines_combo = ["nbs_stats"] + [e for e in engines_combo if e != "nbs_stats"]
308
+ return engines_combo
309
+
310
+
311
+ def resolve_pure_combo_fallback(domain: dict[str, Any]) -> list[str]:
312
+ """pure_combo 域(如 modal_card)缺可用引擎时保留声明组合,避免误入通用兜底。"""
313
+ declared = list(domain.get("engines_combo") or [])
314
+ if not declared and domain.get("primary"):
315
+ declared = [domain["primary"]]
316
+ try:
317
+ from engine_env import is_engine_allowed_by_env
318
+ return [e for e in declared if is_engine_allowed_by_env(e)] or declared
319
+ except ImportError:
320
+ return declared
321
+
322
+
323
+ def build_domain_must_keep(
324
+ domain: dict[str, Any],
325
+ features: dict[str, Any] | None,
326
+ enabled: set[str],
327
+ pure_combo: bool,
328
+ is_dead_fn,
329
+ ) -> list[str]:
330
+ """组装域级保底列表(地理特征 + 垂直域主源 + modal_card/geo_places 专属项)。"""
331
+ must_keep: list[str] = []
332
+ if (features or {}).get("has_geo") and "local_openstreetmap" in enabled and not pure_combo:
333
+ must_keep.append("local_openstreetmap")
334
+ if domain.get("name") in _VERTICAL_KEEP:
335
+ p = domain.get("primary")
336
+ if p and p not in must_keep and (p in enabled or pure_combo) and not is_dead_fn(p):
337
+ must_keep.append(p)
338
+ if domain.get("name") == "modal_card":
339
+ for e in domain.get("engines_combo") or []:
340
+ if e not in must_keep and (e in enabled or pure_combo):
341
+ must_keep.append(e)
342
+ elif p and p in enabled and p not in must_keep and not is_dead_fn(p):
343
+ must_keep.append(p)
344
+ if domain.get("name") == "geo_places" and "local_openstreetmap" in enabled:
345
+ if "local_openstreetmap" not in must_keep:
346
+ must_keep.append("local_openstreetmap")
347
+ return must_keep
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """route_telemetry_export.py — 本地路由遥测脱敏导出飞轮(零原文/零隐私泄露)。
3
+
4
+ 只从本机状态目录读取 `usage_log/route.jsonl`、`usage_log/query.jsonl` 与
5
+ `adaptive.db`,输出严格聚合的脱敏指标,用于离线诊断与回归设计,严禁包含:
6
+ - 原始查询文本(query / final_query)
7
+ - 本机绝对路径、用户名或环境变量值
8
+ - URL 凭据与特定实体标识
9
+
10
+ 用法:
11
+ python3 scripts/route_telemetry_export.py
12
+ python3 scripts/route_telemetry_export.py --out tmp/telemetry_summary.json --min-samples 5
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import collections
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import sqlite3
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ SCRIPTS = Path(__file__).resolve().parent
28
+ if str(SCRIPTS) not in sys.path:
29
+ sys.path.insert(0, str(SCRIPTS))
30
+
31
+ import argo_paths as _paths
32
+
33
+
34
+ def _iter_jsonl(path: Path) -> list[dict[str, Any]]:
35
+ if not path.is_file():
36
+ return []
37
+ rows: list[dict[str, Any]] = []
38
+ try:
39
+ for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
40
+ line = line.strip()
41
+ if not line:
42
+ continue
43
+ try:
44
+ obj = json.loads(line)
45
+ if isinstance(obj, dict):
46
+ rows.append(obj)
47
+ except json.JSONDecodeError:
48
+ continue
49
+ except OSError:
50
+ return []
51
+ return rows
52
+
53
+
54
+ def _adaptive_summary(db_path: Path, min_samples: int = 5) -> dict[str, Any]:
55
+ """统计 adaptive.db 的空语言行占比与高空结果场景桶(无敏感文本)。"""
56
+ out = {
57
+ "total_rows": 0,
58
+ "empty_lang_rows": 0,
59
+ "high_empty_buckets": [],
60
+ }
61
+ if not db_path.is_file():
62
+ return out
63
+ conn: sqlite3.Connection | None = None
64
+ try:
65
+ conn = sqlite3.connect(str(db_path))
66
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(engine_perf)").fetchall()}
67
+ if not cols:
68
+ return out
69
+ has_lang = "lang" in cols
70
+ has_domain = "domain" in cols
71
+ has_empty = "empty" in cols
72
+ total = conn.execute("SELECT COUNT(*) FROM engine_perf").fetchone()[0]
73
+ out["total_rows"] = int(total or 0)
74
+ if has_lang:
75
+ empty_lang = conn.execute(
76
+ "SELECT COUNT(*) FROM engine_perf WHERE lang = '' OR lang IS NULL"
77
+ ).fetchone()[0]
78
+ out["empty_lang_rows"] = int(empty_lang or 0)
79
+ if has_domain and has_lang and has_empty:
80
+ rows = conn.execute(
81
+ "SELECT engine, domain, lang, COUNT(*) AS n, SUM(empty) AS emp "
82
+ "FROM engine_perf "
83
+ "GROUP BY engine, domain, lang "
84
+ "HAVING n >= ? "
85
+ "ORDER BY CAST(emp AS REAL) / n DESC, n DESC "
86
+ "LIMIT 20",
87
+ (max(1, int(min_samples)),),
88
+ ).fetchall()
89
+ alerts = []
90
+ for eng, dom, lang, n, emp in rows:
91
+ emp_i = int(emp or 0)
92
+ rate = round(emp_i / max(n, 1), 3)
93
+ if rate >= 0.5:
94
+ alerts.append({
95
+ "engine": str(eng),
96
+ "domain": str(dom or "(none)"),
97
+ "effective_lang": str(lang or "(empty)"),
98
+ "samples": int(n),
99
+ "empty_count": emp_i,
100
+ "empty_rate": rate,
101
+ })
102
+ out["high_empty_buckets"] = alerts
103
+ except sqlite3.Error:
104
+ return out
105
+ finally:
106
+ if conn is not None:
107
+ conn.close()
108
+ return out
109
+
110
+
111
+ def export_anonymized_telemetry(
112
+ state_dir: Path | str | None = None,
113
+ *,
114
+ min_samples: int = 5,
115
+ ) -> dict[str, Any]:
116
+ """导出严格脱敏的路由健康度与分桶统计报告(不含任何 query 或本机路径)。"""
117
+ root = Path(state_dir) if state_dir else _paths.state_root()
118
+ usage_override = os.environ.get("ARGO_USAGE_LOG_DIR", "").strip()
119
+ log_dir = Path(os.path.expanduser(usage_override)) if (usage_override and not state_dir) else (root / "usage_log")
120
+
121
+ route_rows = _iter_jsonl(log_dir / "route.jsonl")
122
+ query_rows = _iter_jsonl(log_dir / "query.jsonl")
123
+
124
+ lang_counts: collections.Counter[str] = collections.Counter()
125
+ domain_counts: collections.Counter[str] = collections.Counter()
126
+ intent_counts: collections.Counter[str] = collections.Counter()
127
+ skeleton_counts: collections.Counter[tuple[str, str, tuple[str, ...], str]] = collections.Counter()
128
+ fallback_count = 0
129
+
130
+ for row in route_rows:
131
+ dom = str(row.get("domain") or "general_search")
132
+ if dom in ("general_search", "fallback", ""):
133
+ fallback_count += 1
134
+ eff_lang = str(row.get("effective_lang") or row.get("lang_override") or row.get("primary_lang") or "unknown")
135
+ intents = tuple(sorted(str(x) for x in (row.get("intents") or []) if x))
136
+ eng = str(row.get("engine") or "unknown")
137
+ lang_counts[eff_lang] += 1
138
+ domain_counts[dom] += 1
139
+ for it in intents:
140
+ intent_counts[it] += 1
141
+ skeleton_counts[(dom, eff_lang, intents, eng)] += 1
142
+
143
+ total_route = len(route_rows)
144
+ zero_count_queries = sum(1 for r in query_rows if int(r.get("count") or 0) == 0)
145
+
146
+ skeletons = []
147
+ for (dom, lang, intents, eng), cnt in skeleton_counts.most_common(25):
148
+ sig_src = f"{dom}|{lang}|{','.join(intents)}|{eng}"
149
+ skel_id = hashlib.sha256(sig_src.encode("utf-8")).hexdigest()[:12]
150
+ skeletons.append({
151
+ "skeleton_id": skel_id,
152
+ "domain": dom,
153
+ "effective_lang": lang,
154
+ "intents": list(intents),
155
+ "engine": eng,
156
+ "count": cnt,
157
+ })
158
+
159
+ return {
160
+ "schema_version": 1,
161
+ "privacy_guarantee": "aggregated_no_raw_query_no_paths",
162
+ "summary": {
163
+ "route_events": total_route,
164
+ "query_events": len(query_rows),
165
+ "query_zero_result_rate": round(zero_count_queries / len(query_rows), 3) if query_rows else 0.0,
166
+ "route_fallback_rate": round(fallback_count / total_route, 3) if total_route else 0.0,
167
+ "adaptive": _adaptive_summary(root / "adaptive.db", min_samples=min_samples),
168
+ },
169
+ "lang_distribution": dict(lang_counts.most_common()),
170
+ "domain_distribution": dict(domain_counts.most_common(20)),
171
+ "intent_distribution": dict(intent_counts.most_common()),
172
+ "anonymized_fingerprints": skeletons,
173
+ }
174
+
175
+
176
+ def main() -> int:
177
+ parser = argparse.ArgumentParser(description="导出脱敏后的 Argo 路由遥测聚合报告")
178
+ parser.add_argument("--state-dir", default="", help="指定状态目录(默认自动发现)")
179
+ parser.add_argument("--min-samples", type=int, default=5, help="高空结果桶最小样本数")
180
+ parser.add_argument("--out", default="", help="可选输出 JSON 文件路径")
181
+ args = parser.parse_args()
182
+
183
+ payload = export_anonymized_telemetry(
184
+ args.state_dir or None,
185
+ min_samples=args.min_samples,
186
+ )
187
+ rendered = json.dumps(payload, ensure_ascii=False, indent=2)
188
+ if args.out:
189
+ out_path = Path(args.out)
190
+ out_path.parent.mkdir(parents=True, exist_ok=True)
191
+ out_path.write_text(rendered + "\n", encoding="utf-8")
192
+ print(f"已写入脱敏遥测摘要: {out_path}")
193
+ else:
194
+ print(rendered)
195
+ return 0
196
+
197
+
198
+ if __name__ == "__main__":
199
+ raise SystemExit(main())
@@ -10,6 +10,8 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Any
12
12
 
13
+ from caliber_isolation import _dedupe_key, _merge_evidence
14
+
13
15
 
14
16
  def rrf_classic(
15
17
  ranked_lists: list[list[dict[str, Any]]],
@@ -28,35 +30,16 @@ def rrf_classic(
28
30
  items: dict[str, dict[str, Any]] = {}
29
31
  for _li, results in enumerate(ranked_lists):
30
32
  for i, r in enumerate(results):
31
- key = (
32
- _canonical_url(r.get("url", ""))
33
- or (f"__title__:{r.get('title', '')}" if r.get("title") else "")
34
- or (f"__card__:{r.get('card_type', '')}" if r.get("card_type") else "")
35
- or f"__idx__:{_li}:{i}"
36
- )
33
+ key = _dedupe_key(r, _canonical_url, f"__idx__:{_li}:{i}")
37
34
  scores[key] = scores.get(key, 0.0) + 1.0 / (k + i + 1)
38
35
  eng = r.get("_engine") or r.get("source", "") or ""
39
36
  if key not in items:
40
37
  item = dict(r)
41
38
  item["_rrf_score"] = 0.0
42
- cons: list[str] = []
43
- if eng:
44
- cons.append(eng)
45
- item["consensus_engines"] = cons
39
+ item["consensus_engines"] = [eng] if eng else []
46
40
  items[key] = item
47
41
  else:
48
- cur = items[key]
49
- new_txt = f"{r.get('title', '')} {r.get('snippet', '')}"
50
- cur_txt = f"{cur.get('title', '')} {cur.get('snippet', '')}"
51
- if len(new_txt) > len(cur_txt):
52
- cur["title"] = r.get("title", cur.get("title"))
53
- cur["snippet"] = r.get("snippet", cur.get("snippet"))
54
- sources = {cur.get("source", ""), r.get("source", "")}
55
- cur["source"] = "/".join(s for s in sources if s)
56
- cons = list(cur.get("consensus_engines") or [])
57
- if eng and eng not in cons:
58
- cons.append(eng)
59
- cur["consensus_engines"] = cons
42
+ _merge_evidence(items[key], r, extra_eng=eng)
60
43
  ranked = sorted(scores.items(), key=lambda x: -x[1])
61
44
  out = []
62
45
  for key, _ in ranked:
package/scripts/search.py CHANGED
@@ -932,7 +932,8 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
932
932
  return _run_local_seek(q, max_n, search_dir, echo=not quiet)
933
933
 
934
934
  result = shape_response(_ShapeContext(
935
- query=query, kind=kind, tier=tier, envelope=envelope, decision=decision,
935
+ # envelope 与 result["query"](:823)同口径:候选交接包不收 site:/-词 操作符原串
936
+ query=original_query, kind=kind, tier=tier, envelope=envelope, decision=decision,
936
937
  extra_lim=extra_lim, cache=cache, include_domains=include_domains,
937
938
  exclude_domains=exclude_domains, include_local=include_local, n=n,
938
939
  run_local_seek=_local_seek_wrapper,
@@ -49,24 +49,31 @@ def usage_log_attribution(engine_latency: dict[str, Any] | None,
49
49
  top_n: int = DEFAULT_TOP_N,
50
50
  engine_outcomes: Iterable[dict[str, Any]] | None = None
51
51
  ) -> dict[str, Any]:
52
- """usage_log query 流的归因字段(慢源 Top-N + 各引擎交付条数 + 失败类别)。
52
+ """usage_log query 流的归因字段(慢源 Top-N + 各引擎交付条数 + 失败归类)。
53
53
 
54
54
  返回 dict 以便调用方 **展开进日志记录**,未来新增归因维度(如
55
55
  「等待预算被谁耗掉」「缓存未命中的原因分布」)时只扩这里,
56
56
  主管线那一行 `**usage_log_attribution(...)` 不动——归因是会长大的,
57
57
  写入点不该跟着长(主管线有模块大小门禁,见模块 docstring)。
58
58
 
59
- 失败类别只记「哪类」不记条数:errors 已经记了条数,两者互补。
59
+ 失败类别只记「哪类」不记条数,``engine_errors`` 补齐「哪家引擎因何失败」。
60
60
  """
61
+ outcomes = list(engine_outcomes) if engine_outcomes is not None else None
61
62
  out: dict[str, Any] = {
62
63
  "engine_latency_top": top_engine_latency(engine_latency, top_n),
63
64
  }
64
- counts = engine_result_counts(engine_outcomes)
65
+ counts = engine_result_counts(outcomes)
65
66
  if counts:
66
67
  out["engine_results"] = counts
67
- kinds = failure_kinds(engine_outcomes)
68
+ kinds = failure_kinds(outcomes)
68
69
  if kinds:
69
70
  out["failure_kinds"] = kinds
71
+ errs = engine_errors(outcomes)
72
+ if errs:
73
+ out["engine_errors"] = errs
74
+ statuses = engine_error_status(outcomes)
75
+ if statuses:
76
+ out["engine_error_status"] = statuses
70
77
  return out
71
78
 
72
79
 
@@ -166,6 +173,16 @@ def engine_result_counts(engine_outcomes: Iterable[dict[str, Any]] | None,
166
173
  return out
167
174
 
168
175
 
176
+ def _failure_rows(engine_outcomes: Iterable[dict[str, Any]] | None,
177
+ limit: int = 8) -> list[dict[str, Any]]:
178
+ try:
179
+ from output_transparency import build_failures
180
+ except ImportError: # pragma: no cover - 单文件分发时的降级
181
+ return []
182
+ return build_failures({"engine_outcomes": list(engine_outcomes or [])},
183
+ limit=limit)
184
+
185
+
169
186
  def failure_kinds(engine_outcomes: Iterable[dict[str, Any]] | None,
170
187
  limit: int = 6) -> list[str]:
171
188
  """本次调用的失败类别(去重、稳定排序),写进 usage_log 供长期归因。
@@ -174,15 +191,41 @@ def failure_kinds(engine_outcomes: Iterable[dict[str, Any]] | None,
174
191
  output_transparency.build_failures(与 agent 档 failures 同一口径),
175
192
  不在日志侧另写一份分类。
176
193
  """
177
- try:
178
- from output_transparency import build_failures
179
- except ImportError: # pragma: no cover - 单文件分发时的降级
180
- return []
181
- rows = build_failures({"engine_outcomes": list(engine_outcomes or [])},
182
- limit=limit)
194
+ rows = _failure_rows(engine_outcomes, limit=limit)
183
195
  return sorted({str(r.get("category") or "unknown") for r in rows})
184
196
 
185
197
 
198
+ def engine_errors(engine_outcomes: Iterable[dict[str, Any]] | None,
199
+ limit: int = 8) -> dict[str, str]:
200
+ """按引擎提取失败归因映射 ``{engine: "category: detail"}``,供坏例账本定责。"""
201
+ out: dict[str, str] = {}
202
+ for r in _failure_rows(engine_outcomes, limit=limit):
203
+ eng = str(r.get("engine") or "").strip()
204
+ if not eng or eng in out:
205
+ continue
206
+ cat = str(r.get("category") or "unknown").strip()
207
+ detail = str(r.get("detail") or "").strip()
208
+ out[eng] = f"{cat}: {detail[:80]}" if detail else cat
209
+ return out
210
+
211
+
212
+ def engine_error_status(engine_outcomes: Iterable[dict[str, Any]] | None,
213
+ limit: int = 8) -> dict[str, int]:
214
+ """按引擎提取原始 HTTP 状态码 ``{engine: status}``。
215
+
216
+ 403/404/429 这类数字此前只埋在 engine_errors 的自由文本里(要正则才能
217
+ 挖,404 甚至全链路零样本);outcome 透传 http_status 后这里即可结构化
218
+ 落账(2026-11-18 可观测性审计盲区修复)。
219
+ """
220
+ out: dict[str, int] = {}
221
+ for r in _failure_rows(engine_outcomes, limit=limit):
222
+ eng = str(r.get("engine") or "").strip()
223
+ st = r.get("http_status")
224
+ if eng and st is not None and eng not in out:
225
+ out[eng] = int(st)
226
+ return out
227
+
228
+
186
229
  def aggregate_slow_engines(rows: Iterable[dict[str, Any]],
187
230
  top_n: int = 5) -> list[dict[str, Any]]:
188
231
  """聚合多行日志的 engine_latency_top → 按累计耗时的慢源排行。
@@ -99,6 +99,32 @@ class _Prepared:
99
99
 
100
100
 
101
101
 
102
+ def _emit_cache_hit(query: str, payload: dict[str, Any]) -> None:
103
+ """命中写内部 cache_hit 流。不改 payload。
104
+
105
+ query 流只在 finalize 记非缓存搜索;命中在 execute_search 直接返回,
106
+ 那本账上看不到。这里补一条内部记录,响应 JSON 与 argo stats 的时延
107
+ 均值都不读它。emit 自身失败静默。不在这里 import engines:命中热路径
108
+ 的契约是不拖引擎构建栈,表外名由 usage_log 在注册表已加载时拒写。
109
+ """
110
+ q = query[:60] if isinstance(query, str) else ""
111
+ used = payload.get("engines_used")
112
+ record: dict[str, Any] = {
113
+ "query": q,
114
+ "elapsed_ms": payload.get("elapsed_ms"),
115
+ "count": payload.get("count"),
116
+ "engines_used": list(used)[:8] if isinstance(used, list) else [],
117
+ "domain": payload.get("domain"),
118
+ "mode": payload.get("mode"),
119
+ "depth": payload.get("depth"),
120
+ "cache_level": payload.get("cache_level"),
121
+ "cached": True,
122
+ }
123
+ if payload.get("semantic_hit"):
124
+ record["semantic_hit"] = True
125
+ _emit_usage("cache_hit", record)
126
+
127
+
102
128
  def prepare(query: str, decision: dict[str, Any], max_results: int,
103
129
  timeout: int, depth: str, cache: Any, skip_cache: bool,
104
130
  *, mode: str = "auto", since: str | None = None,
@@ -164,7 +190,11 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
164
190
  # 用归一化 ISO(7d 与等价绝对日期共享缓存;相对窗跨天自然过期不串旧数据)。
165
191
  # 仅当组合内含带时间能力引擎时隔离:无时间字段引擎忽略时间窗、结果相同,
166
192
  # 隔离只会降低命中率(7d/30d 查 octen/anysearch 命中同一缓存)。
167
- time_aware = any(_is_time_capable(e) for e in engines)
193
+ # 无时间窗时整段短路:`time_aware` 只被下面两行与后过滤读取,而两者
194
+ # 都以 since/until 非空为前提,此时无论如何取值都不影响结果。旧写法
195
+ # 无条件求值,让默认路径白付一次 307 份 spec 的全量解析。
196
+ time_aware = (bool(since_iso or until_iso)
197
+ and any(_is_time_capable(e) for e in engines))
168
198
  if since_iso and time_aware:
169
199
  cache_engine_key += f"|since={since_iso}"
170
200
  if until_iso and time_aware:
@@ -250,6 +280,7 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
250
280
  on_progress(Stage.DONE, {"count": len(hit_results),
251
281
  "elapsed_ms": cache_elapsed,
252
282
  "cached": True})
283
+ _emit_cache_hit(query, _hit)
253
284
  return _Prepared(cached=_hit)
254
285
 
255
286
  # 缓存未命中才拉起查询理解、词形规范化与网络感知超时(缓存命中热路径零开销)