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
@@ -320,12 +320,24 @@ def is_unusable_url(url: str, title: str = "", snippet: str = "") -> bool:
320
320
 
321
321
  def is_unusable_row(row: dict) -> bool:
322
322
  """条目级闸(issue #29 口径 B):spec 声明 url_kind: none 的条目不以 url 为
323
- 身份,空 url 不判壳页;一旦有 url,SERP 判据照走;内容农场判据恒走。"""
323
+ 身份,空 url 不判壳页;一旦有 url,SERP 判据照走;内容农场判据恒走。
324
+
325
+ 引擎显式标注豁免(url_resolved,2026-11-17):wechat_sogou 在 fast 跳过
326
+ 解析、解析预算耗尽、解析熔断时都会给中间链打 url_resolved=False——这是
327
+ 引擎对「这是文章条目、URL 是跳转链」的显式声明。形状判据无法区分它与真
328
+ 搜索结果页(前缀同为 weixin.sogou.com/weixin),只有声明能区分;此前一概
329
+ 吞掉,fast 档该引擎必然 0 结果且 errors 为空(2026-11-16 外部报告实测:
330
+ returned 10 → filtered 0 → kept 0)。声明过的条目跳过 SERP/跳转判据,
331
+ 农场判据恒走;未声明的野生链照吞。与 url_kind: none 同一哲学:显式声明
332
+ 优先于形状推断。"""
324
333
  if row.get("url_kind") == "none":
325
334
  url = row.get("url", "")
326
335
  if url and is_serp_or_jump_url(url):
327
336
  return True
328
337
  return is_content_farm(url, row.get("title", ""), row.get("snippet", ""))
338
+ if "url_resolved" in row:
339
+ url = row.get("url", "")
340
+ return is_content_farm(url, row.get("title", ""), row.get("snippet", ""))
329
341
  return is_unusable_url(row.get("url", ""), row.get("title", ""), row.get("snippet", ""))
330
342
 
331
343
 
@@ -64,6 +64,7 @@ _OPTIONAL_BOOST_KEYS = [
64
64
  ("exa", "Exa 语义搜索增强 (可选)", ["EXA_API_KEY", "ARGO_EXA_API_KEY"]),
65
65
  ("firecrawl", "Firecrawl 深度清洗 (可选)", ["FIRECRAWL_API_KEY", "ARGO_FIRECRAWL_API_KEY"]),
66
66
  ("anysearch", "AnySearch 搜索通道 (可选)", ["ANYSEARCH_API_KEY", "ARGO_ANYSEARCH_API_KEY"]),
67
+ ("jina", "Jina Reader 抓取通道 (可选,解除免 Key 的 IP 信誉限频)", ["ARGO_JINA_API_KEY"]),
67
68
  ("pixiv", "Pixiv App OAuth (可选)", ["ARGO_PIXIV_REFRESH_TOKEN"]),
68
69
  ]
69
70
 
@@ -452,10 +453,10 @@ def _run_list() -> int:
452
453
 
453
454
 
454
455
  def _read_secret(prompt: str) -> str:
455
- """值只从 stdin 进来:tty 用 getpass 不回显,管道直接读一行。
456
+ """值只从 stdin 进来:tty 用 getpass 不回显,管道或内存流直接读一行。
456
457
  值不进 argv——进程列表与 shell history 都不会留痕。"""
457
- from cli_io import stdin_is_piped
458
- if stdin_is_piped():
458
+ from cli_io import stdin_is_memory_stream, stdin_is_piped
459
+ if stdin_is_piped() or stdin_is_memory_stream():
459
460
  return sys.stdin.readline().rstrip("\r\n").strip()
460
461
  import getpass
461
462
  return getpass.getpass(prompt).strip()
@@ -75,7 +75,7 @@ class SingleFlightCoalescer:
75
75
  step = min(1.0, wait_timeout - waited)
76
76
  event.wait(timeout=step)
77
77
  waited += step
78
- if event.is_set() and slots and not isinstance(slots[0], Exception):
78
+ if event.is_set() and slots and not isinstance(slots[0], BaseException):
79
79
  return slots[0] # type: ignore[return-value]
80
80
  # leader 失败或超时 → 独立执行(韧性)
81
81
  return fn()
