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
@@ -50,6 +50,23 @@ _KNOWN_SWITCHES = [
50
50
  ("ARGO_FETCH_DEADLINE_S", "单次 fetch 总耗时上限(秒,0 关闭)"),
51
51
  ]
52
52
 
53
+ # 核心全局与管线服务凭据(非单个引擎独占)
54
+ _GLOBAL_SERVICES_KEYS = [
55
+ ("jev", "TypeSafe JEV 语义核验 (一手源加权/反驳预警)", ["ARGO_JEV_API_KEY", "TYPESAFE_API_KEY"]),
56
+ ("semantic_scholar", "Semantic Scholar 学术论文增强", ["SEMANTIC_SCHOLAR_API_KEY"]),
57
+ ("twitter_session", "X / Twitter 会话鉴权", ["TWITTER_AUTH_TOKEN", "TWITTER_CT0"]),
58
+ ("network_proxy", "出站网络代理通道", ["ARGO_PROXY", "HTTPS_PROXY"]),
59
+ ]
60
+
61
+ # 可选增强引擎凭据(免 Key 可跑,配置后解除限频或解锁高级通道)
62
+ _OPTIONAL_BOOST_KEYS = [
63
+ ("github", "GitHub 限频提升 (可选)", ["GITHUB_TOKEN", "ARGO_GITHUB_TOKEN"]),
64
+ ("exa", "Exa 语义搜索增强 (可选)", ["EXA_API_KEY", "ARGO_EXA_API_KEY"]),
65
+ ("firecrawl", "Firecrawl 深度清洗 (可选)", ["FIRECRAWL_API_KEY", "ARGO_FIRECRAWL_API_KEY"]),
66
+ ("anysearch", "AnySearch 搜索通道 (可选)", ["ANYSEARCH_API_KEY", "ARGO_ANYSEARCH_API_KEY"]),
67
+ ("pixiv", "Pixiv App OAuth (可选)", ["ARGO_PIXIV_REFRESH_TOKEN"]),
68
+ ]
69
+
53
70
  # MCP / CLI 接入示例(片段不含密钥;密钥由 mcp_launch.sh 启动时注入)
