argo-search 2.14.0 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/AGENTS.md +8 -6
  2. package/README.es.md +56 -824
  3. package/README.ja.md +55 -825
  4. package/README.ko.md +55 -823
  5. package/README.md +128 -868
  6. package/README.zh.md +206 -0
  7. package/SKILL.md +17 -18
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +23 -23
  10. package/backends/concept_vectors.bin +0 -0
  11. package/backends/domain_profiles.json +66 -0
  12. package/backends/engine_concept_vectors.json +1525 -1525
  13. package/backends/engine_registry.yaml +193 -46
  14. package/backends/quota_profiles.json +110 -0
  15. package/bin/argo +30 -17
  16. package/config.yaml +196 -36
  17. package/docs/ADDING_NEW_ENGINE.md +10 -0
  18. package/docs/ARGO_INTRO.md +1 -1
  19. package/docs/CHANGELOG.md +45 -0
  20. package/docs/ENGINE_CATALOG.md +128 -112
  21. package/docs/MCP_SETUP.md +2 -2
  22. package/docs/RELEASE_NOTES_v2.14.0.md +12 -1
  23. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  24. package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
  25. package/docs/RELEASING.md +53 -1
  26. package/engines/specs/ai_labs.yaml +89 -0
  27. package/engines/specs/artic.yaml +11 -1
  28. package/engines/specs/bilibili_hot.yaml +11 -1
  29. package/engines/specs/brave.yaml +3 -3
  30. package/engines/specs/cisa_alerts.yaml +40 -0
  31. package/engines/specs/cleveland.yaml +15 -1
  32. package/engines/specs/clinicaltrials.yaml +16 -1
  33. package/engines/specs/cn_ai_news.yaml +10 -8
  34. package/engines/specs/cnii.yaml +15 -4
  35. package/engines/specs/deezer.yaml +12 -1
  36. package/engines/specs/digup.yaml +11 -6
  37. package/engines/specs/doaj.yaml +14 -1
  38. package/engines/specs/douyin_hot.yaml +11 -1
  39. package/engines/specs/dw_news.yaml +4 -2
  40. package/engines/specs/endoflife.yaml +16 -1
  41. package/engines/specs/eng_blogs.yaml +63 -0
  42. package/engines/specs/eu_opendata.yaml +11 -1
  43. package/engines/specs/europeana.yaml +22 -5
  44. package/engines/specs/feed.yaml +62 -0
  45. package/engines/specs/felo.yaml +3 -3
  46. package/engines/specs/figshare.yaml +12 -1
  47. package/engines/specs/firecrawl.yaml +3 -0
  48. package/engines/specs/fourget.yaml +5 -2
  49. package/engines/specs/france24.yaml +6 -4
  50. package/engines/specs/fxtwitter.yaml +29 -6
  51. package/engines/specs/grepapp_mcp.yaml +62 -0
  52. package/engines/specs/guardian_rss.yaml +6 -4
  53. package/engines/specs/hackernews.yaml +17 -2
  54. package/engines/specs/hal.yaml +19 -1
  55. package/engines/specs/hf_datasets.yaml +59 -0
  56. package/engines/specs/hf_papers.yaml +17 -1
  57. package/engines/specs/itotii.yaml +13 -1
  58. package/engines/specs/jikan.yaml +12 -10
  59. package/engines/specs/kaggle.yaml +5 -3
  60. package/engines/specs/lobsters.yaml +41 -0
  61. package/engines/specs/local_seek.yaml +6 -0
  62. package/engines/specs/maven.yaml +61 -0
  63. package/engines/specs/nasa_cmr.yaml +12 -1
  64. package/engines/specs/nuget.yaml +57 -0
  65. package/engines/specs/open_meteo.yaml +1 -1
  66. package/engines/specs/redskill.yaml +2 -0
  67. package/engines/specs/searxng.yaml +4 -2
  68. package/engines/specs/sec_edgar.yaml +8 -3
  69. package/engines/specs/tatoeba.yaml +14 -1
  70. package/engines/specs/tinyfish.yaml +2 -0
  71. package/engines/specs/tinyfish_news.yaml +2 -0
  72. package/engines/specs/tinyfish_paper.yaml +2 -0
  73. package/engines/specs/toutiao_hot.yaml +11 -1
  74. package/engines/specs/train.yaml +3 -0
  75. package/engines/specs/tvmaze.yaml +5 -1
  76. package/engines/specs/twitter.yaml +4 -0
  77. package/engines/specs/unpaywall.yaml +6 -0
  78. package/engines/specs/usda.yaml +14 -1
  79. package/engines/specs/vam.yaml +17 -3
  80. package/engines/specs/weibo_hot.yaml +11 -1
  81. package/engines/specs/wolframalpha.yaml +3 -3
  82. package/engines/specs/xiaohongshu.yaml +2 -0
  83. package/engines/specs/zhihu.yaml +3 -18
  84. package/engines/specs/zhihu_kb.yaml +18 -0
  85. package/engines/specs/zhihu_questions.yaml +19 -0
  86. package/package.json +4 -2
  87. package/packages/dsh-plugin/README.md +9 -14
  88. package/packages/dsh-plugin/dsh/client.js +467 -1024
  89. package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
  90. package/packages/dsh-plugin/dsh/native-tools.mjs +61 -113
  91. package/packages/dsh-plugin/dsh/runner.js +2 -0
  92. package/packages/dsh-plugin/dsh/wide-research.js +1 -1
  93. package/packages/dsh-plugin/package.json +8 -3
  94. package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
  95. package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
  96. package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
  97. package/packages/dsh-plugin/test/size-gate.test.js +2 -9
  98. package/scripts/adaptive.py +7 -1
  99. package/scripts/archive_run.py +112 -53
  100. package/scripts/argo_paths.py +40 -3
  101. package/scripts/badcase_ledger.py +153 -10
  102. package/scripts/build_concept_table.py +112 -55
  103. package/scripts/build_release_assets.sh +43 -15
  104. package/scripts/cache.py +5 -1
  105. package/scripts/caliber_isolation.py +60 -23
  106. package/scripts/circuit_breaker.py +56 -8
  107. package/scripts/cli_io.py +20 -2
  108. package/scripts/config_cache.py +31 -0
  109. package/scripts/daemon.py +146 -51
  110. package/scripts/dormant_ledger.py +239 -0
  111. package/scripts/engine_dispatch.py +3 -3
  112. package/scripts/engine_env.py +182 -1
  113. package/scripts/engine_families.py +50 -7
  114. package/scripts/engine_states.py +9 -51
  115. package/scripts/engine_validate.py +150 -6
  116. package/scripts/engines.py +15 -67
  117. package/scripts/engines_base.py +68 -124
  118. package/scripts/engines_builders.py +0 -51
  119. package/scripts/engines_builders_batch10.py +346 -100
  120. package/scripts/engines_builders_batch11.py +2 -75
  121. package/scripts/engines_builders_batch9.py +15 -228
  122. package/scripts/engines_builders_cn.py +0 -194
  123. package/scripts/engines_builders_feeds.py +203 -35
  124. package/scripts/engines_builders_intl.py +15 -443
  125. package/scripts/engines_builders_pixiv.py +2 -16
  126. package/scripts/engines_builders_science.py +0 -85
  127. package/scripts/engines_builders_search.py +7 -14
  128. package/scripts/engines_builders_tech.py +5 -112
  129. package/scripts/engines_builders_weather.py +236 -0
  130. package/scripts/engines_fields.py +91 -0
  131. package/scripts/engines_http.py +135 -0
  132. package/scripts/engines_mcp.py +383 -0
  133. package/scripts/engines_parsers.py +196 -27
  134. package/scripts/engines_schema_drift.py +260 -0
  135. package/scripts/evidence.py +13 -0
  136. package/scripts/evidence_loop.py +93 -5
  137. package/scripts/fetch_jsrun.py +15 -11
  138. package/scripts/fetch_v3.py +28 -28
  139. package/scripts/fulltext_store.py +42 -1
  140. package/scripts/fxtwitter_api.py +8 -7
  141. package/scripts/gen_engine_catalog.py +4 -4
  142. package/scripts/gen_native_tools.py +2 -1
  143. package/scripts/general_pool.py +15 -4
  144. package/scripts/health_check.py +1 -1
  145. package/scripts/link_source.py +65 -24
  146. package/scripts/local_intent.py +51 -15
  147. package/scripts/local_seek.py +37 -4
  148. package/scripts/local_seek_adapter.py +57 -17
  149. package/scripts/mcp_handlers.py +173 -99
  150. package/scripts/mcp_handlers_surface.py +6 -18
  151. package/scripts/mcp_server.py +1 -1
  152. package/scripts/mcp_tools.py +143 -61
  153. package/scripts/mcp_transport.py +42 -10
  154. package/scripts/min_version_scan.py +7 -3
  155. package/scripts/network_aware.py +7 -13
  156. package/scripts/pre-commit +57 -31
  157. package/scripts/query_understanding.py +30 -6
  158. package/scripts/quota.py +6 -1
  159. package/scripts/rank_signals.py +9 -0
  160. package/scripts/recompute.py +15 -5
  161. package/scripts/recovery.py +21 -15
  162. package/scripts/release.py +29 -32
  163. package/scripts/release_check.py +6 -26
  164. package/scripts/replay_eval.py +2 -2
  165. package/scripts/research_cli.py +40 -0
  166. package/scripts/research_notes.py +368 -0
  167. package/scripts/route.py +32 -70
  168. package/scripts/route_audit.py +259 -0
  169. package/scripts/route_combo.py +10 -4
  170. package/scripts/route_domains.py +150 -23
  171. package/scripts/route_lang.py +20 -7
  172. package/scripts/route_log.py +26 -9
  173. package/scripts/route_policy.py +91 -7
  174. package/scripts/route_telemetry_export.py +199 -0
  175. package/scripts/rrf_classic.py +5 -22
  176. package/scripts/search.py +2 -1
  177. package/scripts/search_attribution.py +33 -10
  178. package/scripts/search_cli.py +44 -7
  179. package/scripts/search_entry.py +5 -1
  180. package/scripts/search_output.py +5 -4
  181. package/scripts/search_pipeline.py +12 -0
  182. package/scripts/search_rank.py +21 -11
  183. package/scripts/secret_guard.py +106 -0
  184. package/scripts/semantic_evidence.py +539 -117
  185. package/scripts/settings_page.py +83 -11
  186. package/scripts/social_engines/xiaohongshu_engine.py +2 -1
  187. package/scripts/social_engines/zhihu_engine.py +251 -43
  188. package/scripts/sogou_weixin_browser.py +5 -6
  189. package/scripts/source_audit.py +77 -0
  190. package/scripts/source_ledger.py +2 -15
  191. package/scripts/source_selection.py +45 -20
  192. package/scripts/straggler_policy.py +1 -2
  193. package/scripts/sync_backends.py +24 -0
  194. package/scripts/tfidf_router.py +23 -11
  195. package/scripts/time_utils.py +54 -1
  196. package/scripts/train.py +68 -2
  197. package/scripts/usage_log.py +26 -1
  198. package/sub-skills/argo-wide-research/SKILL.md +68 -0
  199. package/sub-skills/ego-search/SKILL.md +1 -1
  200. package/sub-skills/local-seek/scripts/seek_fts.py +67 -4
  201. package/README.en.md +0 -826
  202. package/scripts/caliber_dedupe.py +0 -66
  203. package/scripts/engines_builders_batch16.py +0 -186
  204. package/scripts/health_probe.py +0 -253
  205. package/scripts/image_vision/vision_probe +0 -0
  206. package/scripts/social_engines/twitter_engine.py +0 -514
  207. 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"),