@@ -17,6 +17,7 @@ import os
17
17
  import sys
18
18
  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19
19
  from net_proxy import http_get # noqa: E402
20
+ from engines_http import UA # noqa: E402
20
21
 
21
22
  HN_API = "https://hn.algolia.com/api/v1/search"
22
23
 
@@ -32,7 +33,7 @@ def search(query: str, n: int = 5) -> list[dict[str, Any]]:
32
33
  })
33
34
  url = f"{HN_API}?{params}"
34
35
  try:
35
- body, _ = http_get(url, {"User-Agent": "argo-search/1.0 (+https://github.com/taxueseek/argo)",
36
+ body, _ = http_get(url, {"User-Agent": UA,
36
37
  "Accept": "application/json"})
37
38
  data = json.loads(body.decode("utf-8"))
38
39
  except Exception as e:
@@ -22,6 +22,7 @@ import os
22
22
  import sys
23
23
  sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
24
24
  from net_proxy import http_get # noqa: E402
25
+ from engines_http import UA # noqa: E402
25
26
 
26
27
 
27
28
  _ATOM_NS = {"atom": "http://www.w3.org/2005/Atom"}
@@ -39,7 +40,7 @@ def search_reddit_api(query: str, n: int = 5) -> list[dict]:
39
40
  try:
40
41
  # 单次 GET(stdlib,不重试):无 key 端点按 IP「一次一发」,2026-10 实测
41
42
  # 首次 200 后即连续 429、Retry-After 达分钟级,短间隔重试必然再 429。
42
- body, _ = http_get(url, {"User-Agent": "argo-search/1.0 (by taxueseek)"}, timeout=10)
43
+ body, _ = http_get(url, {"User-Agent": UA}, timeout=10)
43
44
  return _parse_reddit_rss(body, n)
44
45
  except Exception as e:
45
46
  # 吞异常返空会让 MCP 社交搜索把网络故障静默报成「平台成功、0 结果」
@@ -35,7 +35,8 @@ def _child_env() -> dict:
35
35
  ② 宿主注入 NO_PROXY=...,[::1] 时 xhs 内部 httpx 抛
36
36
  InvalidURL: Invalid port ':1]' → 从 NO_PROXY/no_proxy 里剔掉 [::1]。
37
37
  """
38
- env = os.environ.copy()
38
+ from engine_env import build_child_env
39
+ env = build_child_env("xiaohongshu", {"allowed_env": ["ARGO_XHS_TIMEOUT"]})
39
40
  env.setdefault("PYTHONUTF8", "1")
40
41
  env.setdefault("PYTHONIOENCODING", "utf-8")
41
42
  for key in ("NO_PROXY", "no_proxy"):
@@ -9,7 +9,9 @@
9
9
  from __future__ import annotations
10
10
 
11
11
  import json
12
+ import math
12
13
  import os
14
+ import re
13
15
  import time
14
16
  import urllib.error
15
17
  import urllib.parse
@@ -20,8 +22,145 @@ from typing import Any
20
22
  import sys as _sys
21
23
  _sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
24
  from net_proxy import http_get # noqa: E402
25
+ from engines_http import UA # noqa: E402
23
26
 
24
27
  ZHIHU_API = "https://developer.zhihu.com/api/v1/content/zhihu_search"
28
+ ZHIHU_QUESTION_ANSWERS_API = "https://developer.zhihu.com/api/v1/content/question_answers"
29
+ _ZHIHU_SEARCH_COUNT_MAX = 10 # 官方 zhihu_search 上限 10
30
+ _ZHIHU_CLOCK_HINT_RE = re.compile(r"timestamp|时间戳|签名|时钟|clock", re.I)
31
+ _ZHIHU_CLOCK_HINT = "本机时钟可能偏差导致签名过期:先校准系统时间再重试,不必反复换密钥"
32
+ _HTML_TAG_RE = re.compile(r"<[^>]+>")
33
+
34
+
35
+ def parse_authority_level(raw: Any) -> int | None:
36
+ """将上游 AuthorityLevel('1'..'4')解析为 0..4 整数,无效或空串返回 None。"""
37
+ if raw is None or isinstance(raw, bool):
38
+ return None
39
+ text = str(raw).strip()
40
+ if not text:
41
+ return None
42
+ try:
43
+ val = int(float(text))
44
+ except (TypeError, ValueError):
45
+ return None
46
+ return val if 0 <= val <= 4 else None
47
+
48
+
49
+ def epoch_to_iso(ts: Any) -> str | None:
50
+ """秒级 Unix 时间戳 → ISO 8601 UTC 字符串,不可解析返回 None。"""
51
+ if ts is None or isinstance(ts, bool):
52
+ return None
53
+ try:
54
+ val = float(ts)
55
+ except (TypeError, ValueError):
56
+ return None
57
+ if val <= 0:
58
+ return None
59
+ try:
60
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(val))
61
+ except (TypeError, ValueError, OSError):
62
+ return None
63
+
64
+
65
+ def clean_zhihu_title(title: Any) -> str:
66
+ """剥离知乎 API 标题尾部的 ' - 知乎'。"""
67
+ s = str(title or "").strip()
68
+ if s.endswith(" - 知乎"):
69
+ s = s[: -len(" - 知乎")].rstrip()
70
+ return s
71
+
72
+
73
+ def strip_html_tags(text: Any) -> str:
74
+ """去除 <em> 等高亮标签并折叠空白。"""
75
+ cleaned = _HTML_TAG_RE.sub("", str(text or ""))
76
+ return re.sub(r"\s+", " ", cleaned).strip()
77
+
78
+
79
+ def extract_comment_snippets(raw_list: Any, limit: int = 2) -> list[str]:
80
+ """提取 CommentInfoList 中的精选短评内容。"""
81
+ if not isinstance(raw_list, list):
82
+ return []
83
+ out: list[str] = []
84
+ for entry in raw_list:
85
+ if isinstance(entry, dict):
86
+ c = strip_html_tags(entry.get("Content") or "")
87
+ if c:
88
+ out.append(c[:160])
89
+ if len(out) >= limit:
90
+ break
91
+ return out
92
+
93
+
94
+ def zhihu_headers(secret: str) -> dict[str, str]:
95
+ """构造知乎开放平台通用鉴权请求头。"""
96
+ return {
97
+ "Authorization": f"Bearer {secret}",
98
+ "Content-Type": "application/json",
99
+ "X-Request-Timestamp": str(int(time.time())),
100
+ "User-Agent": UA,
101
+ }
102
+
103
+
104
+ def zhihu_error_item(source: str, code: Any, message: Any) -> dict[str, Any]:
105
+ """非成功响应的统一 error item:保留 code/message,时钟类附加校时提示。"""
106
+ text = f"{source} Code={code} {str(message or '')[:100]}".strip()
107
+ if _ZHIHU_CLOCK_HINT_RE.search(str(message or "")):
108
+ text = f"{text};hint: {_ZHIHU_CLOCK_HINT}"
109
+ return {"error": text, "source": source}
110
+
111
+
112
+ def fetch_question_answers(
113
+ question_url: str,
114
+ limit: int = 3,
115
+ timeout: float = 2.5,
116
+ *,
117
+ _secret_override: str | None = None,
118
+ ) -> list[dict[str, Any]]:
119
+ """获取知乎问题下的精选回答摘要(官方 question_answers 端点)。
120
+
121
+ 返回项含 token、url、summary、content_type。网络异常或配额限制时降级返回空列表,不阻断主流程。
122
+ """
123
+ if not question_url or not question_url.strip():
124
+ return []
125
+ secret = _secret_override if _secret_override is not None else _secret()
126
+ if not secret:
127
+ return []
128
+
129
+ # 规范化问题 URL:剥离多余路径和查询参数
130
+ m = re.search(r"(https?://(?:www\.)?zhihu\.com/question/\d+)", question_url.strip())
131
+ clean_url = m.group(1) if m else question_url.strip()
132
+
133
+ params = urllib.parse.urlencode({
134
+ "QuestionUrl": clean_url,
135
+ "Limit": str(max(1, min(int(limit), 50))),
136
+ "Offset": "0",
137
+ })
138
+ url = f"{ZHIHU_QUESTION_ANSWERS_API}?{params}"
139
+ headers = zhihu_headers(secret)
140
+ try:
141
+ body, _ = http_get(url, headers, timeout=timeout)
142
+ data = json.loads(body.decode("utf-8", "replace"))
143
+ if data.get("Code") in (0, None):
144
+ items = (data.get("Data") or {}).get("Items") or []
145
+ answers = []
146
+ for item in items:
147
+ if not isinstance(item, dict):
148
+ continue
149
+ summary = strip_html_tags(item.get("Summary") or "")
150
+ ans_url = item.get("Url") or ""
151
+ token = str(item.get("ContentToken") or "")
152
+ ctype = str(item.get("ContentType") or "answer").lower()
153
+ if summary or ans_url:
154
+ answers.append({
155
+ "token": token,
156
+ "url": ans_url,
157
+ "summary": summary,
158
+ "content_type": ctype,
159
+ })
160
+ return answers
161
+ except (OSError, ValueError, KeyError, TypeError) as exc:
162
+ _ = exc # 降级返回空列表,不阻断搜索主流程
163
+ return []
25
164
 
26
165
 
27
166
  def _secret() -> str:
@@ -34,28 +173,31 @@ def _secret() -> str:
34
173
  return os.environ.get("ZHIHU_ACCESS_SECRET") or os.environ.get("ARGO_ZHIHU_ACCESS_SECRET", "")
35
174
 
36
175
 
37
- def search(query: str, n: int = 5) -> list[dict[str, Any]]:
176
+ def search(
177
+ query: str,
178
+ n: int = 5,
179
+ expand_questions: bool = True,
180
+ *,
181
+ _secret_override: str | None = None,
182
+ _timeout: float = 10.0,
183
+ ) -> list[dict[str, Any]]:
38
184
  """通过知乎开放平台 zhihu_search 搜索站内内容。"""
39
185
  if not query or not query.strip():
40
186
  return []
41
- secret = _secret()
187
+ secret = _secret_override if _secret_override is not None else _secret()
42
188
  if not secret:
43
189
  return []
44
190
 
191
+ # 官方 zhihu_search Count 最大为 10(超出会被服务端截断,也不接受 SearchDB)
192
+ fetch_count = max(1, min(max(int(n) * 2, int(n)), _ZHIHU_SEARCH_COUNT_MAX))
45
193
  params = urllib.parse.urlencode({
46
194
  "Query": query.strip(),
47
- "Count": str(max(1, min(int(n), 20))),
48
- "SearchDB": "zhihu",
195
+ "Count": str(fetch_count),
49
196
  })
50
197
  url = f"{ZHIHU_API}?{params}"
51
- headers = {
52
- "Authorization": f"Bearer {secret}",
53
- "Content-Type": "application/json",
54
- "X-Request-Timestamp": str(int(time.time())),
55
- "User-Agent": "argo-search/2.6 (unified-search@local)",
56
- }
198
+ headers = zhihu_headers(secret)
57
199
  try:
58
- body, _ = http_get(url, headers, timeout=10)
200
+ body, _ = http_get(url, headers, timeout=_timeout)
59
201
  data = json.loads(body.decode("utf-8", "replace"))
60
202
  except urllib.error.HTTPError as e:
61
203
  # 密钥无效/过期(401/403)等必须暴露为 auth-failed,而不是静默
@@ -65,63 +207,129 @@ def search(query: str, n: int = 5) -> list[dict[str, Any]]:
65
207
  return [{"error": f"zhihu API {type(e).__name__}: {e}", "source": "zhihu"}]
66
208
 
67
209
  if data.get("Code") not in (0, None):
68
- return [{"error": f"zhihu API Code={data.get('Code')} "
69
- f"{str(data.get('Message') or '')[:100]}",
70
- "source": "zhihu"}]
210
+ return [zhihu_error_item("zhihu", data.get("Code"), data.get("Message"))]
71
211
 
72
- results: list[dict[str, Any]] = []
212
+ candidates: list[dict[str, Any]] = []
73
213
  items = (data.get("Data") or {}).get("Items") or []
74
- for item in items[:n]:
214
+ expanded_count = 0
215
+ max_expand = 2 # 一次搜索最多下钻展开前 2 个纯问题,平衡配额与延迟
216
+
217
+ for rank, item in enumerate(items):
75
218
  if not isinstance(item, dict):
76
219
  continue
77
- title = (item.get("Title") or "").strip()
78
- # API 标题统一带「 - 知乎」尾巴:截断前剥掉(先剥再切,尾巴不占正文)
79
- if title.endswith(" - 知乎"):
80
- title = title[: -len(" - 知乎")].rstrip()
220
+ title = clean_zhihu_title(item.get("Title"))
81
221
  url_ = item.get("Url") or ""
82
- snippet = (item.get("ContentText") or title or "")[:300]
222
+ raw_text = strip_html_tags(item.get("ContentText") or title)
223
+ snippet = raw_text[:500]
83
224
  if not title and not url_:
84
225
  continue
85
226
  content_id = str(item.get("ContentID") or "")
86
227
  author = item.get("AuthorName") or ""
87
- likes = item.get("VoteUpCount") or 0
88
- comments = item.get("CommentCount") or 0
89
- edit_ts = item.get("EditTime")
90
- published = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(edit_ts)) if edit_ts else None
228
+ content_type = (item.get("ContentType") or "answer").lower()
229
+ try:
230
+ likes = int(item.get("VoteUpCount") or 0)
231
+ except (ValueError, TypeError):
232
+ likes = 0
233
+ try:
234
+ comments = int(item.get("CommentCount") or 0)
235
+ except (ValueError, TypeError):
236
+ comments = 0
237
+ published = epoch_to_iso(item.get("EditTime"))
238
+ upstream_auth = parse_authority_level(item.get("AuthorityLevel"))
239
+ badge_text = str(item.get("AuthorBadgeText") or "").strip()
240
+ top_comments = extract_comment_snippets(item.get("CommentInfoList"))
241
+ ranking_score = item.get("RankingScore")
242
+
243
+ # 识别纯问题:支持自动下钻抓取 Top 精选回答摘要(方案 B:Question Answers Expansion)
244
+ is_pure_question = (content_type == "question") or ("/question/" in url_ and "/answer/" not in url_)
245
+ expanded_answers: list[dict[str, Any]] = []
246
+ if is_pure_question and expand_questions and expanded_count < max_expand:
247
+ expanded_count += 1
248
+ expanded_answers = fetch_question_answers(url_, limit=3, _secret_override=secret)
249
+ if expanded_answers:
250
+ answer_summaries = [f"【回答 {i+1}】{a['summary']}" for i, a in enumerate(expanded_answers[:2]) if a.get("summary")]
251
+ if answer_summaries:
252
+ addon = " ".join(answer_summaries)
253
+ snippet = f"{snippet} | {addon}"[:500] if snippet else addon[:500]
254
+
255
+ # 结合上游相关性序位与社区点赞/评论/权威分做质量综合评分
256
+ base_relevance = max(1.0 - rank * 0.05, 0.2)
257
+ like_boost = min(0.3, math.log10(likes + 1) * 0.08)
258
+ comment_boost = min(0.1, math.log10(comments + 1) * 0.03)
259
+ expand_boost = 0.08 if expanded_answers else 0.0
260
+ auth_boost = (upstream_auth - 1) * 0.02 if upstream_auth and upstream_auth >= 2 else 0.0
261
+ quality_score = round(min(1.0, base_relevance * 0.7 + like_boost + comment_boost + expand_boost + auth_boost), 4)
91
262
 
92
- results.append({
263
+ social_meta: dict[str, Any] = {
264
+ "platform": "zhihu",
265
+ "content_type": content_type,
266
+ "id": content_id,
267
+ "author": author,
268
+ "likes": likes,
269
+ "upvotes": likes,
270
+ "comments": comments,
271
+ "provider": "zhihu_openapi",
272
+ "is_question": is_pure_question,
273
+ "has_expanded_answers": bool(expanded_answers),
274
+ }
275
+ if item.get("AuthorityLevel") not in (None, ""):
276
+ social_meta["authority_level"] = str(item.get("AuthorityLevel"))
277
+ if badge_text:
278
+ social_meta["author_badge_text"] = badge_text
279
+ if top_comments:
280
+ social_meta["top_comments"] = top_comments
281
+ if isinstance(ranking_score, (int, float)):
282
+ social_meta["ranking_score"] = round(float(ranking_score), 4)
283
+ if expanded_answers:
284
+ social_meta["answers"] = [
285
+ {"url": a["url"], "summary": a["summary"]} for a in expanded_answers
286
+ ]
287
+
288
+ entry: dict[str, Any] = {
93
289
  "title": title[:100] + ("..." if len(title) > 100 else ""),
94
290
  "url": url_,
95
291
  "snippet": snippet,
96
292
  "source": "zhihu",
97
- "score": max(1.0 - len(results) * 0.1, 0.1),
293
+ "score": quality_score,
98
294
  "published_at": published,
99
- "social_meta": {
100
- "platform": "zhihu",
101
- "content_type": (item.get("ContentType") or "answer").lower(),
102
- "id": content_id,
103
- "author": author,
104
- "likes": likes,
105
- "comments": comments,
106
- "provider": "zhihu_openapi",
107
- },
108
- })
109
- return results
295
+ "social_meta": social_meta,
296
+ }
297
+ if upstream_auth is not None:
298
+ entry["upstream_authority"] = upstream_auth
299
+ candidates.append(entry)
300
+
301
+ # 按综合得分降序微调,确保高赞高质量答案排在前面,并保留前 n 条
302
+ candidates.sort(key=lambda r: r["score"], reverse=True)
303
+ return candidates[:n]
110
304
 
111
305
 
112
306
  def main():
113
307
  import argparse
114
308
  parser = argparse.ArgumentParser(description="Zhihu search engine (zhihu_openapi)")
115
- parser.add_argument("action", nargs="?", default="search")
116
- parser.add_argument("query", nargs="?")
309
+ parser.add_argument("action", nargs="?", default="search", help="search | answers")
310
+ parser.add_argument("query", nargs="?", help="Search query or question URL")
117
311
  parser.add_argument("-n", type=int, default=5)
312
+ parser.add_argument("--no-expand", action="store_true", help="Disable question answers expansion")
118
313
  parser.add_argument("--json", action="store_true")
119
314
  args = parser.parse_args()
120
315
 
121
316
  if not args.query:
122
317
  print("[]")
123
318
  return
124
- results = search(args.query, args.n)
319
+
320
+ if args.action in ("answers", "question_answers"):
321
+ answers = fetch_question_answers(args.query, limit=args.n)
322
+ if args.json:
323
+ print(json.dumps(answers, ensure_ascii=False))
324
+ else:
325
+ for i, a in enumerate(answers, 1):
326
+ print(f"### Answer {i}")
327
+ print(f"- URL: {a['url']}")
328
+ print(f"- {a['summary']}")
329
+ print()
330
+ return
331
+
332
+ results = search(args.query, args.n, expand_questions=not args.no_expand)
125
333
  if args.json:
126
334
  print(json.dumps(results, ensure_ascii=False))
127
335
  else:
@@ -129,8 +337,9 @@ def main():
129
337
  meta = r.get("social_meta") or {}
130
338
  print(f"### {i}. {r['title']}")
131
339
  print(f"- **URL**: {r['url']}")
132
- print(f"- {r['snippet'][:200]}")
133
- print(f"- likes={meta.get('likes')} comments={meta.get('comments')} @{meta.get('author', '')}")
340
+ print(f"- {r['snippet'][:250]}")
341
+ print(f"- likes={meta.get('likes')} comments={meta.get('comments')} @{meta.get('author', '')} "
342
+ f"[question={meta.get('is_question')} expanded={meta.get('has_expanded_answers')}]")
134
343
  print()
135
344
 
136
345
 
@@ -32,7 +32,6 @@ task.finish()(ego-browser「默认关闭空间」之例外:结果必须留
32
32
  from __future__ import annotations
33
33
 
34
34
  import argparse
35
- import fcntl
36
35
  import json
37
36
  import os
38
37
  import re
@@ -40,6 +39,9 @@ import shutil
40
39
  import subprocess
41
40
  import sys
42
41
  import tempfile
42
+ from pathlib import Path
43
+
44
+ from argo_paths import file_lock
43
45
  import time
44
46
  from datetime import datetime
45
47
  from urllib.parse import quote
@@ -241,11 +243,8 @@ def main(argv: list | None = None) -> int:
241
243
  file=sys.stderr)
242
244
  return 1
243
245
 
244
- # 文件锁串行化:并发调用会争抢同一浏览器页(goto 竞态)与节流窗口
245
- lock_path = state_path + ".lock"
246
- os.makedirs(os.path.dirname(lock_path) or ".", exist_ok=True)
247
- with open(lock_path, "w", encoding="utf-8") as lock_f:
248
- fcntl.flock(lock_f, fcntl.LOCK_EX)
246
+ # 文件锁串行化:并发调用会争抢同一浏览器页(goto 竞态)与节流窗口(复用 argo_paths 跨平台锁)
247
+ with file_lock(Path(state_path), timeout=30.0):
249
248
  state = _load_state(state_path)
250
249
  last_ts = float(state.get("last_ts") or 0)
251
250
  wait = args.min_interval - (time.time() - last_ts)
@@ -11,11 +11,17 @@ spec、派生件、文档、测试。
11
11
 
12
12
  ## 判据(第一性原理:价值 = 命中率 × 结果质量 / 成本)
13
13
 
14
- - `route_hits`:过去 N 天被路由命中的次数
15
- - `result_rate`:命中后返回非空结果的比例
14
+ - `route_hits`:过去 N 天被路由命中**或**在真实查询里被调用的次数
15
+ - `result_rate`:被调用后返回非空结果的比例
16
16
  - `value_score`:route_hits × result_rate(命中率 × 交付率)
17
17
  - `cost`:总调用成本(按 spec.cost_per_call 累加)
18
18
 
19
+ `route_hits` 必须由两路证据合并,不能只看 route 流:route 流是**采样**日志
20
+ (默认 1/20),而 query 流是每次搜索都写。只认 route 流时,采样一断
21
+ (2026-11-12 至 11-15 生产日志实测零条)就会把全部源判成「0 次命中」——
22
+ 实测 163 个源被建议停用,其中 69 个在 query 流里有真实调用记录。
23
+ query 流的 `engines_used` 是「这次搜索真的打了它」,比采样命中更强的证据。
24
+
19
25
  去留规则:
20
26
  - 90 天 route_hits == 0 且非显式专用 → 建议停用(demote)
21
27
  - 90 天 value_score < 5 且非显式专用 → 建议降级为 explicit_only(review)
@@ -106,23 +112,35 @@ def _load_route_log(days: int) -> list[dict]:
106
112
  return rows
107
113
 
108
114
 
115
+ def _query_fingerprint(row: dict[str, Any]) -> str:
116
+ """查询指纹:同一查询的多次重跑算一次命中,避免 route_hits 被刷虚高。
117
+
118
+ 用 query 原文(已由 usage_log 脱敏)+ 域,不做哈希:日志在本机、不进报告,
119
+ 可读性比省几个字节有用。字段缺失时退回 ts,保证每条都拿到稳定值。
120
+ """
121
+ q = str(row.get("query") or "").strip()
122
+ if q:
123
+ return f"{q}\x00{row.get('domain') or ''}"
124
+ return str(row.get("ts") or "")
125
+
126
+
109
127
  def _engine_usage(days: int = 90) -> dict[str, dict[str, Any]]:
110
128
  """统计每个引擎的使用情况。"""
111
129
  queries = _load_query_log(days)
112
130
  routes = _load_route_log(days)
113
131
 
114
132
  stats: dict[str, dict[str, Any]] = defaultdict(lambda: {
115
- "route_hits": 0, "calls": 0, "results": 0, "errors": 0,
116
- "domains": set(),
133
+ "route_hits": 0, "sampled_hits": 0, "calls": 0, "results": 0,
134
+ "errors": 0, "domains": set(), "hit_fps": set(),
117
135
  })
118
136
 
119
- # route 流:被路由命中
137
+ # route 流:被路由命中(**采样**日志,1/20)
120
138
  for r in routes:
121
139
  engines = r.get("engines") or r.get("engines_used") or []
122
140
  if isinstance(engines, str):
123
141
  engines = [engines]
124
142
  for e in engines:
125
- stats[e]["route_hits"] += 1
143
+ stats[e]["sampled_hits"] += 1
126
144
  dom = r.get("domain")
127
145
  if dom:
128
146
  stats[e]["domains"].add(dom)
@@ -140,6 +158,14 @@ def _engine_usage(days: int = 90) -> dict[str, dict[str, Any]]:
140
158
  er = r.get("engine_results") or {}
141
159
  for e in used:
142
160
  stats[e]["calls"] += 1
161
+ # 实调用同样计入 route_hits:engines_used 是「这次真的打了它」,
162
+ # 比采样命中更强的证据。去重按 (查询指纹, 引擎) ——同一查询重跑
163
+ # 多次(缓存失效、A/B 复跑)不该把命中数刷成虚高。
164
+ _fp = _query_fingerprint(r)
165
+ _seen = stats[e]["hit_fps"]
166
+ if _fp not in _seen:
167
+ _seen.add(_fp)
168
+ stats[e]["route_hits"] += 1
143
169
  # 优先用 engine_results(精确),缺失时用 count > 0(粗)
144
170
  n = er.get(e)
145
171
  if isinstance(n, int):
@@ -187,7 +213,14 @@ def audit(days: int = 90, verbose: bool = False) -> dict[str, Any]:
187
213
  cost_per_call = spec.get("cost_per_call", 0.0) or 0.0
188
214
 
189
215
  u = usage.get(name, {})
190
- route_hits = u.get("route_hits", 0)
216
+ # 两路证据相加:route 流是采样命中,query 流是按查询去重后的实调用。
217
+ # 跨源无法去重——route 记录按设计不含 query 原文(只有 domain/engines),
218
+ # 同一查询若同时被采样命中又实调用会被计两次。对「去留判定」而言,
219
+ # 多计只会让源更不容易被误停用,方向是安全的:本模块此前的问题正是
220
+ # 反向(少计 → 163 个源被建议停用,其中 69 个有真实调用)。
221
+ sampled_hits = u.get("sampled_hits", 0)
222
+ flow_hits = u.get("route_hits", 0)
223
+ route_hits = sampled_hits + flow_hits
191
224
  calls = u.get("calls", 0)
192
225
  results = u.get("results", 0)
193
226
  errors = u.get("errors", 0)
@@ -200,6 +233,8 @@ def audit(days: int = 90, verbose: bool = False) -> dict[str, Any]:
200
233
  "explicit_only": explicit,
201
234
  "enabled": enabled,
202
235
  "route_hits": route_hits,
236
+ "sampled_hits": sampled_hits,
237
+ "flow_hits": flow_hits,
203
238
  "calls": calls,
204
239
  "results": results,
205
240
  "errors": errors,
@@ -300,8 +335,8 @@ def render(report: dict, verbose: bool = False) -> str:
300
335
 
301
336
  lines.append(" 运行 `argo doctor --fix` 自动执行停用与隔离;降级需人工判断。")
302
337
  lines.append(" 对交付率异常的声明式源,可运行 `python3 scripts/engine_validate.py -e <id> --diagnose`"
303
- " (或 `--fix`) 探测结构漂移并输出建议补丁(预览态,不写盘);"
304
- "确认无误后加 `--apply` 才落盘。")
338
+ " (或 `--fix`) 探测结构漂移并输出建议补丁(只读预览);"
339
+ "确认无误后手动更新 `engines/specs/<id>.yaml`。")
305
340
  return "\n".join(lines)
306
341
 
307
342
 
@@ -17,6 +17,8 @@ from datetime import datetime, timezone, timedelta
17
17
  from typing import Any, Optional
18
18
  from urllib.parse import urlparse
19
19
 
20
+ from evidence_tier import _extract_host # 主机名提取真源在 evidence_tier,本模块只复用
21
+
20
22
 
21
23
  # ── 数据结构 ────────────────────────────────────────────────────────
22
24
 
@@ -208,21 +210,6 @@ def infer_access_status(url: str, fetch_success: bool = True, http_status: int =
208
210
  return "unknown"
209
211
 
210
212
 
211
- def _extract_host(url: str) -> str:
212
- """提取主机名"""
213
- if not url:
214
- return ""
215
- try:
216
- host = urlparse(url).netloc.lower()
217
- if "@" in host:
218
- host = host.rsplit("@", 1)[1]
219
- if ":" in host:
220
- host = host.split(":", 1)[0]
221
- return host
222
- except Exception:
223
- return ""
224
-
225
-
226
213
  def create_source_record(
227
214
  url: str,
228
215
  publisher: str = "",