54
71
  _CLI_EXAMPLES = [
55
72
  ("搜索", 'argo search "查询词" --json'),
@@ -109,15 +126,29 @@ def collect() -> dict[str, Any]:
109
126
  except Exception:
110
127
  names = []
111
128
 
112
- # 密钥状态只列「声明了 required_env」的引擎——这正是 #41 里
113
- # 「装了 13 个引擎全 skipped」的痛点位;无密钥要求的引擎不上表。
114
- # 判定与 runtime 同源:缺失与否以 missing_env_for(候选链)为准,
115
- # 掩码值以 get_env 为准——显示层绝不自建第二套口径(#41/#42 的教训)。
129
+ # 密钥状态收集:覆盖全局核心服务、商业数据引擎、可选增强源
116
130
  try:
117
131
  from engines import get_engine_spec
118
132
  from engine_env import (required_env_for, missing_env_for, get_env,
119
133
  PLACEHOLDER_ALIASES)
120
134
 
135
+ # 1. 核心全局与管线服务
136
+ for s_id, s_label, s_vars in _GLOBAL_SERVICES_KEYS:
137
+ env_items = []
138
+ for var in s_vars:
139
+ val = get_env(var)
140
+ env_items.append({
141
+ "name": var,
142
+ "status": env_store.mask(val) if val else "缺失",
143
+ })
144
+ data["key_rows"].append({
145
+ "engine": s_id,
146
+ "label": s_label,
147
+ "kind": "service",
148
+ "envs": env_items,
149
+ })
150
+
151
+ # 2. 商业与声明 required_env 的引擎
121
152
  for name in names:
122
153
  spec = get_engine_spec(name) or {}
123
154
  try:
@@ -132,6 +163,8 @@ def collect() -> dict[str, Any]:
132
163
  missing = set(reqs)
133
164
  data["key_rows"].append({
134
165
  "engine": name,
166
+ "label": spec.get("label") or name,
167
+ "kind": "engine",
135
168
  "envs": [{"name": r,
136
169
  "status": (env_store.mask(
137
170
  get_env(PLACEHOLDER_ALIASES.get(r) or _runtime_candidates(r))
@@ -139,6 +172,22 @@ def collect() -> dict[str, Any]:
139
172
  if r not in missing else "缺失")}
140
173
  for r in reqs],
141
174
  })
175
+
176
+ # 3. 可选增强源
177
+ for o_id, o_label, o_vars in _OPTIONAL_BOOST_KEYS:
178
+ env_items = []
179
+ for var in o_vars:
180
+ val = get_env(var)
181
+ env_items.append({
182
+ "name": var,
183
+ "status": env_store.mask(val) if val else "未配置(可选)",
184
+ })
185
+ data["key_rows"].append({
186
+ "engine": o_id,
187
+ "label": o_label,
188
+ "kind": "optional",
189
+ "envs": env_items,
190
+ })
142
191
  except Exception:
143
192
  pass
144
193
 
@@ -369,21 +418,44 @@ def _run_list() -> int:
369
418
  env_in_use = (data.get("paths") or {}).get("env_file_in_use")
370
419
  if env_in_use:
371
420
  print(f"密钥文件:{env_in_use}")
372
- for r in data.get("key_rows", []):
373
- envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
374
- print(f" {r['engine']}: {envs}")
421
+
422
+ services = [r for r in data.get("key_rows", []) if r.get("kind") == "service"]
423
+ engines = [r for r in data.get("key_rows", []) if r.get("kind") == "engine"]
424
+ optionals = [r for r in data.get("key_rows", []) if r.get("kind") == "optional"]
425
+
426
+ if services:
427
+ print("\n[核心与管线服务凭据]")
428
+ for r in services:
429
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
430
+ desc = f" ({r['label']})" if r.get("label") else ""
431
+ print(f" {r['engine']}{desc}: {envs}")
432
+
433
+ if engines:
434
+ print("\n[商业搜索与数据源密钥]")
435
+ for r in engines:
436
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
437
+ print(f" {r['engine']}: {envs}")
438
+
439
+ if optionals:
440
+ print("\n[可选增强源凭据 (免 Key 可用,配置后提权)]")
441
+ for r in optionals:
442
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
443
+ desc = f" ({r['label']})" if r.get("label") else ""
444
+ print(f" {r['engine']}{desc}: {envs}")
445
+
446
+ print("\n[常用功能开关]")
375
447
  for s in data.get("switches", []):
376
448
  print(f" [{s['name']}] {s['value']} — {s['desc']}")
377
- print("修改:echo <值> | argo settings set <变量名>;"
449
+ print("\n修改:echo <值> | argo settings set <变量名>;"
378
450
  "清除:argo settings unset <变量名>。")
379
451
  return 0
380
452
 
381
453
 
382
454
  def _read_secret(prompt: str) -> str:
383
- """值只从 stdin 进来:tty 用 getpass 不回显,管道直接读一行。
455
+ """值只从 stdin 进来:tty 用 getpass 不回显,管道或内存流直接读一行。
384
456
  值不进 argv——进程列表与 shell history 都不会留痕。"""
385
- from cli_io import stdin_is_piped
386
- if stdin_is_piped():
457
+ from cli_io import stdin_is_memory_stream, stdin_is_piped
458
+ if stdin_is_piped() or stdin_is_memory_stream():
387
459
  return sys.stdin.readline().rstrip("\r\n").strip()
388
460
  import getpass
389
461
  return getpass.getpass(prompt).strip()
@@ -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
@@ -22,6 +24,142 @@ _sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
24
  from net_proxy import http_get # noqa: E402
23
25
 
24
26
  ZHIHU_API = "https://developer.zhihu.com/api/v1/content/zhihu_search"
27
+ ZHIHU_QUESTION_ANSWERS_API = "https://developer.zhihu.com/api/v1/content/question_answers"
28
+ _ZHIHU_SEARCH_COUNT_MAX = 10 # 官方 zhihu_search 上限 10
29
+ _ZHIHU_CLOCK_HINT_RE = re.compile(r"timestamp|时间戳|签名|时钟|clock", re.I)
30
+ _ZHIHU_CLOCK_HINT = "本机时钟可能偏差导致签名过期:先校准系统时间再重试,不必反复换密钥"
31
+ _HTML_TAG_RE = re.compile(r"<[^>]+>")
32
+
33
+
34
+ def parse_authority_level(raw: Any) -> int | None:
35
+ """将上游 AuthorityLevel('1'..'4')解析为 0..4 整数,无效或空串返回 None。"""
36
+ if raw is None or isinstance(raw, bool):
37
+ return None
38
+ text = str(raw).strip()
39
+ if not text:
40
+ return None
41
+ try:
42
+ val = int(float(text))
43
+ except (TypeError, ValueError):
44
+ return None
45
+ return val if 0 <= val <= 4 else None
46
+
47
+
48
+ def epoch_to_iso(ts: Any) -> str | None:
49
+ """秒级 Unix 时间戳 → ISO 8601 UTC 字符串,不可解析返回 None。"""
50
+ if ts is None or isinstance(ts, bool):
51
+ return None
52
+ try:
53
+ val = float(ts)
54
+ except (TypeError, ValueError):
55
+ return None
56
+ if val <= 0:
57
+ return None
58
+ try:
59
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(val))
60
+ except (TypeError, ValueError, OSError):
61
+ return None
62
+
63
+
64
+ def clean_zhihu_title(title: Any) -> str:
65
+ """剥离知乎 API 标题尾部的 ' - 知乎'。"""
66
+ s = str(title or "").strip()
67
+ if s.endswith(" - 知乎"):
68
+ s = s[: -len(" - 知乎")].rstrip()
69
+ return s
70
+
71
+
72
+ def strip_html_tags(text: Any) -> str:
73
+ """去除 <em> 等高亮标签并折叠空白。"""
74
+ cleaned = _HTML_TAG_RE.sub("", str(text or ""))
75
+ return re.sub(r"\s+", " ", cleaned).strip()
76
+
77
+
78
+ def extract_comment_snippets(raw_list: Any, limit: int = 2) -> list[str]:
79
+ """提取 CommentInfoList 中的精选短评内容。"""
80
+ if not isinstance(raw_list, list):
81
+ return []
82
+ out: list[str] = []
83
+ for entry in raw_list:
84
+ if isinstance(entry, dict):
85
+ c = strip_html_tags(entry.get("Content") or "")
86
+ if c:
87
+ out.append(c[:160])
88
+ if len(out) >= limit:
89
+ break
90
+ return out
91
+
92
+
93
+ def zhihu_headers(secret: str) -> dict[str, str]:
94
+ """构造知乎开放平台通用鉴权请求头。"""
95
+ return {
96
+ "Authorization": f"Bearer {secret}",
97
+ "Content-Type": "application/json",
98
+ "X-Request-Timestamp": str(int(time.time())),
99
+ "User-Agent": "argo-search/2.6 (unified-search@local)",
100
+ }
101
+
102
+
103
+ def zhihu_error_item(source: str, code: Any, message: Any) -> dict[str, Any]:
104
+ """非成功响应的统一 error item:保留 code/message,时钟类附加校时提示。"""
105
+ text = f"{source} Code={code} {str(message or '')[:100]}".strip()
106
+ if _ZHIHU_CLOCK_HINT_RE.search(str(message or "")):
107
+ text = f"{text};hint: {_ZHIHU_CLOCK_HINT}"
108
+ return {"error": text, "source": source}
109
+
110
+
111
+ def fetch_question_answers(
112
+ question_url: str,
113
+ limit: int = 3,
114
+ timeout: float = 2.5,
115
+ *,
116
+ _secret_override: str | None = None,
117
+ ) -> list[dict[str, Any]]:
118
+ """获取知乎问题下的精选回答摘要(官方 question_answers 端点)。
119
+
120
+ 返回项含 token、url、summary、content_type。网络异常或配额限制时降级返回空列表,不阻断主流程。
121
+ """
122
+ if not question_url or not question_url.strip():
123
+ return []
124
+ secret = _secret_override if _secret_override is not None else _secret()
125
+ if not secret:
126
+ return []
127
+
128
+ # 规范化问题 URL:剥离多余路径和查询参数
129
+ m = re.search(r"(https?://(?:www\.)?zhihu\.com/question/\d+)", question_url.strip())
130
+ clean_url = m.group(1) if m else question_url.strip()
131
+
132
+ params = urllib.parse.urlencode({
133
+ "QuestionUrl": clean_url,
134
+ "Limit": str(max(1, min(int(limit), 50))),
135
+ "Offset": "0",
136
+ })
137
+ url = f"{ZHIHU_QUESTION_ANSWERS_API}?{params}"
138
+ headers = zhihu_headers(secret)
139
+ try:
140
+ body, _ = http_get(url, headers, timeout=timeout)
141
+ data = json.loads(body.decode("utf-8", "replace"))
142
+ if data.get("Code") in (0, None):
143
+ items = (data.get("Data") or {}).get("Items") or []
144
+ answers = []
145
+ for item in items:
146
+ if not isinstance(item, dict):
147
+ continue
148
+ summary = strip_html_tags(item.get("Summary") or "")
149
+ ans_url = item.get("Url") or ""
150
+ token = str(item.get("ContentToken") or "")
151
+ ctype = str(item.get("ContentType") or "answer").lower()
152
+ if summary or ans_url:
153
+ answers.append({
154
+ "token": token,
155
+ "url": ans_url,
156
+ "summary": summary,
157
+ "content_type": ctype,
158
+ })
159
+ return answers
160
+ except (OSError, ValueError, KeyError, TypeError) as exc:
161
+ _ = exc # 降级返回空列表,不阻断搜索主流程
162
+ return []
25
163
 
26
164
 
27
165
  def _secret() -> str:
@@ -34,28 +172,31 @@ def _secret() -> str:
34
172
  return os.environ.get("ZHIHU_ACCESS_SECRET") or os.environ.get("ARGO_ZHIHU_ACCESS_SECRET", "")
35
173
 
36
174
 
37
- def search(query: str, n: int = 5) -> list[dict[str, Any]]:
175
+ def search(
176
+ query: str,
177
+ n: int = 5,
178
+ expand_questions: bool = True,
179
+ *,
180
+ _secret_override: str | None = None,
181
+ _timeout: float = 10.0,
182
+ ) -> list[dict[str, Any]]:
38
183
  """通过知乎开放平台 zhihu_search 搜索站内内容。"""
39
184
  if not query or not query.strip():
40
185
  return []
41
- secret = _secret()
186
+ secret = _secret_override if _secret_override is not None else _secret()
42
187
  if not secret:
43
188
  return []
44
189
 
190
+ # 官方 zhihu_search Count 最大为 10(超出会被服务端截断,也不接受 SearchDB)
191
+ fetch_count = max(1, min(max(int(n) * 2, int(n)), _ZHIHU_SEARCH_COUNT_MAX))
45
192
  params = urllib.parse.urlencode({
46
193
  "Query": query.strip(),
47
- "Count": str(max(1, min(int(n), 20))),
48
- "SearchDB": "zhihu",
194
+ "Count": str(fetch_count),
49
195
  })
50
196
  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
- }
197
+ headers = zhihu_headers(secret)
57
198
  try:
58
- body, _ = http_get(url, headers, timeout=10)
199
+ body, _ = http_get(url, headers, timeout=_timeout)
59
200
  data = json.loads(body.decode("utf-8", "replace"))
60
201
  except urllib.error.HTTPError as e:
61
202
  # 密钥无效/过期(401/403)等必须暴露为 auth-failed,而不是静默
@@ -65,63 +206,129 @@ def search(query: str, n: int = 5) -> list[dict[str, Any]]:
65
206
  return [{"error": f"zhihu API {type(e).__name__}: {e}", "source": "zhihu"}]
66
207
 
67
208
  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"}]
209
+ return [zhihu_error_item("zhihu", data.get("Code"), data.get("Message"))]
71
210
 
72
- results: list[dict[str, Any]] = []
211
+ candidates: list[dict[str, Any]] = []
73
212
  items = (data.get("Data") or {}).get("Items") or []
74
- for item in items[:n]:
213
+ expanded_count = 0
214
+ max_expand = 2 # 一次搜索最多下钻展开前 2 个纯问题,平衡配额与延迟
215
+
216
+ for rank, item in enumerate(items):
75
217
  if not isinstance(item, dict):
76
218
  continue
77
- title = (item.get("Title") or "").strip()
78
- # API 标题统一带「 - 知乎」尾巴:截断前剥掉(先剥再切,尾巴不占正文)
79
- if title.endswith(" - 知乎"):
80
- title = title[: -len(" - 知乎")].rstrip()
219
+ title = clean_zhihu_title(item.get("Title"))
81
220
  url_ = item.get("Url") or ""
82
- snippet = (item.get("ContentText") or title or "")[:300]
221
+ raw_text = strip_html_tags(item.get("ContentText") or title)
222
+ snippet = raw_text[:500]
83
223
  if not title and not url_:
84
224
  continue
85
225
  content_id = str(item.get("ContentID") or "")
86
226
  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
227
+ content_type = (item.get("ContentType") or "answer").lower()
228
+ try:
229
+ likes = int(item.get("VoteUpCount") or 0)
230
+ except (ValueError, TypeError):
231
+ likes = 0
232
+ try:
233
+ comments = int(item.get("CommentCount") or 0)
234
+ except (ValueError, TypeError):
235
+ comments = 0
236
+ published = epoch_to_iso(item.get("EditTime"))
237
+ upstream_auth = parse_authority_level(item.get("AuthorityLevel"))
238
+ badge_text = str(item.get("AuthorBadgeText") or "").strip()
239
+ top_comments = extract_comment_snippets(item.get("CommentInfoList"))
240
+ ranking_score = item.get("RankingScore")
241
+
242
+ # 识别纯问题:支持自动下钻抓取 Top 精选回答摘要(方案 B:Question Answers Expansion)
243
+ is_pure_question = (content_type == "question") or ("/question/" in url_ and "/answer/" not in url_)
244
+ expanded_answers: list[dict[str, Any]] = []
245
+ if is_pure_question and expand_questions and expanded_count < max_expand:
246
+ expanded_count += 1
247
+ expanded_answers = fetch_question_answers(url_, limit=3, _secret_override=secret)
248
+ if expanded_answers:
249
+ answer_summaries = [f"【回答 {i+1}】{a['summary']}" for i, a in enumerate(expanded_answers[:2]) if a.get("summary")]
250
+ if answer_summaries:
251
+ addon = " ".join(answer_summaries)
252
+ snippet = f"{snippet} | {addon}"[:500] if snippet else addon[:500]
91
253
 
92
- results.append({
254
+ # 结合上游相关性序位与社区点赞/评论/权威分做质量综合评分
255
+ base_relevance = max(1.0 - rank * 0.05, 0.2)
256
+ like_boost = min(0.3, math.log10(likes + 1) * 0.08)
257
+ comment_boost = min(0.1, math.log10(comments + 1) * 0.03)
258
+ expand_boost = 0.08 if expanded_answers else 0.0
259
+ auth_boost = (upstream_auth - 1) * 0.02 if upstream_auth and upstream_auth >= 2 else 0.0
260
+ quality_score = round(min(1.0, base_relevance * 0.7 + like_boost + comment_boost + expand_boost + auth_boost), 4)
261
+
262
+ social_meta: dict[str, Any] = {
263
+ "platform": "zhihu",
264
+ "content_type": content_type,
265
+ "id": content_id,
266
+ "author": author,
267
+ "likes": likes,
268
+ "upvotes": likes,
269
+ "comments": comments,
270
+ "provider": "zhihu_openapi",
271
+ "is_question": is_pure_question,
272
+ "has_expanded_answers": bool(expanded_answers),
273
+ }
274
+ if item.get("AuthorityLevel") not in (None, ""):
275
+ social_meta["authority_level"] = str(item.get("AuthorityLevel"))
276
+ if badge_text:
277
+ social_meta["author_badge_text"] = badge_text
278
+ if top_comments:
279
+ social_meta["top_comments"] = top_comments
280
+ if isinstance(ranking_score, (int, float)):
281
+ social_meta["ranking_score"] = round(float(ranking_score), 4)
282
+ if expanded_answers:
283
+ social_meta["answers"] = [
284
+ {"url": a["url"], "summary": a["summary"]} for a in expanded_answers
285
+ ]
286
+
287
+ entry: dict[str, Any] = {
93
288
  "title": title[:100] + ("..." if len(title) > 100 else ""),
94
289
  "url": url_,
95
290
  "snippet": snippet,
96
291
  "source": "zhihu",
97
- "score": max(1.0 - len(results) * 0.1, 0.1),
292
+ "score": quality_score,
98
293
  "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
294
+ "social_meta": social_meta,
295
+ }
296
+ if upstream_auth is not None:
297
+ entry["upstream_authority"] = upstream_auth
298
+ candidates.append(entry)
299
+
300
+ # 按综合得分降序微调,确保高赞高质量答案排在前面,并保留前 n 条
301
+ candidates.sort(key=lambda r: r["score"], reverse=True)
302
+ return candidates[:n]
110
303
 
111
304
 
112
305
  def main():
113
306
  import argparse
114
307
  parser = argparse.ArgumentParser(description="Zhihu search engine (zhihu_openapi)")
115
- parser.add_argument("action", nargs="?", default="search")
116
- parser.add_argument("query", nargs="?")
308
+ parser.add_argument("action", nargs="?", default="search", help="search | answers")
309
+ parser.add_argument("query", nargs="?", help="Search query or question URL")
117
310
  parser.add_argument("-n", type=int, default=5)
311
+ parser.add_argument("--no-expand", action="store_true", help="Disable question answers expansion")
118
312
  parser.add_argument("--json", action="store_true")
119
313
  args = parser.parse_args()
120
314
 
121
315
  if not args.query:
122
316
  print("[]")
123
317
  return
124
- results = search(args.query, args.n)
318
+
319
+ if args.action in ("answers", "question_answers"):
320
+ answers = fetch_question_answers(args.query, limit=args.n)
321
+ if args.json:
322
+ print(json.dumps(answers, ensure_ascii=False))
323
+ else:
324
+ for i, a in enumerate(answers, 1):
325
+ print(f"### Answer {i}")
326
+ print(f"- URL: {a['url']}")
327
+ print(f"- {a['summary']}")
328
+ print()
329
+ return
330
+
331
+ results = search(args.query, args.n, expand_questions=not args.no_expand)
125
332
  if args.json:
126
333
  print(json.dumps(results, ensure_ascii=False))
127
334
  else:
@@ -129,8 +336,9 @@ def main():
129
336
  meta = r.get("social_meta") or {}
130
337
  print(f"### {i}. {r['title']}")
131
338
  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', '')}")
339
+ print(f"- {r['snippet'][:250]}")
340
+ print(f"- likes={meta.get('likes')} comments={meta.get('comments')} @{meta.get('author', '')} "
341
+ f"[question={meta.get('is_question')} expanded={meta.get('has_expanded_answers')}]")
134
342
  print()
135
343
 
136
344
 
@@ -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)
@@ -299,9 +299,67 @@ def render(report: dict, verbose: bool = False) -> str:
299
299
  lines.append("")
300
300
 
301
301
  lines.append(" 运行 `argo doctor --fix` 自动执行停用与隔离;降级需人工判断。")
302
+ lines.append(" 对交付率异常的声明式源,可运行 `python3 scripts/engine_validate.py -e <id> --diagnose`"
303
+ " (或 `--fix`) 探测结构漂移并输出建议补丁(只读预览);"
304
+ "确认无误后手动更新 `engines/specs/<id>.yaml`。")
302
305
  return "\n".join(lines)
303
306
 
304
307
 
308
+ def _apply_fix(report: dict[str, Any], days: int,
309
+ spec_dir: Path | None = None) -> dict[str, Any]:
310
+ """执行 demote(停用)与 quarantine(隔离)。
311
+
312
+ 改写的是 spec 文件里的 `enabled` 与 `disabled_reason` 两个键,保留其余
313
+ 内容(注释、字段顺序、授权常量)不动——整文件重写会丢注释,而 spec 是
314
+ 人工维护的真源。改写后不自动跑 sync_backends:调用方需自行决定何时同步
315
+ 派生件(见 main 的提示)。
316
+
317
+ quarantine 与 demote 落到同一个 `enabled: false`,但 disabled_reason
318
+ 前缀不同,便于区分「低价值停用」与「低交付率隔离」。
319
+ """
320
+ import re as _re
321
+
322
+ target_dir = spec_dir or (Path(__file__).parent.parent / "engines" / "specs")
323
+ actions: list[dict[str, str]] = []
324
+ for action, items in (("demote", report.get("demote") or []),
325
+ ("quarantine", report.get("quarantine") or [])):
326
+ for rec in items:
327
+ name = rec.get("engine") or ""
328
+ path = target_dir / f"{name}.yaml"
329
+ if not path.is_file():
330
+ actions.append({"engine": name, "action": action,
331
+ "status": "spec 不存在"})
332
+ continue
333
+ text = path.read_text(encoding="utf-8")
334
+ reason = (f"{action} by argo doctor --fix "
335
+ f"({rec.get('reason', '')};审计窗口 {days} 天)")
336
+ # 幂等:已停用且原因已标注的跳过
337
+ if _re.search(r"^enabled:\s*false", text, _re.M) and action in text:
338
+ actions.append({"engine": name, "action": action,
339
+ "status": "已停用(跳过)"})
340
+ continue
341
+ if _re.search(r"^enabled:\s*true", text, _re.M):
342
+ text = _re.sub(r"^enabled:\s*true.*$",
343
+ "enabled: false", text, count=1, flags=_re.M)
344
+ else:
345
+ # 无 enabled 键:补在 engine_id 之后
346
+ text = _re.sub(r"^(engine_id:.*)$",
347
+ r"\1\nenabled: false", text, count=1, flags=_re.M)
348
+ # 写 disabled_reason(已有则替换,没有则补在 enabled 之后;用 lambda 避免 reason 中特殊符号引起转义异常)
349
+ if _re.search(r"^disabled_reason:", text, _re.M):
350
+ text = _re.sub(r"^disabled_reason:.*$",
351
+ lambda _: f"disabled_reason: {reason}", text,
352
+ count=1, flags=_re.M)
353
+ else:
354
+ text = _re.sub(r"^(enabled: false.*)$",
355
+ lambda m: f"{m.group(1)}\ndisabled_reason: {reason}", text,
356
+ count=1, flags=_re.M)
357
+ path.write_text(text, encoding="utf-8")
358
+ actions.append({"engine": name, "action": action,
359
+ "status": "已停用"})
360
+ return {"actions": actions}
361
+
362
+
305
363
  def main() -> int:
306
364
  import argparse
307
365
  parser = argparse.ArgumentParser(
@@ -310,10 +368,29 @@ def main() -> int:
310
368
  help="审计窗口(天),默认 90")
311
369
  parser.add_argument("--json", action="store_true", help="JSON 输出")
312
370
  parser.add_argument("--verbose", action="store_true", help="显示全部明细")
371
+ parser.add_argument("--fix", action="store_true",
372
+ help="执行 demote(停用)与 quarantine(隔离)")
313
373
  args = parser.parse_args()
314
374
 
315
375
  report = audit(days=args.days, verbose=args.verbose)
316
376
 
377
+ if args.fix:
378
+ fixed = _apply_fix(report, args.days)
379
+ if args.json:
380
+ try:
381
+ import cli_io
382
+ print(cli_io.dumps(fixed))
383
+ except ImportError:
384
+ print(json.dumps(fixed, ensure_ascii=False, separators=(",", ":")))
385
+ else:
386
+ print(f"已执行 {len(fixed['actions'])} 项动作:")
387
+ for a in fixed["actions"][:20]:
388
+ print(f" - {a['engine']}: {a['action']} → {a['status']}")
389
+ if len(fixed["actions"]) > 20:
390
+ print(f" ... 另有 {len(fixed['actions']) - 20} 项")
391
+ print("\n改写 spec 后请同步派生件:python3 scripts/sync_backends.py")
392
+ return 0
393
+
317
394
  if args.json:
318
395
  # CLI stdout 必须紧凑 JSON(cli_io.dumps)——缩进 JSON 会被
319
396
  # test_context_budget 判为「CLI 输出污染管道」。