@@ -63,7 +63,16 @@ _VERTICAL_NEW_SOURCE: dict[str, tuple[str, ...]] = {
63
63
  # kaggle 补社区数据集(DataCite/Zenodo 是机构仓储,Kaggle 是社区);
64
64
  # hf_papers 补论文社交信号(upvotes/作者,arXiv/OpenAlex 无)。
65
65
  "semantic_discovery": ("mwmbl",),
66
- "dataset_search": ("kaggle",),
66
+ # 2026-11-11:hf_datasets 声明在 kaggle 之后(位次 4),与 kaggle 一并加槽。
67
+ # 两者口径互补(机构仓储 DOI / 竞赛社区 / ML 社区数据集),不是同质重复。
68
+ "dataset_search": ("kaggle", "hf_datasets"),
69
+ # 2026-11-11:maven/nuget 补 Java/JVM 与 .NET 两个生态的关键词发现,
70
+ # 声明在 crates 之后(位次 4/5)。本域基础预算 3,两源需加槽通电。
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",),
67
76
  }
68
77
 
69
78
 
@@ -247,9 +256,10 @@ def _apply_policy_with_new_source_slots(
247
256
  live = [e for e in _VERTICAL_NEW_SOURCE.get((domain or {}).get("name"), ())
248
257
  if e in declared and (enabled is None or e in enabled)]
249
258
  keep = list(must_keep or [])
250
- for e in live:
251
- if e not in engines_combo and e not in keep:
252
- keep.append(e)
259
+ if (mode or "auto") not in ("fast", "budget"):
260
+ for e in live:
261
+ if e not in engines_combo and e not in keep:
262
+ keep.append(e)
253
263
  return _apply_engine_policy(
254
264
  engines_combo, mode=mode, depth=depth, context=context,
255
265
  engines_boost=engines_boost, enabled=enabled,
@@ -257,7 +267,81 @@ def _apply_policy_with_new_source_slots(
257
267
  budget_extra=_new_source_budget_extra(
258
268
  domain, declared or engines_combo, enabled or set(),
259
269
  mode=mode, depth=depth, context=context,
260
- # 传当前 combo:新源还在里面但被重排推出窗口时,额度要按它在
261
- # 当前 combo 的位次算(只在声明位次上算会得到 0,见该函数说明)
262
- live_combo=engines_combo),
270
+ # 传当前 combo:新源还在里面但被重排推出窗口时,额度要按它在
271
+ # 当前 combo 的位次算(只在声明位次上算会得到 0,见该函数说明)
272
+ live_combo=engines_combo),
263
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,28 @@ 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
70
74
  return out
71
75
 
72
76
 
@@ -166,6 +170,16 @@ def engine_result_counts(engine_outcomes: Iterable[dict[str, Any]] | None,
166
170
  return out
167
171
 
168
172
 
173
+ def _failure_rows(engine_outcomes: Iterable[dict[str, Any]] | None,
174
+ limit: int = 8) -> list[dict[str, Any]]:
175
+ try:
176
+ from output_transparency import build_failures
177
+ except ImportError: # pragma: no cover - 单文件分发时的降级
178
+ return []
179
+ return build_failures({"engine_outcomes": list(engine_outcomes or [])},
180
+ limit=limit)
181
+
182
+
169
183
  def failure_kinds(engine_outcomes: Iterable[dict[str, Any]] | None,
170
184
  limit: int = 6) -> list[str]:
171
185
  """本次调用的失败类别(去重、稳定排序),写进 usage_log 供长期归因。
@@ -174,15 +188,24 @@ def failure_kinds(engine_outcomes: Iterable[dict[str, Any]] | None,
174
188
  output_transparency.build_failures(与 agent 档 failures 同一口径),
175
189
  不在日志侧另写一份分类。
176
190
  """
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)
191
+ rows = _failure_rows(engine_outcomes, limit=limit)
183
192
  return sorted({str(r.get("category") or "unknown") for r in rows})
184
193
 
185
194
 
195
+ def engine_errors(engine_outcomes: Iterable[dict[str, Any]] | None,
196
+ limit: int = 8) -> dict[str, str]:
197
+ """按引擎提取失败归因映射 ``{engine: "category: detail"}``,供坏例账本定责。"""
198
+ out: dict[str, str] = {}
199
+ for r in _failure_rows(engine_outcomes, limit=limit):
200
+ eng = str(r.get("engine") or "").strip()
201
+ if not eng or eng in out:
202
+ continue
203
+ cat = str(r.get("category") or "unknown").strip()
204
+ detail = str(r.get("detail") or "").strip()
205
+ out[eng] = f"{cat}: {detail[:80]}" if detail else cat
206
+ return out
207
+
208
+
186
209
  def aggregate_slow_engines(rows: Iterable[dict[str, Any]],
187
210
  top_n: int = 5) -> list[dict[str, Any]]:
188
211
  """聚合多行日志的 engine_latency_top → 按累计耗时的慢源排行。
@@ -409,6 +409,23 @@ def main():
409
409
  logging.disable(logging.WARNING)
410
410
 
411
411
  if args.list_engines:
412
+ # 引擎状态行里含 runtime.failure.evidence 与 admission 等自由文本字段,
413
+ # 是 stdout 上唯一能带回真实凭据的出口(历史上引擎把 401 响应体原样
414
+ # 记进 failure.evidence)。--list-engines 在 search 之前就 return,
415
+ # 走不到文件底部那处脱敏,所以这里必须自带一层。
416
+ # 契约见 tests/test_redactor_guard.py::test_list_engines_output_is_redacted。
417
+ try:
418
+ from secret_guard import redact_data as _redact
419
+ except Exception:
420
+ def _redact(x):
421
+ return x
422
+
423
+ def _emit_json(obj: Any) -> None:
424
+ print(dumps(_redact(obj)))
425
+
426
+ def _emit_text(text: str) -> None:
427
+ print(_redact(text))
428
+
412
429
  # --engine 兼作清单过滤(`--engine auto` 是搜索默认值,不算过滤)。
413
430
  # 全量详细行 2026-09-16 实测 151 KB(runtime/admission 嵌套是大头),
414
431
  # Agent 查单个引擎状态时不该付这个代价——实测此前
@@ -439,10 +456,10 @@ def main():
439
456
  # 单引擎全量诊断仍走 --engine <名>(不受本分支影响)。
440
457
  rows = [compact_engine_row(r) for r in rows]
441
458
  if not _wanted and not args.list_all and args.json_output:
442
- print(dumps(_summarize_engine_rows(rows)))
459
+ _emit_json(_summarize_engine_rows(rows))
443
460
  return
444
461
  if not _wanted and not args.list_all:
445
- print(_format_engine_summary(_summarize_engine_rows(rows)))
462
+ _emit_text(_format_engine_summary(_summarize_engine_rows(rows)))
446
463
  return
447
464
  if _wanted:
448
465
  # 未命中的名字要显式报出(走 stderr,保持 stdout 是纯 JSON)——
@@ -459,13 +476,13 @@ def main():
459
476
  # 单引擎诊断(--engine <名>)仍给逐条全量对象——那一档
460
477
  # 只有 1 条,键名成本可忽略,且需要嵌套的 runtime/admission。
461
478
  if not _wanted:
462
- print(dumps(compact_engine_table(rows)))
479
+ _emit_json(compact_engine_table(rows))
463
480
  else:
464
- print(dumps(rows))
481
+ _emit_json(rows)
465
482
  else:
466
- print(format_engines_table(rows))
483
+ _emit_text(format_engines_table(rows))
467
484
  except Exception as e:
468
- print(dumps({"error": str(e), "engines": available_engines()}))
485
+ _emit_json({"error": str(e), "engines": available_engines()})
469
486
  else:
470
487
  # 不包 try/except TypeError:available_engines 已收 routable_only
471
488
  # (它当初没收,被这里的回退静默吞掉,于是 --routable-only 一直
@@ -473,7 +490,7 @@ def main():
473
490
  names = available_engines(routable_only=args.routable_only)
474
491
  if _wanted:
475
492
  names = [n for n in names if n in set(_wanted)]
476
- print(dumps(names))
493
+ _emit_json(names)
477
494
  # issue #34 第 6 条:本档只回答「有多少个有实现的源」,与
478
495
  # `paths --check` 的 engines=<总收录> 天然不等——差额里是
479
496
  # 停用/缺密钥/别名 spec。以前这层口径差没有任何对外说明,
@@ -668,6 +685,19 @@ def main():
668
685
  f"degraded={rs.get('degraded', 0)} mean_delta={rs.get('mean_delta', 0)}",
669
686
  file=sys.stderr,
670
687
  )
688
+ sem = v.get("semantic") or {}
689
+ if sem.get("contradiction_alert"):
690
+ print(f" ! [事实反驳预警] 检测到权威信源明确反驳查询前提({sem.get('contradicts')} 条冲突)",
691
+ file=sys.stderr)
692
+ if sem.get("primary_sources"):
693
+ print(f" * [一手源置顶] 识别到 {sem.get('primary_sources')} 条官方/一手公告并加权",
694
+ file=sys.stderr)
695
+ if sem.get("substantive_discussions"):
696
+ print(f" * [深度探讨置顶] 识别到 {sem.get('substantive_discussions')} 条深度探讨内容并提权",
697
+ file=sys.stderr)
698
+ if sem.get("passing_mentions"):
699
+ print(f" ~ [顺带提及校准] 识别到 {sem.get('passing_mentions')} 条仅顺带提及内容并去噪",
700
+ file=sys.stderr)
671
701
  ro = results.get("evidence_reorder") or {}
672
702
  if ro.get("reordered"):
673
703
  print(f" [verify] 证据回写排序:调整 {len(ro.get('adjusted') or [])} 条,"
@@ -747,6 +777,13 @@ def main():
747
777
  _vw_ms = (time.perf_counter() - _t_verifywith0) * 1000.0
748
778
  _merge_verify_timing(results["timing"], _vw_ms, stage="verify_with")
749
779
 
780
+ # 敏感信息自动脱敏拦截(防止真实 API Key / 通用敏感凭据在输出流泄露)
781
+ try:
782
+ from secret_guard import redact_data
783
+ results = redact_data(results)
784
+ except Exception:
785
+ pass
786
+
750
787
  if args.json_output:
751
788
  public = {k: v for k, v in results.items() if not k.startswith("_")}
752
789
  # Agent 消费自动瘦身:stdout 非 tty(管道/Agent 调用)且未显式指定
@@ -164,7 +164,11 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
164
164
  # 用归一化 ISO(7d 与等价绝对日期共享缓存;相对窗跨天自然过期不串旧数据)。
165
165
  # 仅当组合内含带时间能力引擎时隔离:无时间字段引擎忽略时间窗、结果相同,
166
166
  # 隔离只会降低命中率(7d/30d 查 octen/anysearch 命中同一缓存)。
167
- time_aware = any(_is_time_capable(e) for e in engines)
167
+ # 无时间窗时整段短路:`time_aware` 只被下面两行与后过滤读取,而两者
168
+ # 都以 since/until 非空为前提,此时无论如何取值都不影响结果。旧写法
169
+ # 无条件求值,让默认路径白付一次 307 份 spec 的全量解析。
170
+ time_aware = (bool(since_iso or until_iso)
171
+ and any(_is_time_capable(e) for e in engines))
168
172
  if since_iso and time_aware:
169
173
  cache_engine_key += f"|since={since_iso}"
170
174
  if until_iso and time_aware: